GUN GAME


import pygame
import random
import time

Initialize Pygame

pygame.init()

Game settings

WIDTH, HEIGHT = 800, 600
FPS = 60
TARGET_RADIUS = 30
GUN_COLOR = (255, 0, 0)
TARGET_COLOR = (0, 255, 0)

Set up the game window

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Target Challenge")

Font settings

font = pygame.font.SysFont('Arial', 24)

Player settings

player_x = WIDTH // 2
player_y = HEIGHT - 50
gun_length = 50

Target settings

targets = []
target_speed = 5
target_spawn_rate = 30 # Frames until a new target appears
target_lifetime = 1000 # Frames before a target disappears
score = 0

Game variables

clock = pygame.time.Clock()
running = True
start_time = time.time()
target_timer = 0

Target class

class Target:
def init(self, x, y):
self.x = x
self.y = y
self.lifetime = target_lifetime

def move(self):
    self.y += target_speed
    if self.y > HEIGHT:
        return False
    return True

def draw(self):
    pygame.draw.circle(screen, TARGET_COLOR, (self.x, self.y), TARGET_RADIUS)

Function to create a new target

def create_target():
x = random.randint(TARGET_RADIUS, WIDTH - TARGET_RADIUS)
y = -TARGET_RADIUS
return Target(x, y)

Main game loop

while running:
screen.fill((0, 0, 0)) # Clear screen

# Event handling
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    if event.type == pygame.MOUSEBUTTONDOWN:
        mouse_x, mouse_y = pygame.mouse.get_pos()
        # Check if player hits a target
        for target in targets:
            if (mouse_x - target.x) ** 2 + (mouse_y - target.y) ** 2 <= TARGET_RADIUS ** 2:
                targets.remove(target)
                score += 10  # Increase score for hitting the target
                break

# Draw the gun (player's aim)
pygame.draw.line(screen, GUN_COLOR, (player_x, player_y), pygame.mouse.get_pos(), 5)

# Create new targets periodically
target_timer += 1
if target_timer >= target_spawn_rate:
    targets.append(create_target())
    target_timer = 0

# Move and draw targets
for target in targets[:]:
    if not target.move():
        targets.remove(target)
    target.draw()

# Display score and time remaining
elapsed_time = time.time() - start_time
remaining_time = max(0, 60 - int(elapsed_time))
score_text = font.render(f"Score: {score}", True, (255, 255, 255))
time_text = font.render(f"Time: {remaining_time}", True, (255, 255, 255))
screen.blit(score_text, (10, 10))
screen.blit(time_text, (WIDTH - 150, 10))

# End game if time runs out
if remaining_time == 0:
    running = False

pygame.display.update()  # Update screen
clock.tick(FPS)  # Frame rate

End game screen

screen.fill((0, 0, 0))
game_over_text = font.render(f"Game Over! Final Score: {score}", True, (255, 0, 0))
screen.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, HEIGHT // 2))
pygame.display.update()
time.sleep(3) # Wait before closing

pygame.quit()