【发布时间】: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