前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用Python写的HangMan游戏

用Python写的HangMan游戏

作者头像
py3study
发布2020-01-07 14:56:47
2.2K0
发布2020-01-07 14:56:47
举报
文章被收录于专栏:python3

选自一本用Python编写自己的电脑游戏一书

代码语言:javascript
复制
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 
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档