# Multiple Bouncing Balls¶

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