Creating a Tetris game in Python is a great way to practice your programming and game development skills. Below is a complete Python script using the pygame library to create a functional Tetris game.
Prerequisites
-
Python Installation: Make sure you have Python installed on your system. You can download it from python.org.
-
Install Pygame: pygame is a popular library for creating games in Python. You can install it using pip:
pip install pygame
Tetris Game Script
Here's the complete Python script for the Tetris game:
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# Play area dimensions
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
# Define 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 their 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 # x position on the grid
self.y = y # y position on the grid
self.shape = shape
self.color = shape_colors[shapes.index(shape)]
self.rotation = 0 # number from 0-3
def create_grid(locked_positions={}):
grid = [[(0,0,0) for _ in range(10)] for _ in range(20)]
for i in range(len(grid)):
for j in range(len(grid[i])):
if (j, i) in locked_positions:
grid[i][j] = locked_positions[(j,i)]
return grid
def convert_shape_format(piece):
positions = []
format = piece.shape[piece.rotation % len(piece.shape)]
for i, line in enumerate(format):
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] == (0,0,0)] 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, 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 draw_grid(surface, grid):
sx = TOP_LEFT_X
sy = TOP_LEFT_Y
for i in range(len(grid)):
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[i])):
pygame.draw.line(surface, (128,128,128), (sx + j*BLOCK_SIZE, sy), (sx + j * BLOCK_SIZE, sy + PLAY_HEIGHT))
def clear_rows(grid, locked):
# Need to see if row is clear then shift every other row above down
inc = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if (0,0,0) not in row:
inc += 1
# Remove the row from locked
ind = i
for j in range(len(row)):
try:
del locked[(j, i)]
except:
continue
if inc > 0:
# Shift every row above down
keys = sorted(list(locked), key=lambda x: x[1])
for key in keys:
x, y = key
if y < ind:
newKey = (x, y + inc)
locked[newKey] = locked.pop(key)
return inc
def draw_next_shape(piece, surface):
font = pygame.font.SysFont("comicsans", 30)
label = font.render("Next Shape", 1, (255,255,255))
sx = TOP_LEFT_X + PLAY_WIDTH + 50
sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
format = piece.shape[piece.rotation % len(piece.shape)]
for i, line in enumerate(format):
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 update_score(nscore):
score = max_score()
with open('scores.txt', 'w') as f:
if int(score) > nscore:
f.write(str(score))
else:
f.write(str(nscore))
def max_score():
try:
with open('scores.txt', 'r') as f:
lines = f.readlines()
score = lines[0].strip()
except:
score = '0'
return score
def draw_window(surface, grid, score=0, last_score=0):
surface.fill((0,0,0))
pygame.font.init()
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))
# Current Score
font = pygame.font.SysFont("comicsans", 30)
label = font.render(f"Score: {score}", 1, (255,255,255))
sx = TOP_LEFT_X + PLAY_WIDTH + 50
sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
surface.blit(label, (sx, sy + 200))
# High Score
label = font.render(f"High Score: {last_score}", 1, (255,255,255))
surface.blit(label, (sx, sy + 250))
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 and border
draw_grid(surface, grid)
pygame.draw.rect(surface, (255,0,0),
(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
last_score = max_score()
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick()
# Increase speed as time goes on
if level_time / 1000 > 5:
level_time = 0
if fall_speed > 0.12:
fall_speed -= 0.005
# Handle 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
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
# If piece hit 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
score += clear_rows(grid, locked_positions) * 10
if check_lost(locked_positions):
run = False
draw_window(win, grid, score, last_score)
draw_next_shape(next_piece, win)
pygame.display.update()
update_score(score)
draw_text_middle("YOU LOST!", 40, (255,255,255), win)
pygame.display.update()
pygame.time.delay(2000)
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()
# Create the game window
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
# Start the game
main_menu(win) # Start with the main menu
How to Run the Game
-
Save the Script: Copy the above script into a file named tetris.py.
-
Run the Script: Open your terminal or command prompt, navigate to the directory containing tetris.py, and run:
python tetris.py
-
Play the Game:
- Left Arrow: Move the piece left.
- Right Arrow: Move the piece right.
- Down Arrow: Move the piece down faster.
- Up Arrow: Rotate the piece.
Features
- Random Shape Generation: The game randomly generates one of the seven standard Tetris shapes.
- Rotation: You can rotate the pieces using the up arrow key.
- Clearing Lines: Complete lines are cleared, and you earn points.
- Next Piece Preview: See the next piece that will appear.
- Score Tracking: Displays the current score and keeps track of the high score.
- Game Over Detection: The game ends when the stack of pieces reaches the top of the play area.
Customization
Feel free to customize the game further by adding features such as:
- Levels: Increase the difficulty as the player progresses.
- Sound Effects: Add sound effects for actions like moving pieces or clearing lines.
- Better Graphics: Enhance the visual appearance with improved graphics and animations.
- Pause Functionality: Allow the game to be paused and resumed.
Troubleshooting
- Pygame Not Installed: Ensure that
pygame is installed. If you encounter an error related to pygame, install it using pip install pygame.
- File Permissions: If you encounter issues with writing the high score to
scores.txt, ensure that the script has the necessary permissions to create and write to files in its directory.
Enjoy your Tetris game!