Python game development, pygame module, python implementation of brick games

preface:

In this issue, we will use python to make a brick playing game. There is no more nonsense. Let's start happily~

Effect display

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-rdjcy4gn-1628066851206)( https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/481421a29d2544219dcd246daf215aa1 ~tplv-k3u1fbpfcp-zoom-1. image)]

development tool

Python version: 3.6 four

Related modules:

pygame module;

And some Python built-in modules.

Environment construction

Install Python and add it to the environment variable. pip can install the relevant modules required.

Principle introduction

Rules of the game (from Wikipedia):

Playing bricks is a video game. There are several layers of bricks in the upper part of the screen. A ball rebounds between the brick and the wall above the screen, the moving short board below the screen and the walls on both sides. When the ball touches the brick, the ball will rebound and the brick will disappear. Players should control the board under the screen and let the "ball" eliminate all the "bricks" through impact. When the ball touches the bottom of the screen, it will disappear. If all the balls disappear, the game will fail. You can break the barrier by eliminating all the bricks. Finally, if your time is not very tight and you want to improve python quickly, the most important thing is not afraid of hardship. It is suggested that you can expand my pseudo xin 762459510. That's really good. Many people make rapid progress and need you to be not afraid of hardship! You can add it and have a look~

Board operation mode: press "→" to the right and "←" to the left.

Step by step:

The implementation of the game is actually very simple. First, we define three game sprite classes according to the game rules, which are:

  • Boards;
  • ball game;
  • Bricks.

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

'''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
    '''Moving 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

For ball games, the computer controls its movement mode (such as automatically changing direction when hitting a wall). The code implementation is as follows: finally, if you are not very nervous about your time and want to improve python quickly, the most important thing is not afraid of hardship. It is suggested that you can expand our pseudo xin 762459510. That's really good. Many people make rapid progress. You need to be not afraid of hardship! You can add it and have a look~

'''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
    '''Moving 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 it collides 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

The brick class is relatively simple, and 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

Then, as before, get a few more levels, one for each level map Level file, for example:

Where B represents the location of the brick.

OK, next, you can consider implementing the main loop of the game. The basic logic is:

That is, at the end of each level, judge whether you have passed the level or GG. Once you have passed the level, you will enter the next level, otherwise you will directly enter the end interface. Of course, the last level is an exception, because you must enter the end interface 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)

This is the end of the article. Thank you for watching, [Python 24 games series]. The next article shares the bomber games

In order to thank readers, I would like to share some of my recent collection of programming dry goods with you and give back to every reader. I hope I can help you.

Dry goods mainly include:

① More than 2000 Python e-books (both mainstream and classic books should be available)

② Python standard library materials (the most complete Chinese version)

③ Project source code (forty or fifty interesting and classic hand training projects and source code)

④ Videos on basic introduction to Python, crawler, web development and big data analysis (suitable for Xiaobai)

⑤ Python learning roadmap (bid farewell to non stream learning)

⑥ Two days of Python crawler training camp live rights

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

Would you like to try to measure the beauty gap between you and the goddess in Python (for entertainment only, please do not associate). If you really meet good colleagues, you are lucky. Come on, hurry up and learn.
Wei Xin (homonym): 762459510
It includes Python skills such as python, python web, crawler and data analysis, as well as learning methods such as artificial intelligence, big data, data mining and office automation.
Create an all-round analysis from zero foundation to project development!

Keywords: Python Programming crawler Data Analysis Game Development

Added by starnol on Sun, 02 Jan 2022 20:23:52 +0200