import pygame
import random
# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Set the dimensions of the screen
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# Define the Player class
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([20, 20])
self.image.fill(WHITE)
self.rect = self.image.get_rect()
def update(self):
# Move the player based on user input
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= 5
elif keys[pygame.K_RIGHT]:
self.rect.x += 5
# Keep the player within the screen bounds
if self.rect.x < 0:
self.rect.x = 0
elif self.rect.x > SCREEN_WIDTH - 20:
self.rect.x = SCREEN_WIDTH - 20
# Define the Enemy class
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([10, 10])
self.image.fill(BLACK)
self.rect = self.image.get_rect()
# Choose a random starting position and velocity for the enemy
self.rect.x = random.randrange(SCREEN_WIDTH - 10)
self.rect.y = random.randrange(-100, -10)
self.velocity = random.randrange(1, 4)
def update(self):
# Move the enemy down the screen
self.rect.y += self.velocity
# Respawn the enemy if it goes off the bottom of the screen
if self.rect.y > SCREEN_HEIGHT:
self.rect.x = random.randrange(SCREEN_WIDTH - 10)
self.rect.y = random.randrange(-100, -10)
self.velocity = random.randrange(1, 4)
# Initialize Pygame
pygame.init()
# Set the dimensions of the screen
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# Set the title of the window
pygame.display.set_caption('Gun Game')
# Create the player sprite
player = Player()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
# Create the enemy sprites
enemies = pygame.sprite.Group()
for i in range(10):
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
# Set the clock for the game loop
clock = pygame.time.Clock()
# Set the game loop condition
game_over = False
# Set the score to zero
score = 0
# Start the game loop
while not game_over:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# Handle shooting events
if event.type == pygame.MOUSEBUTTONDOWN:
# Create a bullet sprite
bullet = pygame.sprite.Sprite()
bullet.image = pygame.Surface([4, 10])
bullet.image.fill(WHITE)
bullet.rect = bullet.image.get_rect()
bullet.rect.x = player.rect.x + 8
bullet.rect.y = player.rect.y - 10
all_sprites.add(bullet)
# Update all sprites
all_sprites.update()
# Check for collisions between bullets and enemies
hits = pygame.sprite.groupcollide(enemies, all_sprites, False, True)
for enemy in hits:
# Respawn the enemy and add to the score
enemy.rect.x = random.randrange(SCREEN_WIDTH - 10)
To embed this program on your website, copy the following code and paste it into your website's HTML: