import turtle import random # Set up the screen screen = turtle.Screen() screen.title("Bouncing Ball") screen.bgcolor("black") screen.setup(width=800, height=600) screen.tracer(0) # Create the ball ball = turtle.Turtle() ball.shape("circle") ball.color("red") ball.penup() ball.speed(0) # Initial ball movement speed ball.dx = random.choice([-3, 3]) ball.dy = random.choice([-3, 3]) # Function to change direction and color def change_direction(): global ball ball.dx, ball.dy = -ball.dy, ball.dx # Rotate direction by 90 degrees ball.color(random.choice(["red", "blue", "green", "yellow", "purple", "white"])) # Ball movement function def move_ball(): global ball x, y = ball.xcor(), ball.ycor() # Move the ball ball.setx(x + ball.dx) ball.sety(y + ball.dy) # Bounce off walls if x + ball.dx > 390 or x + ball.dx < -390: ball.dx *= -1 if y + ball.dy > 290 or y + ball.dy < -290: ball.dy *= -1 screen.update() screen.ontimer(move_ball, 10) # Bind space bar to change direction and color screen.listen() screen.onkey(change_direction, "space") # Start the movement move_ball() # Keep the window open screen.mainloop()