Bouncing Rectangle#
This shows how to animate an item you can draw using the drawing primitives.
1"""
2This simple animation example shows how to bounce a rectangle
3on the screen.
4
5If Python and Arcade are installed, this example can be run
6from the command line with:
7python -m arcade.examples.bouncing_rectangle
8"""
9
10from __future__ import annotations
11
12import arcade
13
14# --- Set up the constants
15
16# Size of the screen
17SCREEN_WIDTH = 600
18SCREEN_HEIGHT = 600
19SCREEN_TITLE = "Bouncing Rectangle Example"
20
21# Rectangle info
22RECT_WIDTH = 50
23RECT_HEIGHT = 50
24RECT_COLOR = arcade.color.DARK_BROWN
25
26BACKGROUND_COLOR = arcade.color.ALMOND
27
28
29class Item:
30 """ This class represents our rectangle """
31
32 def __init__(self):
33
34 # Set up attribute variables
35
36 # Where we are
37 self.center_x = 0
38 self.center_y = 0
39
40 # Where we are going
41 self.change_x = 0
42 self.change_y = 0
43
44 def update(self):
45 # Move the rectangle
46 self.center_x += self.change_x
47 self.center_y += self.change_y
48 # Check if we need to bounce of right edge
49 if self.center_x > SCREEN_WIDTH - RECT_WIDTH / 2:
50 self.change_x *= -1
51 # Check if we need to bounce of top edge
52 if self.center_y > SCREEN_HEIGHT - RECT_HEIGHT / 2:
53 self.change_y *= -1
54 # Check if we need to bounce of left edge
55 if self.center_x < RECT_WIDTH / 2:
56 self.change_x *= -1
57 # Check if we need to bounce of bottom edge
58 if self.center_y < RECT_HEIGHT / 2:
59 self.change_y *= -1
60
61 def draw(self):
62 # Draw the rectangle
63 arcade.draw_rectangle_filled(self.center_x,
64 self.center_y,
65 RECT_WIDTH,
66 RECT_HEIGHT,
67 RECT_COLOR)
68
69
70class MyGame(arcade.Window):
71 """ Main application class. """
72
73 def __init__(self, width, height, title):
74 super().__init__(width, height, title)
75
76 # Create our rectangle
77 self.item = Item()
78 self.item.center_x = 200
79 self.item.center_y = 300
80 self.item.change_x = 2
81 self.item.change_y = 3
82
83 # Set background color
84 self.background_color = BACKGROUND_COLOR
85
86 def on_update(self, delta_time):
87 # Move the rectangle
88 self.item.update()
89
90 def on_draw(self):
91 """ Render the screen. """
92
93 # Clear screen
94 self.clear()
95 # Draw the rectangle
96 self.item.draw()
97
98
99def main():
100 """ Main function """
101 MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
102 arcade.run()
103
104
105if __name__ == "__main__":
106 main()