forked from UTSAVS26/PyVerse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCatch_the_fruit.py
82 lines (59 loc) · 1.95 KB
/
Catch_the_fruit.py
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
import pygame
import random
pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Catch the Falling Fruits")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
clock = pygame.time.Clock()
BASKET_WIDTH, BASKET_HEIGHT = 100, 20
basket_x = SCREEN_WIDTH // 2 - BASKET_WIDTH // 2
basket_y = SCREEN_HEIGHT - BASKET_HEIGHT - 10
basket_speed = 10
FRUIT_SIZE = 30
fruit_speed = 5
fruits = []
score = 0
font = pygame.font.SysFont(None, 36)
def draw_basket(x, y):
pygame.draw.rect(screen, GREEN, [x, y, BASKET_WIDTH, BASKET_HEIGHT])
def draw_fruit(fruit):
pygame.draw.circle(screen, YELLOW, (fruit['x'], fruit['y']), FRUIT_SIZE // 2)
def display_score(score):
score_text = font.render(f'Score: {score}', True, WHITE)
screen.blit(score_text, (10, 10))
def generate_fruit():
x = random.randint(0, SCREEN_WIDTH - FRUIT_SIZE)
return {'x': x, 'y': -FRUIT_SIZE}
running = True
while running:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and basket_x - basket_speed > 0:
basket_x -= basket_speed
if keys[pygame.K_RIGHT] and basket_x + BASKET_WIDTH + basket_speed < SCREEN_WIDTH:
basket_x += basket_speed
if random.randint(1, 30) == 1:
fruits.append(generate_fruit())
for fruit in fruits[:]:
fruit['y'] += fruit_speed
if fruit['y'] > SCREEN_HEIGHT:
fruits.remove(fruit)
elif (basket_y < fruit['y'] + FRUIT_SIZE and
basket_x < fruit['x'] < basket_x + BASKET_WIDTH):
fruits.remove(fruit)
score += 10
draw_basket(basket_x, basket_y)
for fruit in fruits:
draw_fruit(fruit)
display_score(score)
pygame.display.flip()
clock.tick(30)
pygame.quit()