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

如何在PyGame中每次显示新问题时保存用户输入至列表?

PyGame对话系统答案保存问题解决方案

我是编程新手,花了两个月写这段PyGame代码。需求是:每次屏幕显示新问题时,把用户输入的user_text存入answers列表(比如3个问题对应答案列表是[1,4,3])。但现在遇到三个问题:

  • 列表为空,完全存不住输入
  • 只能保存单个答案,没法存所有输入
  • current_dialogue_index混乱,导致问题跳过

需要易懂的基础解决方案,之后要根据答案总分做后续逻辑。

原代码

#Dialogue
messages = ["Hello and welcome to Dr. Collins' office. (Press the 'Enter' key to continue).",
            "I presume you have an appointment with us today?",
            "To use our tele-health system click on the input box below when prompted.",
            "When the input box is green, you may begin to type your response.",
            "Now, please hold a moment. Dr. Collins will be with you shortly."
            ]
intro = ["Hello there, my name is Dr. Collins. What is your name?",
             "Hello",
             ]
questions =  ["On a scale of 1 to 5, 1 being not at all and 5 being all the time: Are you experiencing any pain?",
             "On a scale of 1 to 5, 1 being not at all and 5 being all the time: Have you ever contimplated suicide?",
             "On a scale of 1 to 5, 1 being not at all and 5 being all the time: Do you ever have trouble sleeping?",
             "On a scale of 1 to 5, 1 being not at all and 5 being all the time: Do you ever have trouble concentrating?",
             "On a scale of 1 to 5, 1 being not at all and 5 being all the time: Do you struggle with poor appetite or overeating?"
             ]

Final_Messages = ["Thank you for you time today.",
                  "I'm going to review your questions.",
                  "Your prescription will print shortly.",
                  "When you received your prescription, you may click the 'Finish' button."
                 ]

answers = []

doctor_images = [pygame.image.load('DoctorFrown.png').convert(),
                 pygame.image.load('DoctorSmile.png').convert(),
                 pygame.image.load('DoctorGlitch.png').convert()
                 ]
secretary_images = [pygame.image.load('Secretary.png').convert(),
                   pygame.image.load('secretaryGlitch.png').convert()]
done = False

#Main Game play
def game_loop():
    doctor_mode = False
    active = False
    user_text = ''
    name = ''
    save_name = False
    current_dialogue_index = 0
    current_list = messages

    # Switch between pictures
    current_doctor_image = 0
    doctor_image = doctor_images[current_doctor_image]
    current_secretary_image = 0
    secretary_image = secretary_images[current_secretary_image]
    image_change_timer = pygame.time.get_ticks() + 10000

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                if input_rect.collidepoint(event.pos):
                    active = True
                else:
                    active = False

            # Dialogue
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    if current_list == messages and current_dialogue_index == len(current_list) - 1:
                        current_list = intro
                        current_dialogue_index = 0
                        doctor_mode = True
                    elif current_list == intro and current_dialogue_index == len(current_list) - 1:
                        current_list = questions
                        current_dialogue_index = 0

# I was adding the answers.append(user_text) here assuming it would save the user_text to answers,but as stated it wasn't working. I've also tried user_text = ''.join(answers)? 

                    elif current_list == intro and current_dialogue_index == 0 and not save_name:
                        name = user_text
                        save_name = True
                    elif current_list == questions and current_dialogue_index == len(current_list) - 1:
                        current_list = Final_Messages
                        current_dialogue_index = 0
                    elif current_list == Final_Messages and current_dialogue_index == len(current_list) - 1:
                        screen.fill((0,0,0))
                    else:
                        current_dialogue_index += 1
                        if current_dialogue_index >= len(current_list):
                            done = True
                            break
                    if active:  # Check if input box is active
                        if current_dialogue_index < len(current_list) - 1:  # Check if there are more questions
                            current_dialogue_index += 1

# I was also trying to add it here as well

                        else:
                            done = True  # No more questions, end the dialogue

                if active == True:
                    if event.key == pygame.K_BACKSPACE:
                        user_text = user_text[:-1]
                    else:
                        if len(user_text) < 8 and event.unicode.isalpha() or (event.unicode.isdigit() and int(event.unicode) >= 1 and int(event.unicode) <= 5):
                            user_text += event.unicode
                        elif event.key == pygame.K_RETURN:
                            user_text = ''

解决方案

问题根源是答案保存时机错误+索引重复修改,以下是分步修正:

1. 声明全局answers列表

函数内默认会创建局部变量,导致外部的answers始终为空。在game_loop开头加:

global answers

2. 修复答案保存逻辑

只有在问题列表(questions)提交输入时,才把user_text加入answers,同时清空输入框准备下一题。

3. 移除重复的索引修改代码

原代码末尾的if active:块会额外累加current_dialogue_index,直接导致问题跳过,必须删掉。

修正后的回车事件核心逻辑

替换原代码中回车事件的处理部分:

if event.key == pygame.K_RETURN:
    if current_list == messages and current_dialogue_index == len(current_list) - 1:
        current_list = intro
        current_dialogue_index = 0
        doctor_mode = True
    elif current_list == intro and current_dialogue_index == len(current_list) - 1:
        current_list = questions
        current_dialogue_index = 0
    elif current_list == intro and current_dialogue_index == 0 and not save_name:
        name = user_text
        save_name = True
        user_text = ''  # 保存名字后清空输入
    elif current_list == questions:
        # 保存当前问题的答案
        answers.append(user_text)
        user_text = ''
        # 切换到下一题或结束问题环节
        if current_dialogue_index == len(current_list) - 1:
            current_list = Final_Messages
            current_dialogue_index = 0
        else:
            current_dialogue_index += 1
    elif current_list == Final_Messages and current_dialogue_index == len(current_list) - 1:
        screen.fill((0,0,0))
    else:
        current_dialogue_index += 1
        if current_dialogue_index >= len(current_list):
            done = True
            break

验证效果

  • 每个问题提交后,answers会自动添加输入的数字,最终会得到完整的答案列表
  • current_dialogue_index只会在正确时机+1,不会跳步
  • 之后可以用sum(answers)计算总分,或遍历列表实现后续逻辑

内容的提问来源于stack exchange,提问作者Lisa Collins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:33:00