今天的练手小程序名字叫“侩子手”,有没有感到扑面而来的杀气,同样的,题目来自Knight Lab
下面来简单介绍一下程序的要求,其实程序跟“侩子手”没有半毛钱关系啦,我们要做的就是一个猜字游戏,从预先设定的单词列表中随机选出一个单词,然后根据玩家输入的字母,给出该单词中的该字母的数量,然后打印出字母。整个游戏要限制猜测次数!
然后我们来分析一下程序要求:
- 一个预设的单词列表,用于随机生成待猜测单词
- 需要一个函数来判断用户输入的是否是单个字符,不是的话给出提示,直到用户正确输入
- 一个判断字符是否在单词中的函数,并给出字符出现次数和位置信息
- 主函数
下面是我的代码块:
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
import random
import string
# pre-defined words for random choice
words = [
'python',
'django',
'framwork',
'window',
'array',
'assert',
'buttons',
'class',
'hierachy',
'class',
'compiler',
'control',
'context',
'linux',
'random',
'reference'
]
# generate a random word for guess
hidden_word = random.choice(words)
# a function for checking if the user input is a letter
def is_char(letter):
if letter in string.ascii_letters and len(letter) == 1:
return True
else:
return False
# define a function to get user's input
def get_letter():
while True:
letter = raw_input("Input the letter you guseed. ").strip().lower()
if is_char(letter):
return letter
else:
print "Please ensure that you input a solo letter. Thanks"
def change_char(hidden_word, letter, show_word):
if show_word == '':
show_word = '*'*len(hidden_word)
out_word = ''
for zip_letter in zip(hidden_word, show_word):
out_word += zip_letter[0] if letter in zip_letter else zip_letter[1]
return out_word
def hungman():
limite = 10
show_word = ''
while limite > 0:
if show_word == hidden_word:
print "You got it!"
break
else:
letter = get_letter()
if is_char(letter):
show_word = change_char(hidden_word, letter, show_word)
count = hidden_word.count(letter)
print "'%s' is appeared %d time(s) in hidden word, and thi position is %s" % (letter, count, show_word)
limite -= 1
print "%d times remain." % limite
if __name__ == "__main__":
hungman()