Skip to content
Home » Blog Posts » Build a Tetris Game Using AI: Step-by-Step Guide with Python & Pygame

Build a Tetris Game Using AI: Step-by-Step Guide with Python & Pygame

    Difficulty Level: Intermediate

    This project involves minimal Python programming skills as well as experience with Pygame-based game development. The AI implementation uses simple heuristics instead of complex machine learning, making it accessible even for beginners with limited experience.

    Pre-requisites

    Before building the Tetris game using AI, ensure you have the following:

    1. Basic Programming Knowledge

    • Understanding of Python (variables, loops, functions, classes)
    • Familiarity with basic AI concepts (optional but helpful)

    2. Installed Software & Libraries

    • Python 3.x (Download from python.org)
    • Install necessary libraries using pip:
      bash pip install pygame numpy

    3. Development Environment

    You can use any code editor or IDE, such as:

    • VS Code (Recommended)
    • PyCharm
    • Jupyter Notebook (for testing AI models)

    4. AI Knowledge (Optional but Helpful)

    • Understanding of heuristics in AI (for optimizing moves)
    • Basics of Reinforcement Learning (if you want to improve AI decision-making)

    Step-by-Step Guide with Python & Pygame

    Before starting development, define the core elements of the Tetris game:

    • Grid Size: A 10×20 board
    • Tetromino Shapes: 7 different shapes (I, J, L, O, S, T, Z)
    • Game Mechanics: Piece rotation, collision detection, row clearing
    • AI Integration: Automatic piece placement using heuristics or machine learning

    Step 1: Planning the Game

    Before you begin coding, define the core components of your Tetris game:

    • Grid Size: A 10×20 board
    • Tetromino Shapes: 7 different shapes (I, J, L, O, S, T, Z)
    • Game Mechanics: Piece rotation, collision detection, row clearing
    • AI Integration: Automated piece placement using heuristics or machine learning

    Tools & AI Models You Can Use:

    • Code Generation AI: OpenAI’s Codex, ChatGPT, or Google’s Gemini
    • Game Design AI: DeepAI, Leonardo.AI, Scenario.gg (for assets)
    • AI for Optimization: Reinforcement Learning using TensorFlow or PyTorch

    Step 2: Setting Up the Development Environment

    You’ll need a game development framework and AI tools. In this guide, we’ll use Python and Pygame.

    Install Dependencies

    First, install Python and the required libraries:

    pip install pygame numpy

    Step 3: Creating the Game Grid

    The Tetris grid is a 10×20 matrix, where each cell represents a block. We initialize it as a 2D list.

    Code for the Grid

    import pygame
    import random
    
    # Define grid size
    GRID_WIDTH = 10
    GRID_HEIGHT = 20
    CELL_SIZE = 30  # Size of each cell
    
    # Initialize the grid (empty = 0)
    grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
    

    Step 4: Defining Tetromino Shapes

    Tetris consists of 7 Tetrominoes, each represented as a list of coordinates.

    Code for Tetrominoes

    TETROMINOES = {
        'I': [[(0, -1), (0, 0), (0, 1), (0, 2)]],
        'O': [[(0, 0), (0, 1), (1, 0), (1, 1)]],
        'T': [[(0, -1), (0, 0), (0, 1), (1, 0)]],
        'S': [[(0, 0), (0, 1), (1, -1), (1, 0)]],
        'Z': [[(0, 0), (0, -1), (1, 0), (1, 1)]],
        'J': [[(0, -1), (0, 0), (0, 1), (1, -1)]],
        'L': [[(0, -1), (0, 0), (0, 1), (1, 1)]],
    }
    

    Step 5: Handling Piece Movement

    Each Tetromino must:
    ✅ Move left/right
    ✅ Move down
    Rotate
    ✅ Detect collision

    Code for Movement

    class Tetromino:
        def __init__(self, shape, x, y):
            self.shape = shape
            self.cells = TETROMINOES[shape]
            self.x = x
            self.y = y
    
        def move(self, dx, dy):
            self.x += dx
            self.y += dy
    
        def rotate(self):
            self.cells = [(-y, x) for x, y in self.cells]  # Rotate 90 degrees
    

    Step 6: Detecting Line Clears

    When a row is completely filled, remove it and shift everything above down.

    Code for Line Clearing

    def clear_lines(grid):
        new_grid = [row for row in grid if any(cell == 0 for cell in row)]
        while len(new_grid) < GRID_HEIGHT:
            new_grid.insert(0, [0] * GRID_WIDTH)
        return new_grid
    

    Step 7: Implementing AI to Play the Game

    Now, let’s add AI to automatically play Tetris! The AI will:
    ✅ Analyze available positions
    ✅ Choose the best move
    ✅ Drop the piece accordingly

    Step 7.1: Creating a Heuristic Function

    A heuristic function evaluates how “good” a board state is. The board is scored based on:

    • Block Height (lower is better)
    • Number of Holes (fewer is better)
    • Lines Cleared (higher is better)

    Code for Heuristic Function

    def evaluate_board(grid):
        height = sum(row.count(1) for row in grid)
        holes = sum(1 for x in range(GRID_WIDTH) for y in range(GRID_HEIGHT) if grid[y][x] == 0 and y > 0)
        return -height + (10 * holes)
    

    Step 7.2: Implementing AI Decision Making

    The AI will simulate all possible moves, evaluate them, and select the best one.

    Code for AI Decision Making

    def best_move(grid, tetromino):
        best_score = float('-inf')
        best_position = None
    
        for rotation in range(4):
            for x in range(GRID_WIDTH):
                new_grid = simulate_drop(grid, tetromino, x, rotation)
                score = evaluate_board(new_grid)
                if score > best_score:
                    best_score = score
                    best_position = (x, rotation)
    
        return best_position
    

    Step 8: Running the Game

    Now, integrate everything into a game loop that:
    ✅ Spawns new tetrominoes
    ✅ Moves the current piece
    ✅ Allows AI to make decisions
    Clears lines and updates the screen

    Code for the Game Loop

    def game_loop():
        running = True
        current_piece = Tetromino(random.choice(list(TETROMINOES.keys())), 5, 0)
    
        while running:
            best_x, best_rotation = best_move(grid, current_piece)
            current_piece.rotate(best_rotation)
            current_piece.move(best_x, 0)
    
            # Drop the piece and update grid
            grid = clear_lines(grid)
    
            # Check for game over
            if any(cell == 1 for cell in grid[0]):
                print("Game Over")
                running = False
    

    Step 9: Adding Graphics

    Use Pygame to draw the blocks on the screen.

    Code for Drawing the Grid

    def draw_grid(screen):
        for y in range(GRID_HEIGHT):
            for x in range(GRID_WIDTH):
                if grid[y][x] == 1:
                    pygame.draw.rect(screen, (0, 255, 0), (x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE))
    

    Conclusion

    Congratulations! 🎉 You’ve built a Tetris AI that plays the game on its own! 🚀

    Ways to Improve:

    ✔ Add deep learning models for smarter AI
    ✔ Enhance graphics with animations
    ✔ Implement multiplayer mode

    Leave a Reply

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