您能用python编写一段hangman小游戏的代码吗?
时间: 2024-02-07 20:02:25 浏览: 117
当然可以!以下是一个简单的 Hangman(猜词游戏)的 Python 代码示例:
```python
import random
def hangman():
word_list = ['apple', 'banana', 'orange', 'watermelon', 'strawberry'] # 单词列表
word = random.choice(word_list) # 从列表中随机选择一个单词
guessed_letters = [] # 存储已猜过的字母
tries = 6 # 猜错的次数
correct_guesses = 0 # 猜对的字母数量
print("Welcome to Hangman!")
print("_ " * len(word)) # 打印出初始的下划线,表示未猜中的字母
while tries > 0 and correct_guesses < len(word):
guess = input("Guess a letter: ").lower()
if len(guess) != 1:
print("Please enter a single letter!")
continue
if guess in guessed_letters:
print("You have already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in word:
print("Correct guess!")
correct_guesses += word.count(guess) # 计算猜对的字母数量
else:
print("Wrong guess!")
tries -= 1
display_word = "" # 用于显示当前的单词状态
for letter in word:
if letter in guessed_letters:
display_word += letter + " "
else:
display_word += "_ "
print(display_word)
if correct_guesses == len(word):
print("Congratulations! You guessed the word correctly!")
else:
print("Sorry, you ran out of tries. The word was:", word)
hangman()
```
运行这段代码,你将能够玩一个简单的 Hangman 小游戏。代码会随机选择一个单词,然后你需要猜测每个字母,直到你猜出整个单词或者猜错次数达到限制。祝你玩得愉快!
阅读全文