Python 猜词游戏:使用 AI 随机打乱单词
导入所需的库
import random
定义一个列表
words = ['apple', 'banana', 'orange', 'watermelon', 'grape', 'pineapple', 'mango']
定义一个函数:从列表中随机选择一个单词
def choose_word(words): return random.choice(words)
定义一个函数:将单词中的字母随机打乱
def jumble_word(word): jumbled_word = ''.join(random.sample(word, len(word))) return jumbled_word
定义一个函数:游戏主体
def play_game(): # 选择一个单词 word = choose_word(words) # 将单词打乱 jumbled = jumble_word(word) # 输出打乱后的单词 print('Jumbled word is: ', jumbled) # 循环进行猜词 while True: # 获取用户输入的猜测 guess = input('Guess the word: ') # 如果猜对了,输出恭喜信息并退出循环 if guess == word: print('Congratulations! You guessed it right!') break # 如果猜错了,输出提示信息继续猜测 else: print('Oops! That's not the word. Try again.')
执行游戏
play_game()
原文地址: https://www.cveoy.top/t/topic/ndB2 著作权归作者所有。请勿转载和采集!