Skip to content
  • SiteMap
  • Our Services
  • Frequently Asked Questions (FAQ)
  • Support
  • About Us

UpdateGadh

Update Your Skills.

  • Home
  • Projects
    •  Blockchain projects
    • Python Project
    • Data Science
    •  Ai projects
    • Machine Learning
    • PHP Project
    • React Projects
    • Java Project
    • SpringBoot
    • JSP Projects
    • Java Script Projects
    • Code Snippet
    • Free Projects
  • Tutorials
    • Ai
    • Machine Learning
    • Advance Python
    • Advance SQL
    • DBMS Tutorial
    • Data Analyst
    • Deep Learning Tutorial
    • Data Science
    • Nodejs Tutorial
  • Blog
  • Contact us
  • Toggle search form
How to Create a Tetris Game Using Python in Pygame - Tetris Game Using Python

How to Create a Tetris Game Using Python in Pygame

Posted on January 7, 2025January 16, 2026 By Rishabh saini No Comments on How to Create a Tetris Game Using Python in Pygame

Tetris Game Using Python

In this blog post, we’ll walk through creating a Tetris game in Python using the Pygame library. We’ll cover the code, explain each part step by step, and provide output visuals to help you understand how it works.

Tetris Game Using Python

Download New Real Time Projects :-Click here

1. Introduction to Tetris and Pygame

Tetris is a classic puzzle game where blocks of various shapes fall from the top, and the player arranges them to clear lines. Python, with its Pygame library, makes it easy to create such a game.

2. Setting Up Pygame

First, install Pygame if you haven’t already. Run the following command in your terminal or command prompt:

pip install pygame

Then, import Pygame and initialize it in your script.

import pygame
import random

pygame.init()

3. Defining Colors and Shapes

We’ll use a grid-based approach for the game. Define colors and the shapes of Tetris blocks:

colors = [
    (0, 0, 0),  # Background
    (120, 37, 179),  # Purple
    (100, 179, 179),  # Cyan
    (80, 34, 22),  # Brown
    (80, 134, 22),  # Green
    (180, 34, 22),  # Red
    (180, 34, 122),  # Pink
]

class Figure:
    figures = [
        [[1, 5, 9, 13], [4, 5, 6, 7]],  # I-shape
        [[4, 5, 9, 10], [2, 6, 5, 9]],  # Z-shape
        # Add more shapes here
    ]

4. Creating the Game Components

Create a Tetris_Game class to handle the grid, falling blocks, and game logic:

class Tetris_Game:
    def __init__(self, height, width):
        self.height = height
        self.width = width
        self.field = [[0] * width for _ in range(height)]
        self.figure = None
        self.state = "start"

    def new_figure(self):
        self.figure = Figure(3, 0)

5. Implementing Game Logic

Implement key functionalities like block movement, collision detection, and line clearing:

def go_down(self):
    self.figure.y += 1
    if self.intersects():
        self.figure.y -= 1
        self.freeze()

def intersects(self):
    # Check for collisions with walls or existing blocks
    pass

def break_lines(self):
    # Remove filled lines and increase score
    pass

6. Adding the Main Game Loop

Set up the game loop to handle user inputs and render the game screen:

screen = pygame.display.set_mode((400, 500))
pygame.display.set_caption("Tetris_Game")
done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        # Handle key inputs

7. Testing and Running the Game

Save the script and run it:

python tetris_game.py

PHP PROJECT:- CLICK HERE

8. Full Code

Here’s the complete code:

import pygame
import random

colors = [
    (0, 0, 0),
    (120, 37, 179),
    (100, 179, 179),
    (80, 34, 22),
    (80, 134, 22),
    (180, 34, 22),
    (180, 34, 122),
]


class Figure:
    x = 0
    y = 0

    figures = [
        [[1, 5, 9, 13], [4, 5, 6, 7]],
        [[4, 5, 9, 10], [2, 6, 5, 9]],
        [[6, 7, 9, 10], [1, 5, 6, 10]],
        [[1, 2, 5, 9], [0, 4, 5, 6], [1, 5, 9, 8], [4, 5, 6, 10]],
        [[1, 2, 6, 10], [5, 6, 7, 9], [2, 6, 10, 11], [3, 5, 6, 7]],
        [[1, 4, 5, 6], [1, 4, 5, 9], [4, 5, 6, 9], [1, 5, 6, 9]],
        [[1, 2, 5, 6]],
    ]

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.type = random.randint(0, len(self.figures) - 1)
        self.color = random.randint(1, len(colors) - 1)
        self.rotation = 0

    def image(self):
        return self.figures[self.type][self.rotation]

    def rotate(self):
        self.rotation = (self.rotation + 1) % len(self.figures[self.type])


