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

Generate python code for a simple 2d game like tetris

  1. User

    Generate python code for a simple 2d game like tetris

  2. Assistant

    Certainly! Below is a simple implementation of a 2D Tetris-like game using Python and Pygame. This game includes basic Tetris functionality: moving, rotating, and stacking blocks as they fall. To run this code, you'll need to have Python and Pygame installed on your system.

    Install Pygame

    You can install Pygame using pip:

    pip install pygame
    

    Tetris Game Code

    import pygame
    import random
    
    # Initialize Pygame
    pygame.init()
    
    # Screen dimensions
    SCREEN_WIDTH = 300  # 10 blocks wide
    SCREEN_HEIGHT = 600  # 20 blocks high
    BLOCK_SIZE = 30
    
    # Grid dimensions
    GRID_WIDTH = SCREEN_WIDTH // BLOCK_SIZE
    GRID_HEIGHT = SCREEN_HEIGHT // BLOCK_SIZE
    
    # Define the shapes and their rotations
    S = [['.....',
          '.....',
          '..00.',
          '.00..',
          '.....'],
         ['.....',
          '..0..',
          '..00.',
          '...0.',
          '.....']]
    
    Z = [['.....',
          '.....',
          '.00..',
          '..00.',
          '.....'],
         ['.....',
          '..0..',
          '.00..',
          '.0...',
          '.....']]
    
    I = [['..0..',
          '..0..',
          '..0..',
          '..0..',
          '.....'],
         ['.....',
          '0000.',
          '.....',
          '.....',
          '.....']]
    
    O = [['.....',
          '.....',
          '.00..',
          '.00..',
          '.....']]
    
    J = [['.....',
          '.0...',
          '.000.',
          '.....',
          '.....'],
         ['.....',
          '..00.',
          '..0..',
          '..0..',
          '.....'],
         ['.....',
          '.....',
          '.000.',
          '...0.',
          '.....'],
         ['.....',
          '..0..',
          '..0..',
          '.00..',
          '.....']]
    
    L = [['.....',
          '...0.',
          '.000.',
          '.....',
          '.....'],
         ['.....',
          '..0..',
          '..0..',
          '..00.',
          '.....'],
         ['.....',
          '.....',
          '.000.',
          '.0...',
          '.....'],
         ['.....',
          '.00..',
          '..0..',
          '..0..',
          '.....']]
    
    T = [['.....',
          '..0..',
          '.000.',
          '.....',
          '.....'],
         ['.....',
          '..0..',
          '..00.',
          '..0..',
          '.....'],
         ['.....',
          '.....',
          '.000.',
          '..0..',
          '.....'],
         ['.....',
          '..0..',
          '.00..',
          '..0..',
          '.....']]
    
    # List of shapes and their corresponding colors
    SHAPES = [S, Z, I, O, J, L, T]
    SHAPE_COLORS = [
        (0, 255, 0),     # S - green
        (255, 0, 0),     # Z - red
        (0, 255, 255),   # I - cyan
        (255, 255, 0),   # O - yellow
        (255, 165, 0),   # J - orange
        (0, 0, 255),     # L - blue
        (128, 0, 128)    # T - purple
    ]
    
    # Define the grid
    def create_grid(locked_positions={}):
        grid = [[(0, 0, 0) 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
    
    # Represents a single Tetris piece
    class Piece:
        def __init__(self, x, y, shape):
            self.x = x  # X position on the grid
            self.y = y  # Y position on the grid
            self.shape = shape
            self.color = SHAPE_COLORS[SHAPES.index(shape)]
            self.rotation = 0  # Rotation state
    
    # Convert the shape format to positions on the grid
    def convert_shape_format(piece):
        positions = []
        shape_format = piece.shape[piece.rotation % len(piece.shape)]
        for i, line in enumerate(shape_format):
            row = list(line)
            for j, column in enumerate(row):
                if column == '0':
                    positions.append((piece.x + j - 2, piece.y + i - 4))
        return positions
    
    # Check if the current position is valid (within the grid and not occupied)
    def valid_space(piece, grid):
        accepted_positions = [[(j, i) for j in range(GRID_WIDTH) if grid[i][j] == (0, 0, 0)] for i in range(GRID_HEIGHT)]
        accepted_positions = [pos for sublist in accepted_positions for pos in sublist]
        formatted = convert_shape_format(piece)
        for pos in formatted:
            if pos not in accepted_positions and pos[1] > -1:
                return False
        return True
    
    # Check if any positions are above the top of the screen
    def check_lost(positions):
        for pos in positions:
            x, y = pos
            if y < 1:
                return True
        return False
    
    # Choose a random shape
    def get_shape():
        return Piece(GRID_WIDTH // 2, 0, random.choice(SHAPES))
    
    # Clear complete rows
    def clear_rows(grid, locked):
        cleared_rows = 0
        for i in range(len(grid) - 1, -1, -1):
            row = grid[i]
            if (0, 0, 0) not in row:
                cleared_rows += 1
                index = i
                for j in range(len(row)):
                    try:
                        del locked[(j, i)]
                    except:
                        continue
        if cleared_rows > 0:
            for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
                x, y = key
                if y < index:
                    new_key = (x, y + cleared_rows)
                    locked[new_key] = locked.pop(key)
        return cleared_rows
    
    # Draw text in the middle of the screen
    def draw_text_middle(surface, text, size, color):
        font = pygame.font.SysFont('comicsans', size, bold=True)
        label = font.render(text, True, color)
        surface.blit(
            label, 
            (SCREEN_WIDTH / 2 - label.get_width() / 2, SCREEN_HEIGHT / 2 - label.get_height() / 2)
        )
    
    # Draw the grid lines
    def draw_grid(surface, grid):
        for i in range(GRID_HEIGHT):
            pygame.draw.line(surface, (128, 128, 128), (0, i * BLOCK_SIZE), (SCREEN_WIDTH, i * BLOCK_SIZE))
        for j in range(GRID_WIDTH):
            pygame.draw.line(surface, (128, 128, 128), (j * BLOCK_SIZE, 0), (j * BLOCK_SIZE, SCREEN_HEIGHT))
    
    # Draw the next shape in the side window
    def draw_next_shape(piece, surface):
        font = pygame.font.SysFont('comicsans', 30)
        label = font.render('Next Shape:', True, (255, 255, 255))
        sx = SCREEN_WIDTH + 50
        sy = SCREEN_HEIGHT / 2 - 100
        shape_format = piece.shape[piece.rotation % len(piece.shape)]
        for i, line in enumerate(shape_format):
            row = list(line)
            for j, column in enumerate(row):
                if column == '0':
                    pygame.draw.rect(
                        surface, piece.color, 
                        (sx + j * BLOCK_SIZE, sy + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0
                    )
        surface.blit(label, (sx + 10, sy - 30))
    
    # Update the display window
    def draw_window(surface, grid, score=0):
        surface.fill((0, 0, 0))
        # Tetris title
        font = pygame.font.SysFont('comicsans', 60)
        label = font.render('TETRIS', True, (255, 255, 255))
        surface.blit(label, (SCREEN_WIDTH / 2 - label.get_width() / 2, 30))
        # Current score
        font = pygame.font.SysFont('comicsans', 30)
        label = font.render(f'Score: {score}', True, (255, 255, 255))
        surface.blit(label, (SCREEN_WIDTH - label.get_width() - 10, 10))
        # Draw grid and current pieces
        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
                )
        # Grid lines
        draw_grid(surface, grid)
        pygame.draw.rect(surface, (255, 0, 0), (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), 5)
    
    # Main game function
    def main():
        global SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE
        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
        score = 0
    
        # Create the game window
        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 falling 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()
                    pygame.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
                    if event.key == pygame.K_RIGHT:
                        current_piece.x += 1
                        if not valid_space(current_piece, grid):
                            current_piece.x -= 1
                    if event.key == pygame.K_DOWN:
                        current_piece.y += 1
                        if not valid_space(current_piece, grid):
                            current_piece.y -= 1
                    if event.key == pygame.K_UP:
                        current_piece.rotation += 1
                        if not valid_space(current_piece, grid):
                            current_piece.rotation -= 1
    
            # Convert shape format and add to the grid
            shape_pos = convert_shape_format(current_piece)
            for pos in shape_pos:
                x, y = pos
                if y > -1:
                    grid[y][x] = current_piece.color
    
            # Lock the piece and generate a new one
            if change_piece:
                for pos in shape_pos:
                    p = (pos[0], pos[1])
                    locked_positions[p] = current_piece.color
                current_piece = next_piece
                next_piece = get_shape()
                change_piece = False
                # Clear rows and update score
                cleared_rows = clear_rows(grid, locked_positions)
                if cleared_rows:
                    score += cleared_rows * 10
    
            draw_window(win, grid, score)
            draw_next_shape(next_piece, win)
            pygame.display.update()
    
            # Check for game over
            if check_lost(locked_positions):
                draw_text_middle(win, "GAME OVER", 80, (255, 255, 255))
                pygame.display.update()
                pygame.time.delay(2000)
                run = False
    
        pygame.quit()
    
    # Start the game
    if __name__ == '__main__':
        main()
    

    Explanation

    • Imports and Initialization: The script imports pygame and random libraries and initializes Pygame.
    • Constants: Defines screen dimensions, block size, and grid dimensions.
    • Shapes: Each Tetris shape is represented as a list of strings, where each string represents a row in the shape's grid.
    • Colors: Each shape has an associated color.
    • Piece Class: Represents a Tetris piece, keeping track of its position, shape, color, and rotation.
    • Game Functions:
      • create_grid: Creates the game grid, accounting for locked positions.
      • convert_shape_format: Converts the shape's format based on its rotation and position.
      • valid_space: Checks if the piece is in a valid position.
      • check_lost: Checks if the game is over.
      • get_shape: Returns a new random piece.
      • clear_rows: Clears completed rows from the grid and updates the locked positions.
      • draw_text_middle, draw_grid, draw_next_shape, draw_window: Functions responsible for drawing elements on the screen.
    • Main Game Loop (main function):
      • Handles the game logic, events, piece movement, and drawing.
      • Updates the falling piece based on the fall time and speed.
      • Responds to user input for moving and rotating the piece.
      • Checks for full rows to clear and updates the score.
      • Checks for game over condition and handles game termination.

    Running the Game

    Save the code to a file named tetris.py and run it using:

    python tetris.py
    
    • Controls:
      • Left Arrow: Move piece left
      • Right Arrow: Move piece right
      • Up Arrow: Rotate piece
      • Down Arrow: Move piece down faster

    Notes

    • This is a basic implementation and may not include all features of a complete Tetris game.
    • Feel free to enhance the game by adding features like a score leaderboard, levels that increase the fall speed, sounds, or more sophisticated graphics.

    Enjoy playing your very own Tetris game!