【问题标题】:How to reduce redundancy in multiple if-elif blocks?如何减少多个 if-elif 块中的冗余?
【发布时间】:2018-01-07 13:23:56
【问题描述】:

我正在使用名为 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()

我创建了一个字典,每次用户在特定坐标内单击时,字典中的一个键都会增加一个。最后,价值最高的钥匙就是赢家。

【问题讨论】:

  • Esther,您是否尝试过为您的代码实现一些单元测试?如果您认为有帮助,我建议您尝试一些测试驱动开发技术来提高您的编码技能。
  • 您可以为参数化函数重构代码,删除这些函数中的重复代码。为变化创建参数。

标签: python dictionary if-statement redundancy


【解决方案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()

【讨论】:

    猜你喜欢
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2019-06-06
    相关资源
    最近更新 更多