pygame/6. speles_atrums/main.py

100 lines
2.5 KiB
Python

# Code is taken from https://realpython.com/pygame-a-primer/
# Import and initialize the pygame library
import pygame
from player import Player
from enemy import Enemy
from settings import SCREEN_HEIGHT, SCREEN_WIDTH
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT,
)
pygame.init()
# Create the screen object
# The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Create a custom event for adding a new enemy
ADDENEMY = pygame.USEREVENT + 1
pygame.time.set_timer(ADDENEMY, 250)
# Variable to keep the main loop running
running = True
player = Player()
# Create groups to hold enemy sprites and all sprites
# - enemies is used for collision detection and position updates
# - all_sprites is used for rendering
enemies = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
bg = pygame.image.load("sprites/background.png").convert()
# Setup the clock for a decent framerate
clock = pygame.time.Clock()
# Main loop
while running:
screen.blit(bg, (0,0))
# Look at every event in the queue
for event in pygame.event.get():
# Did the user hit a key?
if event.type == KEYDOWN:
# Was it the Escape key? If so, stop the loop.
if event.key == K_ESCAPE:
running = False
# Did the user click the window close button? If so, stop the loop.
elif event.type == QUIT:
running = False
# Add a new enemy?
elif event.type == ADDENEMY:
# Create the new enemy and add it to sprite groups
new_enemy = Enemy()
enemies.add(new_enemy)
all_sprites.add(new_enemy)
# Get all the keys currently pressed
pressed_keys = pygame.key.get_pressed()
# Update the player sprite based on user keypresses
player.update(pressed_keys)
# Update enemy position
enemies.update()
# Draw all sprites
for entity in all_sprites:
screen.blit(entity.surf, entity.rect)
# Check if any enemies have collided with the player
if pygame.sprite.spritecollideany(player, enemies):
# If so, then remove the player and stop the loop
player.kill()
running = False
# Flip the display
pygame.display.flip()
# Ensure program maintains a rate of 30 frames per second
clock.tick(30)
# Done! Time to quit.
pygame.quit()