# author: Lisa Dion # import the random number generator library module import random # set a list of speeds that we will choose from speeds = [-4, -3, 3, 4] # create the ball and set initial values ball = codesters.Circle(0, 0, 50, "green") ball.set_size(0.5) ball.set_x_speed(speeds[random.randint(0, len(speeds)-1)]) ball.set_y_speed(speeds[random.randint(0, len(speeds)-1)]) # create rectangles for the paddles # sprite = codesters.Rectangle(x, y, width, height, "color") player1 = codesters.Rectangle(-230, 0, 10, 50, "yellow") player2 = codesters.Rectangle(230, 0, 10, 50, "gray") # create rectangles against the left and right walls left_wall = codesters.Rectangle(-250, 0, 10, 500, "red") right_wall = codesters.Rectangle(250, 0, 10, 500, "red") # create a function for when 'w' is pressed def w_key(): # make sure there is room to move up if player1.get_y() < 220: player1.move_up(20) # create a function for when 's' is pressed def s_key(): # make sure there is room to move down if player1.get_y() > -220: player1.move_down(20) # create a function for when up is pressed def up_key(): # make sure there is room to move up if player2.get_y() < 220: player2.move_up(20) # create a function for when down is pressed def down_key(): # make sure there is room to move down if player2.get_y() > -220: player2.move_down(20) # make the program listen for the keys stage.event_key("s", s_key) stage.event_key("w", w_key) stage.event_key("up", up_key) stage.event_key("down", down_key) # create a function to detect collision def collision(sprite, hit_sprite): # make ball bounce off paddles by changing its x-direction ball.set_x_speed(-ball.get_x_speed()) # check if the ball hit the left or right wall if hit_sprite.get_color() == "red": # stop the ball ball.set_x_speed(0) ball.set_y_speed(0) if hit_sprite.get_x() < 0: # ball hit left wall. message = codesters.Text("Player 2 wins!", 0, 0, "red") else: # ball hit right wall. message = codesters.Text("Player 1 wins!", 0, 0, "red") # make the program listen for collisions ball.event_collision(collision)
  • Run Code
  • Show Console
  • Codesters How To (opens in a new tab)