我正在尝试在屏幕上移动一个三角形。这是我用来定义三角形的类。
class Triangle:
def __init__(self):
self.points = [[100, 100], [100, 150], [180, 125]]
self.color = (180, 255, 100)
self.speed = 2
def draw(self):
pygame.draw.polygon(D, self.color, self.points)
我想移动三角形。为此,我试图做这样的事情
def move(self):
keys = pygame.key.get_pressed()
counter = 0
if keys[pygame.K_RIGHT]:
for points in self.points:
points[0][counter] += self.speed
counter += 1
但是我不断收到这个错误TypeError: 'int' object is not subscriptable
。我将如何解决此问题并移动三角形?谢谢
在函数移动中,您正在遍历列表“ self.points”,因此您要添加到的“ point”变量实际上只是点之一,而不是完整的“ self.points”点列表。
我想这就是你要的:)
def move(self):
keys = pygame.key.get_pressed()
counter = 0
if keys[pygame.K_RIGHT]:
for points in self.points:
self.points[counter][0] += self.speed
counter += 1
做到这一点的另一个好方法是枚举。
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
for point_index,point in enumerate(self.points):
self.points[point_index][0] += self.speed
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句