📅  最后修改于: 2020-05-20 06:31:05             🧑  作者: Mango
Hangman是一款文字游戏,其中计算机会从字典中随机选择一个单词,玩家必须在给定的回合数内正确猜出它。要猜的单词由一排星星表示。如果猜出的字母是单词,脚本将自动放置到正确的位置。
猜词规则:
- 一圈输入单个字母。
- 不要使用重复的字母。
- 每次猜测后转弯次数都会减少。
这是代码words.txt中使用的文本文件,其中包含50,000个英语单词。
所需模块:
import random
下面是实现:
# Python程式执行Hangman游戏
# 导入随机模块
import random
# 从字典中随机选择一个单词的函数
def get_word():
# 文本文件的路径
with open('/Users/Admin/Desktop/words.txt', 'r') as f:
# Reads each word after splitting
words1 = f.read().splitlines()
# 返回任何随机词
return random.choice(words1)
myword = get_word()
# 函数打印一行文字代替单词
for i in myword:
print("*", end = " ")
# 计算字长
l = len(myword)
print("\nWord has %d letters" %l)
# 检查输入的字母是否正确
def check(myword, your_word, guess1):
status = ''
matches = 0
for letter in myword:
if letter in your_word:
status += letter
else:
status += '*'
if letter == guess1:
matches += 1
if matches > 1:
print(matches, guess1)
elif matches == 1:
print(guess1)
return status
# 游戏主要函数
def game():
guess = 0
guessed = False
your_word = []
turns = len(myword) + 1
turns1 = turns
print("Total turns: ", turns)
while guess < turns1:
guess1 = input("Enter your guess: ")
# 每次猜测后递减转弯
turns -= 1
# 打印左转
print("Turns left", turns)
# 如果已经猜到字母
if guess1 in your_word:
print("You already guessed")
elif len(guess1) == 1:
# 在其位置附加字母
your_word.append(guess1)
result = check(myword, your_word, guess1)
if result == myword:
guessed = True
print("You won " + name)
print(myword)
else:
print(result)
else:
print("Invalid entry")
guess += 1
if guess == turns1:
print("Word is:")
print(myword)
# 测试代码
game()
输出:
* * * * *
Word has 5 letters
Total turns: 11
Enter your guess: a
Turns left 10
**********
Enter your guess: i
Turns left 9
i
**i**i****
Enter your guess: s
Turns left 8
s
**i**i**ss
Enter your guess: r
Turns left 7
**i**i**ss
Enter your guess: h
Turns left 6
**i**i**ss
Enter your guess: e
Turns left 5
e
**i**i*ess
Enter your guess: o
Turns left 4
**i**i*ess
Enter your guess: u
Turns left 3
u
*ui**i*ess
Enter your guess: t
Turns left 2
t
*ui*ti*ess
Enter your guess: n
Turns left 1
n
*ui*tiness
Enter your guess: l
Turns left 0
l
*uiltiness
Word is:
guiltiness