This is the 41st original article for beginners learning Python.
Reading this article will take approximately 15 minutes.
In previous articles, we discussed several concepts related to classes. To help everyone better grasp the concept of classes and apply this knowledge flexibly, I have created a fun and interesting bouncing ball game. This not only allows us to integrate our knowledge of classes but also deepens our interest in Python.
You will find that writing small games in Python is quite convenient and enjoyable~~
First, let’s take a look at our final effect diagram.
We will explain how to write this small game in 9 steps.
1. Create the main interface of the game.
We will use Python’s built-in module Tkinter to accomplish this. It is Python’s standard GUI toolkit, which makes it very convenient to create GUI tools. Since it is cross-platform, it can easily run on both Windows and Linux. We will use the canvas drawing function in Tk to create a small game. Let’s start by drawing the main interface.
1). Create an instance of Tk.
2). Then give this window a name called ‘game’.
3). Notify the window manager to adjust the layout size; 0,0 means it cannot be resized.
4). Create a 400×500 interface with the default background color and a border thickness of 0.
5). Notify the window manager to register the components.
6). Refresh the interface.
2. Create a Ball class.
Now that we have the main interface, let’s start creating the ball.
1) First, we create a Ball class. This class has two initialization parameters:
One is the canvas used to draw the ball, and the other is the color, which represents the ball’s color.
2) In the class’s initialization function:
-
Initialize the canvas.
-
Draw a solid ball and record its ID.
-
Create the default position of the ball on the main interface; we will place it in the center of the screen.
Then let the ball appear on the main interface:
3. Make the ball move upwards.
In the Ball class, there is a draw function. We will now add some code to this function to make the ball move upwards.
4. Make the ball bounce.
1). In the third step, the ball can move upwards. Now we want it to bounce off the walls.
-
Previously, we hardcoded self.canvas.move(self.id,0,-1), where 0,-1 means the x-coordinate remains unchanged while the y-coordinate continuously decreases by 1, indicating the ball is moving upwards.
-
Now we will set these two values as variables self.x, self.y, so that when the ball reaches the upper boundary, we will add 1 to self.y, making it move downwards.
-
When it reaches the lower boundary, we will subtract 1 from self.y, indicating it moves upwards.
2). So how do we determine if the ball has hit the wall? It’s simple; we dynamically check the ball’s coordinates [x1,y1,x2,y2].
-
x1,y1 represents the top-left coordinates.
-
x2,y2 represents the bottom-right coordinates.
After obtaining the ball’s coordinates (which is a list), we can simply check pos[1] and pos[3].
5. Add a direction to the ball’s movement.
Currently, the ball’s movement direction is fixed. We want the ball’s movement direction to be random each time; otherwise, it would be too boring. How do we do this? It’s simple; we just need to add a random function.
In the __init__() function, we will modify:
self.x = 0
self.y = -1
to:
starts=[-3,-2,-1,1,1,2,3]
random.shuffle(starts)
self.x=starts[0]# Randomly select one from the list
self.y=-3# -3 indicates the speed of movement along the y-axis
6. Add a paddle.
Now that our ball can move around the interface, we will add a paddle to hit the ball.
7. Make the paddle movable.
We will bind some keyboard events to allow the paddle to move.
We will add two functions for left and right movement. Some students may ask what ‘evt’ is; don’t worry, it will be explained below.
def turn_left(self, evt):
self.x = -2
def turn_right(self, evt):
self.x = 2
In the Paddle’s initialization function, bind the two keyboard events:
-
Pressing the left arrow key will trigger self.turn_left.
-
Pressing the right arrow key will trigger self.turn_right.
-
evt is the event registered with the system.
8. Add collision detection between the ball and the paddle.
Now that we have the ball and the paddle, and the paddle can move left and right, the most exciting part is about to begin, which is to add the functionality for the ball to bounce off the paddle. So how do we determine if the ball has hit the paddle? It’s simple; we just need to add a function in the ball class to check for collisions.
def draw(self):
–snip–
if self.hit_paddle(pos) == True:
self.y = -3
–snip–
9. Determine when the game ends if the ball reaches the bottom.
After the above 8 steps, the basic functionality of the game is complete. So how do we determine when the game ends? We set the condition that if the ball reaches the bottom (which can be considered as the ball hitting the ground), the game is over. A few lines of code will accomplish this.
class Ball():
def __init__(self,canvas,paddle,color):
–snip–
self.hit_bottom=False
def draw(self):
–snip–
if pos[3]>=self.canvas_height:# Check if the ball’s bottom edge is greater than or equal to the height of the main interface
self.hit_bottom=True
–snip–
paddle=Paddle(canvas,”blue”)
ball=Ball(canvas,paddle,”red”)
while 1:
if ball.hit_bottom==False and ball.paddle.started :
ball.draw()
paddle.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.01)
The source code is about 100 lines to implement simple functionality. In fact, this game can be enhanced with many features, such as score tracking, adding start and end prompts, increasing the types of paddles and balls, and adding levels and difficulties. Everyone can explore this further; completing it is quite fulfilling~~
If you need the source code, please type: Bouncing Ball Source Code
Alright,the fun programming with Python classes ends here. I hope it can inspire beginners. If you have any questions, feel free to leave a comment for discussion.
Lastly,writing is really not easy, I hope everyone can show some support. Welcome toshare, share, share,leave comments, leave comments, leave comments, which is important to say three times, it is also a bit of encouragement and motivation.
More students who like Python are welcome to follow Beginners Learning Python, let’s learn Python together.