我正试着在屏幕上做一个三角形的移动。这是我用来定义三角形的类。
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
。我如何解决这个问题并移动三角形呢?谢谢
发布于 2020-01-28 07:11:29
在函数move中,您正在迭代列表"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
另一种很好的方法是使用enumerate。
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
发布于 2020-01-28 07:21:29
正如每个人都已经回答的那样,问题是代码正在迭代一个列表列表,其中外部列表只包含三个三角点。因此,points[0]
是列表计数器,points[1]
是[100, 150]
,依此类推。您的代码失败是因为points[0][counter]
对于计数器< 3才是“正确的”。一旦计数器大于点数,代码就会失败。
你的意思可能是:
for point in self.points:
# point is a co-ordinate: [ x, y ]
point[0] += self.speed # update x-coordinate of each point
我认为在Triangle
类中添加一个move()
函数会更好,将内部更新代码保留在类中:
class Triangle:
# ...
def move( self, x_change, y_change ):
""" Move each triangle point by x_change and y_change, at self.speed """
for i, point in enumerate( self.points ):
x, y = point
new_x = x + ( x_change * self.speed )
new_y = y + ( y_change * self.speed )
self.points[i] = [ new_x, new_y ]
这允许一个简单的移动调用来处理按键和对角移动。
# Movement keys
keys = pygame.key.get_pressed()
if ( keys[pygame.K_UP] ):
tri.move( 0, -1 )
if ( keys[pygame.K_DOWN] ):
tri.move( 0, 1 )
if ( keys[pygame.K_LEFT] ):
tri.move( -1, 0 )
if ( keys[pygame.K_RIGHT] ):
tri.move( 1, 0 )
发布于 2020-01-28 07:03:43
看看你的数据结构,你滥用了它。
self.points = [[100, 100], [100, 150], [180, 125]]
...
for points in self.points:
# For the first iteration, points = [100, 100]
points[0][counter] += self.speed
points[0]
是整数100。100counter是一个无效的操作,导致您的错误消息。我不能告诉你如何修复这个问题,因为你想用这段代码做什么并不是很清楚。关于如何在PyGame中移动对象,网上有很多例子。
https://stackoverflow.com/questions/59940100
复制相似问题