Session 8: Cheatsheet
scroll_x = 0
speed = 4
# Every frame:
scroll_x -= speed
if scroll_x <= -WIDTH:
scroll_x = 0
screen.blit(bg_image, (int(scroll_x), 0))
screen.blit(bg_image, (int(scroll_x) + WIDTH, 0))
Spawning objects from the right
# Create an obstacle (off the right of the screen):
obs = pygame.Rect(WIDTH, random.randint(50, HEIGHT - 100), 30, 80)
obstacles.append(obs)
# Move to the left every frame:
for obs in obstacles[:]:
obs.x -= speed
if obs.x < -obs.width:
obstacles.remove(obs)
Spawn timer with USEREVENT
SPAWN_EVENT = pygame.USEREVENT + 1
pygame.time.set_timer(SPAWN_EVENT, 1500) # every 1.5 seconds
for event in pygame.event.get():
if event.type == SPAWN_EVENT:
obstacles.append(pygame.Rect(WIDTH, ...))
Drawing lives
for i in range(lives):
pygame.draw.rect(screen, RED, (10 + i * 25, 10, 18, 18))
Scaling the speed
BASE_SPEED = 4
speed = BASE_SPEED + score * 0.1
# Scaling the spawn interval:
interval = max(500, 1800 - score * 30)
pygame.time.set_timer(SPAWN_EVENT, interval)
Collision with lives
if ship_rect.colliderect(obs):
obstacles.remove(obs)
lives -= 1
if lives <= 0:
running = False
Game over screen
# After the while loop:
screen.fill(BLACK)
go = font.render("GAME OVER", True, RED)
screen.blit(go, (WIDTH // 2 - go.get_width() // 2, HEIGHT // 2))
pygame.display.flip()
pygame.time.wait(3000)