You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

游戏选择while循环中,如何调用对应函数并输出结果的技术求助

问题解决:根据用户选择调用游戏函数并输出结果

原代码存在的问题

  • 多余的first = input()语句会导致程序额外等待一次输入,打断正常流程
  • else语句无对应if判断,属于语法错误
  • 退出询问逻辑位置错误,应放在循环内部,每次操作后询问是否退出
  • 未实现根据用户选择调用对应游戏函数的核心逻辑

修正后的完整代码

import random

def coin_flip():
    gen_num = random.randint(0, 1)
    if gen_num == 0:
        return "Coin flip: Tails"
    else:
        return "Coin flip: Heads"

def roll_d6():
    gen_num = random.randint(1, 6)
    return f"D6 roll: {gen_num}"

def roll_d20():
    gen_num = random.randint(1, 20)
    return f"D20 roll: {gen_num}"

def pick_card():
    suit = random.randint(0, 3)
    if suit == 0: suit = "Spades"
    elif suit == 1: suit = "Hearts"
    elif suit == 2: suit = "Diamonds"
    else: suit = "Clubs"
    value = random.randint(1, 13)
    if value == 1: value = "Ace"
    elif value == 11: value = "Jack"
    elif value == 12: value = "Queen"
    elif value == 13: value = "King"
    return f"Your card: {value} of {suit}"

print('Welcome to the game arena!\nHere are your options:')
stop = False
while not stop:
    print('\t1) Flip a coin\n\t2) Pick a random playing card')
    print('\t3) Roll a 6-sided dice\n\t4) Roll a 20-sided dice')
    choice = input('What would you like to do? ')
    
    # 根据选择调用对应函数并打印结果
    if choice == '1':
        print(coin_flip())
    elif choice == '2':
        print(pick_card())
    elif choice == '3':
        print(roll_d6())
    elif choice == '4':
        print(roll_d20())
    else:
        print('Invalid Operation')
    
    # 询问是否退出
    user_quit = input('Do you want to quit? (y/n): ')
    if user_quit.lower() == 'y':
        stop = True

关键修改说明

  1. 移除冗余输入:删掉first = input(),避免流程中断
  2. 添加选择判断:通过if-elif-else匹配用户输入的选项,直接调用对应函数并打印返回结果
  3. 优化条件判断:将pick_card中的独立if改为elif,减少不必要的判断步骤
  4. 调整退出逻辑:将退出询问移至循环内部,确保每次操作后都能触发退出判断,正确终止循环
  5. 兼容大小写输入:使用lower()方法,支持用户输入大写Y退出程序

内容的提问来源于stack exchange,提问作者jake hanes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:25:29