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

Make a normal tetris game in pygame. It should show next move as well as hold. Hold…

  1. User

    Make a normal tetris game in pygame. It should show next move as well as hold. Hold should be binded as SHIFT and the keys to move should be arrow keys, as well as up/down to flip the piece. They should be correctly colored.

  2. Assistant

    Sure! Below is a Python script using Pygame that implements a Tetris game according to your specifications:

    • Arrow keys: Move the piece left/right.
    • Up/Down keys: Rotate the piece.
    • Shift key: Hold the current piece.
    • Displays the next piece and the hold piece.
    • Pieces are correctly colored.
    import pygame
    import random
    import sys
    
    # Initialize pygame
    pygame.init()
    
    # Screen dimensions
    block_size = 30
    grid_width = 10
    grid_height = 20
    screen_width = block_size * grid_width
    screen_height = block_size * grid_height
    play_width = screen_width
    play_height = screen_height
    
    # Colors
    BLACK = (0, 0, 0)
    GRAY = (128, 128, 128)
    COLORS = [
        (0, 255, 255),   # Cyan for 'I'
        (0, 0, 255),     # Blue for 'J'
        (255, 165, 0),   # Orange for 'L'
        (255, 255, 0),   # Yellow for 'O'
        (0, 255, 0),     # Green for 'S'
        (255, 0, 0),     # Red for 'Z'
        (128, 0, 128)    # Purple for 'T'
    ]
    
    # Shape formats
    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 = COLORS
    
    # Grid creation
    def create_grid(locked_positions={}):
        grid = [[BLACK for _ in range(grid_width)] for _ in range(grid_height)]
        for y in range(grid_height):
            for x in range(grid_width):
                if (x, y) in locked_positions:
                    c = locked_positions[(x, y)]
                    grid[y][x] = c
        return grid
    
    # Convert shape format
    def convert_shape_format(shape):
        positions = []
        format = shape.shape[shape.rotation % len(shape.shape)]
        for i, line in enumerate(format):
            for j, char in enumerate(line):
                if char == '0':
                    positions.append((shape.x + j - 2, shape.y + i - 4))
        return positions
    
    # Check valid space
    def valid_space(shape, grid):
        accepted_positions = [[(x, y) for x in range(grid_width) if grid[y][x] == BLACK] for y in range(grid_height)]
        accepted_positions = [pos for sublist in accepted_positions for pos in sublist]
        formatted = convert_shape_format(shape)
        for pos in formatted:
            if pos not in accepted_positions:
                if pos[1] > -1:
                    return False
        return True
    
    # Check if player lost
    def check_lost(positions):
        for pos in positions:
            x, y = pos
            if y < 1:
                return True
        return False
    
    # Get a random shape
    def get_shape():
        return Piece(5, 0, random.choice(shapes))
    
    # Piece class
    class Piece(object):
        def __init__(self, x, y, shape):
            self.x = x
            self.y = y
            self.shape = shape
            self.color = shape_colors[shapes.index(shape)]
            self.rotation = 0
    
    # Draw text in the middle
    def draw_text_middle(text, size, color, surface):
        font = pygame.font.SysFont('comicsans', size, bold=True)
        label = font.render(text, 1, color)
        surface.blit(label, (play_width/2 - label.get_width()/2, play_height/2 - label.get_height()/2))
    
    # Clear rows
    def clear_rows(grid, locked):
        cleared_rows = 0
        for y in range(grid_height-1, -1, -1):
            row = grid[y]
            if BLACK not in row:
                cleared_rows += 1
                # Remove positions from locked
                for x in range(grid_width):
                    try:
                        del locked[(x, y)]
                    except:
                        continue
                # Shift every row above down
                for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
                    x, y_pos = key
                    if y_pos < y:
                        newKey = (x, y_pos + 1)
                        locked[newKey] = locked.pop(key)
        return cleared_rows
    
    # Draw next shape
    def draw_next_shape(shape, surface):
        font = pygame.font.SysFont('comicsans', 30)
        label = font.render('Next Shape', 1, (255,255,255))
        sx = play_width + 50
        sy = play_height/2 - 100
        format = shape.shape[shape.rotation % len(shape.shape)]
        for i, line in enumerate(format):
            for j, char in enumerate(line):
                if char == '0':
                    pygame.draw.rect(surface, shape.color, (sx + j*block_size, sy + i*block_size, block_size, block_size), 0)
        surface.blit(label, (sx + 10, sy - 30))
    
    # Draw hold shape
    def draw_hold_shape(shape, surface):
        font = pygame.font.SysFont('comicsans', 30)
        label = font.render('Hold', 1, (255,255,255))
        sx = play_width + 50
        sy = play_height/2 + 100
        if shape:
            format = shape.shape[shape.rotation % len(shape.shape)]
            for i, line in enumerate(format):
                for j, char in enumerate(line):
                    if char == '0':
                        pygame.draw.rect(surface, shape.color, (sx + j*block_size, sy + i*block_size, block_size, block_size), 0)
        surface.blit(label, (sx + 10, sy - 30))
    
    # Draw window
    def draw_window(surface, grid):
        surface.fill(BLACK)
        pygame.font.init()
        font = pygame.font.SysFont('comicsans', 60)
        label = font.render('Tetris', 1, (255,255,255))
        surface.blit(label, (play_width / 2 - label.get_width() / 2, 30))
        for y in range(grid_height):
            for x in range(grid_width):
                pygame.draw.rect(surface, grid[y][x], (x*block_size, y*block_size, block_size, block_size), 0)
        # Draw grid lines
        for y in range(grid_height):
            pygame.draw.line(surface, GRAY, (0, y*block_size), (play_width, y*block_size))
            for x in range(grid_width):
                pygame.draw.line(surface, GRAY, (x*block_size, 0), (x*block_size, play_height))
        # Draw border
        pygame.draw.rect(surface, (255, 0, 0), (0, 0, play_width, play_height), 5)
    
    # Main game function
    def main():
        global grid
        locked_positions = {}
        grid = create_grid(locked_positions)
        change_piece = False
        run = True
        current_piece = get_shape()
        next_piece = get_shape()
        hold_piece = None
        hold_used = False
        clock = pygame.time.Clock()
        fall_time = 0
        fall_speed = 0.5
        screen = pygame.display.set_mode((play_width + 200, play_height))
        pygame.display.set_caption('Tetris')
    
        while run:
            fall_time += clock.get_rawtime()
            clock.tick()
            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()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    # Move left
                    if event.key == pygame.K_LEFT:
                        current_piece.x -= 1
                        if not(valid_space(current_piece, grid)):
                            current_piece.x += 1
                    # Move right
                    elif event.key == pygame.K_RIGHT:
                        current_piece.x += 1
                        if not(valid_space(current_piece, grid)):
                            current_piece.x -= 1
                    # Rotate clockwise
                    elif event.key == pygame.K_UP:
                        current_piece.rotation += 1
                        if not(valid_space(current_piece, grid)):
                            current_piece.rotation -= 1
                    # Rotate counterclockwise
                    elif event.key == pygame.K_DOWN:
                        current_piece.rotation -= 1
                        if not(valid_space(current_piece, grid)):
                            current_piece.rotation += 1
                    # Hold piece
                    elif event.key == pygame.K_LSHIFT or event.key == pygame.K_RSHIFT:
                        if not hold_used:
                            if hold_piece is None:
                                hold_piece = current_piece
                                current_piece = next_piece
                                next_piece = get_shape()
                            else:
                                hold_piece, current_piece = current_piece, hold_piece
                                current_piece.x = 5
                                current_piece.y = 0
                            hold_used = True
    
            shape_positions = convert_shape_format(current_piece)
            # Add shape to the grid
            for pos in shape_positions:
                x, y = pos
                if y > -1:
                    grid[y][x] = current_piece.color
    
            if change_piece:
                for pos in shape_positions:
                    p = (pos[0], pos[1])
                    locked_positions[p] = current_piece.color
                current_piece = next_piece
                next_piece = get_shape()
                change_piece = False
                hold_used = False
                # Clear rows
                clear_rows(grid, locked_positions)
    
            draw_window(screen, grid)
            draw_next_shape(next_piece, screen)
            draw_hold_shape(hold_piece, screen)
            pygame.display.update()
            if check_lost(locked_positions):
                draw_text_middle("YOU LOST", 80, (255, 255, 255), screen)
                pygame.display.update()
                pygame.time.delay(2000)
                run = False
    
    # Start the game
    if __name__ == '__main__':
        main()
    

    Explanation:

    • Piece Class: Represents each Tetris piece with its position, shape, color, and rotation.
    • Grid: The playing field, created as a 2D list.
    • Shapes: Defined as 2D arrays using string representations of the shapes.
    • Color Mapping: Each shape has a specific color.
    • Drawing Functions: draw_window, draw_next_shape, and draw_hold_shape handle all drawing operations.
    • Game Loop: Handles the timing for piece movement, event handling for user input, and game logic such as collision detection and line clearing.
    • Hold Feature: Implemented by storing the current piece in hold_piece when the Shift key is pressed. The hold piece can be swapped back into play.

    Controls:

    • Left Arrow: Move piece left.
    • Right Arrow: Move piece right.
    • Up Arrow: Rotate piece clockwise.
    • Down Arrow: Rotate piece counterclockwise.
    • Shift: Hold the current piece (can only be used once per drop).

    Notes:

    • Ensure you have Pygame installed (pip install pygame).
    • The game window includes additional space on the right to display the next piece and the hold piece.
    • The clear_rows function checks for complete lines and removes them, shifting the above rows down.

    Customization:

    • Adjust Speed: Modify fall_speed in the main function to change how fast pieces fall.
    • Add Score: You can implement a scoring system by keeping track of cleared lines.
    • Sounds and Music: Add sound effects using pygame.mixer for a more immersive experience.

    Feel free to ask if you have any questions or need further modifications!