Untitled
unknown
plain_text
5 months ago
3.5 kB
3
Indexable
import pygame import random # Pygame ko initialize karen pygame.init() # Screen size WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("2D Shooting Game") # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) # Player properties player_width = 50 player_height = 50 player_x = WIDTH // 2 - player_width // 2 player_y = HEIGHT - player_height - 10 player_velocity = 5 player_image = pygame.Surface((player_width, player_height)) player_image.fill(BLUE) # Bullet properties bullet_width = 10 bullet_height = 20 bullet_velocity = 7 bullets = [] # Enemy properties enemy_width = 50 enemy_height = 50 enemy_velocity = 3 enemies = [] # Game variables score = 0 clock = pygame.time.Clock() # Font for score font = pygame.font.SysFont("Arial", 30) # Function to draw the player def draw_player(x, y): screen.blit(player_image, (x, y)) # Function to draw bullets def draw_bullets(bullets): for bullet in bullets: pygame.draw.rect(screen, WHITE, pygame.Rect(bullet[0], bullet[1], bullet_width, bullet_height)) # Function to draw enemies def draw_enemies(enemies): for enemy in enemies: pygame.draw.rect(screen, RED, pygame.Rect(enemy[0], enemy[1], enemy_width, enemy_height)) # Function to display score def display_score(score): score_text = font.render(f"Score: {score}", True, WHITE) screen.blit(score_text, (10, 10)) # Main game loop def game_loop(): global player_x, player_y, score run_game = True while run_game: screen.fill(BLACK) # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: run_game = False # Get key presses for movement and shooting keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and player_x > 0: player_x -= player_velocity if keys[pygame.K_RIGHT] and player_x < WIDTH - player_width: player_x += player_velocity if keys[pygame.K_SPACE]: # Shoot bullet bullets.append([player_x + player_width // 2 - bullet_width // 2, player_y]) # Move bullets and check collision with enemies for bullet in bullets[:]: bullet[1] -= bullet_velocity if bullet[1] < 0: bullets.remove(bullet) else: for enemy in enemies[:]: if (bullet[0] > enemy[0] and bullet[0] < enemy[0] + enemy_width and bullet[1] > enemy[1] and bullet[1] < enemy[1] + enemy_height): enemies.remove(enemy) # Destroy enemy bullets.remove(bullet) # Destroy bullet score += 1 # Increase score # Create enemies randomly if random.randint(1, 50) == 1: enemy_x = random.randint(0, WIDTH - enemy_width) enemies.append([enemy_x, 0]) # Move enemies down the screen for enemy in enemies[:]: enemy[1] += enemy_velocity if enemy[1] > HEIGHT: enemies.remove(enemy) # Draw everything draw_player(player_x, player_y) draw_bullets(bullets) draw_enemies(enemies) display_score(score) # Update the display pygame.display.update() # Frame rate control (60 FPS) clock.tick(60) pygame.quit() # Run the game game_loop()
Editor is loading...
Leave a Comment