用Python3写一段字谜的代码每段字谜有三次机会回答回答错误就显示猜错了并显示还剩多少次机会当机会用完时就显示正确答案回答正确就显示猜对了!。每次结束一把游戏都询问玩家是否继续
import random
定义函数,用于随机选择一个单词和生成提示
def get_word(): words = ['apple', 'banana', 'cherry', 'durian', 'elderberry'] word = random.choice(words) hint = '_' * len(word) return word, hint
定义函数,用于显示当前游戏进度和剩余机会
def show_progress(hint, chances): print('当前单词为:', hint) print('还剩', chances, '次机会')
主程序
while True: word, hint = get_word() chances = 3 while chances > 0: show_progress(hint, chances) guess = input('请输入一个字母或完整单词:') if guess == word: print('猜对了!') break elif guess in word: for i in range(len(word)): if word[i] == guess: hint = hint[:i] + guess + hint[i+1:] if hint == word: print('猜对了!') break else: chances -= 1 print('猜错了!') else: print('机会用完了,正确答案是:', word) choice = input('是否继续(y/n)?') if choice != 'y': brea
原文地址: https://www.cveoy.top/t/topic/hu2s 著作权归作者所有。请勿转载和采集!