Untitled

 avatar
unknown
plain_text
2 years ago
1.3 kB
4
Indexable
import pygame
import random

# initialize pygame
pygame.init()

# set up the game window
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Alien Invasion")

# define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# create the player
player_image = pygame.image.load("player.png")
player_rect = player_image.get_rect()
player_rect.centerx = 400
player_rect.bottom = 580

# create the alien
alien_image = pygame.image.load("alien.png")
alien_rect = alien_image.get_rect()
alien_rect.centerx = random.randint(50, 750)
alien_rect.centery = random.randint(50, 200)

# set up the game clock
clock = pygame.time.Clock()

# main game loop
running = True
while running:
    # handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # update the player position
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player_rect.centerx -= 5
    if keys[pygame.K_RIGHT]:
        player_rect.centerx += 5
    
    # update the alien position
    alien_rect.centery += 2
    
    # check for collision between player and alien
    if player_rect.colliderect(alien_rect):
        alien_rect.centerx = random.randint(50, 750)
        alien_rect.centery = random.randint(50, 200)
    
Editor is loading...