python - 程序添加两个元素,但它应该只添加一个。Python
问题描述
我正在制作一个简单的数独游戏,但这段代码应该只在列表中添加一个元素,但它添加了两个。虽然它没有造成任何问题,但是当列表变得更大时,我可以减慢程序性能。
这是一段代码:
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 的任何其他元素。
解决方案
现在它工作正常。代码:
for j in range(-1, len(text_cor)):
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 j == len(text_cor) - 1) and numbers != 0:
text_cor.append([numbers, pos[0] + 15, pos[1] + 10])
equal = False
numbers = 0
else:
equal = False
推荐阅读
- vue.js - Vue.js - 如何在滚动时更改图像 src?
- c# - 如何更正用于创建 Canvas 的过时代码
- node.js - 如何使用 node.js 将 JSON 文件加载到谷歌 Bigquery
- reactjs - 错误:分页(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null
- .net - Azure B2C .. 无法授予管理员同意。您的组织没有以下 API 的订阅(或服务主体)
- laravel - 为什么当从数字搜索以 0 开始时 Laravel 控制器不显示零前导
- javascript - 这是传播运算符的有效用法吗
- jdbc - 如何使用 Google Cloud 上的 Ingress 公开 CockroachDB 以进行外部负载测试
- jquery - 如何延迟 onClick 图像链接,以便 .gif 动画可以在页面切换之前完成?
- rust - &() 语法的目的是什么?