Hand made Python Games: Tetris (1)

Time:2020-7-31

Hand made Python Games: Tetris 1

Hand made Python Games: Tetris (1)

Hello everyone, the first time the novice writes an article, please give me more advice

A. Preparatory work:

Here we use pyGame library, because Python has no built-in, so we need to download it
If you don’t have pyGame, you can download it from the official website
PyGame official website, click on the right: pyGame download address link
Add down can import try, here the author I use is
Visual studio code because it has a very convenient place that the author likes: it can be automatically saved

Set this:Hand made Python Games: Tetris (1)
Open and click file
Click auto save in this menu
To run the program: right click and click to run Python file on the terminal

How to download vs Code? Click the link on the right: official website

After that:Hand made Python Games: Tetris (1)
Search separately:

1. Search Chinese to download the first plug-in (Chinese, simplified)
2. Search Python and download the first one (it should be noted that you should download Python before adding this plug-in, as the author does)
3. We strongly recommend that you update to the latest version, so that you can directly run the program by clicking the Green Triangle Line in the upper right corner
Hand made Python Games: Tetris (1)

As there are many websites, papers and notes about vs Code and pyGame, I will only introduce them here. You can search them.

Next, let’s get down to business
Hand made Python Games: Tetris (1)

B. 1 the first step in making Tetris:

You can learn while doing, but of course I suggest that you can take chapters as the unit, read them and compile them by yourself. It’s good for you.
First import the pyGame library

import pygame 

After that, you can run it once. Take a look to see if there are any errors. If not, the installation of the library is correct. Otherwise, it is necessary to check whether it is installed and whether the installation is correct.

If no problem, start making Tetris games
First, import some libraries that you need to use (except pyGame, others are already built-in)

Import pyGame ා this library is not built in
Import random ා this library is already built in
Import sys ා this library is already built in
Import time ා this library is already built in
from  pygame.locals  Import * represents all

Next, we will define some variables, which will be used later, but we will not explain them here

initialization

FPS = 25
WINDOWWIDTH = 640
WINDOWHEIGTH = 480
BOXSIZE = 20
BOARDWIDTH = 10
BOARDHEIDTH = 20
BLANK = "."
MOVESIDEWAYSFREQ = 0.15
MOVEDOWNFREQ = 0.1
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * BOXSIZE))/2)
TOPMARGIN = WINDOWHEIGHT - (BOARDHEIGHT * BOXSIZE) - 5
#Here are the RGB settings for some colors
WHITE = (255, 255, 255)
GRAY = (185, 185, 185)
BLACK = (0, 0, 0)
RED = (155, 0, 0)
LIGHTRED = (175, 20, 20)
GREEN = (0, 155, 0)
LIGHTBLUE = (20, 20, 175)
BLUE = (0, 0, 155)
YELLOW = (155, 155, 0)
LIGHTYELLOW = (175, 175, 20)
BORDERCOLOR = BLUE
BGCOLOR = BLACK
TEXTCOLOR = WHITE
TEXTSHADOWCOLOR = GRAY
COLORS = (GLUE, RED, GREEN, YELLOW)
LIGHTCOLORS = (LIGHTGLUE, LIGHTRED, LIGHTGREEN, LIGHTYELLOW)
Assert LEC (colors) = = len (lightcolors) ා each color must have a corresponding bright color
TEMPLATEWIDTH = 5
TEMPLATEHEIGHT = 5

This is the end of the first part of the code. You can write it yourself or copy and paste it.
Let me analyze some of them
1. In the above code, the functions of boxsize, boardwidth, boardheight are: to establish the relationship between the game and the screen pixels.
2.

MOVESIDEWAYSFREQ = 0.15
MOVEDOWNFREQ = 0.1

Through the above two variables, whenever the player presses the left / right / down key in the keyboard, the falling box will also move a square to the left / right / down accordingly. And the player can press and hold it all the time to make it move all the time.
The first is to move 1 grid (left / right) every 0.15s, and the second is to move every 0.1s (bottom). You can try to change the data at the end

