Python 猜单词游戏代码示例 - 简单易懂
以下是一个简单的 Python 猜单词游戏代码示例:
import random
words = ['apple', 'banana', 'orange', 'peach', 'grape']
def play_game():
word = random.choice(words)
guessed_letters = []
tries = 6
while tries > 0:
guess = input('Guess a letter: ').lower()
if len(guess) != 1:
print('Please enter a single letter.')
continue
if guess in guessed_letters:
print('You already guessed that letter.')
continue
guessed_letters.append(guess)
if guess in word:
print('Correct!')
else:
tries -= 1
print('Wrong guess. You have', tries, 'tries left.')
# Check if the word has been completely guessed
if all(letter in guessed_letters for letter in word):
print('Congratulations! You guessed the word:', word)
return
print('Game over. The word was', word)
play_game()
在这个代码中,'words' 列表包含了游戏中可能的单词。'play_game()' 函数是游戏的主体逻辑。在每一轮中,程序会要求玩家输入一个字母作为猜测。程序会检查该字母是否在单词中出现,如果猜测正确,程序会显示 'Correct!',否则会显示 'Wrong guess' 并减少剩余尝试次数。当玩家猜测完整的单词时,程序会显示 'Congratulations!' 并结束游戏。
请注意,这只是一个简单的示例代码,游戏逻辑和界面可以根据需求进行扩展和改进。
原文地址: https://www.cveoy.top/t/topic/pfXj 著作权归作者所有。请勿转载和采集!