我正在嘗試創建一個導彈命令克隆來挑戰/擴展我的Python和Pygame技能和知識。下面是遊戲到目前爲止的代碼(這是最基本的,我是一個初學者):Pygame,Python列表索引問題
import math
import pygame
class Missile:
def __init__(self, surface):
self.surface = surface
self.missileList = []
self.color = (0, 255, 0)
def draw(self):
if len(self.missileList) > 0:
self.missileList.sort()
for i in range(0, len(self.missileList)):
if self.missileList[i][1] < self.missileList[i][4]:
self.missileList.pop(i)
else:
self.update(i)
self.surface.set_at((int(self.missileList[i][0]), int(self.missileList[i][1])), self.color)
def update(self, i):
self.missileList[i][0] -= self.missileList[i][3] * math.cos(self.missileList[i][2])
self.missileList[i][1] -= self.missileList[i][3] * math.sin(self.missileList[i][2])
width = 640
height = 480
BGCOLOR = (0, 0, 0)
mousex = 0
mousey = 0
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
startx = int(width/2)
starty = height - 10
speed = 2
missile = Missile(screen)
running = True
while running:
screen.fill(BGCOLOR)
missile.draw()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
elif event.type == pygame.MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
endx = mousex
endy = mousey
trajectory = math.atan2(height - endy, (width/2) - endx)
missile.missileList += [[startx, starty, trajectory, speed, endy]]
pygame.display.flip()
clock.tick(75)
所以我每次點擊鼠標按鈕,missile.missileList後附加一個需要得到的所有信息'導彈'從頭到尾。當導彈到達其終點時,那些列表條目將被刪除。問題是,這會拋出此後的列表索引,並且如果有另一個導彈被跟蹤,則會拋出一個錯誤(列表索引超出範圍)。我認爲在每次draw()調用開始時對列表進行排序會有所幫助,但是並沒有。有任何想法嗎?
,完美的工作。我還沒有想到我在修改它的事實,而它仍然在迭代它。感謝您的快速回復。 –