Apr-10-2019, 04:53 AM
I'm working on this space invaders game and the tail end of the logic is confusing me. There is a nested loop in the conclusion.
Here is the full code.
i = 0 while i <len(badguys): j = 0 while j < len(missiles): if badguys[i].touching(missiles[j]): del badguys[i] del missiles[j] i -= 1 break j += 1 i += 1The program will delete a badguy and missile if they touch but I'm confused as to why you have to use i = i - 1 if you're already deleting the object by its index. Additionally, I don't follow the logic here too well. You break and then add 1 to i? Ugh, it's just confusing me right now. I've tried to find the answer elsewhere but I just dont' get it. I get about the collision detection but not why or how i-= 1 is working or j += 1 or the 1 +=1
Here is the full code.
import pygame,sys,random,time from pygame.locals import * pygame.init() sprite = pygame.image.load("badguy.png") plane = pygame.image.load("fighter.png") missile_image = pygame.image.load("missile.png") missile_image.set_colorkey((255,255,255)) plane.set_colorkey((255,255,255)) sprite.set_colorkey((0,0,0)) clock = pygame.time.Clock() spawn_time = 0 title = pygame.display.set_caption("Space Invaders") screen = pygame.display.set_mode((600,600)) class Missile: def __init__(self,x): self.x = x self.y = 510 def move(self): self.y -= 5 def off_screen(self): return self.y < -8 def draw(self): screen.blit(missile_image,(self.x,self.y)) class Fighter: def __init__(self): self.x = 300 self.y = 530 def move(self): if pressed_keys[K_LEFT] and self.x > 0: self.x -= 5 if pressed_keys[K_RIGHT] and self.x < 500: self.x += 5 def draw(self): screen.blit(plane,(self.x,self.y)) def fire(self): missiles.append(Missile(self.x+50)) class Badguy: def __init__(self): self.x = random.randint(0,500) self.y = 200 def touching(self,missile): return pygame.Rect((self.x,self.y),(70,45)).collidepoint(missile.x,missile.y) def move(self): self.y += 3 def draw(self): screen.blit(sprite,(self.x,self.y)) def off_screen(self): return self.y > 590 badguys = [] missiles = [] f = Fighter() while True: clock.tick(60) for event in pygame.event.get(): if event.type == QUIT: sys.exit() if event.type == KEYDOWN and event.key == K_SPACE: f.fire() pressed_keys = pygame.key.get_pressed() screen.fill((0,0,0)) if time.time() - spawn_time > 0.5: badguys.append(Badguy()) spawn_time = time.time() i = 0 while i < len(badguys): badguys[i].move() badguys[i].draw() if badguys[i].off_screen(): del badguys[i] i = i - 1 i = i + 1 i = 0 while i < len(missiles): missiles[i].move() missiles[i].draw() if missiles[i].off_screen(): del missiles[i] i = i - 1 i = i + 1 i = 0 while i <len(badguys): j = 0 while j < len(missiles): if badguys[i].touching(missiles[j]): del badguys[i] del missiles[j] i -= 1 break j += 1 i += 1 f.move() f.draw()