用python写一个hangman游戏程序
时间: 2023-11-26 07:03:35 浏览: 110
好的,下面是一个简单的hangman游戏程序的Python代码:
```
import random
# 初始设置
word_list = ["apple", "banana", "orange", "watermelon", "peach", "grape", "kiwi"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
display = ["_"] * word_length
lives = 6
# 游戏开始
print("Welcome to Hangman!")
while "_" in display and lives > 0:
guess = input("Guess a letter: ").lower()
# 判断猜测是否正确
if guess in chosen_word:
for i in range(word_length):
if chosen_word[i] == guess:
display[i] = guess
print(f"{' '.join(display)}")
else:
lives -= 1
print(f"Wrong guess. You have {lives} lives left.")
# 显示当前状态
if "_" not in display:
print("Congratulations! You win!")
elif lives == 0:
print(f"You lose. The word was {chosen_word}.")
```
运行这个程序后,游戏会开始,程序会随机从 `word_list` 中选择一个单词作为答案,然后让玩家猜测每个单词中的字母。程序会显示一个下划线代表每个未知字母,并在玩家猜测正确时显示正确的字母。当玩家猜测错误时,他们会失去一条生命,并在程序显示他们还剩几条生命。如果玩家在生命耗尽之前猜出单词,他们赢了,如果他们在生命耗尽之后仍然没有猜到单词,他们输了。
阅读全文