1 回答

TA貢獻1772條經驗 獲得超5個贊
問題是,您每幀都調用該類,這會將其值放回 中分配的值。您應該在開始時調用該類一次,然后每幀調用一次方法。這是一個鏈接,用于了解有關類的更多信息。__init__
要修復代碼,請執行以下操作:
while True:
#do other stuff
for invader in invaders:
invader.move_invader()
#do other stuff
由于所有入侵者都具有相同的圖像,因此您可以
invader_image = pygame.image.load('invader.bmp')
invaders = []
for x in invader_x:
invaders.append(Invader(invader_image,x,40,1))
這應該使每個入侵者每幀移動1個像素
要獲取沖突的矩形,您可以將矩形添加到類中
class Invader
def __init__(self, invader, invader_x, invader_y, movement):
self.rect = invader.get_rect()
self.rect.x = invader_x
self.rect.y = invader_y
#rest of code
def move_invader(self):
#if moveing move x
self.rect.x = x
#rest of code
和碰撞
for bullet in range(len(bullets_fired)-1,-1,-1):
for invader in invaders:
if invader.rect.colliderect(bullets_fired[bullet]):
score += 1
invader_x = DISPLAYSURF_rect.centerx
invader_x = DISPLAYSURF_rect.top + 40
del bullets_fired[bullet]
invaders.remove(invader) #to get rid of the invader too
bullet_fired = False
break
elif bullets_fired[bullet].y > 0:
bullet_fired = True
bullets_fired[bullet].y -= 14
bullet_rect = pygame.draw.rect(DISPLAYSURF, RED, (x, y, width, height))
對于碰撞,我向后循環,因為如果您刪除列表中的第2個項目符號,則第3個項目符號將成為第2個項目符號,循環轉到跳過項目符號的第3個項目符號(即第4個項目符號)。但是,如果你向后走,如果你刪除了一個項目符號,你已經檢查過的項目符號就會被移動,你可以繼續檢查下一個項目符號。
對于子彈,你有子彈和bullet_rect它們是一回事,你有一個項目符號列表,就個人而言,我會擺脫bullet_rect
bullet = pygame.draw.rect(screen,RED,(x,y,w,y))
為
pygame.draw.rect(screen,RED,bullets_fired[bullet]
現在對于您添加項目符號的位置,當您按空格鍵時,而不是獲得y,只需獲取矩形
elif event.key == K_SPACE:
if bullet_fired == False:
rect = spaceship_rect.copy() # this makes the bullet the same size as the ship
#you could also do rect = pygame.rect(0,0,0,0)
rect.x = spaceship_rect.centerx - 3
rect.y = spaceship_rect.top
#rect.w = width
#rect.h = height
bullets_fired.append(rect)
并返回到碰撞循環中,將 y 更改為bullets_fired[項目符號]y
添加回答
舉報