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:
-
Import the necessary libraries:
pygamefor creating the game andrandomfor generating random tetrominoes. -
Initialize pygame and set up the game window.
-
Define the colors used in the game.
-
Define the size of each block in the grid and calculate the number of rows and columns based on the window size.
-
Define the shapes of the tetrominoes using nested lists.
-
Define the colors of the tetrominoes.
-
Define the initial position of the falling tetromino.
-
Define the initial score.
-
Create the grid using a nested list.
-
Define functions to draw the grid, draw a tetromino, check for collisions, clear full rows, and end the game.
-
Define the main game loop function
tetris_game(). -
Inside the game loop, generate a random tetromino and set its initial position.
-
Handle user input to move and rotate the tetromino.
-
Check for collisions and update the tetromino’s position accordingly.
-
If the tetromino collides with the bottom or another tetromino, add it to the grid and check for full rows.
-
If a full row is found, remove it and shift the rows above it down.
-
Generate a new random tetromino and reset its position.
-
If the new tetromino collides with the top of the grid, end the game.
-
Update the game window with the grid and tetromino.
-
Limit the frame rate to control the speed of the game.
-
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.
Loading...