赞
踩
这个游戏是我初学python时写的,个人觉得例子非常好,现在分享给大家。
每一行代码不懂得直接评论吧我都会详细解释~,希望能有助于各位的学习。
游戏如下:
在单词库中给出一系列单词,如果猜错火柴人会一步步形成:
如果猜对,则会显示单词,并恭喜您答对单词~
附上源码:
- import random
- # 构建图像
- HANGMAN_PICS = ['''
- # +---+
- # |
- # |
- # |
- # ===''','''
- # +---+
- # 0 |
- # |
- # |
- # === ''','''
- # +---+
- # 0 |
- # | |
- # |
- # === ''','''
- # +---+
- # 0 |
- # /| |
- # |
- # === ''','''
- # +---+
- # 0 |
- # /| |
- # |
- # === ''','''
- # +---+
- # 0 |
- # /| |
- # / |
- # === ''','''
- # +---+
- # 0 |
- # /| |
- # / |
- # === ''']
- # 定义单词库
- words = 'fantasy salute tike pisces raven zara stussy'.split()
- # 定义选择的单词方法
- # wordList为单词列表
- def getRandomWord(wordList):
- wordIndex = random.randint(0,len(wordList) - 1)
- return wordList[wordIndex]
-
- # 定义显示板
- # missedLetters correctLetters secretWord 玩家猜过不在神秘单词里面,玩家猜过在神秘单词,神秘单词
- def displayBoard(missedLetters,correctLetters,secretWord):
- # HANGMAN_PICS为全局变量,即整个火柴的全部内容
- print(HANGMAN_PICS[len(missedLetters)])
- print()
- # 打印出错误的字母,用for 循环在打印出每个字母
- print('Missed letters:',end='')
- for letter in missedLetters:
- print(letter,end='')
- print()
-
-
- # 对__的长度进变化
- blank='_'*len(secretWord)
- # 对blank中的东西进行替换
- for i in range(len(secretWord)):
- if secretWord[i] in correctLetters:
- # --[:2]=>0,1 [2:]=>2到最后 含头不含尾
- blank = blank[:i]+secretWord[i]+blank[i+1:]
- for letter in blank:
- print(letter,end='')
- print()
-
-
- # 玩家猜测的数据
- def getGuess(alreadyGuessed):
- while True:
- print('Guess a letter.')
- guess = input()
- guess = guess.lower()
- if len(guess)!=1:
- print("please enter a single letter")
- elif guess in alreadyGuessed:
- print("猜对了,请继续")
- else:
- return guess
- # 判断玩家是否还想在玩一次
- def playAgian():
- print("你还想再玩么 (yes or no)")
- return input().lower().startswith('y')
-
- # 程序开始执行并循环
- print('H A N G M A N ')
- missedLetters = ''
- correctLetters = ''
- secretWord = getRandomWord(words)
- gameisDone = False
- while True:
- displayBoard(missedLetters,correctLetters,secretWord)
- guess = getGuess(missedLetters + correctLetters)
- if guess in secretWord:
- correctLetters =correctLetters+ guess
- foundAllLetters = True
- for i in range(len(secretWord)):
- if secretWord[i] not in correctLetters:
- foundAllLetters = False
- break
- if foundAllLetters:
- print('yes! the secretWord is " '+ secretWord +'"! you have won ')
- gameisDone
-
- else:
- missedLetters = missedLetters +guess
-
- if len(missedLetters)== len(HANGMAN_PICS) -1:
- displayBoard(missedLetters,correctLetters,secretWord)
- print('you have run out of guesses! n After '+ str(len(missedLetters)) + 'missed guesses and ' +
- str(len(correctLetters)) + 'correct guessed,the word was "' + secretWord + '" ')
- gameisDone = True
-
-
- if gameisDone:
- if playAgian():
- missedLetters=''
- correctLetters=''
- gameisDone=False
- secretWord = getRandomWord(words)
- else:
- break
输入win+R=》cmd打开终端,再将文档拖入终端内,即可执行(或者直接用python运行)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。