1
+ import pygame
2
+ from pygame .locals import *
3
+
4
+ FRAMERATE = 30
5
+ WIDTH = 800
6
+ HEIGHT = 600
7
+
8
+ pygame .init ()
9
+
10
+ screen = pygame .display .set_mode ((WIDTH , HEIGHT ))
11
+
12
+ class Rectangles ():
13
+ def __init__ (self , topleft , wh , speed , screensize ):
14
+ self .rect = pygame .Rect (topleft , wh )
15
+ self .speed = speed
16
+ self .screen = pygame .Rect ((0 , 0 ), screensize )
17
+
18
+ def update (self ):
19
+ keys = pygame .key .get_pressed ()
20
+ if keys [K_UP ]:
21
+ self .rect = self .rect .move (0 , - self .speed )
22
+ if keys [K_LEFT ]:
23
+ self .rect = self .rect .move (- self .speed , 0 )
24
+ if keys [K_DOWN ]:
25
+ self .rect = self .rect .move (0 , self .speed )
26
+ if keys [K_RIGHT ]:
27
+ self .rect = self .rect .move (self .speed , 0 )
28
+
29
+ if self .rect .y < self .screen .y :
30
+ self .rect .y = self .screen .y
31
+ if self .rect .x < self .screen .x :
32
+ self .rect .x = self .screen .x
33
+ if self .rect .bottom > self .screen .bottom :
34
+ self .rect .y = self .screen .bottom - self .rect .height
35
+ if self .rect .right > self .screen .right :
36
+ self .rect .x = self .screen .right - self .rect .width
37
+
38
+ def draw (self , screen ):
39
+ pygame .draw .rect (screen , (255 , 0 , 0 ), self .rect )
40
+
41
+ rect = Rectangles ((200 , 150 ), (200 , 300 ), 10 , (WIDTH , HEIGHT ))
42
+
43
+ clock = pygame .time .Clock ()
44
+
45
+ while True :
46
+ clock .tick (FRAMERATE )
47
+ for event in pygame .event .get ():
48
+ if event .type == QUIT :
49
+ raise SystemExit
50
+ screen .fill ((255 ,255 ,255 ))
51
+ rect .update ()
52
+ rect .draw (screen )
53
+
54
+ pygame .display .update ()
0 commit comments