Creating a Tetris game using Python and Pygame is a great way to practice your programming skills. Below is a complete implementation of Tetris with explanations to help you understand how it works. Make sure you have Python and Pygame installed on your system.
1. Install Pygame
First, if you haven't installed Pygame yet, you can do so using pip:
bash
pip install pygame
2. Tetris Game Code
Here's a complete Python script for the Tetris game using Pygame:
python
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
PLAY_WIDTH = 300 # 10 blocks wide
PLAY_HEIGHT = 600 # 20 blocks high
BLOCK_SIZE = 30
# Grid dimensions
GRID_WIDTH = 10
GRID_HEIGHT = 20
# Define shapes
SHAPES = [
[['.....',
'.....',
'..O..',
'..O..',
'..O..'],
['.....',
'.....',
'.....',
'OOO..',
'.....']],
[['.....',
'.....',
'.OO..',
'.OO..',
'.....']],
[['.....',
'.....',
'..O..',
'.OOO.',
'.....'],
['.....',
'..O..',
'..OO.',
'..O..',
'.....']],
[['.....',
'.....',
'.O...',
'.OOO.',
'.....'],
['.....',
'..OO.',
'..O..',
'..O..',
'.....']],
[['.....',
'.....',
'...O.',
'.OOO.',
'.....'],
['.....',
'..O..',
'..O..',
'.OO..',
'.....']],
[['.....',
'.....',
'..O..',
'..OO.',
'...O.'],
['.....',
'.....',
'.O...',
'.OO..',
'.O...']],
[['.....',
'.....',
'.O...',
'..OO.',
'..O..'],
['.....',
'.....',
'..OO.',
'.OO..',
'.....']]
]
# Colors corresponding to shapes
SHAPE_COLORS = [
(0, 255, 0), # S
(255, 0, 0), # Z
(0, 255, 255), # I
(255, 165, 0), # L
(0, 0, 255), # J
(255, 255, 0), # O
(128, 0, 128) # T
]
# 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
def create_grid(locked_positions={}):
grid = [[(0,0,0) for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
if (j, i) in locked_positions:
grid[i][j] = locked_positions[(j, i)]
return grid
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 == 'O':
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(GRID_WIDTH) if grid[i][j] == (0,0,0)] for i in range(GRID_HEIGHT)]
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] >= 0:
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(surface, text, size, color):
font = pygame.font.SysFont('comicsans', size, bold=True)
label = font.render(text, 1, color)
surface.blit(label, (SCREEN_WIDTH /2 - (label.get_width() /2), SCREEN_HEIGHT/2 - label.get_height()/2))
def draw_grid(surface, grid):
sx = 0
sy = 0
for i in range(GRID_HEIGHT):
pygame.draw.line(surface, (128,128,128), (sx, sy + i*BLOCK_SIZE), (sx + PLAY_WIDTH, sy + i * BLOCK_SIZE))
for j in range(GRID_WIDTH):
pygame.draw.line(surface, (128,128,128), (sx + j*BLOCK_SIZE, sy), (sx + j*BLOCK_SIZE, sy + PLAY_HEIGHT))
def clear_rows(grid, locked):
increment = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if (0,0,0) not in row:
increment +=1
ind = i
for j in range(len(row)):
try:
del locked[(j, i)]
except:
continue
if increment > 0:
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_next_shape(piece, surface):
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', 1, (255,255,255))
sx = SCREEN_WIDTH + 50
sy = SCREEN_HEIGHT / 2 - 100
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 == 'O':
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((0,0,0))
font = pygame.font.SysFont('comicsans', 60)
label = font.render('Tetris', 1, (255,255,255))
surface.blit(label, (SCREEN_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 = SCREEN_WIDTH + 50
sy = SCREEN_HEIGHT / 2 - 100
surface.blit(label, (sx, sy + 200))
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j], (j*BLOCK_SIZE, i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
draw_grid(surface, grid)
pygame.draw.rect(surface, (255,0,0), (0,0, PLAY_WIDTH, PLAY_HEIGHT), 5)
def main():
global SCREEN_WIDTH, SCREEN_HEIGHT, PLAY_WIDTH, PLAY_HEIGHT
screen = pygame.display.set_mode((SCREEN_WIDTH + 200, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
clock = pygame.time.Clock()
fall_time = 0
fall_speed = 0.5
grid = create_grid()
change_piece = False
run = True
current_piece = get_shape()
next_piece = get_shape()
locked_positions = {}
score = 0
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_time()
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
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
if event.key == pygame.K_RIGHT:
current_piece.x +=1
if not valid_space(current_piece, grid):
current_piece.x -=1
if event.key == pygame.K_DOWN:
current_piece.y +=1
if not valid_space(current_piece, grid):
current_piece.y -=1
if 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)
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = current_piece.color
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
draw_window(screen, grid, score)
draw_next_shape(next_piece, screen)
pygame.display.update()
if check_lost(locked_positions):
draw_text_middle(screen, "YOU LOSE!", 80, (255,255,255))
pygame.display.update()
pygame.time.delay(2000)
run = False
def main_menu():
screen = pygame.display.set_mode((SCREEN_WIDTH + 200, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
run = True
while run:
screen.fill((0,0,0))
draw_text_middle(screen, '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()
pygame.quit()
if __name__ == "__main__":
main_menu()
3. Understanding the Code
Here's a brief overview of the main components of the code:
Imports and Initialization:
The script starts by importing necessary modules (pygame, random) and initializing Pygame.
Constants and Configuration:
Define screen dimensions, grid size, block size, shapes, and their colors.
Piece Class:
Represents each Tetris piece with its position, shape, color, and rotation state.
Grid Management:
create_grid: Creates the game grid and marks locked positions.
convert_shape_format: Converts the shape's string format into grid positions.
valid_space: Checks if the current position of the piece is valid.
check_lost: Determines if the game is over.
Drawing Functions:
draw_text_middle: Displays text in the center of the screen.
draw_grid: Draws the grid lines.
draw_next_shape: Shows the next piece.
draw_window: Renders the entire game window, including the grid and score.
Game Logic (main function):
Handles the main game loop, including piece movement, collision detection, row clearing, and game over conditions.
Main Menu (main_menu function):
Displays the start screen and waits for the player to press a key to start the game.
4. Running the Game
Save the Code:
Save the provided code in a file named tetris.py.
Run the Game:
Open your terminal or command prompt, navigate to the directory containing tetris.py, and run:
bash
python tetris.py
Controls:
Left Arrow: Move piece left
Right Arrow: Move piece right
Down Arrow: Move piece down faster
Up Arrow: Rotate piece
5. Enhancements
This basic implementation provides a functional Tetris game. Here are some ideas to enhance it further:
Levels: Increase the speed as the player clears more rows.
Score Tracking: Implement high scores or more detailed scoring.
Hold Piece: Allow players to hold a piece for later use.
Sound Effects and Music: Add sounds for moving, rotating, clearing lines, and background music.
Better Graphics: Improve the visuals with more detailed graphics and animations.
Feel free to modify and expand upon this code to create your own unique version of Tetris!