使用Python编写的简单游戏案例:猜单词游戏
发布时间:2023-12-04 19:35:06
下面是一个使用Python编写的简单猜单词游戏的案例,该游戏会随机从一个单词列表中选取一个单词,玩家需要根据提示猜出正确的单词。以下是完整的代码及其使用示例。
import random
def get_word():
words = ["apple", "banana", "orange", "watermelon", "mango"]
return random.choice(words)
def play_game():
word = get_word()
guessed_letters = []
attempts = 6
while True:
print("
Word: ", end="")
for letter in word:
if letter in guessed_letters:
print(letter, end=" ")
else:
print("_", end=" ")
if set(word) == set(guessed_letters):
print("
Congratulations! You guessed the word correctly!")
break
if attempts == 0:
print("
Game over! You failed to guess the word. The word was", word)
break
print("
Attempts remaining:", attempts)
guess = input("Enter a letter: ").lower()
if len(guess) > 1:
print("Please enter only one letter at a time!")
continue
if guess in guessed_letters:
print("You have already guessed that letter!")
continue
guessed_letters.append(guess)
if guess not in word:
attempts -= 1
print("Incorrect guess!")
play_game()
使用示例:
Word: _ _ _ _ _ Attempts remaining: 6 Enter a letter: a Word: a _ _ _ _ Attempts remaining: 6 Enter a letter: e Word: a _ _ _ _ Attempts remaining: 5 Enter a letter: p Word: a p p _ _ Attempts remaining: 5 Enter a letter: l Congratulations! You guessed the word correctly!
