-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
94 lines (71 loc) · 2.44 KB
/
Copy pathmain.py
File metadata and controls
94 lines (71 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import pygame
import random
# Initialize Pygame
pygame.init()
# Set screen dimensions
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# Define colors Â
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# Player and obstacle properties
player_size = 30
player_x = screen_width // 2
player_y = screen_height - player_size
player_vel = 5
obstacle_size = 20
obstacle_speed = 5
obstacles = []
# Game loop
running = True
clock = pygame.time.Clock()
score = 0
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle player movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_vel
if keys[pygame.K_RIGHT] and player_x < screen_width - player_size:
player_x += player_vel
if keys[pygame.K_UP] and player_y > 0:
player_y -= player_vel
if keys[pygame.K_DOWN] and player_y < screen_height - player_size:
player_y += player_vel
# Generate obstacles
if random.randint(0, 100) < 5:
obstacles.append([screen_width, random.randint(0, screen_height - obstacle_size)])
# Move obstacles and check for collisions
for obstacle in obstacles:
obstacle[0] -= obstacle_speed
if player_x + player_size > obstacle[0] and player_x < obstacle[0] + obstacle_size:
if player_y + player_size > obstacle[1] and player_y < obstacle[1] + obstacle_size:
running = False
if obstacle[0] < 0:
obstacles.remove(obstacle)
score += 1
# Fill the screen with white
screen.fill(white)
# Draw the player and obstacles
pygame.draw.rect(screen, black, (player_x, player_y, player_size, player_size))
for obstacle in obstacles:
pygame.draw.rect(screen, red, (obstacle[0], obstacle[1], obstacle_size, obstacle_size))
# Draw the score
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, black)
screen.blit(text, (10, 10))
# Update the display
pygame.display.update()
# Limit the frame rate
clock.tick(60)
# Show final score
font = pygame.font.Font(None, 72)
text = font.render("Game Over! Score: " + str(score), True, black)
screen.blit(text, (screen_width // 2 - text.get_width() // 2, screen_height // 2 - text.get_height() // 2))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()