Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Write the game tetris

  1. User

    Write the game tetris

  2. Assistant

    Sure! Let's create a simple version of the classic game Tetris using Python and the pygame library. This will help you understand the fundamentals of game development, including handling user input, game loops, and rendering graphics.

    Prerequisites:

    • Python 3.x installed on your system.
    • The pygame library installed. You can install it using pip install pygame.

    Step-by-Step Guide to Building Tetris with Pygame

    1. Import Necessary Libraries

    import pygame
    import random
    

    2. Define Game Constants

    Set up some constants to define the game window size, grid size, and colors.

    # Screen dimensions
    SCREEN_WIDTH = 300
    SCREEN_HEIGHT = 600
    
    # Grid dimensions
    GRID_WIDTH = 10
    GRID_HEIGHT = 20
    BLOCK_SIZE = 30
    
    # Colors (R, G, B)
    BLACK = (0, 0, 0)
    GRAY = (128, 128, 128)
    
    # Shapes and their colors
    SHAPES = {
        'S': [
            ['.....',
             '.....',
             '..OO.',
             '.OO..',
             '.....'],
            ['.....',
             '..O..',
             '..OO.',
             '...O.',
             '.....'],
        ],
        'Z': [
            ['.....',
             '.....',
             '.OO..',
             '..OO.',
             '.....'],
            ['.....',
             '..O..',
             '.OO..',
             '.O...',
             '.....'],
        ],
        'I': [
            ['..O..',
             '..O..',
             '..O..',
             '..O..',
             '.....'],
            ['.....',
             'OOOO.',
             '.....',
             '.....',
             '.....'],
        ],
        'O': [
            ['.....',
             '.....',
             '.OO..',
             '.OO..',
             '.....'],
        ],
        'J': [
            ['.....',
             '.O...',
             '.OOO.',
             '.....',
             '.....'],
            ['.....',
             '..OO.',
             '..O..',
             '..O..',
             '.....'],
            ['.....',
             '.....',
             '.OOO.',
             '...O.',
             '.....'],
            ['.....',
             '..O..',
             '..O..',
             '.OO..',
             '.....'],
        ],
        'L': [
            ['.....',
             '...O.',
             '.OOO.',
             '.....',
             '.....'],
            ['.....',
             '..O..',
             '..O..',
             '..OO.',
             '.....'],
            ['.....',
             '.....',
             '.OOO.',
             '.O...',
             '.....'],
            ['.....',
             '.OO..',
             '..O..',
             '..O..',
             '.....'],
        ],
        'T': [
            ['.....',
             '..O..',
             '.OOO.',
             '.....',
             '.....'],
            ['.....',
             '..O..',
             '..OO.',
             '..O..',
             '.....'],
            ['.....',
             '.....',
             '.OOO.',
             '..O..',
             '.....'],
            ['.....',
             '..O..',
             '.OO..',
             '..O..',
             '.....'],
        ],
    }
    
    SHAPE_COLORS = {
        'S': (0, 255, 0),
        'Z': (255, 0, 0),
        'I': (0, 255, 255),
        'O': (255, 255, 0),
        'J': (255, 165, 0),
        'L': (0, 0, 255),
        'T': (128, 0, 128),
    }
    

    3. Create the Piece Class

    This class will handle the pieces' shapes, positions, rotations, and colors.

    class Piece:
        def __init__(self, x, y, shape):
            self.x = x  # Horizontal position on the grid
            self.y = y  # Vertical position on the grid
            self.shape = shape  # The shape represented by a list of rotations
            self.color = SHAPE_COLORS[shape]
            self.rotation = 0  # Current rotation
    
        def image(self):
            return SHAPES[self.shape][self.rotation % len(SHAPES[self.shape])]
    

    4. Initialize the Game Grid

    The grid represents the game board and will keep track of occupied positions.

    def create_grid(locked_positions={}):
        grid = [[BLACK for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
        for i in range(GRID_HEIGHT):
            for j in range(GRID_WIDTH):
                if (j, i) in locked_positions:
                    grid[i][j] = locked_positions[(j, i)]
        return grid
    

    5. Implement Utility Functions

    Functions to handle piece creation, rotation, collision detection, line clearing, and more.

    def get_shape():
        return Piece(GRID_WIDTH // 2 - 2, 0, random.choice(list(SHAPES.keys())))
    
    def valid_space(piece, grid):
        accepted_positions = [[(j, i) for j in range(GRID_WIDTH) if grid[i][j] == BLACK] for i in range(GRID_HEIGHT)]
        accepted_positions = [j for sub in accepted_positions for j in sub]
        formatted_shape = convert_shape_format(piece)
        for pos in formatted_shape:
            if pos not in accepted_positions:
                if pos[1] > -1:
                    return False
        return True
    
    def convert_shape_format(piece):
        positions = []
        shape = piece.image()
        for i, line in enumerate(shape):
            row = list(line)
            for j, column in enumerate(row):
                if column == 'O':
                    positions.append((piece.x + j - 2, piece.y + i - 4))
        return positions
    
    def check_lost(positions):
        for pos in positions:
            x, y = pos
            if y < 1:
                return True
        return False
    
    def clear_rows(grid, locked_positions):
        increment = 0
        for i in range(GRID_HEIGHT - 1, -1, -1):
            row = grid[i]
            if BLACK not in row:
                increment += 1
                ind = i
                for j in range(GRID_WIDTH):
                    try:
                        del locked_positions[(j, i)]
                    except:
                        continue
        if increment > 0:
            for key in sorted(list(locked_positions), key=lambda x: x[1])[::-1]:
                x, y = key
                if y < ind:
                    newKey = (x, y + increment)
                    locked_positions[newKey] = locked_positions.pop(key)
        return increment
    

    6. Draw the Game Window

    This function will render the grid, current piece, and locked positions onto the screen.

    def draw_window(surface, grid, score=0):
        surface.fill(BLACK)
        pygame.font.init()
        font = pygame.font.SysFont('comicsans', 30)
        label = font.render(f'Score: {score}', 1, (255,255,255))
        surface.blit(label, (SCREEN_WIDTH - label.get_width() - 10, 10))
    
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                pygame.draw.rect(
                    surface,
                    grid[i][j],
                    (j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE),
                    0
                )
    
        # Draw grid lines
        draw_grid(surface)
        pygame.display.update()
    
    def draw_grid(surface):
        for i in range(GRID_HEIGHT):
            pygame.draw.line(surface, GRAY, (0, i * BLOCK_SIZE), (SCREEN_WIDTH, i * BLOCK_SIZE))
        for j in range(GRID_WIDTH):
            pygame.draw.line(surface, GRAY, (j * BLOCK_SIZE, 0), (j * BLOCK_SIZE, SCREEN_HEIGHT))
    

    7. Implement the Main Game Loop

    Handle user input, piece movement, collision detection, and game over conditions.

    def main():
        locked_positions = {}
        grid = create_grid(locked_positions)
    
        change_piece = False
        run = True
        current_piece = get_shape()
        next_piece = get_shape()
        clock = pygame.time.Clock()
        fall_time = 0
        fall_speed = 0.5  # Adjust the speed as needed
        score = 0
    
        pygame.init()
        win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption('Tetris')
    
        while run:
            grid = create_grid(locked_positions)
            fall_time += clock.get_rawtime()
            clock.tick()
    
            # Piece fall logic
            if fall_time / 1000 >= fall_speed:
                fall_time = 0
                current_piece.y += 1
                if not(valid_space(current_piece, grid)) and current_piece.y > 0:
                    current_piece.y -=1
                    change_piece = True
    
            # Event handling
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                    pygame.display.quit()
                    quit()
    
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        current_piece.x -=1
                        if not valid_space(current_piece, grid):
                            current_piece.x +=1
                    elif event.key == pygame.K_RIGHT:
                        current_piece.x +=1
                        if not valid_space(current_piece, grid):
                            current_piece.x -=1
                    elif event.key == pygame.K_DOWN:
                        current_piece.y +=1
                        if not valid_space(current_piece, grid):
                            current_piece.y -=1
                    elif event.key == pygame.K_UP:
                        current_piece.rotation +=1
                        if not valid_space(current_piece, grid):
                            current_piece.rotation -=1
    
            shape_pos = convert_shape_format(current_piece)
    
            # Add piece to the grid for drawing
            for i in range(len(shape_pos)):
                x, y = shape_pos[i]
                if y > -1:
                    grid[y][x] = current_piece.color
    
            # Piece locked in place
            if change_piece:
                for pos in shape_pos:
                    locked_positions[(pos[0], pos[1])] = current_piece.color
                current_piece = next_piece
                next_piece = get_shape()
                change_piece = False
                # Clear rows
                cleared = clear_rows(grid, locked_positions)
                score += cleared * 10
    
            draw_window(win, grid, score)
    
            # Check if the game is lost
            if check_lost(locked_positions):
                run = False
    
        # Game over message
        font = pygame.font.SysFont('comicsans', 60)
        label = font.render('GAME OVER', 1, (255,255,255))
        win.blit(label, (SCREEN_WIDTH // 2 - label.get_width() // 2, SCREEN_HEIGHT // 2 - label.get_height() // 2))
        pygame.display.update()
        pygame.time.delay(2000)
    

    8. Run the Game

    if __name__ == '__main__':
        main()
    

    How to Run the Game

    1. Save the Code: Copy the entire code into a file named tetris.py.

    2. Install Dependencies: Ensure you have pygame installed:

      pip install pygame
      
    3. Run the Game: Execute the script:

      python tetris.py
      

    Controls

    • Left Arrow: Move the piece left.
    • Right Arrow: Move the piece right.
    • Up Arrow: Rotate the piece.
    • Down Arrow: Move the piece down faster.

    Conclusion

    This basic implementation covers the core mechanics of Tetris. You can enhance it by adding features like:

    • Hold piece functionality.
    • Previewing the next few pieces.
    • Implementing levels that increase speed.
    • Adding a high score leaderboard.
    • Improving the graphics and user interface.

    Feel free to modify and expand the code to create your own unique version of the game!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.