Python: Sample 1942

Return to Python resources

import pygame, time, random
from pygame.locals import *

WIDTH = 500
HEIGHT = 500
pygame.init()
window = pygame.display.set_mode((WIDTH,HEIGHT))
fps = pygame.time.Clock()

# Declare colours, fonts, sprites and sounds
BACKGROUND = (0x04, 0x92, 0xfc)
PLAYER_COLOUR = (0,0,0)
ENEMY_COLOUR = (0xFF, 0, 0)

# Variables needed for keeping track of positions
quit = False
deltaX = 0
deltaY = 0
playerX = 250
playerY = 350
enemies = []
enemySpeed = 20

# Main game loop
while not quit:

    # Process events
    for event in pygame.event.get():
        if event.type == QUIT:
            quit = True
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                quit = True
            elif event.key == K_LEFT:
                deltaX = -20
            elif event.key == K_RIGHT:
                deltaX = 20
            elif event.key == K_UP:
                deltaY = -10
            elif event.key == K_DOWN:
                deltaY = 10
        elif event.type == KEYUP:
            if event.key == K_UP or event.key == K_DOWN:
                deltaY = 0
            elif event.key == K_LEFT or event.key == K_RIGHT:
                deltaX = 0

    # Perform calculations
    print(enemies)
    for enemy in enemies:
        enemy[1] = enemy[1]+enemySpeed
        if enemy[1] > 500:
            enemies = [x for x in enemies if not (x[0] == enemy[0] and x[1] == enemy[1])]
    if random.randint(0,10) == 0: # create a new enemy??
        enemies.append( [random.randint(0,500), 0] )
    playerX += deltaX
    playerX = playerX % WIDTH
    playerY += deltaY
    if playerY < 0:
        playerY = 0
    elif playerY > HEIGHT:
        playerY = HEIGHT

    # Draw graphics
    window.fill(BACKGROUND)
    for enemy in enemies:
        pygame.draw.polygon(window, ENEMY_COLOUR, ( (enemy[0], enemy[1]+15), (enemy[0]+15,enemy[1]-15), (enemy[0]-15, enemy[1]-15) ))
    pygame.draw.polygon(window, PLAYER_COLOUR, ( (playerX, playerY-15), (playerX+15,playerY+15), (playerX-15, playerY+15) ))
    pygame.display.update()
    fps.tick(10)

pygame.quit()