Creating a fully functional Tetris game in Python is an excellent way to practice your programming skills. Below is a complete Python script using the pygame library, which handles graphics and game logic. Before running the script, make sure you have pygame installed. You can install it using pip:
bash
pip install pygame
Here's the complete Python script for the Tetris game:
python
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# Playfield dimensions
PLAY_WIDTH = 10 * BLOCK_SIZE # 300
PLAY_HEIGHT = 20 * BLOCK_SIZE # 600
PLAY_TOP_LEFT_X = 0
PLAY_TOP_LEFT_Y = 0
# Shapes
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 and corresponding colors
shapes = [S, Z, I, O, J, L, T]
shape_colors = [
(0, 255, 0), # S - Green
(255, 0, 0), # Z - Red
(0, 255, 255), # I - Cyan
(255, 255, 0), # O - Yellow
(255, 165, 0), # J - Orange
(0, 0, 255), # L - Blue
(128, 0, 128) # T - Purple
]
class Piece:
def __init__(self, x, y, shape):
self.x = x # Position on the grid
self.y = y
self.shape = shape
self.color = shape_colors[shapes.index(shape)]
self.rotation = 0 # Number from 0 to len(shape) - 1
def create_grid(locked_positions={}):
grid = [[(0,0,0) for _ in range(10)] for _ in range(20)]
for (x, y) in locked_positions:
grid[y][x] = locked_positions[(x, y)]
return grid
def convert_shape_format(shape):
positions = []
format = shape.shape[shape.rotation % len(shape.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == '0':
positions.append((shape.x + j - 2, shape.y + i - 4))
return positions
def valid_space(shape, grid):
accepted_positions = [[(x, y) for x in range(10) if grid[y][x] == (0,0,0)] for y in range(20)]
accepted_positions = [x for sub in accepted_positions for x in sub]
formatted = convert_shape_format(shape)
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, 1, color)
surface.blit(label, (PLAY_TOP_LEFT_X + PLAY_WIDTH/2 - (label.get_width()/2),
PLAY_TOP_LEFT_Y + PLAY_HEIGHT/2 - label.get_height()/2))
def draw_grid(surface, grid):
sx = PLAY_TOP_LEFT_X
sy = PLAY_TOP_LEFT_Y
for y in range(len(grid)):
pygame.draw.line(surface, (128,128,128), (sx, sy + y*BLOCK_SIZE), (sx + PLAY_WIDTH, sy + y*BLOCK_SIZE))
for x in range(len(grid[y])):
pygame.draw.line(surface, (128,128,128), (sx + x*BLOCK_SIZE, sy), (sx + x*BLOCK_SIZE, sy + PLAY_HEIGHT))
def clear_rows(grid, locked):
# Need to see if row is clear then shift everything down
increment = 0
for y in range(len(grid)-1, -1, -1):
row = grid[y]
if (0,0,0) not in row:
increment += 1
ind = y
for x in range(len(row)):
try:
del locked[(x, y)]
except:
continue
if increment > 0:
# Shift rows down
for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
newKey = (x, y + increment)
locked[newKey] = locked.pop(key)
return increment
def draw_window(surface, grid, score=0):
surface.fill((0,0,0))
font = pygame.font.SysFont('comicsans', 60)
label = font.render('Tetris', 1, (255,255,255))
surface.blit(label, (PLAY_WIDTH /2 - (label.get_width()/2), 30))
# Current Score
font = pygame.font.SysFont('comicsans', 30)
label = font.render(f'Score: {score}', 1, (255,255,255))
sx = PLAY_TOP_LEFT_X + PLAY_WIDTH + 50
sy = PLAY_TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
surface.blit(label, (sx + 20, sy + 160))
for y in range(len(grid)):
for x in range(len(grid[y])):
pygame.draw.rect(surface, grid[y][x],
(PLAY_TOP_LEFT_X + x*BLOCK_SIZE, PLAY_TOP_LEFT_Y + y*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
draw_grid(surface, grid)
pygame.draw.rect(surface, (255, 0, 0),
(PLAY_TOP_LEFT_X, PLAY_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.5
level_time = 0
score = 0
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick()
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
if level_time/1000 > 5:
level_time = 0
if fall_speed > 0.15:
fall_speed -= 0.005
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 +=1
if not valid_space(current_piece, grid):
current_piece.rotation -=1
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
# If piece hits the ground
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
# Clear rows
cleared = clear_rows(grid, locked_positions)
if cleared > 0:
score += cleared * 10
draw_window(win, grid, score)
pygame.display.update()
if check_lost(locked_positions):
draw_text_middle("YOU LOST!", 40, (255,255,255), win)
pygame.display.update()
pygame.time.delay(2000)
run = False
def main_menu(win):
run = True
while run:
win.fill((0,0,0))
draw_text_middle("Press Any Key To Play", 30, (255,255,255), 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__":
win = pygame.display.set_mode((PLAY_WIDTH + 200, PLAY_HEIGHT))
pygame.display.set_caption('Tetris')
main_menu(win) # Start game
Explanation of the Code
Imports and Initialization:
The script starts by importing necessary libraries (pygame, random) and initializing Pygame.
Screen dimensions and playfield settings are defined for the game window.
Shape Definitions:
Each Tetris piece (S, Z, I, O, J, L, T) is defined in a list of rotations. Each shape is represented by a list of strings, where '0' indicates a block present in that position.
Piece Class:
The Piece class represents each Tetris piece, storing its position, shape, color, and rotation state.
Grid Creation and Management:
create_grid: Creates the game grid and populates it with locked (placed) positions.
convert_shape_format: Converts the shape's current rotation into grid positions.
valid_space: Checks if the current piece's position is valid (not colliding or out of bounds).
check_lost: Determines if the player has lost the game by checking if any block is above the visible grid.
Drawing Functions:
draw_text_middle: Renders text at the center of the screen.
draw_grid: Draws the grid lines on the game surface.
draw_window: Draws the entire game window, including the grid, score, and borders.
Game Logic:
clear_rows: Clears completed rows from the grid and updates locked positions.
get_shape: Randomly selects the next Tetris piece.
Main Game Loop (main function):
Manages game state, including piece movement, rotation, collision detection, row clearing, scoring, and increasing game speed over time.
Handles user input for moving and rotating pieces.
Detects game over condition and displays a "YOU LOST!" message.
Main Menu:
main_menu function displays a start screen. Pressing any key starts the game.
Running the Game:
The script initializes the game window and starts the main menu when executed.
Running the Game
Ensure pygame is Installed:
Make sure you have pygame installed. If not, install it using:
bash
pip install pygame
Save the Script:
Save the provided script to a file named, for example, tetris.py.