Review past

Python is a classic pac-Man game

Python implements the game of elimination

Python real dinosaur jump a little game now

Python to achieve a simple version of the aircraft war mini-game

Python implements tetris mini-games

Python to implement alien invasion small game

Python implements the “bunnies and Bun” game

Python implements eight-note mini-games

Python implements jigsaw puzzles

Skiing mini-games in Python

Python implements the classic 90 Tank Battle

Python FlappyBird implementation small game

Python for tower defense minigames

Python implementation of fruit and gold minigames

Python to implement the small game of pushing boxes

Python implements 24-point mini-games

Table tennis in Python

Preface:

In this installment, we are going to make a small game using Python to break bricks. Without further ado, let’s have fun

Results show

The development tools

Python version: 3.6.4

Related modules:

Pygame module;

And some modules that come with Python.

Environment set up

Install Python and add it to the environment variables. PIP installs the required related modules.

Introduction of the principle

Rules of the game (from Wikipedia) :

Brick breaking is a video game. There are several layers of bricks at the top of the screen, and a ball bounces between the brick and the wall at the top of the screen, the moving short board at the bottom of the screen and the walls on either side. When the ball hits the brick, the ball bounces and the brick disappears. The player controls the board at the bottom of the screen, and the “ball” knocks away all the “bricks”. When the ball hits the bottom of the screen, it disappears. Remove all the bricks to break the level.

Board operation mode: Press → to go right, press ← to go left.

Step by step:

The game is actually quite simple to implement. First of all, we define three game sprites according to the rules of the game, which are:

  • The board class;
  • Ball games;
  • The brick classes.

The advantage of defining game sprites first is to facilitate subsequent collision detection between game sprites and operation management of game sprites. Specifically, for the board subclass, it should have the function of moving according to the player operation, the code implementation is as follows:

"' the board '
class Paddle(pygame.sprite.Sprite) :
    def __init__(self, x, y, width, height, SCREENWIDTH, SCREENHEIGHT, **kwargs) :
        pygame.sprite.Sprite.__init__(self)
        self.init_state = [x, y, width, height]
        self.rect = pygame.Rect(x, y, width, height)
        self.base_speed = 10
        self.SCREENWIDTH = SCREENWIDTH
        self.SCREENHEIGHT = SCREENHEIGHT
    "Move board"
    def move(self, direction) :
        if direction == 'left':
            self.rect.left = max(0, self.rect.left-self.base_speed)
        elif direction == 'right':
            self.rect.right = min(self.SCREENWIDTH, self.rect.right+self.base_speed)
        else:
            raise ValueError('Paddle.move.direction unsupport <%s>... ' % direction)
        return True
    Bind to screen
    def draw(self, screen, color) :
        pygame.draw.rect(screen, color, self.rect)
        return True
    "' reset ' ' '
    def reset(self) :
        self.rect = pygame.Rect(self.init_state[0], self.init_state[1], self.init_state[2], self.init_state[3])
        return True
Copy the code

For the ball, it is controlled by the computer to move the way (such as hit the wall automatically change direction, etc.), its code is implemented as follows:

"' ball ' ' '
class Ball(pygame.sprite.Sprite) :
    def __init__(self, x, y, radius, SCREENWIDTH, SCREENHEIGHT, **kwargs) :
        pygame.sprite.Sprite.__init__(self)
        self.init_state = [x, y, radius*2, radius*2]
        self.rect = pygame.Rect(x, y, radius*2, radius*2)
        self.base_speed = [5.5]
        self.direction = [random.choice([1, -1]), -1]
        self.radius = radius
        self.SCREENWIDTH = SCREENWIDTH
        self.SCREENHEIGHT = SCREENHEIGHT
    Move the ball.
    def move(self) :
        self.rect.left += self.direction[0] * self.base_speed[0]
        self.rect.top += self.direction[1] * self.base_speed[1]
        if self.rect.left <= 0:
            self.rect.left = 0
            self.direction[0] = -self.direction[0]
        elif self.rect.right >= self.SCREENWIDTH:
            self.rect.right = self.SCREENWIDTH
            self.direction[0] = -self.direction[0]
        if self.rect.top <= 0:
            self.rect.top = 0
            self.direction[1] = -self.direction[1]
        elif self.rect.bottom >= self.SCREENHEIGHT:
            return False
        return True
    Change the speed and direction of movement (when colliding with the racket)
    def change(self) :
        self.base_speed = [random.choice([4.5.6]), random.choice([4.5.6])]
        self.direction = [random.choice([1, -1]), -1]
        return True
    Bind to screen
    def draw(self, screen, color) :
        pygame.draw.circle(screen, color, (self.rect.left+self.radius, self.rect.top+self.radius), self.radius)
        return True
    "' reset ' ' '
    def reset(self) :
        self.rect = pygame.Rect(self.init_state[0], self.init_state[1], self.init_state[2], self.init_state[3])
        return True
Copy the code

For the brick class, it is relatively simple, its code implementation is as follows:

"' brick '
class Brick(pygame.sprite.Sprite) :
    def __init__(self, x, y, width, height, **kwargs) :
        pygame.sprite.Sprite.__init__(self)
        self.init_state = [x, y, width, height]
        self.rect = pygame.Rect(x, y, width, height)
    Bind to screen
    def draw(self, screen, color) :
        pygame.draw.rect(screen, color, self.rect)
        return True
    "' reset ' ' '
    def reset(self) :
        self.rect = pygame.Rect(self.init_state[0], self.init_state[1], self.init_state[2], self.init_state[3])
        return True
Copy the code

Then, as before, create several more levels, each level map using a. Level file to design the definition, for example:

Where B represents the position of the brick.

OK, now consider implementing the game’s main loop. The basic logic is:

That is, at the end of each level to judge whether it is passed or GG, passed into the next level, otherwise directly into the end interface. Of course, the last level is an exception, because it must enter the end screen after the end. Specifically, the main logic code is implemented as follows:

def run(self) :
    while True:
        self.__startInterface()
        for idx, levelpath in enumerate(self.cfg.LEVELPATHS):
            state = self.__runLevel(levelpath)
            if idx == len(self.cfg.LEVELPATHS)-1:
                break
            if state == 'win':
                self.__nextLevel()
            else:
                break
        if state == 'fail':
            self.__endInterface(False)
        else:
            self.__endInterface(True)
Copy the code

That’s the end of this article, thanks for watching Python24 mini-games, next article shares bomber mini-games

To thank you readers, I’d like to share some of my recent programming favorites to give back to each and every one of you in the hope that they can help you.

Dry goods mainly include:

① Over 2000 Python ebooks (both mainstream and classic books should be available)

②Python Standard Library (Most Complete Chinese version)

③ project source code (forty or fifty interesting and classic practice projects and source code)

④Python basic introduction, crawler, Web development, big data analysis video (suitable for small white learning)

⑤ A Roadmap for Learning Python

⑥ Two days of Python crawler boot camp live access

All done~ see personal profile or private letter for complete source code.