O'Reilly logo

Python Game Programming By Example by Joseph Howse, Alejandro Rodas de Paz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Movement and collisions

Now that we have placed all of our game objects, we can define the methods that will be executed in the game loop. This loop runs indefinitely until the game ends, and each iteration updates the position of the ball and checks the collision that occurs.

With the Canvas widget, we can calculate what the items that overlap with the given coordinates are, so for now, we will implement the methods that are responsible for moving the ball and changing its direction.

Let's start with the movement of the ball and the conditions for recreating the bouncing effect when it reaches the canvas borders:

 def update(self): coords = self.get_position() width = self.canvas.winfo_width() if coords[0] <= 0 or coords[2] >= width: self.direction[0] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required