How to Create a Tetris Game in Python? Free Source Code

The Python Tetris Game is a GUI-based title-matching puzzle game that is very easy to understand and use. Talking about the gameplay it’s all the same as the real one.

The user has to manage the random sequence of Tetriminos. In this Tetris Game In Python project, I will teach you How to make a Tetris Game In Python.

Tetris Game in Python Code: Project Information

Project Name:Tetris Python Code
Language/s Used:Python (GUI) Based
Python version (Recommended):2.x or 3.x
Database:None
Type:Python App
Developer:IT SOURCECODE
Updates:0
Tetris Game Code in Python

A Tetris Game Python player has steps to follow in playing the game, first, the player has to move each one sideways and rotate quarter-turns to form a solid horizontal line without leaving gaps.

It disappears whenever such lines are formed. The user can only enter to next level if they cross the specific number by the game rules.

As the game progresses, the Tetriminos fall faster and faster.

As a result, the game ends when the stack of Tetriminos reaches the top of the field and no new Tetriminos are able to enter.

Anyway, if you want to level up your knowledge in programming especially games in Python, try this new article I’ve made for you Code For Game in Python: Python Game Projects With Source Code.

This Tetris Game In Python also includes a downloadable Tetris Game Source Code In Python, just find the downloadable source code below and click to start downloading.

To start Creating Tetris In Python, make sure that you have PyCharm IDE installed on your computer.

By the way, if you are new to Python programming and don’t know what Python IDE is and how to use it, I have here a list of the Best Python IDE for Windows, Linux, and Mac OS that will suit you. I also have here How to Download and Install the Latest Version of Python on Windows.

How to create a Tetris Game in Python? A step-by-step Guide with Source Code

Time needed: 5 minutes

These are the Steps on how to create a Tetris Game Code in Python

  • Step 1: Create a project name.

    First, open Pycharm IDE and then create a “project name” After creating a project name click the “create” button.
    Tetris In Python Code Project Name

  • Step 2: Create a python file.

    Second, after creating a project name, “right-click” your project name and then click “new.” After that click the “python file“.
    Tetris In Python Code Python File

  • Step 3: Name your python file.

    Third, after creating a Python file, Name your Python file after that click “enter“.
    Tetris In Python Code Python File Name

  • Step 4: The Actual Code.

    You are free to copy the code given below and download the full source code below.

Code Explanations

1. Installation of Pygame

Code:

pip install pygame

2. Importing PyGame

Code:

import pygame

3. The Code Given Below Is For The Class Game

Code:

    class Game(object):
    def main(self, screen):
        clock = pygame.time.Clock()

        self.matris = Matris()
        
        screen.blit(construct_nightmare(screen.get_size()), (0,0))
        
        matris_border = Surface((MATRIX_WIDTH*BLOCKSIZE+BORDERWIDTH*2, VISIBLE_MATRIX_HEIGHT*BLOCKSIZE+BORDERWIDTH*2))
        matris_border.fill(BORDERCOLOR)
        screen.blit(matris_border, (MATRIS_OFFSET,MATRIS_OFFSET))
        
        self.redraw()

        while True:
            try:
                timepassed = clock.tick(50)
                if self.matris.update((timepassed / 1000.) if not self.matris.paused else 0):
                    self.redraw()
            except GameOver:
                return
      

    def redraw(self):
        if not self.matris.paused:
            self.blit_next_tetromino(self.matris.surface_of_next_tetromino)
            self.blit_info()

            self.matris.draw_surface()

        pygame.display.flip()


    def blit_info(self):
        textcolor = (255, 255, 255)
        font = pygame.font.Font(None, 30)
        width = (WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2)) - MATRIS_OFFSET*2

        def renderpair(text, val):
            text = font.render(text, True, textcolor)
            val = font.render(str(val), True, textcolor)

            surf = Surface((width, text.get_rect().height + BORDERWIDTH*2), pygame.SRCALPHA, 32)

            surf.blit(text, text.get_rect(top=BORDERWIDTH+10, left=BORDERWIDTH+10))
            surf.blit(val, val.get_rect(top=BORDERWIDTH+10, right=width-(BORDERWIDTH+10)))
            return surf

        scoresurf = renderpair("Score", self.matris.score)
        levelsurf = renderpair("Level", self.matris.level)
        linessurf = renderpair("Lines", self.matris.lines)
        combosurf = renderpair("Combo", "x{}".format(self.matris.combo))

        height = 20 + (levelsurf.get_rect().height + 
                       scoresurf.get_rect().height +
                       linessurf.get_rect().height + 
                       combosurf.get_rect().height )

        area = Surface((width, height))
        area.fill(BORDERCOLOR)
        area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, width-BORDERWIDTH*2, height-BORDERWIDTH*2))

        area.blit(levelsurf, (0,0))
        area.blit(scoresurf, (0, levelsurf.get_rect().height))
        area.blit(linessurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height))
        area.blit(combosurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height + linessurf.get_rect().height))

        screen.blit(area, area.get_rect(bottom=HEIGHT-MATRIS_OFFSET, centerx=TRICKY_CENTERX))


    def blit_next_tetromino(self, tetromino_surf):
        area = Surface((BLOCKSIZE*5, BLOCKSIZE*5))
        area.fill(BORDERCOLOR)
        area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, BLOCKSIZE*5-BORDERWIDTH*2, BLOCKSIZE*5-BORDERWIDTH*2))

        areasize = area.get_size()[0]
        tetromino_surf_size = tetromino_surf.get_size()[0]
        # ^^ I'm assuming width and height are the same

        center = areasize/2 - tetromino_surf_size/2
        area.blit(tetromino_surf, (center, center))

        screen.blit(area, area.get_rect(top=MATRIS_OFFSET, centerx=TRICKY_CENTERX))

