选自一本用Python编写自己的电脑游戏一书
import random
HANGMANPICS = ['''''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider tork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()
def getRandomWord(wordList): #在words字典里随机选出候选单词
wordIndex = random.randint(0,len(wordList) - 1)
return wordList[wordIndex] #返回选定单词
def displayBoard (HANGMANPICS,missedLetters,correctLetters,secretWord):
print('\n\n* * * * * * * * * * * *',end = '')
print(HANGMANPICS[len(missedLetters)]) #猜错几个字母,返回第几张图片
print()
print('Missed letters:',end=' ')
for letter in missedLetters: #输出猜错的字母
print(letter,end=' ')
print()
blanks = '_' *len(secretWord) #将所选单词所有字母替换成"_"
for i in range(len(secretWord)): ########这段程序的难点
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:] #将猜出的字母替换掉"_"
for letter in blanks:
print(letter ,end=' ') #输出blanks,并插入空格
print()
def getGuess(alreadyGuessed): #判断用户输入是否合法
while True:
print('* * * * * * * * * * * *')
guess = input('Guess a letter:')
guess = guess.lower()
if len(guess) != 1:
print('Please enter a single letter.')
elif guess in alreadyGuessed:
print('You have already guessed that letter. Choose again.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please enter a LETTER.')
else:
return guess #返回用户输入的字母
def playAgain(): #判断是否继续游戏
print()
return input('Do you want to play again?(yea or no):').lower().startswith('y') # lower(): #输入的字符串转变成小写;
print(' == H A N G M A N ==')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
while True:
displayBoard(HANGMANPICS,missedLetters,correctLetters,secretWord) # 调用displayBoard函数,并传递相应的值
guess = getGuess(missedLetters + correctLetters) #调用getGuess函数,并传递用户猜过的字母(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess #如果所猜的字母在随机单词内,correctLetters收录该字母
foundAllLetters = True #假定字母全部猜出
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters: #如果单词内有字母没被correctLetters收录,foundAllLetters为假,并跳出循环
foundAllLetters = False
break
if foundAllLetters == True: #如果字母全部猜出,gameIsDone 为真
print('Yes! The secret word is "' + secretWord + '"! You have won!')
gameIsDone = True
else:
missedLetters = missedLetters + guess #如果所猜的字母不在随机单词内,missedLetters收录该字母
if len(missedLetters) == len(HANGMANPICS) - 1: #如果用户猜错6次,游戏结束
displayBoard(HANGMANPICS,missedLetters,correctLetters,secretWord)
print('You have run out of guesses!\nAfter ' +str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
gameIsDone = True
if gameIsDone: #游戏结束
if playAgain(): #调用playAgain(),如果返回为真,进行初始化
missedLetters = ''
correctLetters = ''
gameIsDone = False
secretWord = getRandomWord(words)
else:
break