B. Step 2: set shape

Add down is to set the shape of each figure: it is recommended that you copy and paste, no technical content

sShapeTemplate = [['.....',
                '.....',
                '..OO.',
                '.OO..',
                '.....']
               ['.....',
                '..O..',
                '..OO.',
                '...O.',
                '.....']]
iShapeTemplate = [['..O..',
                '..O..',
                '..O..',
                '..O..',
                '.....']
               ['.....',
                '.....',
                'OOOO.',
                '.....',
                '.....']]
zShapeTemplate = [['.....',
                '.....',
                '.OO..',
                '..OO.',
                '.....']
               ['.....',
                '..O..',
                '.OO..',
                '.O...',
                '.....']]
oShapeTemplate = [['.....',
                '.....',
                '.OO..',
                '.OO..',
                '.....']]
jShapeTemplate = [['.....',
                '.O...',
                '.OOO.',
                '.....',
                '.....'],
               ['.....',
                '..OO.',
                '..O..',
                '..O..',
                '.....'],
               ['.....',
                '.....',
                '.OOO.',
                '...O.',
                '.....'],
               ['.....',
                '..O..',
                '..O..',
                '.OO..',
                '.....']]
lShapeTemplate = [['.....',
                '...O.',
                '.OOO.',
                '.....',
                '.....'],
               ['.....',
                '..O..',
                '..O..',
                '..OO.',
                '.....'],
               ['.....',
                '.....',
                '.OOO.',
                '.O...',
                '.....'],
               ['.....',
                '.OO..',
                '..O..',
                '..O..',
                '..O..']]
tShapeTemplate = [['.....',
                '..O..',
                '.OOO.',
                '.....',
                '.....'],
               ['.....',
                '..O..',
                '..OO.',
                '..O..',
                '.....'],
               ['.....',
                '.....',
                '.OOO.',
                '..O..',
                '.....'],
               ['.....',
                '..O..',
                '.OO..',
                '..O..',
                '.....']]
                

Let me explain
When defining each square, you must know that each type of square has several “different” shapes. In the above code, the list is embedded with a small list of strings to form the template. A so-called template includes all the transformations of a shape.

B. Step 3: create a shape dictionary

Here we need a dictionary variable pieces to store all changes of all different shapes. The specific code is as follows:

PIECES = {'S':sShapeTemplate
          'I':iShapeTemplate
          'Z':zShapeTemplate
          'O':oShapeTemplate
          'J':jShapeTemplate
          'L':lShapeTemplate
          'T':tShapeTemplate}

B. Step 4: write the main function

That’s the point. Come on
Hand made Python Games: Tetris (1)
Principal functionmain()To create some global variables and display a start screen before the game starts. The code is as follows:

def main():
    global FPSCLOCK, DISPLAYSURF, BASICFONT, BIGFONT
    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))
    BASICFONT = pygame.font.Font("freesansbold.ttf",18)
    BIGFONT = pygame.font.Font("freesansbold.ttf",100)
    pygame.display.set_caption("Tetromino")
    
    #showTextScreen("Tetromino")
    while True:  #Game Loop
        #if random.randint(0,1) == 0:
            #pygame.mixer.music.looad("tetrisb.mid")
        #else:
            #pygame.mixer.music.looad("tetrisc.mid")
        #pygame.mixer.music.play(-1, 0.0)
        runGame()
        #pygame.mixer.music.stop()
        showTextScreen("Game Over !")

In the above coderunGame() Function is the core, in the loop first randomly decides which music to play. Then callrunGame()Function to run the game. When the game fails,runGame()The function returnsmain()Function will stop the background music and display the game failure screen. When the player presses a key, the functionshowTextScreen()The game failed is displayed and the game cycle starts again, and then the next game is played.

The following contents are all in the second chapter

https://segmentfault.com/a/1190000022010515 (Chapter 2 website)
Hand made Python Games: Tetris (1)

If you like, please pay attention to me