如何在python中随机分配变量?

2024-10-03 13:18:39 发布

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

你好,我想在pygame中做一个简单的选择题测验。这是我写的代码,它按预期工作。在

from random import choice
qUsed=[]
qEasy = [
    {
        "question": "What year is it",
        "choices": {"a": "2009", "b": "2016", "c": "2010"},
        "answer": "b"
    },
    {
        "question": "Another Question",
        "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"},
        "answer": "a"
    },
    {
        "question": "Another Question",
        "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"},
        "answer": "a"
    },
    {
        "question": "Another Question",
        "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"},
        "answer": "a"
    },
    {
        "question": "Another Question",
        "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"},
        "answer": "a"
    }
]

def Quiz(qLevel):
    global qUsed
    if qLevel == []: # if qLevel becomes empty
        qLevel = qUsed # dump everything from qUsed to qLevel
        qUsed = [] # reset qUsed to an empty list
    x = choice(qLevel) # assign x to a random question in qLevel
    print(x.get('question')) # print the question
    answer = input(x.get('choices')).lower() # print the choices

    if answer == x.get('answer'): # if answer is correct
        print("You got it")
    else:
        print("Wrong")
    qLevel.remove(x) # remove used question from list
    qUsed.append(x) # add it to an empty unused list (qUsed)

Quiz(qEasy)
Quiz(qEasy)

当我编写一个pygame脚本来打开一个以问题为标题的窗口时,问题就出现了,三个可能的答案随机地在三个黑色矩形上闪烁。我想做的是从列表中随机选择一个问题,在屏幕上快速显示“在这里插入问题”,然后将答案随机分配给三个矩形。如果你要按右边的矩形,那么矩形会变成绿色,否则,它会变成红色。但我不知道怎么做。在

^{pr2}$

Tags: toanswerfromifanotheritchoicesquestion
2条回答

列表是获得随机答案的一种非常好的方法。在

你首先要进入一个远程循环:

for i in range(3):
    myList.append(answers['Your question'][random.randint(0, 3)])

然后你可以索引新的列表,当你需要画

text = myFont.render(myList[0], True, (255, 255, 255))

稍后您可能会想添加一些重复的检测代码,但我希望这会有所帮助。在

为了循环这些问题,我定义了一个index变量,并将当前的问题选项answer dict赋给一个变量(我在这里称之为question)。在

questions = qEasy
random.shuffle(questions)
index = 0
question = questions[index]

当用户切换到下一个question(我会在事件循环中这样做)时增加索引。在

^{pr2}$

将问题文本和选项传递给font.render(当文本需要更新时,只能呈现一次)。在

Question_surf = FONT.render(question["question"], True, BLACK)
A1_surf = FONT.render(question["choices"]["a"], True, WHITE)
# etc.

当用户单击一个按钮时,检查相应的答案是否正确,然后更改按钮/矩形的颜色。在

if A1.collidepoint(e.pos):
    if question["answer"] == "a":
        A1_color = GREEN
    else:
        A1_color = RED

将当前矩形颜色传递给pygame.draw.rect。在

pygame.draw.rect(screen, A1_color, A1)

当用户切换到下一个问题时,重置按钮颜色。在

相关问题 更多 >