Bouncing Rectangle¶

This shows how to animate an item you can draw using the drawing primitives.

bouncing_rectangle.py
```  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:
8"""
9
11
12# --- Set up the constants
13
14# Size of the screen
15SCREEN_WIDTH = 600
16SCREEN_HEIGHT = 600
17SCREEN_TITLE = "Bouncing Rectangle Example"
18
19# Rectangle info
20RECT_WIDTH = 50
21RECT_HEIGHT = 50
23
25
26
27class Item:
28    """ This class represents our rectangle """
29
30    def __init__(self):
31
32        # Set up attribute variables
33
34        # Where we are
35        self.center_x = 0
36        self.center_y = 0
37
38        # Where we are going
39        self.change_x = 0
40        self.change_y = 0
41
42    def update(self):
43        # Move the rectangle
44        self.center_x += self.change_x
45        self.center_y += self.change_y
46        # Check if we need to bounce of right edge
47        if self.center_x > SCREEN_WIDTH - RECT_WIDTH / 2:
48            self.change_x *= -1
49        # Check if we need to bounce of top edge
50        if self.center_y > SCREEN_HEIGHT - RECT_HEIGHT / 2:
51            self.change_y *= -1
52        # Check if we need to bounce of left edge
53        if self.center_x < RECT_WIDTH / 2:
54            self.change_x *= -1
55        # Check if we need to bounce of bottom edge
56        if self.center_y < RECT_HEIGHT / 2:
57            self.change_y *= -1
58
59    def draw(self):
60        # Draw the rectangle
62            arcade.rect.XYWH(self.center_x, self.center_y, RECT_WIDTH, RECT_HEIGHT), RECT_COLOR)
63
64
66    """ Main application class. """
67
68    def __init__(self, width, height, title):
69        super().__init__(width, height, title)
70
71        # Create our rectangle
72        self.item = Item()
73        self.item.center_x = 200
74        self.item.center_y = 300
75        self.item.change_x = 2
76        self.item.change_y = 3
77
78        # Set background color
79        self.background_color = BACKGROUND_COLOR
80
81    def on_update(self, delta_time):
82        # Move the rectangle
83        self.item.update()
84
85    def on_draw(self):
86        """ Render the screen. """
87
88        # Clear screen
89        self.clear()
90        # Draw the rectangle
91        self.item.draw()
92
93
94def main():
95    """ Main function """
96    MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)