laitimes

At home on the weekends, tidying up my second Python little project

author:Programmer zhenguo

Hello, I'm zhenguo

Today is the second issue of the Python Project series, working with you to make a 2048 game.

This game was popular all over the world that year, the rules of the game were extremely simple, and it was quite simple to play, but it was not an easy task to finally spell out 2048. And it's fun to play, and I always want to challenge one by one.

Similar to the 2048 game style, its code implementation is also very concise, the code is only less than 200 lines, and it is pure Python, without any third-party packages.

1 Python implementation of the 2048 game interface

Let's take a look at the final implementation of the game interface, incidentally to help readers who do not know about the 2048 game to familiarize themselves with it.

Game main interface:

At home on the weekends, tidying up my second Python little project

Basic rules of the game:

  1. There are four arrows in the keyboard, up, down, left and right, corresponding to 4 drifting directions
  2. merge. Two squares with equal values can be merged into 1 square, and the value is multiplied by 2, as shown in the lower left corner of the figure below, the two 2 squares can be merged into one 4 square
At home on the weekends, tidying up my second Python little project

After the merger, the bottom left corner is the 4 squares:

At home on the weekends, tidying up my second Python little project

But why is there 2 more squares above it? Note that this is the third rule:

  1. Random 2 squares. When a merge operation occurs, a random one is selected from the gray cells and 2 squares are created
  2. float. There is another fun operation, I call it drifting, next to the picture above, if I press the right arrow, the two 4 squares in the lower left corner are first merged into 8 squares according to rule 2. At the same time, all the squares drift to the right as a whole (in the direction of the arrow). Because a merge operation has occurred, according to Rule 3, another 2 square is generated. Thus we get the following interface:
At home on the weekends, tidying up my second Python little project

This is the rule of the game, after you download my complete code, after playing, the understanding of the rules should be deeper, play really cool.

2 Project environment

This project does not use any third-party packages, all of which are Python's own modules, and only use 2 modules, which shows the charm of the 2048 game, and the code implemented is effortless.

One module is Tkinter, which is used to make the interface, and the random module random module is also used.

3 Project code explanation

Less than 200 lines of code, it's a small frame. There are two main categories:

  • Board
  • Game

Let's cover each one below.

3.1 Board class

There are three main capabilities that correspond to the above three rules:

  • Merge rules, corresponding to the methods of the Board class merge_grid
  • 2 squares are created randomly, corresponding to the method random_cell of the Board class
  • Drifting, the method corresponding to the Board class drifting_left

3.2 Game class

It mainly provides Tkinter's keyboard message and event processing capabilities, and the corresponding methods are event_handlers, which is relatively simple, so it mainly explains the Board class

merge_grid method

Writing the logic of the merge_grid method, assuming that when the left arrow is pressed, why this is assumed, I will focus on the analysis later, which is the core of understanding this set of code. Based on this, merging two adjacent non-zero equal cells is simple to implement:

def merge_grid(self):
        """
        向左移动,合并邻近的两个非零相等单元格
        :return:
        """
        self.merge = False
        for i in range(4):
            for j in range(3):
                if self.grid_cell[i][j] == self.grid_cell[i][j + 1] and self.grid_cell[i][j] != 0:
                    self.grid_cell[i][j] *= 2
                    self.grid_cell[i][j + 1] = 0
                    self.score += self.grid_cell[i][j]
                    self.merge = True
           

random_cell method

The way to implement random_cell is even simpler, randomly choose one of the gray (squares without numbers) squares, and assign a value of 2:

def random_cell(self):
        """
        从零单元格中随机产生一个2号单元格
        :return:
        """
        i, j = random.choice([(i, j) for i in range(4) for j in range(4) if self.grid_cell[i][j] == 0])
        self.grid_cell[i][j] = 2
           

drifting_left method

The method of implementing drifting drifting_left uses the most basic fast and slow pointer, cnt is a slow pointer, and j is a fast pointer.

def drifting_left(self):
        """
        向左偏流,消除0方格
        :return:
        """
        self.compress = False
        temp = [[0] * 4 for _ in range(4)]
        for i in range(4):
            # cnt:慢指针,j: 快指针
            cnt = 0
            for j in range(4):
                if self.grid_cell[i][j] != 0:
                    temp[i][cnt] = self.grid_cell[i][j]
                    if cnt != j:
                        self.compress = True
                    cnt += 1

        self.grid_cell = temp
           

3.3 Code Core

The 2048 game will have 4 drifting directions, namely up, down, left and right.

The above code assumes that the drift is left, and the logic of drifting to the left is written based on this.

This is precisely the cleverness of this code implementation, other up, down, right three directions of drifting, after the reverse (reverse) or transpose (transition rank), can be converted to the logic of drifting to the left. Both intermediate operations are also provided in the Board class.

For example, when the right drift is realized, the reverse is performed once, then the drifting_left is executed, and the reverse is executed again, and the right drift is achieved.

When achieving upward drifting, first turn rank, then drift left, and then turn rank.

This change of thinking, everyone draws a picture on paper, a look will know.

There are still doubts, the message area exchanges.

4 Project code explanation

Above the complete py code file, interested can send me a private message.

Read on