头图

PONG - Write a pinball game in 100 lines of code

Crossin先生
中文

Hello everyone, welcome to Crossin's programming classroom!

Today I will talk to you about: how to make games

https://www.bilibili.com/video/BV1Pr4y1s7wk/?aid=767744534&cid=560981438&page=1

The theme of the game is the pinball game "PONG", the first arcade game in history. That's why I chose it as the theme for the first installment of my game development series.

The game engine uses a Python game library: pgzero. It is an encapsulation of pygame, so you don't need to write redundant routine code, just configure the content logic of the game.

Our game is written with it, and it only takes 100 lines of code in total.

First you need to install the python environment. For students who have not done this step, you can refer to our python introductory tutorial: http://python666.cn , there are detailed graphic introductions above.

Then you need to install the pgzero library, which can be installed through the pip command from the command line:

pip install pgzero

After installation, run a sentence

pgzrun.go()

The door to our game world has opened.

It was still chaotic at the beginning, and it was pitch black.

image.png

Set the coordinates of the upper left corner and the length and width of a rectangle, fill it with the specified color in the game's drawing function draw, and we get a rectangle.

pad_1 = Rect((20, 20), (10, 100))

def draw():
    screen.clear()
    screen.draw.filled_rect(pad_1, 'white')

With proper adjustment, you get a board that is used to block the ball in the game.

image.png

Add judgment in the update function of the game, when the "up" and "down" buttons on the keyboard are pressed, modify the y-coordinate of the bezel, and then the movement of the bezel can be controlled in the game.

PAD_SPEED = 10

def update(dt):
    if keyboard.up:
        pad_1.y -= PAD_SPEED
    elif keyboard.down:
        pad_1.y += PAD_SPEED

This completes the player-controlled character in the PONG game: a flap that can move up and down. And now we only use 10 lines of code.

Some friends may have noticed that there are two functions here, one is called draw, which is responsible for drawing the picture in the game, and the other is called update, which is responsible for the logic update in the game.

We often hear that the game runs at 30 frames per second, 60 frames per second, or the like, or FPS (Frames Per Second). draw and update is what is done in the "one frame" of the game. The higher the performance of your computer or game console, the less computing time it takes per frame, the higher the number of game frames, and the smoother the game experience.

Create a type called Ball with property values including position and velocity. Then, draw a circle with the position of the ball as the center in the drawing function, and calculate the position of the ball in the next frame according to the displacement formula of uniform linear motion in the update function, that is, displacement = speed x time. In this way, a small ball that can move is realized.

class Ball():
    def __init__(self):
        self.pos = [300, 200]
        self.speed = [1, 1]        
    def update(self, dt):
        for i in range(2):
            self.pos[i] += self.speed[i] * dt

ball = Ball()

def draw():
    screen.clear()
    screen.draw.filled_rect(pad_1, 'white')
    screen.draw.filled_circle(ball.pos, BALL_RADIUS, 'white')

Set the boundary conditions again, so that when the ball reaches the edge of the screen, the corresponding velocity direction can be changed. When it hits the upper and lower edges, the y velocity component is multiplied by -1. If it exceeds the left and right edges, the position is reset to the center of the screen.

class Ball():
    ...      

    def update(self, dt):
        for i in range(2):
            self.pos[i] += self.speed[i]

        if self.pos[1] < 0 or self.pos[1] > HEIGHT:
            self.speed[1] *= -1
        if self.pos[0] < 0 or self.pos[0] > WIDTH:
            self.reset()

With the board, with the ball, the next step is to make the connection between them.

Do a collision check in the update function: if the rectangle of the board intersects the center of the ball, let the ball bounce back.

def update(dt):
    ...
    
    ball.update(dt)

    if pad_1.collidepoint(ball.pos) and ball.speed[0] < 0:
        ball.speed[0] *= -1

At this point, the core physical rules of the game have been defined.

In the same way, create a second board on the right side of the screen, controlled by additional buttons. Then, when the ball goes beyond the left and right boundaries, score points for the opposing team respectively.

class Ball():
    ...      

    def dead(self, side):
        scores[side] += 1
        self.reset()

In this way, one of the simplest, two-player pinball games is completed.

Of course, if you can't find another person to play with, you can also play with your left hand and your right.

Or, add a little bit of auto-tracking code to one side of the board: make the board's position move with the ball's position. This is also a game AI.

def auto_move_pad(dt):
    if ball.pos[0] > WIDTH / 2 and ball.speed[0] > 0:
        if pad_2.y + pad_2.height * 0.25 > ball.pos[1]:
            pad_2.y -= PAD_SPEED * dt
            if pad_2.top < 0:
                pad_2.top = 0
        elif pad_2.y + pad_2.height * 0.75 < ball.pos[1]:
            pad_2.y += PAD_SPEED * dt
            if pad_2.bottom > HEIGHT:
                pad_2.bottom = HEIGHT

So far, a pinball game PONG with complete core gameplay has been completed. Plus spaces are less than 100 lines of code. It is especially suitable for novice programmers who are new to game development to practice.

However, I also added a little detail to the game, and interested friends can click on the video at the beginning of the article to watch it. If you like it, please like and retweet!

In the future, I will try more game types and more ways to play. Aim to complete the initial FLAG: achieve 100 games. If you want to see a certain type of game or the implementation of a certain game, or have questions about a certain implementation detail, you can also let me know in the message, and I will give priority to it.

The code is open source and available through "Crossin's Programming Classroom"

https://github.com/crossin/games100


For more tutorials and cases,

Welcome to search and follow: Crossin's programming classroom

5 minutes a day, easy to learn programming.

阅读 639

Crossin的编程教室
本专栏旨在为编程初学者提供浅显易懂的入门指导。 另有同名公众号,及面向零基础学习者的 Python 入门教...
936 声望
192 粉丝
0 条评论
936 声望
192 粉丝
文章目录
宣传栏