surdeus revised this gist . Go to revision
No changes
surdeus revised this gist . Go to revision
1 file changed, 73 insertions
game.py(file created)
@@ -0,0 +1,73 @@ | |||
1 | + | import pygame | |
2 | + | ||
3 | + | screen = pygame.display.set_mode((640, 480)) | |
4 | + | fps = 30 | |
5 | + | ||
6 | + | class GameContext: | |
7 | + | def __init__(self, keys, dt, screen): | |
8 | + | self.dt = dt | |
9 | + | self.keys = keys | |
10 | + | self.screen = screen | |
11 | + | ||
12 | + | class MyCube: | |
13 | + | def __init__( | |
14 | + | self, | |
15 | + | x=0, y=0, | |
16 | + | w=100, h=100, | |
17 | + | fill_color=(255, 255, 255), | |
18 | + | speed=100, | |
19 | + | ) : | |
20 | + | self.x = x | |
21 | + | self.y = y | |
22 | + | self.w = w | |
23 | + | self.h = h | |
24 | + | self.fill_color = fill_color | |
25 | + | self.speed = speed | |
26 | + | self.visible = True | |
27 | + | def update(self, ctx): | |
28 | + | if ctx.keys[pygame.K_a] : | |
29 | + | self.x -= self.speed * ctx.dt | |
30 | + | if ctx.keys[pygame.K_d] : | |
31 | + | self.x += self.speed * ctx.dt | |
32 | + | if ctx.keys[pygame.K_w] : | |
33 | + | self.y -= self.speed * ctx.dt | |
34 | + | if ctx.keys[pygame.K_s] : | |
35 | + | self.y += self.speed * ctx.dt | |
36 | + | def draw(self, ctx): | |
37 | + | if not self.visible : | |
38 | + | return | |
39 | + | pygame.draw.rect( | |
40 | + | ctx.screen, self.fill_color, | |
41 | + | (self.x, self.y, self.w, self.h) | |
42 | + | ) | |
43 | + | ||
44 | + | clock = pygame.time.Clock() | |
45 | + | running = True | |
46 | + | import random | |
47 | + | cubes = [MyCube( | |
48 | + | speed=random.randint(30, 200), | |
49 | + | fill_color=(random.randint(0, 255), random.randint(0, 255), | |
50 | + | random.randint(0, 255)) | |
51 | + | ) for i in range(1000)] | |
52 | + | ||
53 | + | bg_color=(0, 0, 0) | |
54 | + | ||
55 | + | while running : | |
56 | + | screen.fill(bg_color) | |
57 | + | dt = clock.tick(30) / 1000.0 | |
58 | + | keys = pygame.key.get_pressed() | |
59 | + | events = pygame.event.get() | |
60 | + | for event in events : | |
61 | + | if event.type == pygame.QUIT : | |
62 | + | running = False | |
63 | + | ctx = GameContext(keys, dt, screen) | |
64 | + | #cube1.update(ctx) | |
65 | + | #cube1.draw(ctx) | |
66 | + | #cube2.update(ctx) | |
67 | + | #cube2.draw(ctx) | |
68 | + | for cube in cubes : | |
69 | + | cube.update(ctx) | |
70 | + | cube.draw(ctx) | |
71 | + | pygame.display.update() | |
72 | + | pygame.quit() | |
73 | + |
Newer
Older