Sure! Below is a complete Python script for a basic implementation of the classic Tetris game using the pygame library. This script covers the essential features of Tetris, including piece generation, movement, rotation, collision detection, line clearing, scoring, and game over conditions.
Prerequisites
-
Python Installation: Make sure you have Python installed on your system. You can download it from python.org.
-
Pygame Installation: This script uses the pygame library for handling graphics and game mechanics. Install it using pip:
pip install pygame
Tetris Game Script
import pygame
import random
# Initialize Pygame
pygame.init()
# Global Variables
s_width = 800
s_height = 700
play_width = 300 # 300 // 10 = 30 width per block
play_height = 600 # 600 // 20 = 30 height per block
block_size = 30
top_left_x = (s_width - play_width) // 2
top_left_y = s_height - play_height - 50
# 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
shapes = [S, Z, I, O, J, L, T]
shape_colors = [
(0, 255, 0), # S
(255, 0, 0), # Z
(0, 255, 255), # I
(255, 255, 0), # O
(255, 165, 0), # J
(0, 0, 255), # L
(128, 0, 128) # T
]
# Define the Piece class
class Piece:
def __init__(self, x, y, shape):
self.x = x # horizontal position
self.y = y # vertical position
self.shape = shape
self.color = shape_colors[shapes.index(shape)]
self.rotation = 0 # rotation state
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(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 = [[(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(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, (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):
inc = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if (0,0,0) not in row:
inc +=1
ind = i
for j in range(len(row)):
try:
del locked[(j,i)]
except:
continue
if inc > 0:
for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
newKey = (x, y + inc)
locked[newKey] = locked.pop(key)
return inc
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 + 50
sy = top_left_y + play_height/2 - 100
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':
pygame.draw.rect(surface, shape.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 + 20, sy + 160))
# High Score
label = font.render(f'High Score: {last_score}', 1, (255,255,255))
sx = top_left_x - 200
sy = top_left_y + 200
surface.blit(label, (sx + 20, sy + 160))
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)
pygame.draw.rect(surface, (255, 0, 0),
(top_left_x, top_left_y, play_width, play_height), 5)
draw_grid(surface, grid)
# pygame.display.update()
def main(win):
last_score = max_score()
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
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 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
# Clear rows
cleared = clear_rows(grid, locked_positions)
if cleared > 0:
score += cleared * 10
draw_window(win, grid, score, last_score)
draw_next_shape(next_piece, win)
pygame.display.update()
# Check for loss
if check_lost(locked_positions):
draw_text_middle("YOU LOST!", 80, (255,255,255), win)
pygame.display.update()
pygame.time.delay(1500)
run = False
update_score(score)
def main_menu(win):
run = True
while run:
win.fill((0,0,0))
draw_text_middle("Press Any Key To Play", 60, (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 Pygame window
win = pygame.display.set_mode((s_width, s_height))
pygame.display.set_caption('Tetris')
main_menu(win) # Start the game
Explanation of the Script
-
Imports and Initialization:
- The script begins by importing necessary modules and initializing Pygame.
-
Global Variables:
- Defines the screen dimensions, play area dimensions, and block size.
- Calculates the top-left coordinates to center the play area.
-
Shapes Definition:
- Each Tetris piece (S, Z, I, O, J, L, T) is defined with their rotation states using multi-line strings.
-
Piece Class:
- Represents a Tetris piece with its position, shape, color, and rotation state.
-
Grid Creation and Handling:
create_grid: Creates the game grid and populates it with locked positions.
convert_shape_format: Converts the piece's shape into grid positions.
valid_space: Checks if the current position of the piece is valid (no collisions).
check_lost: Determines if the game is over.
-
Drawing Functions:
draw_text_middle: Renders text in the middle of the screen (used for game over and menu).
draw_grid: Draws the grid lines on the play area.
draw_next_shape: Shows the next Tetris piece.
draw_window: Renders the entire game window, including the score and high score.
-
Gameplay Mechanics:
- Handles piece movement, rotation, collision detection, line clearing, scoring, and increasing difficulty over time.
-
Scoring:
- The game keeps track of the current score and high score, storing the high score in a
scores.txt file.
-
Main Game Loop (main):
- Handles the core game loop, processing user input, updating the game state, and rendering graphics.
-
Main Menu (main_menu):
- Displays the main menu and waits for the player to start the game by pressing any key.
-
Starting the Game:
- Creates the Pygame window and starts the main menu.
Running the Game
-
Save the Script: Save the script to a file named, for example, tetris.py.
-
Run the Script:
python tetris.py
-
Controls:
- Left Arrow: Move piece left
- Right Arrow: Move piece right
- Down Arrow: Move piece down faster
- Up Arrow: Rotate piece
-
Objective:
- Arrange the Tetris pieces to form complete horizontal lines without gaps. Completed lines disappear, and you earn points. The game ends when the stack of pieces reaches the top of the play area.
Customization and Enhancements
This basic implementation can be extended with additional features such as:
- Different Levels: Increase the game's speed as the player clears more lines.
- Sound Effects and Music: Add background music and sound effects for actions like rotating or clearing lines.
- Graphical Enhancements: Improve the visual appearance with better graphics or animations.
- Pause Functionality: Allow the player to pause and resume the game.
- Multiple Difficulty Settings: Offer different difficulty levels with varying speeds and piece frequencies.
Feel free to modify and enhance the script to suit your preferences and to add more features!