Explanation:

In this class which is declare the following module:

  • main – The main module of the class Game
  • redraw – In this module which is the draw surface
  • blit_info – In this module which declares the text color, font, and width
  • renderpair – In this module which is displayed the score, level, lines, and combo of the game in the changing process of time.
  • blit_next_tetromino – In this module which declares the size of the surface

4. The Code Given Below Is For The Class Menu

Code:

class Menu(object):
    running = True
    def main(self, screen):
        clock = pygame.time.Clock()
        menu = kezmenu.KezMenu(
            ['Play!', lambda: Game().main(screen)],
            ['Quit', lambda: setattr(self, 'running', False)],
        )
        menu.position = (50, 50)
        menu.enableEffect('enlarge-font-on-focus', font=None, size=60, enlarge_factor=1.2, enlarge_time=0.3)
        menu.color = (255,255,255)
        menu.focus_color = (40, 200, 40)

        nightmare = construct_nightmare(screen.get_size())
        highscoresurf = self.construct_highscoresurf()

        timepassed = clock.tick(30) / 1000.

        while self.running:
            events = pygame.event.get()

            for event in events:
                if event.type == pygame.QUIT:
                    exit()

            menu.update(events, timepassed)

            timepassed = clock.tick(30) / 1000.

            if timepassed > 1: # A game has most likely been played 
                highscoresurf = self.construct_highscoresurf()

            screen.blit(nightmare, (0,0))
            screen.blit(highscoresurf, highscoresurf.get_rect(right=WIDTH-50, bottom=HEIGHT-50))
            menu.draw(screen)
            pygame.display.flip()

    def construct_highscoresurf(self):
        font = pygame.font.Font(None, 50)
        highscore = load_score()
        text = "Highscore: {}".format(highscore)
        return font.render(text, True, (255,255,255))

def construct_nightmare(size):
    surf = Surface(size)

    boxsize = 8
    bordersize = 1
    vals = '1235' # only the lower values, for darker colors and greater fear
    arr = pygame.PixelArray(surf)
    for x in range(0, len(arr), boxsize):
        for y in range(0, len(arr[x]), boxsize):

            color = int(''.join([random.choice(vals) + random.choice(vals) for _ in range(3)]), 16)

            for LX in range(x, x+(boxsize - bordersize)):
                for LY in range(y, y+(boxsize - bordersize)):
                    if LX < len(arr) and LY < len(arr[x]):
                        arr[LX][LY] = color
    del arr
    return surf

Explanation:

In this class which is declare the following module:

  • main – The main module of the class menu that you see on the first page when you run the game.
  • construct_highscoresurf – This module which is declaring the font design and high score of the game.
  • construct_nightmare – In this module which is declaring the size of the surface and its conditions.

5. The Code Given Below Is For The Class Game Over

Code:

class GameOver(Exception):
    """Exception used for its control flow properties"""

def get_sound(filename):
    return pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), "resources", filename))

BGCOLOR = (15, 15, 20)
BORDERCOLOR = (140, 140, 140)

BLOCKSIZE = 30
BORDERWIDTH = 10

MATRIS_OFFSET = 20

MATRIX_WIDTH = 10
MATRIX_HEIGHT = 22

LEFT_MARGIN = 340

WIDTH = MATRIX_WIDTH*BLOCKSIZE + BORDERWIDTH*2 + MATRIS_OFFSET*2 + LEFT_MARGIN
HEIGHT = (MATRIX_HEIGHT-2)*BLOCKSIZE + BORDERWIDTH*2 + MATRIS_OFFSET*2

TRICKY_CENTERX = WIDTH-(WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2))/2

VISIBLE_MATRIX_HEIGHT = MATRIX_HEIGHT - 2

Explanation:

In this class which is declare the following module:

  • get_sound – This module which is getting the sound when you are already game over.

Downloadable Source Code

I have here the list of Best Python Projects with Source code free to download for free, I hope this can help you a lot.

Summary

The Tetris In Python Code is written in Python programming language, Python is very smooth to research the syntax emphasizes readability and it is able to reduce time ingesting in developing.

Also, this tutorial is the simplest way for beginners or students to enhance their logical skills in programming. Aside from that, this game project is a way for students or beginners to design and develop games.

Inquiries

If you have any questions or suggestions about the Python Tetris Game with Source Code, please feel free to leave a comment below.

1 thought on “How to Create a Tetris Game in Python? Free Source Code”

  1. Hi, thank you for the games code. Great and original idea for traditional Tetris also with additional specific accent. After I played it for a while I came to idea that would be great to have bigger background window which would cover desktop icons. Basically the biggest part can be covered with games surface and game itself as single element. As a sample I have attached pong game https://github.com/MyreMylar/pygame_gui_examples How could I make/creat it?

    Thank you in advance

Leave a Comment