用python写一个猜文字游戏
时间: 2023-07-01 11:11:38 浏览: 41
好的,下面是一个简单的猜文字游戏的 Python 代码:
```python
import random
# 定义一个列表存储需要猜的单词
words = ["apple", "banana", "orange", "grape", "pear"]
# 从单词列表中随机选择一个单词
word = random.choice(words)
# 生成一个由“_”组成的等长字符串,表示单词的隐藏状态
hidden_word = "_" * len(word)
# 初始化猜测次数
guesses = 0
# 限制最大猜测次数
max_guesses = 10
# 开始猜测
while guesses < max_guesses and hidden_word != word:
print("Guess the word:", hidden_word)
guess = input("Enter a letter or the complete word: ")
# 如果猜测的是完整单词
if guess == word:
hidden_word = word
# 如果猜测的是单个字母
elif len(guess) == 1:
# 将猜测的字母与单词中的字母进行比较
for i in range(len(word)):
if guess == word[i]:
hidden_word = hidden_word[:i] + guess + hidden_word[i+1:]
guesses += 1
# 判断游戏结果
if hidden_word == word:
print("Congratulations! You guessed the word in", guesses, "guesses.")
else:
print("Sorry, you ran out of guesses. The word was", word + ".")
```
这个程序的功能比较简单,它会随机从一个单词列表中选择一个单词,然后让玩家猜测这个单词是什么。玩家可以猜测单个字母或者完整的单词,程序会根据猜测的结果给出提示。如果玩家在规定的猜测次数内猜对了单词,程序会输出“Congratulations! You guessed the word in X guesses.”,反之则输出“Sorry, you ran out of guesses. The word was Y.”。