Download presentation
Presentation is loading. Please wait.
Published byMaría Mercedes Mendoza Gutiérrez Modified over 5 years ago
1
Adding a paddle (1) We now have a code, which will run forever and just have a ball bouncing around the screen until we shut down the program. To make it more of a ‘game’, we will add a paddle and then add some more code to improve the game elements. Let’s begin by adding a Paddle class…
2
Adding a paddle (2) class Paddle: def __init__(self, canvas, color): self.canvas. = canvas self.id = canvas.create_rectangle(0,0,100,10, fill = color) self.canvas.move(self.id, 200, 300) def draw(self): pass **This is almost EXACTLY like our Ball class, but we are drawing a rectangle instead of an oval. ** we will come back to our draw function later.
3
Adding a paddle (3) Let’s make some changes in our code.
Create an object of the Paddle class Change the main loop to call the paddle’s draw function. paddle = Paddle(canvas, ‘blue’) ** Place this just above the ball = Ball(canvas, ‘red’) In our main loop paddle.draw( ) # Just below the ball.draw( )
4
What has happened so far?
We have a bouncing ball and a stationary paddle. Much better, but still not a ‘game’. We need to make the paddle move, but more importantly, we need to be able to control the paddle. We will use event bindings, so our left and right arrow keys can control the movement of the paddle.
5
making the paddle move First, we will add the x object to our __init__ function and a variable for the width of the canvas. Just like we did to our Ball class. Add this to our __init__ function in our Paddle class self.x = 0 self.canvas_width = self.canvas.winfo_width( )
6
making the paddle move (2)
Now we just need the functions for changing the direction. Add these just after the draw function (Paddle class) def turn_left(self, evt): self.x = -2 def turn_right(self, evt): self.x = 2
7
making the paddle move (3)
We will now bind these functions to the correct keys. In our __init__ function, let’s add the following: self.canvas.bind_all(‘<KeyPress-Left>’, self.turn_left) self.canvas.bind_all(‘<KeyPress-Right>’, self.turn_right)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.