用python写一个单词猎手游戏
时间: 2023-07-04 09:04:33 浏览: 194
好的,下面是一个简单的单词猎手游戏的Python代码:
```python
import random
words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew', 'kiwi', 'lemon', 'mango', 'nectarine', 'orange', 'pear', 'quince', 'raspberry', 'strawberry', 'tangerine', 'watermelon']
def play_game():
word = random.choice(words)
blanks = "_" * len(word)
attempts = 6
guessed_letters = []
print("Welcome to Word Hunter!")
print("The word contains", len(word), "letters.")
print(blanks)
while attempts > 0 and "_" in blanks:
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You already guessed that letter. Try again.")
elif guess not in word:
attempts -= 1
print("Sorry, that letter is not in the word. You have", attempts, "attempts left.")
else:
guessed_letters.append(guess)
indices = [i for i in range(len(word)) if word[i] == guess]
for index in indices:
blanks = blanks[:index] + guess + blanks[index+1:]
print(blanks)
if "_" not in blanks:
print("Congratulations, you guessed the word!")
else:
print("Sorry, you ran out of attempts. The word was", word)
play_game()
```
这个代码会随机选择一个单词,并生成一个由下划线组成的字符串来表示单词中的每个字母。玩家需要通过猜测字母来猜出单词,每次猜测都会提示玩家是否猜中了字母,以及单词的当前状态。玩家有6次猜测机会,如果在这些机会内无法猜出单词,游戏失败。
阅读全文