Sure! Let's create a simple version of Tetris using Python and Pygame. This implementation will cover the basic functionalities of Tetris, including moving shapes, rotating them, clearing lines, and keeping score.
Prerequisites
Before we begin, make sure you have Pygame installed. You can install it using pip:
pip install pygame
Overview
We'll structure our game with the following components:
- Constants and Configurations: Define screen dimensions, grid size, colors, shapes, etc.
- Game Grid: Manage the state of the game grid and handle line clearing.
- Tetromino Shapes: Define the seven standard Tetris pieces.
- Game Logic: Handle piece movement, rotation, collision detection, and game state updates.
- Main Loop: Handle user input, update the game state, and render updates to the screen.
Full Code
Below is the complete code for the Tetris game:
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# Grid dimensions
GRID_WIDTH = SCREEN_WIDTH // BLOCK_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // BLOCK_SIZE
# Define shapes (S, Z, I, O, J, L, T)
SHAPES = [
[['.....',
'.....',
'..00.',
'.00..',
'.....'],
['.....',
'..0..',
'..00.',
'...0.',
'.....']],
[['.....',
'.....',
'.00..',
'..00.',
'.....'],
['.....',
'..0..',
'.00..',
'.0...',
'.....']],
[['..0..',
'..0..',
'..0..',
'..0..',
'.....'],
['.....',
'0000.',
'.....',
'.....',
'.....']],
[['.....',
'.....',
'.00..',
'.00..',
'.....']],
[['.....',
'.0...',
'.000.',
'.....',
'.....'],
['.....',
'..00.',
'..0..',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'...0.',
'.....'],
['.....',
'..0..',
'..0..',
'.00..',
'.....']],
[['.....',
'...0.',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..0..',
'..00.',
'.....'],
['.....',
'.....',
'.000.',
'.0...',
'.....'],
['.....',
'.00..',
'..0..',
'..0..',
'.....']],
[['.....',
'..0..',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..00.',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'..0..',
'.....'],
['.....',
'..0..',
'.00..',
'..0..',
'.....']]
]
# Define shape colors (RGB)
SHAPE_COLORS = [
(0, 255, 0), # S - Green
(255, 0, 0), # Z - Red
(0, 255, 255), # I - Cyan
(255, 255, 0), # O - Yellow
(0, 0, 255), # J - Blue
(255, 165, 0), # L - Orange
(128, 0, 128) # T - Purple
]
class Tetromino:
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 # Shape represented as a list of rotations
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0 # Current rotation
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(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, shape.y + i))
# Adjust positions
positions = [(x - 2, y - 4) for x, y in positions]
return positions
def valid_space(shape, 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(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 Tetromino(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, True, color)
surface.blit(label, (SCREEN_WIDTH // 2 - label.get_width() // 2, SCREEN_HEIGHT // 2 - label.get_height() // 2))
def clear_rows(grid, locked):
# Need to check if row is clear then shift every other row above down one
increment = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if (0,0,0) not in row:
increment += 1
# Add positions to remove from locked
ind = i
for j in range(len(row)):
try:
del locked[(j, i)]
except:
continue
if increment > 0:
# Shift every row above down
for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
new_key = (x, y + increment)
locked[new_key] = locked.pop(key)
return increment
def draw_grid(surface, grid):
for i in range(GRID_HEIGHT):
pygame.draw.line(surface, (128,128,128), (0, i*BLOCK_SIZE), (SCREEN_WIDTH, i*BLOCK_SIZE))
for j in range(GRID_WIDTH):
pygame.draw.line(surface, (128,128,128), (j*BLOCK_SIZE, 0), (j*BLOCK_SIZE, SCREEN_HEIGHT))
def draw_window(surface, grid, score=0):
surface.fill((0, 0, 0))
# Draw title
font = pygame.font.SysFont('comicsans', 40)
label = font.render('Tetris', True, (255,255,255))
surface.blit(label, (SCREEN_WIDTH // 2 - label.get_width() // 2, 30))
# Draw score
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Score: ' + str(score), True, (255,255,255))
surface.blit(label, (10, SCREEN_HEIGHT - 30))
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 lines
draw_grid(surface, grid)
pygame.display.update()
def main():
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 # Adjust to change difficulty
level_time = 0
score = 0
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick()
# Increase difficulty over time
if level_time / 1000 > 5:
level_time = 0
if fall_speed > 0.12:
fall_speed -= 0.005
# 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()
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)
# Add piece to the grid
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = current_piece.color
# If piece hit the ground
if change_piece:
for pos in shape_pos:
locked_positions[(pos[0], pos[1])] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
# Clear rows and update score
cleared = clear_rows(grid, locked_positions)
score += cleared * 10
draw_window(screen, grid, score)
if check_lost(locked_positions):
draw_text_middle(screen, "Game Over", 80, (255,255,255))
pygame.display.update()
pygame.time.delay(2000)
run = False
pygame.quit()
if __name__ == '__main__':
main()
Explanation
- Tetromino Class: Represents a Tetris piece with position, shape, color, and rotation.
- Game Grid: A 2D list representing the game area where each cell can be empty or contain a block.
- Piece Movement: Handles user input for moving left, right, down, and rotating pieces.
- Collision Detection: Checks if the new position after movement is valid.
- Line Clearing: Checks for complete lines, removes them, and shifts everything above down.
- Scoring: Increments the score when lines are cleared.
- Game Loop: Continues running until the game is over, updating the game state and rendering.
Running the Game
-
Save the code in a file named tetris.py.
-
Run the script:
python tetris.py
-
Control the pieces using:
- Left Arrow: Move left
- Right Arrow: Move right
- Down Arrow: Move down faster
- Up Arrow: Rotate
Customizations
- Adjusting Difficulty: Modify
fall_speed to make pieces fall faster or slower.
- Adding Levels: Implement level increases based on the score or time elapsed.
- Improving Graphics: Replace rectangle draws with images for blocks.
- Sound Effects: Use Pygame's mixer to add sounds when lines are cleared or pieces are placed.
Conclusion
This code provides a basic framework for Tetris using Pygame. You can extend it further by adding features like a preview of the next piece, saving high scores, or implementing different game modes. Happy coding!