game
unknown
python
24 days ago
2.0 kB
1
Indexable
Never
import pygame import random # Initialize Pygame pygame.init() # Screen dimensions WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Space Defender") # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) # Load assets player_image = pygame.Surface((50, 30)) player_image.fill(WHITE) enemy_image = pygame.Surface((50, 30)) enemy_image.fill(RED) # Player class class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = player_image self.rect = self.image.get_rect() self.rect.center = (WIDTH // 2, HEIGHT - 50) self.speed = 5 def update(self): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.rect.x -= self.speed if keys[pygame.K_RIGHT]: self.rect.x += self.speed if keys[pygame.K_SPACE]: # Handle shooting (not implemented in this snippet) pass # Enemy class class Enemy(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = enemy_image self.rect = self.image.get_rect() self.rect.x = random.randint(0, WIDTH - self.rect.width) self.rect.y = random.randint(-150, -self.rect.height) self.speed = random.randint(1, 3) def update(self): self.rect.y += self.speed if self.rect.y > HEIGHT: self.kill() # Groups all_sprites = pygame.sprite.Group() enemies = pygame.sprite.Group() player = Player() all_sprites.add(player) for _ in range(5): enemy = Enemy() all_sprites.add(enemy) enemies.add(enemy) # Main game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False all_sprites.update() screen.fill(BLACK) all_sprites.draw(screen) pygame.display.flip() pygame.time.delay(30) pygame.quit()
Leave a Comment