Advertisement
tokyoedtech

Python Bouncing Ball Example

Sep 19th, 2019
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. import turtle
  2. import random
  3.  
  4. # Step 1: Getting Started
  5.  
  6. wn = turtle.Screen()
  7. wn.bgcolor("maroon")
  8. wn.title("Bouncing Ball Simulator")
  9. wn.tracer(0)
  10.  
  11. balls = []
  12.  
  13. for _ in range   (0):
  14.     balls.append(turtle.Turtle())
  15.  
  16. colors = ["indian red", "light salmon", "orange", "white", "salmon"]
  17. shapes = ["circle", "triangle", "square"]
  18.  
  19. for ball in balls:
  20.     ball.penup()
  21.     ball.shape(random.choice(shapes))
  22.     ball.color(random.choice(colors))
  23.     ball.speed(0)
  24.     x = random.randint (-290, 290)
  25.     y = random.randint (200, 400)
  26.     ball.goto(x, y)
  27.     ball.dy = 0
  28.     ball.dx = random.randint(-3, 3)
  29.     ball.da = random.randint(-5, 5)
  30.  
  31. def add_ball(x,y):
  32.     ball = turtle.Turtle()
  33.     ball.penup()
  34.     ball.shape(random.choice(shapes))
  35.     ball.color(random.choice(colors))
  36.     ball.speed(0)
  37.     #x = random.randint (-290, 290)
  38.     #y = random.randint (200, 400)
  39.     ball.goto(x, y)
  40.     ball.dy = 0
  41.     ball.dx = random.randint(-3, 3)
  42.     ball.da = random.randint(-5, 5)
  43.     balls.append(ball)
  44.     print(len(balls))
  45.    
  46. add_ball(0,0)
  47.  
  48. gravity = 0.2
  49.  
  50. wn.onclick(add_ball)
  51.  
  52. while True:
  53.     wn.update()
  54.    
  55.     for ball in balls:
  56.         ball.rt(ball.da)
  57.         ball.dy -= gravity
  58.         ball.sety(ball.ycor() + ball.dy)
  59.    
  60.         ball.setx(ball.xcor() + ball.dx)
  61.    
  62.         # Check for a ball collision
  63.         if ball.xcor() > 300:
  64.             ball.dx *= -1
  65.             ball.dx *= -1
  66.        
  67.         if ball.xcor() < -300:
  68.             ball.dx *= -1
  69.             ball.dx *= -1
  70.    
  71.         # Step 2: Check for a Bounce
  72.         if ball.ycor() < -300:
  73.             ball.sety(-300)
  74.             ball.dy *= -1
  75.             ball.dx *= -1
  76.  
  77. wn.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement