Creating a Tetris Game Using ChatGPT-4o

Creating a Tetris Game Using ChatGPT-4o

Step 1: Set Up Your Development Environment

1. Install Python:

2. Install Pygame:

  • Open your Command Prompt (Windows) or Terminal (Mac).
  • Install Pygame by typing:

pip install pygame        

Step 2: Create a New Project Folder

1. Create a new folder named Tetris on your desktop.

2. Open the Command Prompt/Terminal and navigate to the folder:

cd path\to\Tetris        

Step 3: Generate the Tetris Game Code

1. Ask ChatGPT to Generate Tetris Game Code:

  • You can use ChatGPT to generate the code. Here’s an example prompt:

Describe Tetris in a way to include all the specifications needed to design the game        

  • After receiving the specifications, prompt ChatGPT to create the complete code:

Great, now create all the code for it        

2. Copy the Generated Code:

  • Copy the entire code provided by ChatGPT.

Step 4: Save the Code

  1. Open any text editor (Notepad++, VSCode, or even the default Notepad).
  2. Paste the copied code into the text editor.
  3. Save the file as Tetris.py in the Tetris folder.

Step 5: Run the Game

  • Double-click the Tetris.py file to run the game. If double-clicking doesn't work, you can run it from the Command Prompt/Terminal:

python Tetris.py        

Step 6: Make Improvements

1. Initial Issues:

  • You may notice initial issues such as incorrect speed, the score not displaying or a grid showing on the screen.
  • Prompt ChatGPT to adjust these issues by specifying what needs fixing. For example:

Remove the gridlines        

  • Copy the updated code provided by ChatGPT, replace the old code in Tetris.py, and save.

2. Enhancements:

  • You can ask ChatGPT for additional features like a smoother down movement or displaying the score:

Make the down arrow key movement smoother and add a score display in the top left corner        

3. Handling Game Over:

  • To handle game over scenarios more gracefully, ask ChatGPT to include a game over screen instead of closing the game abruptly:

Display the final score on a game over screen at the end of the game. On the game over screen give the option to press q to quit or p to play again        

Step 7: Test the Game

1. Run the updated Tetris.py file again to see the changes.

2. Test all functionalities and ensure the game runs smoothly.

Example Code

Here’s a simplified example of what the initial code might look like:

import pygame
import random

# Initialize Pygame
pygame.init()

# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
GRID_WIDTH = SCREEN_WIDTH // BLOCK_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // BLOCK_SIZE

# Colors
COLORS = [
    (0, 0, 0),  # Black (background)
    (0, 255, 255),  # Cyan (I)
    (0, 0, 255),  # Blue (J)
    (255, 165, 0),  # Orange (L)
    (255, 255, 0),  # Yellow (O)
    (0, 255, 0),  # Green (S)
    (128, 0, 128),  # Purple (T)
    (255, 0, 0)  # Red (Z)
]

# Tetromino shapes
SHAPES = [
    [[1, 1, 1, 1]],  # I
    [[1, 0, 0], [1, 1, 1]],  # J
    [[0, 0, 1], [1, 1, 1]],  # L
    [[1, 1], [1, 1]],  # O
    [[0, 1, 1], [1, 1, 0]],  # S
    [[0, 1, 0], [1, 1, 1]],  # T
    [[1, 1, 0], [0, 1, 1]]  # Z
]

# Initialize screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Tetris")

# Define Tetromino class
class Tetromino:
    def __init__(self, shape):
        self.shape = shape
        self.color = COLORS[SHAPES.index(shape) + 1]
        self.x = GRID_WIDTH // 2 - len(shape[0]) // 2
        self.y = 0

    def rotate(self):
        self.shape = [list(row) for row in zip(*self.shape[::-1])]

