Telling the ball when it has hit the paddle If we dont do anything the ball will go right through the paddle oh no We need to tell the paddle when it has been hit We also need to tell the ball when it has hit a wall ID: 598608
Download Presentation The PPT/PDF document "Ball meets Paddle" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Ball meets PaddleSlide2
Telling the ball when it has hit the paddle
If we don’t do anything, the ball will go right through the paddle (oh no!)
We need to tell the paddle when it has been hit.
We also need to tell the ball when it has hit a wall.
We will make code easier to manage by chunking it into smaller pieces and keeping our functions simple.Slide3
Change the Ball class __
init
__ function (1)
Pass the paddle object into our ball __
init
__ function
Change the parameters to:
def
__
init
__(self, canvas, paddle, color):
And
Add the following (just below the
self.canvas
= canvas):
self.paddle
= paddleSlide4
Change the Ball class __
init
__ function (2)
We also need to pass the paddle object into the ball object
At the bottom of the program, just before the main loop, change
ball = Ball(canvas, paddle, ‘red’)Slide5
hit_paddle
Function
(1)
Adding a code to see of the ball has struck the paddle is more complicated than seeing if the ball has hit a wall, so we will write a new function called
hit_paddle
to the
draw
function of the
Ball
class.
First, let’s update the draw function to allow for our new
hit_paddle
, which we are about to create:
Add this just below the (if
pos
[3] >=
seld.canvas_height
…) lines:
if
self.hit_paddle
(
pos
) == True:
self.y
= -3Slide6
hit_paddle
function (2)
def
hit_paddle
(self,
pos
):
paddle_pos
=
self.canvas.coords
(self.paddle.id)
if
pos
[2] >=
paddle_pos
[0] and
pos
[0] <
paddle_pos
[2]:
if
pos
[3] >=
paddle_pos
[1] and
pos
[3] <=
paddle_pos
[3]:
return True
return False