Create your own
teaching resources

Sign up for a free account to try! It takes less than 20 seconds

Teacherbot 07 Nov, 16:31:57

Sure! Here’s an example of a Tetris game code in Python with explanations:

```python import pygame import random

Initialize pygame

pygame.init()

Set up the game window

window_width = 800 window_height = 600 window = pygame.display.set_mode((window_width, window_height)) pygame.display.set_caption(“Tetris”)

Define colors

black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) cyan = (0, 255, 255) magenta = (255, 0, 255) yellow = (255, 255, 0) orange = (255, 165, 0)

Define the size of each block in the grid

block_size = 30

Define the number of rows and columns in the grid

rows = window_height // block_size columns = window_width // block_size

Define the shapes of the tetrominoes

tetrominoes = [ [[1, 1, 1, 1]], # I-shape [[1, 1], [1, 1]], # O-shape [[1, 1, 1], [0, 1, 0]], # T-shape [[1, 1, 0], [0, 1, 1]], # Z-shape [[0, 1, 1], [1, 1, 0]], # S-shape [[1, 1, 1], [0, 0, 1]], # J-shape [[1, 1, 1], [1, 0, 0]] # L-shape ]

Define the colors of the tetrominoes

tetromino_colors = [cyan, yellow, magenta, green, red, blue, orange]

Define the initial position of the falling tetromino

initial_x = columns // 2 initial_y = 0

Define the initial score

score = 0

Define the grid

grid = [[black for _ in range(columns)] for _ in range(rows)]

def draw_grid(): for row in range(rows): for column in range(columns): pygame.draw.rect(window, grid[row][column], (column * block_size, row * block_size, block_size, block_size))

def draw_tetromino(tetromino, x, y, color): for row in range(len(tetromino)): for column in range(len(tetromino[row])): if tetromino[row][column] == 1: pygame.draw.rect(window, color, ((x + column) * block_size, (y + row) * block_size, block_size, block_size))

def is_collision(tetromino, x, y): for row in range(len(tetromino)): for column in range(len(tetromino[row])): if tetromino[row][column] == 1: if x + column < 0 or x + column >= columns or y + row >= rows or grid[y + row][x + column] != black: return True return False

def clear_rows(): global score full_rows = [] for row in range(rows): if all(color != black for color in grid[row]): full_rows.append(row) for row in full_rows: del grid[row] grid.insert(0, [black for _ in range(columns)]) score += 1

def game_over(): pygame.quit() quit()

def tetris_game(): global score tetromino_index = random.randint(0, len(tetrominoes) - 1) tetromino = tetrominoes[tetromino_index] tetromino_color = tetromino_colors[tetromino_index] x = initial_x y = initial_y

clock = pygame.time.Clock()
game_over_flag = False

while not game_over_flag:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                if not is_collision(tetromino, x - 1, y):
                    x -= 1
            elif event.key == pygame.K_RIGHT:
                if not is_collision(tetromino, x + 1, y):
                    x += 1
            elif event.key == pygame.K_DOWN:
                if not is_collision(tetromino, x, y + 1):
                    y += 1
            elif event.key == pygame.K_UP:
                rotated_tetromino = list(zip(*reversed(tetromino)))
                if not is_collision(rotated_tetromino, x, y):
                    tetromino = rotated_tetromino

    if not is_collision(tetromino, x, y + 1):
        y += 1
    else:
        for row in range(len(tetromino)):
            for column in range(len(tetromino[row])):
                if tetromino[row][column] == 1:
                    grid[y + row][x + column] = tetromino_color
        clear_rows()
        tetromino_index = random.randint(0, len(tetrominoes) - 1)
        tetromino = tetrominoes[tetromino_index]
        tetromino_color = tetromino_colors[tetromino_index]
        x = initial_x
        y = initial_y

        if is_collision(tetromino, x, y):
            game_over_flag = True

    window.fill(black)
    draw_grid()
    draw_tetromino(tetromino, x, y, tetromino_color)
    pygame.display.update()
    clock.tick(10)

game_over()

tetris_game() ```

Explanation:

  1. Import the necessary libraries: pygame for creating the game and random for generating random tetrominoes.

  2. Initialize pygame and set up the game window.

  3. Define the colors used in the game.

  4. Define the size of each block in the grid and calculate the number of rows and columns based on the window size.

  5. Define the shapes of the tetrominoes using nested lists.

  6. Define the colors of the tetrominoes.

  7. Define the initial position of the falling tetromino.

  8. Define the initial score.

  9. Create the grid using a nested list.

  10. Define functions to draw the grid, draw a tetromino, check for collisions, clear full rows, and end the game.

  11. Define the main game loop function tetris_game().

  12. Inside the game loop, generate a random tetromino and set its initial position.

  13. Handle user input to move and rotate the tetromino.

  14. Check for collisions and update the tetromino’s position accordingly.

  15. If the tetromino collides with the bottom or another tetromino, add it to the grid and check for full rows.

  16. If a full row is found, remove it and shift the rows above it down.

  17. Generate a new random tetromino and reset its position.

  18. If the new tetromino collides with the top of the grid, end the game.

  19. Update the game window with the grid and tetromino.

  20. Limit the frame rate to control the speed of the game.

  21. Call the tetris_game() function to start the game.

This code provides a basic implementation of the Tetris game in Python using the Pygame library. You can further enhance the game by adding features like a scoring system, level progression, and user interface elements.