class Tetris_Game:
    level = 2
    score = 0
    state = "start"
    field = []
    height = 0
    width = 0
    x = 100
    y = 60
    zoom = 20
    figure = None

    def __init__(self, height, width):
        self.height = height
        self.width = width
        self.field = []
        self.score = 0
        self.state = "start"
        for i in range(height):
            new_line = []
            for j in range(width):
                new_line.append(0)
            self.field.append(new_line)

    def new_figure(self):
        self.figure = Figure(3, 0)

    def intersects(self):
        intersection = False
        for i in range(4):
            for j in range(4):
                if i * 4 + j in self.figure.image():
                    if i + self.figure.y > self.height - 1 or \
                            j + self.figure.x > self.width - 1 or \
                            j + self.figure.x < 0 or \
                            self.field[i + self.figure.y][j + self.figure.x] > 0:
                        intersection = True
        return intersection

    def break_lines(self):
        lines = 0
        for i in range(1, self.height):
            zeros = 0
            for j in range(self.width):
                if self.field[i][j] == 0:
                    zeros += 1
            if zeros == 0:
                lines += 1
                for i1 in range(i, 1, -1):
                    for j in range(self.width):
                        self.field[i1][j] = self.field[i1 - 1][j]
        self.score += lines ** 2

    def go_space(self):
        while not self.intersects():
            self.figure.y += 1
        self.figure.y -= 1
        self.freeze()

    def go_down(self):
        self.figure.y += 1
        if self.intersects():
            self.figure.y -= 1
            self.freeze()

    def freeze(self):
        for i in range(4):
            for j in range(4):
                if i * 4 + j in self.figure.image():
                    self.field[i + self.figure.y][j + self.figure.x] = self.figure.color
        self.break_lines()
        self.new_figure()
        if self.intersects():
            self.state = "gameover"

    def go_side(self, dx):
        old_x = self.figure.x
        self.figure.x += dx
        if self.intersects():
            self.figure.x = old_x

    def rotate(self):
        old_rotation = self.figure.rotation
        self.figure.rotate()
        if self.intersects():
            self.figure.rotation = old_rotation


# Initialize the game engine
pygame.init()

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)

