读书须用意,一字值千金。
以一个文本游戏 – 经典的 Hangman 猜词游戏为例。
游戏规则如下:
1.玩家一挑选一个秘密单词,单词中有多少个字母,则划多少条横线(这里用下划线表示)。
2.玩家二每次猜一个字母。
3.如果玩家二猜测的字母正确,玩家一将下划线修改为正确的字母。在本书的游戏版本中,如果单词中有一个字母出现两次,玩家二必须猜两次。如果玩家二猜测错误,玩家一则画出上吊的人的一部分身体(从头部开始),如下图所示。
4.如果玩家二在玩家一画完上吊的人之前猜对单词,玩家二胜利,反之失败。
源码_V1
def hangman(word):
wrong = 0 # 记录错误的次数
stages = [
" _____ ",
"| | ",
"| | ",
"| 0 ",
"| /|\ ",
"| / \ ",
"|________ "
]
rletters = list(word)#形成被猜列表['c', 'a', 't']
board = ["__"] * len(word) #列表乘法['__', '__', '__']
win = False
print("Welcome to Hangman")
while wrong < len(stages) : #如果猜错的次数小于 Hangman 列表的长度
print("\n")
char = input("Guess a letter") #用户输入,猜测字母
if char in rletters: # 如果猜测的字母在被猜列表中
cind = rletters.index(char) #取出被猜中的字母的索引
board[cind] = char # 将 '_' 变为字母
rletters[cind] = '$'#将被猜测列表中原字母位置被替换为 '$',使得该位不再参与遍历,不再与下一个 char 进行比较
print((" ".join(board))) #输出当前猜测的进度 board 列表
else:
# print((" ".join(board))) #输出当前猜测的进度 board 列表
print("\n".join(stages[0:wrong+1]))
wrong += 1 #如果用户猜测不正确则 wrong+1
if "__" not in board:
print("\n\nYou win!")
print(" ".join(board))# board 列表种每一个元素以空格隔开输出
win = True
break
if not win:
# print("\n".join(stages[0:e]))
print("You lose! It was {}.".format(word))#提示游戏失败,并输出最终答案
def main():
hangman("cat")
if __name__=='__main__':
main()
源码_V2
该版本较第一个版本的区别是 while count<len(stages)
以猜错字数小于打印字符的长度为条件进行 while
循环如果猜测全部正确则打印 "you win"
并使用 return 0
终止程序如果在打印字符全部打印出来后还是没能全部猜出来,则 while
循环结束并打印 "you are failed"
def hangman(word):
stages = [
" _____ ",
"| | ",
"| | ",
"| 0 ",
"| /|\ ",
"| / \ ",
"|________ "
]
rletters = list(word)#形成被猜列表['c', 'a', 't']
board = ["__"] * len(word) #列表乘法['__', '__', '__']
win = False
print("Welcome to Hangman")
count = 0
limit = len(stages)
while count < limit:
guess = input("\nguess the char: ")
if guess in rletters:
addr = rletters.index(guess)
board[addr] = guess
rletters[addr] = '$'
else:
count += 1
print(" ".join(board))
# print("猜错次数:",count)
print("\n".join(stages[0:count]))
if "__" not in board:
print("You win")
return 0
print("You are failed")
def main():
hangman("cat")
if __name__=='__main__':
main()
猪头
2020.4.23