电脑根据单词列表随机生成一个单词,打印出这个单词长度个 ‘ _ ’ ,玩家随机输入一个这个单词可能包含的英文字母,如果玩家猜对了,电脑则会在正确的空格处填写这个字母,如果没有猜对,游戏次数就减一。如果玩家在游戏次数减为零前猜对这个单词的所有字母,则玩家获胜,否则玩家输掉比赛。
from random import*
words = 'tiger lion wolf elephant zebra ducksheep rabbit mouse'.split()
#得到要猜的神秘单词
def getWord(wordList):
n = randint(0,len(wordList)-1)
return wordList[n]
#游戏界面
def display(word,wrongLetters,rightLetters,chance):
print('你还有{:n}次机会'.format(chance).center(40,'-'))
print('已经猜错的字母:'+ wrongLetters)
print()
blanks = '_'*len(word)
for i in range(len(word)):
if word[i] in rightLetters:
blanks = blanks[:i] + word[i] +blanks[i+1:]
for i in blanks:
print(i+' ',end='')
print()
print()
#从玩家的输入得到一个猜测的字母
def getLetter(alreadyGuessed):
while True:
print('请输入一个可能的字母:')
guess = input()
guess = guess.lower()
if guess[0] in alreadyGuessed:
print('你已经猜过这个字母了!')
elif guess[0] not in 'qwertyuiopasdfghjklzxcvbnm':
print('请输入一个英文字母!(a-z)')
else:
return guess[0]
#是否再玩一次
def playAgain():
print('是否在玩一次?(y/n)')
s = input()
s = s.lower()
if s[0] == 'y':
return 1
return 0
#游戏初始化
wrongLetters = ''
rightLetters = ''
word = getWord(words)
chance = 6 #初始为6次机会
done = False
while True:
display(word,wrongLetters,rightLetters,chance)
guess = getLetter(wrongLetters+rightLetters)
if guess in word:
rightLetters = rightLetters+ guess
foundAll = True
for i in range(len(word)):
if word[i] not in rightLetters:
foundAll = False
break
if foundAll:
print('你真棒,这个单词就是'+ word +',你赢了!')
done = True
else:
wrongLetters = wrongLetters + guess
chance = chance - 1
if chance == 0:
display(word,wrongLetters,rightLetters,chance)
print("你已经没有机会了!你一共猜错了"+str(len((wrongLetters))+"次,猜对了"+str(len(rightLetters))+"次,正确的单词是:"+ word)
done = True
if done:
if playAgain():
wrongLetters = ''
rightletters = ''
word = getWord(words)
chance = 6 #初始为6次机会
done = 0
else:
break