Okay, here's a Python implementation of a Tetris clone using the Pygame library.
Prerequisites:
You'll need to install Pygame:
pip install pygame
tetris.py
import pygame
import random
# --- Constants ---
SCREEN_WIDTH = 400 # Width of the game window
SCREEN_HEIGHT = 600 # Height of the game window
PLAY_WIDTH = 300 # Width of the play area (10 blocks)
PLAY_HEIGHT = 600 # Height of the play area (20 blocks)
BLOCK_SIZE = 30
TOP_LEFT_X = (SCREEN_WIDTH - PLAY_WIDTH) // 2
TOP_LEFT_Y = SCREEN_HEIGHT - PLAY_HEIGHT
# --- Shapes ---
# Shape formats: list of lists of (row, col) offsets
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..',
'.....']]
SHAPES = [S, Z, I, O, J, L, T]
SHAPE_COLORS = [
(0, 255, 0), # Green (S)
(255, 0, 0), # Red (Z)
(0, 255, 255), # Cyan (I)
(255, 255, 0), # Yellow (O)
(0, 0, 255), # Blue (J)
(255, 165, 0), # Orange (L)
(128, 0, 128) # Purple (T)
]
# --- Piece Class ---
class Piece:
def __init__(self, column, row, shape):
self.x = column
self.y = row
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0 # current rotation index
def get_formatted_shape(self):
# Returns the actual coordinates of the blocks for the current rotation
positions = []
shape_format = self.shape[self.rotation % len(self.shape)] # Current rotation
for i, line in enumerate(shape_format):
row = list(line)
for j, column in enumerate(row):
if column == '0':
positions.append((self.x + j, self.y + i))
# Offset positions to be relative to the piece's top-left corner
# This makes collision detection easier
for i, pos in enumerate(positions):
positions[i] = (pos[0] - 2, pos[1] - 4) # Adjust based on 5x5 grid
return positions
# --- Game Functions ---
def create_grid(locked_positions={}):
# 10 columns, 20 rows
grid = [[(0,0,0) for _ in range(10)] for _ in range(20)] # (0,0,0) is black
for r in range(len(grid)):
for c in range(len(grid[r])):
if (c,r) in locked_positions:
color = locked_positions[(c,r)]
grid[r][c] = color
return grid
def get_shape():
return Piece(5, 0, random.choice(SHAPES)) # Start piece in middle-top
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':
# Add offset for the piece's current position on the board
positions.append((piece.x + j, piece.y + i))
# Normalize positions to be relative to the piece's top-left for grid placement
# The 5x5 representation often has padding, this adjusts for it.
# These values might need slight tuning based on how shapes are defined.
offset_x = min(p[0] for p in positions) if positions else 0
offset_y = min(p[1] for p in positions) if positions else 0
final_positions = []
for pos in positions:
final_positions.append((pos[0] - offset_x, pos[1] - offset_y))
# This part is tricky and depends heavily on how the SHAPES are defined.
# The goal is to get grid coordinates.
# Let's use the simpler get_formatted_shape method for collision
return piece.get_formatted_shape()
def valid_space(piece, grid):
# Get all (col, row) positions on the grid that are accepted (empty)
accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == (0,0,0)] for i in range(20)]
accepted_positions = [j for sub in accepted_positions for j in sub] # Flatten list
formatted = convert_shape_format(piece)
for pos in formatted:
# Check if position is within bounds and not occupied
if not (0 <= pos[0] < 10 and 0 <= pos[1] < 20): # Check X and Y bounds
return False
if pos not in accepted_positions: # Check if it's an empty cell
# Ensure we're not checking a part of the piece that is above the play area
# (e.g., during initial spawn or after a rotation)
if pos[1] >= 0: # Only consider positions within the visible grid for collision
return False
return True
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1: # If any locked piece is in the top row (or above)
return True
return False
def clear_rows(grid, locked):
increment = 0 # Number of rows cleared
new_locked = {}
# Iterate from bottom up
for i in range(len(grid)-1, -1, -1):
row_full = True
for j in range(len(grid[i])):
if grid[i][j] == (0,0,0): # If any cell in the row is empty
row_full = False
break
if row_full:
increment += 1
# Mark row for clearing (or rather, don't copy it to new_locked)
else:
# If row is not full, copy its locked pieces to new_locked, shifted down by 'increment'
for j in range(len(grid[i])):
if (j, i) in locked:
new_locked[(j, i + increment)] = locked[(j,i)]
return increment, new_locked
def draw_grid_lines(surface, grid):
sx = TOP_LEFT_X
sy = TOP_LEFT_Y
for i in range(len(grid)): # Rows
pygame.draw.line(surface, (128,128,128), (sx, sy + i*BLOCK_SIZE), (sx + PLAY_WIDTH, sy + i*BLOCK_SIZE))
for j in range(len(grid[0])+1): # Columns
pygame.draw.line(surface, (128,128,128), (sx + j*BLOCK_SIZE, sy), (sx + j*BLOCK_SIZE, sy + PLAY_HEIGHT))
def draw_window(surface, grid, score=0, level=0, last_score=0):
surface.fill((0,0,0)) # Black background
# Title
font = pygame.font.SysFont('comicsans', 60)
label = font.render('TETRIS', 1, (255,255,255))
surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH / 2 - (label.get_width() / 2), 30))
# Score
font = pygame.font.SysFont('comicsans', 30)
label_score = font.render('Score: ' + str(score), 1, (255,255,255))
sx = TOP_LEFT_X + PLAY_WIDTH + 20
sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
surface.blit(label_score, (sx + 10, sy + 150))
# Level
label_level = font.render('Level: ' + str(level), 1, (255,255,255))
surface.blit(label_level, (sx + 10, sy + 180))
# Last Score (optional, if you implement high score)
# label_last = font.render('High Score: ' + str(last_score), 1, (255,255,255))
# surface.blit(label_last, (sx + 10, sy + 210))
# Draw the game grid (locked pieces)
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j],
(TOP_LEFT_X + j*BLOCK_SIZE, TOP_LEFT_Y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
# Draw border around play area
pygame.draw.rect(surface, (255,0,0), (TOP_LEFT_X, TOP_LEFT_Y, PLAY_WIDTH, PLAY_HEIGHT), 4)
draw_grid_lines(surface, grid)
# pygame.display.update() # Moved to main loop
def draw_next_shape(shape, surface):
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', 1, (255,255,255))
sx = TOP_LEFT_X + PLAY_WIDTH + 20
sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
surface.blit(label, (sx + 10, sy + 0))
# Get the first rotation of the shape
shape_format = shape.shape[0] # Use the first rotation for display
# Center the preview shape
preview_grid_x = sx + 20
preview_grid_y = sy + 40
for i, line in enumerate(shape_format):
row = list(line)
for j, column in enumerate(row):
if column == '0':
pygame.draw.rect(surface, shape.color,
(preview_grid_x + j*BLOCK_SIZE, preview_grid_y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
def main(win):
locked_positions = {} # (x,y): (R,G,B)
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
level_time = 0
score = 0
level = 1
fall_speed = 0.27 # seconds per step down, decreases with level
while run:
grid = create_grid(locked_positions) # Update grid with locked pieces
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick() # This ensures game runs at a consistent speed relative to fall_time
# --- Leveling ---
if level_time/1000 > 15: # Increase level every 15 seconds (or by lines)
level_time = 0
if fall_speed > 0.12: # Cap speed
fall_speed -= 0.005 * level # Speed up slightly more at higher levels
level +=1
# --- Piece Falling ---
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 # Revert move
change_piece = True # Lock piece
# --- Event Handling ---
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_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
elif event.key == pygame.K_RIGHT:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
elif event.key == pygame.K_DOWN:
current_piece.y += 1
if not valid_space(current_piece, grid):
current_piece.y -= 1
elif event.key == pygame.K_UP: # Rotate
current_piece.rotation = (current_piece.rotation + 1) % len(current_piece.shape)
if not valid_space(current_piece, grid):
current_piece.rotation = (current_piece.rotation - 1 + len(current_piece.shape)) % len(current_piece.shape) # Revert
# --- Add Piece to Grid ---
shape_pos = convert_shape_format(current_piece)
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1: # Only draw if within the visible grid bounds
# The grid array indices are (row, col) which is (y, x)
if 0 <= y < len(grid) and 0 <= x < len(grid[0]):
grid[y][x] = current_piece.color
# --- Lock Piece and Check for Cleared Rows ---
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
rows_cleared, locked_positions = clear_rows(grid, locked_positions) # Update locked_positions
if rows_cleared > 0:
score += rows_cleared * 10 * level # Basic scoring
# You can add more complex scoring (e.g., Tetris bonus)
if rows_cleared == 1: score += 40 * level
elif rows_cleared == 2: score += 100 * level
elif rows_cleared == 3: score += 300 * level
elif rows_cleared >= 4: score += 1200 * level # Tetris!
grid = create_grid(locked_positions) # Recreate grid with potentially cleared rows
# --- Draw Everything ---
draw_window(win, grid, score, level)
draw_next_shape(next_piece, win)
pygame.display.update()
# --- Check Game Over ---
if check_lost(locked_positions):
draw_text_middle(win, "YOU LOST!", 80, (255,255,255))
pygame.display.update()
pygame.time.delay(2000) # Pause for 2 seconds
run = False
# update_score(score) # If you implement high score saving
def draw_text_middle(surface, text, size, color):
font = pygame.font.SysFont("comicsans", size, bold=True)
label = font.render(text, 1, color)
surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH/2 - (label.get_width()/2),
TOP_LEFT_Y + PLAY_HEIGHT/2 - label.get_height()/2))
def main_menu(win):
run = True
while run:
win.fill((0,0,0))
draw_text_middle(win, 'Press Any Key To Play', 60, (255,255,255))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
main(win) # Start the game
pygame.quit()
if __name__ == '__main__':
pygame.font.init()
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Python Tetris')
main_menu(win)
How to Run:
- Save the code above as
tetris.py.
- Make sure Pygame is installed (
pip install pygame).
- Open a terminal or command prompt, navigate to the directory where you saved the file, and run:
python tetris.py
Explanation and Features:
- Constants: Define screen dimensions, play area, block size.
- Shapes (Tetrominoes):
S, Z, I, O, J, L, T are defined as lists of 5x5 grids using '.' for empty and '0' for a block.
- Each shape has a list of its possible rotations.
SHAPE_COLORS maps each shape type to a color.
Piece Class:
- Represents a single Tetris piece.
- Stores its
x, y (column, row on the grid, not pixel coordinates), shape type, color, and current rotation.
get_formatted_shape(): A crucial method that converts the 5x5 string representation of the current rotation into a list of (column, row) coordinates on the game grid. This is important for collision detection and drawing.
- Game Logic Functions:
create_grid(locked_positions): Creates a 2D list representing the playfield (10x20). (0,0,0) (black) means empty. locked_positions is a dictionary {(col, row): color} storing pieces that have already landed.
get_shape(): Returns a new random Piece object, positioned at the top-middle.
convert_shape_format(piece): Similar to Piece.get_formatted_shape(), gets the grid coordinates of the piece's blocks.
valid_space(piece, grid): Checks if the piece's current position and rotation are valid (within bounds and not colliding with locked pieces).
check_lost(positions): Determines if any locked piece has reached the top of the screen.
clear_rows(grid, locked):
- Iterates through the grid from bottom to top.
- If a row is full, it's "cleared."
- Rows above cleared rows are shifted down.
- Updates the
locked_positions dictionary.
- Returns the number of rows cleared (for scoring).
draw_grid_lines(surface, grid): Draws the light gray grid lines on the play area.
draw_window(surface, grid, score, level): The main drawing function. It fills the background, draws the title, score, level, the play area border, and all the locked pieces on the grid.
Potential Improvements (Further Steps):
- "Ghost" Piece: Show a semi-transparent outline of where the piece will land.
- Hard Drop: (e.g., Spacebar) Instantly drops the piece to the bottom.
- Hold Piece: Allow the player to swap the current piece with a "held" piece once per turn.
- Wall Kicks/SRS: Implement more advanced rotation systems like the Super Rotation System for smoother rotations near walls or other pieces.
- Sound Effects: Add sounds for movement, rotation, line clear, game over.
- Music: Background music.
- High Score: Save and display high scores (e.g., in a text file).
- Pause Menu: Allow pausing the game.
- More Sophisticated Scoring: Different points for T-spins, back-to-back Tetris, etc.
- Difficulty Curve: Base level increase on lines cleared rather than just time.
This implementation provides a solid foundation for a Tetris game. Enjoy playing and customizing it!