Skip to content

Commit 0ff9b55

Browse files
Add files via upload
This game serves as a beginner-level introduction to Pygame. It showcases simple collision detection, text rendering, drawings, and essential Pygame code. Feel free to use it, and please enjoy.
1 parent a9f3097 commit 0ff9b55

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

Dodge the Falling Blocks.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import pygame
2+
import sys
3+
import random
4+
5+
pygame.init()
6+
7+
# Screen setup
8+
WIDTH, HEIGHT = 800, 600
9+
screen = pygame.display.set_mode((WIDTH, HEIGHT))
10+
pygame.display.set_caption("Dodge the Falling Blocks")
11+
clock = pygame.time.Clock()
12+
font = pygame.font.SysFont('Arial', 36)
13+
14+
# Player setup
15+
player_size = 50
16+
player = pygame.Rect(WIDTH // 2 - player_size // 2, HEIGHT - player_size - 10, player_size, player_size)
17+
player_speed = 7
18+
19+
# Falling block setup
20+
block_width = 50
21+
block_height = 50
22+
block_speed = 5
23+
blocks = []
24+
25+
# Spawn blocks periodically
26+
SPAWN_EVENT = pygame.USEREVENT + 1
27+
pygame.time.set_timer(SPAWN_EVENT, 700) # Spawn every 700ms
28+
29+
score = 0
30+
game_over = False
31+
32+
def draw_text(text, x, y):
33+
img = font.render(text, True, (255, 255, 255))
34+
screen.blit(img, (x, y))
35+
36+
while True:
37+
for event in pygame.event.get():
38+
if event.type == pygame.QUIT:
39+
pygame.quit()
40+
sys.exit()
41+
if event.type == SPAWN_EVENT and not game_over:
42+
# Spawn a new block at a random x position at the top
43+
x_pos = random.randint(0, WIDTH - block_width)
44+
new_block = pygame.Rect(x_pos, 0, block_width, block_height)
45+
blocks.append(new_block)
46+
47+
if not game_over:
48+
keys = pygame.key.get_pressed()
49+
if keys[pygame.K_LEFT] and player.left > 0:
50+
player.x -= player_speed
51+
if keys[pygame.K_RIGHT] and player.right < WIDTH:
52+
player.x += player_speed
53+
54+
# Move blocks down
55+
for block in blocks[:]:
56+
block.y += block_speed
57+
if block.top > HEIGHT:
58+
blocks.remove(block)
59+
score += 1 # Increase score for each block dodged
60+
61+
# Check collision
62+
for block in blocks:
63+
if player.colliderect(block):
64+
game_over = True
65+
break
66+
67+
# Drawing
68+
screen.fill((30, 30, 30)) # Dark background
69+
pygame.draw.rect(screen, (0, 255, 0), player) # Player in green
70+
71+
for block in blocks:
72+
pygame.draw.rect(screen, (255, 0, 0), block) # Blocks in red
73+
74+
draw_text(f"Score: {score}", 10, 10)
75+
76+
if game_over:
77+
draw_text("GAME OVER! Press R to Restart", WIDTH // 6, HEIGHT // 2)
78+
79+
pygame.display.flip()
80+
clock.tick(60)
81+
82+
# Restart game
83+
if game_over:
84+
keys = pygame.key.get_pressed()
85+
if keys[pygame.K_r]:
86+
player.x = WIDTH // 2 - player_size // 2
87+
blocks.clear()
88+
score = 0
89+
game_over = False

0 commit comments

Comments
 (0)