hangman猜字游戏 python
时间: 2023-06-30 17:13:58 浏览: 54
好的,我可以帮你写一个简单的 Hangman 猜字游戏。以下是代码实现:
```python
import random
# 定义要猜的单词列表
word_list = ["apple", "banana", "cherry", "orange", "peach", "pear"]
# 随机选择一个单词
word = random.choice(word_list)
# 定义初始的猜测次数和猜测的字母集合
guesses = 6
letters_guessed = set()
# 定义提示信息
print("Welcome to Hangman!")
print(f"The word is {len(word)} letters long.")
# 当还有猜测次数,且单词没有被猜中时,继续游戏
while guesses > 0 and set(word) != letters_guessed:
# 显示当前已经猜对的字母
guessed_word = "".join([letter if letter in letters_guessed else "_" for letter in word])
print(f"You have {guesses} guesses left. The word is: {guessed_word}")
# 用户输入猜测的字母
guess = input("Guess a letter: ").lower()
# 检查猜测的字母是否已经猜过
if guess in letters_guessed:
print("You already guessed that letter! Try again.")
else:
letters_guessed.add(guess)
# 检查猜测的字母是否在单词中出现
if guess in word:
print("Good guess!")
else:
print("Bad luck!")
guesses -= 1
# 游戏结束,根据猜测次数和单词是否被猜中显示结果
if set(word) == letters_guessed:
print("Congratulations, you guessed the word!")
else:
print(f"Sorry, you ran out of guesses. The word was {word}.")
```
在这个实现中,我们首先定义了一个单词列表,然后从中随机选择一个单词作为要猜的单词。之后我们定义了初始的猜测次数和猜测的字母集合。在每一轮游戏中,我们先显示当前已经猜对的字母,让用户输入猜测的字母,然后检查猜测的字母是否已经猜过,如果没有猜过,则将其加入猜测的字母集合中。如果猜测的字母在单词中出现,则提示用户猜对了,否则提示用户猜错了,并将猜测次数减一。当猜测次数为零或者单词被猜中时,游戏结束,根据情况显示结果。
阅读全文