Dojo Defender Session 7: Cheatsheet
Power-up variables
powerups = [] # list of power-up GameObjects
active_powerup = None # 'spread', 'shield', 'speed' or None
powerup_timer = 0 # frames remainingSpawning a power-up (on enemy death)
def spawn_powerup(x, y):
if random.random() < 0.2: # 20% chance
ptype = random.choice(['spread', 'shield', 'speed'])
pu = GameObject(f'powerup_{ptype}.png', x, y)
pu.pu_type = ptype
pu.speed = 2
powerups.append(pu)Collecting a power-up
for pu in powerups[:]:
pu.rect.y += pu.speed
if pu.rect.top > HEIGHT + 30:
powerups.remove(pu)
elif pu.rect.colliderect(ship.rect) and ship.visible:
active_powerup = pu.pu_type
powerup_timer = 300 # 5 seconds
powerups.remove(pu)Timer for the active power-up
if active_powerup:
powerup_timer -= 1
if powerup_timer <= 0:
active_powerup = NoneSpread shot (3 bullets)
if active_powerup == 'spread' and shoot_cooldown == 0:
angles = [-15, 0, 15]
for a in angles:
rad = math.radians(a)
bullet = GameObject('bullet.png', x, y)
bullet.dx = math.sin(rad) * 3
bullet.dy = -8
bullets.append(bullet)
shoot_cooldown = 10For normal shooting: bullet.dx = 0 and bullet.dy = -8.
Shield — absorbing a hit
if active_powerup == 'shield':
active_powerup = None # shield is used up
invincible = True
invincible_timer = 300 # 5 seconds of invincibilitySpeed boost — 2x faster
ship_speed = 5
if active_powerup == 'speed':
ship_speed = 10Saving the high score
def load_highscore():
path = 'highscore.txt'
if os.path.exists(path):
with open(path) as f:
return int(f.read().strip())
return 0
def save_highscore(val):
if val > load_highscore():
with open('highscore.txt', 'w') as f:
f.write(str(val))Adding reset in reset_game()
Don’t forget to reset the power-up variables in reset_game():
powerups.clear()
active_powerup = None
powerup_timer = 0