Skip to content

Commit 4c1ef4a

Browse files
committed
Python Pygame Animation with Rectangle
Python Pygame Animation with Rectangle
1 parent 19a8626 commit 4c1ef4a

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

main.py

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import pygame, sys, time
2+
from pygame.locals import *
3+
4+
# Set up pygame
5+
pygame.init()
6+
7+
# Set up the window
8+
WINDOWWIDTH = 400
9+
WINDOWHEIGHT = 400
10+
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
11+
pygame.display.set_caption('Animation')
12+
13+
# Set up direction variable
14+
DOWNLEFT = 'downleft'
15+
DOWNRIGHT = 'downright'
16+
UPLEFT = 'upleft'
17+
UPRIGHT = 'upright'
18+
19+
MOVESPEED = 4
20+
21+
# Set up the colors.
22+
WHITE = (255, 255, 255)
23+
RED = (255, 0, 0)
24+
GREEN = (0, 255, 0)
25+
BLUE = (0, 0, 255)
26+
27+
# Set up box data struture.
28+
b1 = {'rect':pygame.Rect(300, 80, 50, 100), 'color':RED, 'dir':UPRIGHT}
29+
b2 = {'rect':pygame.Rect(200, 200, 90, 60), 'color':GREEN, 'dir':UPLEFT}
30+
b3 = {'rect':pygame.Rect(100, 150, 60, 60), 'color':BLUE, 'dir':DOWNLEFT}
31+
boxes = [b1, b2, b3]
32+
33+
# Run the game loop.
34+
while True:
35+
# Check for Quit event
36+
for event in pygame.event.get():
37+
if event.type == QUIT:
38+
pygame.quit()
39+
sys.exit()
40+
41+
# Draw the white background on the surface.
42+
windowSurface.fill(WHITE)
43+
44+
for b in boxes:
45+
# Move the box data structure.
46+
if b['dir'] == DOWNLEFT:
47+
b['rect'].left -= MOVESPEED
48+
b['rect'].top += MOVESPEED
49+
if b['dir'] == DOWNRIGHT:
50+
b['rect'].left += MOVESPEED
51+
b['rect'].top += MOVESPEED
52+
if b['dir'] == UPLEFT:
53+
b['rect'].left -= MOVESPEED
54+
b['rect'].top -= MOVESPEED
55+
if b['dir'] == UPRIGHT:
56+
b['rect'].left += MOVESPEED
57+
b['rect'].top -= MOVESPEED
58+
59+
# Check whether the box has moved out of the window.
60+
if b['rect'].top < 0:
61+
# The box has moved past the top
62+
if b['dir'] == UPLEFT:
63+
b['dir'] = DOWNLEFT
64+
if b['dir'] == UPRIGHT:
65+
b['dir'] = DOWNRIGHT
66+
if b['rect'].bottom > WINDOWHEIGHT:
67+
# The box has moved past the bottom
68+
if b['dir'] == DOWNLEFT:
69+
b['dir'] = UPLEFT
70+
if b['dir'] == DOWNRIGHT:
71+
b['dir'] = UPRIGHT
72+
if b['rect'].left < 0:
73+
# The box has moved past the left side
74+
if b['dir'] == DOWNLEFT:
75+
b['dir'] = DOWNRIGHT
76+
if b['dir'] == UPLEFT:
77+
b['dir'] = UPRIGHT
78+
if b['rect'].right > WINDOWWIDTH:
79+
# The box has moved past the right side
80+
if b['dir'] == DOWNRIGHT:
81+
b['dir'] = DOWNLEFT
82+
if b['dir'] == UPRIGHT:
83+
b['dir'] = UPLEFT
84+
85+
# Draw the box onto the surface.
86+
pygame.draw.rect(windowSurface, b['color'], b['rect'])
87+
88+
# Draw the winow onto the screen.
89+
pygame.display.update()
90+
time.sleep(0.02)

0 commit comments

Comments
 (0)