size = (400, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Tetris_Game")

# Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
fps = 25
game = Tetris_Game(20, 10)
counter = 0

pressing_down = False

while not done:
    if game.figure is None:
        game.new_figure()
    counter += 1
    if counter > 100000:
        counter = 0

    if counter % (fps // game.level // 2) == 0 or pressing_down:
        if game.state == "start":
            game.go_down()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                game.rotate()
            if event.key == pygame.K_DOWN:
                pressing_down = True
            if event.key == pygame.K_LEFT:
                game.go_side(-1)
            if event.key == pygame.K_RIGHT:
                game.go_side(1)
            if event.key == pygame.K_SPACE:
                game.go_space()
            if event.key == pygame.K_ESCAPE:
                game.__init__(20, 10)

    if event.type == pygame.KEYUP:
            if event.key == pygame.K_DOWN:
                pressing_down = False

    screen.fill(WHITE)

    for i in range(game.height):
        for j in range(game.width):
            pygame.draw.rect(screen, GRAY, [game.x + game.zoom * j, game.y + game.zoom * i, game.zoom, game.zoom], 1)
            if game.field[i][j] > 0:
                pygame.draw.rect(screen, colors[game.field[i][j]],
                                 [game.x + game.zoom * j + 1, game.y + game.zoom * i + 1, game.zoom - 2, game.zoom - 1])

    if game.figure is not None:
        for i in range(4):
            for j in range(4):
                p = i * 4 + j
                if p in game.figure.image():
                    pygame.draw.rect(screen, colors[game.figure.color],
                                     [game.x + game.zoom * (j + game.figure.x) + 1,
                                      game.y + game.zoom * (i + game.figure.y) + 1,
                                      game.zoom - 2, game.zoom - 2])

    font = pygame.font.SysFont('Calibri', 25, True, False)
    font1 = pygame.font.SysFont('Calibri', 65, True, False)
    text = font.render("Score: " + str(game.score), True, BLACK)
    text_game_over = font1.render("Game Over", True, (255, 125, 0))
    text_game_over1 = font1.render("Press ESC", True, (255, 215, 0))

    screen.blit(text, [0, 0])
    if game.state == "gameover":
        screen.blit(text_game_over, [20, 200])
        screen.blit(text_game_over1, [25, 265])

    pygame.display.flip()
    clock.tick(fps)

pygame.quit()


tetris python code copy and paste
how to create a tetris game using python in pygame
tetris python code without-pygame
tetris game code c++
how to create a tetris game using python
create a tetris game using python
tetris python code github
tetris game using pygame
tetris code
how to create a tetris game using python in pygame
tetris game using python
games in python
tetris code copy and paste
tetris game using python pdf
tetris game using python github
how to create a tetris game using python in pygame
create a tetris game using python github
tetris game using python for beginners

Post Views: 1,358
PythonFreeProject Tags:how to create tetris in python, pygame tetris, pygame tetris code, pygame tetris tutorial, Python, python game development, python pygame tetris, python tetris, python tetris ai, python tetris code, python tetris game, python tetris game tutorial, python tetris tutorial, Python Tutorial, tetris, tetris code python, tetris in python, tetris in python code, tetris in python pygame, tetris in python tutorial, tetris tutorial python

Post navigation

Previous Post: RTO Management System Using PHP And MYSQL
Next Post: How to Convert Integer to String in Python: A Comprehensive Guide

More Related Articles

Fake News Detection Fake News Detection Web App in Python using Flask PythonFreeProject
Movie Recommendation System in Python with Source Code - Movie Recommendation System in Python Movie Recommendation System in Python with Source Code PythonFreeProject
Face Recognition based Attendance System Learn How to Create Face Recognition based Attendance System in python! PythonFreeProject

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

  1. E-commerce Website using Django With Free Source Code
  2. Library Menu in Python with Free Source Code
  3. Movie Recommendation System in Python with Source Code
  4. Detecting Malicious URLs with Django
  5. Hotel Price Prediction Machine Learning
  6. Best Money Management System Using Python – A Django & MySQL Based Personal Finance Management System

Most Viewed Posts

  1. Top Large Language Models in 2025
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. login form in php and mysql , Step-by-Step with Free Source Code
  4. Flipkart Clone using PHP And MYSQL Free Source Code
  5. News Portal Project in PHP and MySql Free Source Code
  6. User Login & Registration System Using PHP and MySQL Free Code
  7. Top 10 Final Year Project Ideas in Python
  8. Online Bike Rental Management System Using PHP and MySQL
  9. E learning Website in php with Free source code
  10. E-Commerce Website Project in Java Servlets (JSP)
  • AI
  • ASP.NET
  • Blockchain
  • ChatCPT
  • code Snippets
  • Collage Projects
  • Data Science Project
  • Data Science Tutorial
  • DBMS Tutorial
  • Deep Learning Tutorial
  • Final Year Projects
  • Free Projects
  • How to
  • html
  • Interview Question
  • Java Notes
  • Java Project
  • Java Script Notes
  • JAVASCRIPT
  • Javascript Project
  • JSP JAVA(J2EE)
  • Machine Learning Project
  • Machine Learning Tutorial
  • MySQL Tutorial
  • Node.js Tutorial
  • PHP Project
  • Portfolio
  • Python
  • Python Interview Question
  • Python Projects
  • PythonFreeProject
  • React Free Project
  • React Projects
  • Spring boot
  • SQL Tutorial
  • TOP 10
  • Uncategorized
  • Online Examination System in PHP with Source Code
  • AI Chatbot for College and Hospital
  • Job Portal Web Application in PHP MySQL
  • Online Tutorial Portal Site in PHP MySQL — Full Project with Source Code
  • Online Job Portal System in JSP Servlet MySQL

Most Viewed Posts

  • Top Large Language Models in 2025 (8,612)
  • Online Shopping System using PHP, MySQL with Free Source Code (5,209)
  • login form in php and mysql , Step-by-Step with Free Source Code (4,859)

Copyright © 2026 UpdateGadh.

Powered by PressBook Green WordPress theme