如何减少多个ifelif块中的冗余?

2024-09-30 01:29:32 发布

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

我正在用一个名为绘图.py。 我是新手,不知道如何减少代码的冗余。在

代码运行得很好,但我知道它并不完全整洁。
以下是我想减少的:

def question1():
    question("Which device would \n you most want to have?") #draws #question
    answer1()  #draws the answer boxes. 
    mouseclicks = 0

    while mouseclicks != 1:
        if Draw.mousePressed():   #checks if the user clicks.

            xCoord= Draw.mouseX()   #check x-y coordinates
            yCoord= Draw.mouseY()

            if  xCoord >= 91 and xCoord <= 390 and yCoord >= 400 \
                and  yCoord <= 552:
                ChooseAnswer(88,400,300,150)  #Chosen answer, turns green #when user clicks
                characters["question 1"]["PC"] += 1  
                mouseclicks += 1    
                answer1()

            elif xCoord >= 601 and xCoord <= 900  and yCoord >= 402 \
            and yCoord <= 550:
                ChooseAnswer(600,400,300,150)
                characters["question 1"]["BJ"] += 1   
                mouseclicks += 1 
                answer1()

            elif xCoord >= 92 and xCoord <= 388  and yCoord >= 602 \
            and yCoord <= 750:
                ChooseAnswer(88,600,300,150)
                characters["question 1"]["Mr.P"] += 1                
                mouseclicks += 1    
                answer1()

            elif xCoord >= 602 and xCoord <= 902  and yCoord >= 603 \
            and yCoord <= 750:
                ChooseAnswer(600,600,300,150)
                characters["question 1"]["Diane"] += 1
                mouseclicks += 1
                answer1()

我创建了一个字典,每当用户在某个坐标内单击时,字典中的一个键就会上升一个。最后,价值最高的钥匙就是赢家。在


Tags: andtheanswerifquestiondrawelifcharacters
1条回答
网友
1楼 · 发布于 2024-09-30 01:29:32

您可以这样创建坐标列表、ChooseAnswer的参数和{}的键:

coordinates = [(91, 390, 400, 552),
               (601, 900, 402, 550),
               (92, 388, 602, 750),
               (602, 902, 603, 750)]
answers = [(88, 400, 300, 150),
           (600, 400, 300, 150),
           (88, 600, 300, 150),
           (600, 600, 300, 150)]
keys = ["PC", "BJ", "Mr.P", "Diane"]

然后迭代coordinates,检查哪些满足您的条件,最后用相应的参数调用ChooseAnswer,并为相应的键增加一个值characters

^{pr2}$

相关问题 更多 >

    热门问题