Creating a fully functional Tetris game in Python can be an exciting project! Below is a complete Python script using the pygame library to implement Tetris. This script includes all the essential features of the game, such as piece movement, rotation, line clearing, scoring, and game-over detection.
Prerequisites
Before running the script, ensure you have Python installed on your system. Additionally, you'll need to install the pygame library. You can install it using pip:
pip install pygame
Tetris Game Script
import pygame
import random
# Initialize Pygame
pygame.init()
# Define game constants
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
PLAY_WIDTH = 10 * BLOCK_SIZE # 300
PLAY_HEIGHT = 20 * BLOCK_SIZE # 600
TOP_LEFT_X = (SCREEN_WIDTH - PLAY_WIDTH) // 2
TOP_LEFT_Y = SCREEN_HEIGHT - PLAY_HEIGHT - 50
# Define the shapes of the pieces
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
SHAPES = [S, Z, I, O, J, L, T]
# Corresponding colors for each shape
SHAPE_COLORS = [pygame.Color('green'), pygame.Color('red'), pygame.Color('cyan'),
pygame.Color('yellow'), pygame.Color('blue'), pygame.Color('orange'),
pygame.Color('purple')]
# Define the Piece class
class Piece:
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
# Utility functions
def create_grid(locked_positions={}):
grid = [[pygame.Color('black') for _ in range(10)] for _ in range(20)]
for (x, y), color in locked_positions.items():
if y < 20:
grid[y][x] = color
return grid
def convert_shape_format(piece):
positions = []
shape = piece.shape[piece.rotation % len(piece.shape)]
for i, line in enumerate(shape):
row = list(line)
for j, column in enumerate(row):
if column == '0':
positions.append((piece.x + j - 2, piece.y + i - 4))
return positions
def valid_space(piece, grid):
accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == pygame.Color('black')] for i in range(20)]
accepted_positions = [j for sub in accepted_positions for j in sub]
formatted = convert_shape_format(piece)
for pos in formatted:
if pos not in accepted_positions:
if pos[1] > -1:
return False
return True
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
def get_shape():
return Piece(5, 0, random.choice(SHAPES))
def draw_text_middle(text, size, color, surface):
font = pygame.font.SysFont('comicsans', size, bold=True)
label = font.render(text, True, 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 draw_grid(surface, grid):
sx = TOP_LEFT_X
sy = TOP_LEFT_Y
for i in range(len(grid)):
pygame.draw.line(surface, pygame.Color('gray'), (sx, sy + i*BLOCK_SIZE),
(sx + PLAY_WIDTH, sy + i*BLOCK_SIZE))
for j in range(len(grid[i])):
pygame.draw.line(surface, pygame.Color('gray'), (sx + j*BLOCK_SIZE, sy),
(sx + j*BLOCK_SIZE, sy + PLAY_HEIGHT))
def clear_rows(grid, locked):
cleared = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if pygame.Color('black') not in row:
cleared += 1
del grid[i]
grid.insert(0, [pygame.Color('black') for _ in range(10)])
# Adjust locked positions
locked = {(x, y - 1): color for (x, y), color in locked.items() if y < i}
return cleared, locked
def draw_next_shape(piece, surface):
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', True, pygame.Color('white'))
sx = TOP_LEFT_X + PLAY_WIDTH + 50
sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
shape = piece.shape[piece.rotation % len(piece.shape)]
for i, line in enumerate(shape):
row = list(line)
for j, column in enumerate(row):
if column == '0':
pygame.draw.rect(surface, piece.color,
(sx + j*BLOCK_SIZE, sy + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
surface.blit(label, (sx + 10, sy - 30))
def draw_window(surface, grid, score=0):
surface.fill(pygame.Color('black'))
# Title
font = pygame.font.SysFont('comicsans', 60)
label = font.render('Tetris', True, pygame.Color('white'))
surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH / 2 - (label.get_width() / 2), 30))
# Current Score
font = pygame.font.SysFont('comicsans', 30)
label = font.render(f'Score: {score}', True, pygame.Color('white'))
sx = TOP_LEFT_X - 200
sy = TOP_LEFT_Y + 200
surface.blit(label, (sx + 20, sy + 160))
# Draw grid
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 grid lines
draw_grid(surface, grid)
# Draw border
pygame.draw.rect(surface, pygame.Color('white'),
(TOP_LEFT_X, TOP_LEFT_Y, PLAY_WIDTH, PLAY_HEIGHT), 5)
def main(win):
locked_positions = {}
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
fall_speed = 0.27
level_time = 0
score = 0
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick()
# Increase speed over time
if level_time / 1000 > 5:
level_time = 0
if fall_speed > 0.12:
fall_speed -= 0.005
# Handle 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
change_piece = True
# 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:
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)
shape_pos = convert_shape_format(current_piece)
# Add piece to the grid for drawing
for pos in shape_pos:
x, y = pos
if y > -1:
grid[y][x] = current_piece.color
# Check if piece needs to be locked
if change_piece:
for pos in shape_pos:
x, y = pos
locked_positions[(x, y)] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
# Clear rows
cleared, locked_positions = clear_rows(grid, locked_positions)
if cleared > 0:
score += cleared ** 2 * 100
# Check for game over
if check_lost(locked_positions):
run = False
draw_window(win, grid, score)
draw_next_shape(next_piece, win)
pygame.display.update()
draw_text_middle("YOU LOST", 80, pygame.Color('white'), win)
pygame.display.update()
pygame.time.delay(2000)
def main_menu():
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
run = True
while run:
win.fill(pygame.Color('black'))
draw_text_middle('Press Any Key to Play', 60, pygame.Color('white'), win)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
main(win)
pygame.quit()
if __name__ == '__main__':
main_menu()
How to Run the Game
-
Save the Script: Save the above script to a file named tetris.py.
-
Install Pygame: Ensure you have pygame installed. If not, install it using:
pip install pygame
-
Run the Script: Execute the script using Python:
python tetris.py
Game Controls
- Left Arrow: Move the piece left.
- Right Arrow: Move the piece right.
- Down Arrow: Move the piece down faster.
- Up Arrow: Rotate the piece clockwise.
Game Features
- Piece Movement & Rotation: Use arrow keys to navigate and rotate the Tetris pieces.
- Line Clearing: Complete lines are cleared, and the score increases based on the number of lines cleared simultaneously.
- Next Piece Preview: Displays the next piece that will appear.
- Increasing Difficulty: The game speed increases over time, making it progressively more challenging.
- Game Over Detection: The game ends when the stacked pieces reach the top of the play area.
Customization
Feel free to modify the script to enhance the game further. You can add features like:
- Sound Effects: Incorporate sounds for actions like moving, rotating, and clearing lines.
- Different Levels: Implement multiple levels with varying speeds.
- High Score Tracking: Keep track of high scores across game sessions.
- Graphical Enhancements: Improve the visual aspects with better graphics or animations.
Enjoy playing your own Tetris game built with Python!