【发布时间】:2021-09-11 12:40:29
【问题描述】:
我正在制作一个简单的数独游戏,但这段代码应该只在列表中添加一个元素,但它添加了两个。虽然它没有造成任何问题,但是当列表变得更大时,我可以降低程序性能。
这是一段代码:
def typing(text_cor, pos):
global numbers, equal
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
numbers = 1
if keys[pygame.K_8]:
numbers = 8
if keys[pygame.K_7]:
numbers = 7
if keys[pygame.K_6]:
numbers = 6
if keys[pygame.K_5]:
numbers = 5
if keys[pygame.K_4]:
numbers = 4
if keys[pygame.K_3]:
numbers = 3
if keys[pygame.K_2]:
numbers = 2
if keys[pygame.K_9]:
numbers = 9
if numbers in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
if len(text_cor) > 0:
for j in range(len(text_cor) - 1):
if (
pos[0] + 15 == text_cor[j][1] and pos[1] + 10 == text_cor[j][2]
) and text_cor[j][0] != 0:
equal = True
numbers = 0
if (
pos[0] + 15 == text_cor[j][1] and pos[1] + 10 == text_cor[j][2]
) and text_cor[j][0] == 0:
equal = True
text_cor[j][0] = numbers
numbers = 0
if equal == False and numbers != 0:
text_cor.append([numbers, pos[0] + 15, pos[1] + 10])
numbers = 0
equal = True
else:
equal = False
numbers = 0
if len(text_cor) == 0:
text_cor.append([numbers, pos[0] + 15, pos[1] + 10])
numbers = 0
我已尝试对其进行编程,使其不会添加相同 x 和 y cor 的任何其他元素。
【问题讨论】:
-
我的第一个建议是不要在
typing之后命名函数,因为这是 Python 中的内置模块。如果可能,请尝试更改函数名称。 -
对不起,问问题的方式如此糟糕。我是堆栈溢出的新手
-
我可以建议您使用
for event in pygame.event.get():,然后检查if event.type == pygame.KEYDOWN:,然后在if 语句event.unicode下执行,然后检查是否可以将其转换为整数并检查是否为一个整数在你需要的范围内,这样你会节省几行不必要的代码,为什么你需要保存坐标?只需拥有整个棋盘的二维数组,并将值计算为该数组中的一个项目 -
@matiss 我无法理解你在说什么“只有整个板的二维数组,并将值计算为该数组中的一个项目”我不知道数组和哪里使用它。