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. Finally, if your time is not very tight, and you want to improve Python quickly, the most important thing is not to be afraid of hardship, I suggest you to extend my pseudo xin 762459510, that is really good, many people progress quickly, need you not to be afraid of hardship! You can go to add a look at ~

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:

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, Self. SCREENWIDTH = SCREENWIDTH self.SCREENHEIGHT = SCREENHEIGHT "" def move(self, SCREENHEIGHT) self.SCREENWIDTH = SCREENWIDTH self.SCREENHEIGHT = SCREENHEIGHT" 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>... Def draw(self, screen, color) def draw(self, screen, color): Pygame.draw. rect(screen, color, self.rect) return True "" def reset(self): self.rect = pygame.Rect(self.init_state[0], self.init_state[1], self.init_state[2], self.init_state[3]) return TrueCopy 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: Finally, if your time is not very tight, and you want to improve Python quickly, the most important thing is not to be afraid of hardship, I suggest you to extend my pseudo xin 762459510, that is really good, many people progress quickly, need you not to be afraid of hardship! You can go to add a look at ~

Class Ball(pygame.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 "" 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 "" "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 "" def draw(self, screen, color): pygame.draw.circle(screen, color, (self.rect.left+self.radius, self.rect.top+self.radius), Self. radius) return True "" def reset(self): self.rect = pygame.Rect(self.init_state[0], self.init_state[1], self.init_state[2], self.init_state[3]) return TrueCopy the code

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

Def __init__(self, x, y, width, height, **kwargs): 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, Def draw(self, screen, color): Pygame.draw. rect(screen, color, self.rect) return True "" def reset(self): self.rect = pygame.Rect(self.init_state[0], self.init_state[1], self.init_state[2], self.init_state[3]) return TrueCopy 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, thank you for watching, 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.

If you do meet a good coworker, you’ll be lucky. Come on!

Include Python, PythonWeb, crawler, data analysis and other Python skills, as well as artificial intelligence, big data, data mining, automated office learning methods. Build from zero to the project development hands-on combat all-round analysis!