pygame中的While循环问题未暂停事件处理

2024-09-30 22:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在pygame中构建一个多项选择测验游戏,但是我的while循环有一个问题。你知道吗

我成功地用python构建了这个游戏,没有GUI,所有的逻辑都可以正常工作,但是当我尝试将GUI添加到逻辑中时,它的工作方式就不一样了。你知道吗

在我的工作逻辑游戏中,由于我使用“raw\u input()”函数,连续while循环在每个问题上都会暂停,并等待用户回答。当我做GUI版本时,我的问题被成功地读入,但是它一次读入所有问题,没有时间回答。你知道吗

我试着添加时间。睡眠()但这意味着程序不响应事件处理程序。如果事件处理程序能够工作,那么这将是一个完美的解决方案,给用户一定的时间来回答。你知道吗

下面的示例代码不会编译,因为我遗漏了许多类和方法,但希望说明这就是我的问题所在。我阅读了中的字典键和值,然后尝试将用户输入与正确答案的索引相匹配,该索引在被洗牌之前始终是answerMain[0]。你知道吗

有没有人遇到过类似的问题或知道可能的解决方案?你知道吗

        attemptMain = {'Q': 'Question Here', 'A': 'Answer1','B': 'Answer2','c': 'Answer3','D': 'Answer4',  }

        def normalQuestions(self, list):
             for i in list:
                questionMain = self.attemptMain.keys()[i - 1]
                answersMain = (self.attemptMain.values()[i - 1])
                correctAnswerMain = answersMain[0]
                shuffle(answersMain)
                answersMainIndex =  (1 + answersMain.index(correctAnswerMain) )
                self.layout.questionandAnswers(questionMain, answersMain[0], answersMain[1], answersMain[2], answersMain[3])
                time.sleep(10)
                x = self.layout.controls()
                if (x == answersMainIndex):
                    print("this is the correct answer")

            def controls(self):
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_1:
                        print("here" + str(1))
                        return '1'
                    elif event.key == pygame.K_2:
                        print("here" + str(2))
                        return '2'
                    elif event.key == pygame.K_3:
                        print("here" + str(3))
                        return '3'
                    elif event.key == pygame.K_4:
                        print("here" + str(4))
                        return '4'

Tags: key用户selfevent游戏returnifhere
1条回答
网友
1楼 · 发布于 2024-09-30 22:19:12

下面是一个问答游戏的例子。我使用链接答案的dt = clock.tick(fps)解。只需将time变量减去dt,如果它低于0,则切换到下一个问题。用户可以输入1-4,然后与问题元组的最后一个元素进行比较,以检查答案是否正确。你知道吗

import random
import pygame as pg


pg.init()
FONT = pg.font.Font(None, 34)
FONT_SMALL = pg.font.Font(None, 24)
BLUE = pg.Color('steelblue1')


def get_question(questions, question_index):
    """Create a surface with the question and the 4 answer choices."""
    question, *answers, _ = questions[question_index]

    # Blit the question and answers onto this transparent surface.
    question_surface = pg.Surface((500, 150), pg.SRCALPHA)
    question_surface.blit(FONT.render(str(question), True, BLUE), (0, 0))
    for y, answer in enumerate(answers, 1):
        txt = FONT_SMALL.render('{}:  {}'.format(y, answer), True, BLUE)
        question_surface.blit(txt, (0, 20*y+20))
    return question_surface


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    dt = 0
    time_to_answer = 5  # User has 5 seconds to answer.
    time = time_to_answer

    # A list of tuples that contain the question, 4 multiple choice
    # answers and the last element is the correct answer.
    questions = [
        ('Is it A, B, C or D?', 'A', 'B', 'C', 'D', '3'),
        ("What's 2+3?", '23', '5', '3', '2', '2'),
        ]
    random.shuffle(questions)
    question_index = 0
    question_surface = get_question(questions, question_index)

    correct = 0
    incorrect = 0
    game_over = False
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if not game_over:
                    user_input = event.unicode
                    correct_answer = questions[question_index][-1]
                    if user_input == correct_answer:
                        print('Correct')
                        correct += 1
                        time = time_to_answer
                    else:
                        incorrect += 1
                        time = time_to_answer

                    question_index += 1
                    if question_index >= len(questions):
                        game_over = True
                    else:
                        question_surface = get_question(questions, question_index)
                else:  # Restart.
                    game_over = False
                    correct = 0
                    incorrect = 0
                    random.shuffle(questions)
                    question_index = 0
                    question_surface = get_question(questions, question_index)

        if not game_over:
            time -= dt
            # If the timer is below 0, switch to the next question.
            if time <= 0:
                question_index += 1
                incorrect += 1
                if question_index >= len(questions):
                    game_over = True
                else:
                    time = time_to_answer
                    print('next')
                    question_surface = get_question(questions, question_index)

        screen.fill((30, 30, 30))
        if not game_over:
            screen.blit(question_surface, (20, 50))
            time_surface = FONT.render(str(round(time, 1)), True, BLUE)
            screen.blit(time_surface, (20, 20))
        correct_answer_surface = FONT_SMALL.render(
            'Correct {}, incorrect {}'.format(correct, incorrect),
            True, BLUE)
        screen.blit(correct_answer_surface, (20, 250))

        pg.display.flip()
        dt = clock.tick(30) / 1000


if __name__ == '__main__':
    main()
    pg.quit()

相关问题 更多 >