# Multiple Bouncing Balls¶

bouncing_balls.py
```  1"""
2Bounce balls on the screen.
3Spawn a new ball for each mouse-click.
4
5If Python and Arcade are installed, this example can be run from the command line with:
7"""
8
10import random
11
12# --- Set up the constants
13
14# Size of the screen
15SCREEN_WIDTH = 600
16SCREEN_HEIGHT = 600
17SCREEN_TITLE = "Bouncing Balls Example"
18
19
20class Ball:
21    """
22    Class to keep track of a ball's location and vector.
23    """
24    def __init__(self):
25        self.x = 0
26        self.y = 0
27        self.change_x = 0
28        self.change_y = 0
29        self.size = 0
30        self.color = None
31
32
33def make_ball():
34    """
35    Function to make a new, random ball.
36    """
37    ball = Ball()
38
39    # Size of the ball
40    ball.size = random.randrange(10, 30)
41
42    # Starting position of the ball.
43    # Take into account the ball size so we don't spawn on the edge.
44    ball.x = random.randrange(ball.size, SCREEN_WIDTH - ball.size)
45    ball.y = random.randrange(ball.size, SCREEN_HEIGHT - ball.size)
46
47    # Speed and direction of rectangle
48    ball.change_x = random.randrange(-2, 3)
49    ball.change_y = random.randrange(-2, 3)
50
51    # Color
52    ball.color = (random.randrange(256), random.randrange(256), random.randrange(256))
53
54    return ball
55
56
58    """ Main application class. """
59
60    def __init__(self):
61        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
62        self.ball_list = []
63        ball = make_ball()
64        self.ball_list.append(ball)
65
66    def on_draw(self):
67        """
68        Render the screen.
69        """
70
71        # This command has to happen before we start drawing
73
74        for ball in self.ball_list:
76
77        # Put the text on the screen.
78        output = "Balls: {}".format(len(self.ball_list))
80
81    def on_update(self, delta_time):
82        """ Movement and game logic """
83        for ball in self.ball_list:
84            ball.x += ball.change_x
85            ball.y += ball.change_y
86
87            if ball.x < ball.size:
88                ball.change_x *= -1
89
90            if ball.y < ball.size:
91                ball.change_y *= -1
92
93            if ball.x > SCREEN_WIDTH - ball.size:
94                ball.change_x *= -1
95
96            if ball.y > SCREEN_HEIGHT - ball.size:
97                ball.change_y *= -1
98
99    def on_mouse_press(self, x, y, button, modifiers):
100        """
101        Called whenever the mouse button is clicked.
102        """
103        ball = make_ball()
104        self.ball_list.append(ball)
105
106
107def main():
108    MyGame()