# Game functions
def create_grid(locked_positions={}):
    grid = [[COLORS[0] 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:
                grid[y][x] = locked_positions[(x, y)]
    return grid

def draw_grid(surface, grid):
    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)

def valid_space(tetromino, grid):
    for y, row in enumerate(tetromino.shape):
        for x, cell in enumerate(row):
            if cell:
                if x + tetromino.x < 0 or x + tetromino.x >= GRID_WIDTH or y + tetromino.y >= GRID_HEIGHT:
                    return False
                if grid[y + tetromino.y][x + tetromino.x] != COLORS[0]:
                    return False
    return True

def clear_lines(grid, locked_positions):
    lines_cleared = 0
    for y in range(GRID_HEIGHT - 1, -1, -1):
        if COLORS[0] not in grid[y]:
            lines_cleared += 1
            del grid[y]
            grid.insert(0, [COLORS[0] for _ in range(GRID_WIDTH)])
            for x in range(GRID_WIDTH):
                try:
                    del locked_positions[(x, y)]
                except:
                    continue
    for x, y in sorted(list(locked_positions), key=lambda pos: pos[1])[::-1]:
        if y < GRID_HEIGHT:
            locked_positions[(x, y + lines_cleared)] = locked_positions.pop((x, y))
    return lines_cleared

def draw_next_shape(tetromino, surface):
    font = pygame.font.SysFont('comicsans', 30)
    label = font.render('Next Shape', 1, (255, 255, 255))
    surface.blit(label, (SCREEN_WIDTH + 10, 30))
    for y, row in enumerate(tetromino.shape):
        for x, cell in enumerate(row):
            if cell:
                pygame.draw.rect(surface, tetromino.color, (SCREEN_WIDTH + 10 + x * BLOCK_SIZE, 60 + y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)

def draw_window(surface, grid, score=0, level=0):
    surface.fill((0, 0, 0))
    font = pygame.font.SysFont('comicsans', 60)
    label = font.render('Tetris', 1, (255, 255, 255))
    surface.blit(label, (SCREEN_WIDTH // 2 - label.get_width() // 2, 30))
    font = pygame.font.SysFont('comicsans', 30)
    label = font.render('Score: ' + str(score), 1, (255, 255, 255))
    surface.blit(label, (10, 10))
    draw_grid(surface, grid)

def game_over_screen(surface, score):
    surface.fill((0, 0, 0))
    font = pygame.font.SysFont('comicsans', 60)
    label = font.render('Game Over', 1, (255, 255, 255))
    surface.blit(label, (SCREEN_WIDTH // 2 - label.get_width() // 2, SCREEN_HEIGHT // 2 - label.get_height() // 2))
    font = pygame.font.SysFont('comicsans', 30)
    label = font.render(f'Final Score: {score}', 1, (255, 255, 255))
    surface.blit(label, (SCREEN_WIDTH // 2 - label.get_width() // 2, SCREEN_HEIGHT // 2 + 30))
    label = font.render('Press P to Play Again or Q to Quit', 1, (255, 255, 255))
    surface.blit(label, (SCREEN_WIDTH // 2 - label.get_width() // 2, SCREEN_HEIGHT // 2 + 60))
    pygame.display.update()

def main():
    locked_positions = {}
    grid = create_grid(locked_positions)
    change_tetromino = False
    run = True
    current_tetromino = Tetromino(random.choice(SHAPES))
    next_tetromino = Tetromino(random.choice(SHAPES))
    clock = pygame.time.Clock()
    fall_time = 0
    fall_speed = 0.3
    score = 0
    level = 0

    while run:
        grid = create_grid(locked_positions)
        fall_time += clock.get_rawtime()
        clock.tick()

        if fall_time / 1000 >= fall_speed:
            fall_time = 0
            current_tetromino.y += 1
            if not valid_space(current_tetromino, grid) and current_tetromino.y > 0:
                current_tetromino.y -= 1
                change_tetromino = True

        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_tetromino.x -= 1
                    if not valid_space(current_tetromino, grid):
                        current_tetromino.x += 1
                if event.key == pygame.K_RIGHT:
                    current_tetromino.x += 1
                    if not valid_space(current_tetromino, grid):
                        current_tetromino.x -= 1
                if event.key == pygame.K_DOWN:
                    current_tetromino.y += 1
                    if not valid_space(current_tetromino, grid):
                        current_tetromino.y -= 1
                if event.key == pygame.K_UP:
                    current_tetromino.rotate()
                    if not valid_space(current_tetromino, grid):
                        current_tetromino.rotate()
                        current_tetromino.rotate()
                        current_tetromino.rotate()
                if event.key == pygame.K_SPACE:
                    while valid_space(current_tetromino, grid):
                        current_tetromino.y += 1
                    current_tetromino.y -= 1
                    change_tetromino = True

        shape_pos = [[current_tetromino.x + x, current_tetromino.y + y] for y, row in enumerate(current_tetromino.shape) for x, cell in enumerate(row) if cell]

        for pos in shape_pos:
            p = (pos[0], pos[1])
            if p[1] > -1:
                grid[p[1]][p[0]] = current_tetromino.color

        if change_tetromino:
            for pos in shape_pos:
                p = (pos[0], pos[1])
                locked_positions[p] = current_tetromino.color
            current_tetromino = next_tetromino
            next_tetromino = Tetromino(random.choice(SHAPES))
            change_tetromino = False
            score += clear_lines(grid, locked_positions) * 100

        draw_window(screen, grid, score, level)
        draw_next_shape(next_tetromino, screen)
        pygame.display.update()

        if any(y < 1 for x, y in locked_positions):
            run = False

    while True:
        game_over_screen(screen, score)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    pygame.quit()
                    quit()
                if event.key == pygame.K_p:
                    main()

def main_menu():
    run = True
    while run:
        screen.fill((0, 0, 0))
        font = pygame.font.SysFont('comicsans', 60)
        label = font.render('Press Any Key To Play', 1, (255, 255, 255))
        screen.blit(label, (SCREEN_WIDTH // 2 - label.get_width() // 2, SCREEN_HEIGHT // 2 - label.get_height() // 2))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                main()
    pygame.quit()

main_menu()
        

Conclusion

Creating a Tetris game with ChatGPT-4.0 is a straightforward process. By leveraging the AI's capabilities, you can quickly generate the code, refine it, and add custom features to enhance the gameplay experience. This step-by-step guide should help you get started and explore the possibilities of AI-assisted game development.

Paul Hankin is the author of:

AI Adoption: A Practical Guide for Business

and

AI and Law: Navigating the Future

要查看或添加评论,请登录

社区洞察

其他会员也浏览了