-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathColourful_bounce.py
More file actions
82 lines (62 loc) · 2.2 KB
/
Copy pathColourful_bounce.py
File metadata and controls
82 lines (62 loc) · 2.2 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
import pygame
import random
pygame.init()
SPRITE_COLOR_CHANGE_EVENT = pygame.USEREVENT + 1
BACKGROUND_COLOR_CHANGE_EVENT = pygame.USEREVENT + 2
BLUE = pygame.Color('blue')
LIGHTBLUE = pygame.Color('lightblue')
DARKBLUE = pygame.Color('darkblue')
YELLOW = pygame.Color('yellow')
MAGENTA = pygame.Color('magenta')
ORANGE = pygame.Color('orange')
WHITE = pygame.Color('white')
#class - sprite
class Sprite(pygame.sprite.Sprite):
def __init__(self,color,height,width):
super().__init__()
self.image = pygame.Surface([width,height])
self.image.fill(color)
self.rect = self.image.get_rect()
self.velocity = [random.choice([-1,1]), random.choice ([-1,1])]
def update(self):
self.rect.move_ip(self.velocity)
boundary_hit = False
if self.rect.left <= 0 or self.rect.right >= 500:
self.velocity[0] = -self.velocity[0]
boundary_hit = True
if self.rect.top <= 0 or self.rect.bottom >= 400:
self.velocity[1] = -self.velocity[1]
boundary_hit = True
if boundary_hit:
pygame.event.post(pygame.event.Event(SPRITE_COLOR_CHANGE_EVENT))
pygame.event.post(pygame.event.Event(BACKGROUND_COLOR_CHANGE_EVENT))
def change_color(self):
self.image.fill(random.choice([YELLOW,MAGENTA,ORANGE,WHITE]))
def change_background_color():
global bg_color
bg_color = random.choice([BLUE,LIGHTBLUE,DARKBLUE])
all_sprites_list = pygame.sprite.Group()
sp1 = Sprite(WHITE,40,50)
sp1.rect.x = random.randint(0,480)
sp1.rect.y = random.randint(0,370)
all_sprites_list.add(sp1)
screen = pygame.display.set_mode((500,400))
pygame.display.set_caption("Bounce Sprite")
bg_color = BLUE
screen.fill(bg_color)
exit = False
clock = pygame.time.Clock()
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
elif event.type == SPRITE_COLOR_CHANGE_EVENT:
sp1.change_color()
elif event.type == BACKGROUND_COLOR_CHANGE_EVENT:
change_background_color()
all_sprites_list.update()
screen.fill(bg_color)
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(240)
pygame.quit()