如何减少多个if-elif块的冗余?

时间:2018-01-07 13:23:56

标签: python dictionary if-statement redundancy

我正在写一个"问答游戏"使用名为 Draw.py 的GUI包。 我是新手,我真的不知道如何减少代码的冗余。

代码完美无缺,但我知道它并不完全整洁 这就是我想要减少的内容:

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()

我创建了一个字典,每当用户在某些坐标中点击时,字典中的一个键就会增加一个。最后,具有最高价值的关键是获胜者。

1 个答案:

答案 0 :(得分:1)

您可以做的是创建ChooseAnswer的坐标列表,characters的参数和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,并为相应的键增加for index, coordinate in enumerate(coordinates): if (coordinate[0] <= xCoord <= coordinate[1] and coordinate[2] <= yCoord <= coordinate[3]): ChooseAnswer(*answers[index]) characters["question 1"][keys[index]] += 1 mouseclicks += 1 answer1() 的值:

=Table1[[#This row];[first_column]]