forked from furas/python-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-3.py
More file actions
128 lines (82 loc) · 2.54 KB
/
Copy pathexample-3.py
File metadata and controls
128 lines (82 loc) · 2.54 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/bin/env python3
import pygame
# --- constants ---
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
# --- classes ---
class Rectangle():
def __init__(self, color, rect, time=1000, show=True):
self.color = color
self.rect = pygame.rect.Rect(rect)
self.show = show
self.time = time
# list for tasks to execute with delay
self.tasks = []
# add task to do after 0 ms
self.after(0, self.task_show)
def draw(self, surface):
if self.show:
#surface.blit(self.image, self.rect)
pygame.draw.rect(surface, self.color, self.rect)
def after(self, delay, callback):
'''add new task to list'''
current_time = pygame.time.get_ticks()
self.tasks.append((current_time+delay, callback))
def update(self):
self.update_tasks()
def update_tasks(self):
current_time = pygame.time.get_ticks()
temp = []
# execute tasks and keep only not executed
for task_time, task_callback in self.tasks:
if current_time >= task_time:
task_callback(current_time)
else:
temp.append((task_time, task_callback))
self.tasks = temp
def task_show(self, current_time):
self.show = True
self.after(self.time, self.task_hide)
def task_hide(self, current_time):
self.show = False
self.after(self.time, self.task_show)
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((800, 600))
# - objects -
# first time check at once
green_rect = Rectangle(GREEN, (0, 0, 100, 100), time=1000)
red_rect = Rectangle(RED, (100, 0, 100, 100), time=100)
# other
rect = pygame.Rect(0, 0, 50, 50)
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# - updates -
# update object
green_rect.update()
red_rect.update()
# other
rect.center = pygame.mouse.get_pos()
# - draws -
screen.fill(BLACK)
green_rect.draw(screen)
red_rect.draw(screen)
pygame.draw.rect(screen, WHITE, rect)
pygame.display.flip()
# - FPS -
clock.tick(30)
# - end -
pygame.quit()