Create your own shooting game with python
A basic shooting game with python.
Source code:
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("Shooting Game")
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# Player and Target settings
player_width = 50
player_height = 10
player_x = WIDTH // 2 - player_width // 2
player_y = HEIGHT - player_height - 10
player_speed = 10
target_width = 50
target_height = 10
target_x = random.randint(0, WIDTH - target_width)
target_y = 50
target_speed = 5
# Bullet settings
bullet_width = 5
bullet_height = 10
bullet_speed = 15
bullets = []
# Game variables
running = True
score = 0
# Main game loop
while running:
screen.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Get pressed keys
keys = pygame.key.get_pressed()
# Move player
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_speed
if keys[pygame.K_RIGHT] and player_x < WIDTH - player_width:
player_x += player_speed
# Shoot bullet
if keys[pygame.K_SPACE]:
if len(bullets) < 1: # Limit to one bullet on screen at a time
bullet_x = player_x + player_width // 2 - bullet_width // 2
bullet_y = player_y
bullets.append([bullet_x, bullet_y])
# Move bullets
for bullet in bullets:
bullet[1] -= bullet_speed
if bullet[1] < 0:
bullets.remove(bullet)
# Check for collision with target
bullet_rect = pygame.Rect(bullet[0], bullet[1], bullet_width, bullet_height)
target_rect = pygame.Rect(target_x, target_y, target_width, target_height)
if bullet_rect.colliderect(target_rect):
bullets.remove(bullet)
score += 1
target_x = random.randint(0, WIDTH - target_width)
target_y = 50
# Move target
target_x += target_speed
if target_x <= 0 or target_x >= WIDTH - target_width:
target_speed = -target_speed
# Draw player, target, and bullets
pygame.draw.rect(screen, BLACK, (player_x, player_y, player_width, player_height))
pygame.draw.rect(screen, RED, (target_x, target_y, target_width, target_height))
for bullet in bullets:
pygame.draw.rect(screen, GREEN, (bullet[0], bullet[1], bullet_width, bullet_height))
# Draw score
font = pygame.font.SysFont(None, 36)
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))
# Update display
pygame.display.flip()
# Cap the frame rate
pygame.time.Clock().tick(60)
# Quit Pygame
pygame.quit()
Comments
Post a Comment