Block Stacker: a falling-block puzzle
Rotate and drop seven block shapes to complete lines. A ghost outline shows where each piece will land.
- Difficulty
- Advanced
- Source size
- 254 lines, 1 file
- Requires
- Python 3.10+, pygame-ce or pygame
- Assets
- None (drawn in code)
Controls
- Left Right Move
- Up X Rotate
- Down Soft drop
- Space Hard drop
- P R Pause / restart
On this page
What you'll learn#
- Representing a board as a 2D list
- Rotating shapes with a coordinate formula
- Wall kicks: trying small shifts when a rotation is blocked
- Clearing full lines and scoring combinations
- A fair randomiser that deals every shape once per bag
Run it on your computer#
- Install Python 3.10 or newer and Pygame:
python -m pip install pygame-ce(orpygame). See the installation guides. - Download tetris_style.py into any folder.
- Open a terminal in that folder and run
python tetris_style.py.
No images or sounds are needed: everything is drawn in code. The game also runs unchanged in Pygame Online, because its loop uses asyncio to hand control to the browser each frame.
How it works#
Board and pieces#
The board is a list of 20 rows, each a list of 10 cells holding None or a shape letter. A piece is four (x, y) cells inside a small box plus the box's position on the board. fits() checks whether a set of cells is inside the walls and on empty squares, and every move, rotation and drop is "try it, keep it only if it fits".
Rotation and wall kicks#
Rotating a cell clockwise inside a box of size n maps (x, y) to (n - 1 - y, x). Near a wall a rotated piece may poke outside, so rotate() also tries shifting it 1 or 2 columns left and right. These small shifts, called wall kicks, make rotation feel forgiving.
Line clears and levels#
After a piece locks, any full row is deleted and an empty row is inserted at the top. Clearing more lines at once scores much more (100, 300, 500, 800, multiplied by the level), and every ten lines the level rises and pieces fall faster.
The 7-bag randomiser#
Pure random choice can deal the same piece many times in a row. The game shuffles all seven shapes into a "bag" and deals them one by one, refilling when empty, so droughts are impossible.
This is an original implementation of the falling-block genre with its own visuals and names; it isn't affiliated with any commercial game.
Complete source code#
"""Block Stacker - a Pygame.net game project (a falling-block puzzle).
Rotate and drop the seven block shapes to complete horizontal lines.
Clearing lines scores points and speeds the game up every ten lines.
Run it: pip install pygame-ce (or: pip install pygame)
python tetris_style.py
Controls: Left/Right move, Up or X rotate, Down soft drop, Space hard drop,
P pause, R restart.
License: MIT - https://pygame.net/licenses/
"""
import asyncio
import random
import pygame
CELL = 22
COLS, ROWS = 10, 20
BOARD_X, BOARD_Y = 40, 20
WIDTH, HEIGHT = 640, 480
FPS = 60
BG = (16, 26, 48)
WELL = (11, 18, 34)
GRID = (28, 42, 72)
WHITE = (230, 236, 247)
# Each shape is a list of (x, y) cells in a 4x4 box; rotation is computed.
SHAPES = {
"I": [(0, 1), (1, 1), (2, 1), (3, 1)],
"O": [(1, 0), (2, 0), (1, 1), (2, 1)],
"T": [(1, 0), (0, 1), (1, 1), (2, 1)],
"S": [(1, 0), (2, 0), (0, 1), (1, 1)],
"Z": [(0, 0), (1, 0), (1, 1), (2, 1)],
"J": [(0, 0), (0, 1), (1, 1), (2, 1)],
"L": [(2, 0), (0, 1), (1, 1), (2, 1)],
}
COLORS = {
"I": (90, 200, 230), "O": (244, 197, 49), "T": (170, 120, 230), "S": (110, 200, 120),
"Z": (232, 93, 82), "J": (91, 147, 230), "L": (240, 140, 64),
}
LINE_SCORES = {1: 100, 2: 300, 3: 500, 4: 800}
class Piece:
def __init__(self, kind):
self.kind = kind
self.cells = list(SHAPES[kind])
self.x, self.y = 3, -1
def rotated(self):
if self.kind == "O":
return list(self.cells)
size = 4 if self.kind == "I" else 3
return [(size - 1 - y, x) for x, y in self.cells]
def blocks(self, cells=None, dx=0, dy=0):
return [(self.x + x + dx, self.y + y + dy) for x, y in (cells or self.cells)]
class Game:
def __init__(self, seed=None):
self.rng = random.Random(seed)
self.font = pygame.font.Font(None, 30)
self.big = pygame.font.Font(None, 56)
self.reset()
def reset(self):
self.board = [[None] * COLS for _ in range(ROWS)]
self.bag = []
self.piece = Piece(self.next_kind())
self.next = Piece(self.next_kind())
self.score = 0
self.lines = 0
self.level = 1
self.fall_timer = 0.0
self.state = "playing"
def next_kind(self):
# "7-bag" randomiser: every shape appears once per seven pieces.
if not self.bag:
self.bag = list(SHAPES)
self.rng.shuffle(self.bag)
return self.bag.pop()
@property
def fall_delay(self):
return max(0.08, 0.8 - (self.level - 1) * 0.07)
def fits(self, blocks):
for x, y in blocks:
if x < 0 or x >= COLS or y >= ROWS:
return False
if y >= 0 and self.board[y][x] is not None:
return False
return True
def move(self, dx, dy):
if self.fits(self.piece.blocks(dx=dx, dy=dy)):
self.piece.x += dx
self.piece.y += dy
return True
return False
def rotate(self):
cells = self.piece.rotated()
for kick in (0, -1, 1, -2, 2): # simple wall kicks
if self.fits(self.piece.blocks(cells, dx=kick)):
self.piece.cells = cells
self.piece.x += kick
return True
return False
def hard_drop(self):
dropped = 0
while self.move(0, 1):
dropped += 1
self.score += dropped * 2
self.lock()
def lock(self):
for x, y in self.piece.blocks():
if y < 0:
self.state = "over"
return
self.board[y][x] = self.piece.kind
self.clear_lines()
self.piece, self.next = self.next, Piece(self.next_kind())
if not self.fits(self.piece.blocks()):
self.state = "over"
def clear_lines(self):
full = [r for r in range(ROWS) if all(self.board[r][c] is not None for c in range(COLS))]
for r in full:
del self.board[r]
self.board.insert(0, [None] * COLS)
if full:
self.lines += len(full)
self.score += LINE_SCORES[len(full)] * self.level
self.level = 1 + self.lines // 10
return len(full)
def handle_event(self, event):
if event.type != pygame.KEYDOWN:
return
if event.key == pygame.K_r:
self.reset()
return
if event.key == pygame.K_p and self.state != "over":
self.state = "paused" if self.state == "playing" else "playing"
return
if self.state != "playing":
if self.state == "over" and event.key == pygame.K_SPACE:
self.reset()
return
if event.key in (pygame.K_LEFT, pygame.K_a):
self.move(-1, 0)
elif event.key in (pygame.K_RIGHT, pygame.K_d):
self.move(1, 0)
elif event.key in (pygame.K_UP, pygame.K_x, pygame.K_w):
self.rotate()
elif event.key in (pygame.K_DOWN, pygame.K_s):
if self.move(0, 1):
self.score += 1
self.fall_timer = 0
elif event.key == pygame.K_SPACE:
self.hard_drop()
def update(self, dt):
if self.state != "playing":
return
self.fall_timer += dt
if self.fall_timer >= self.fall_delay:
self.fall_timer = 0
if not self.move(0, 1):
self.lock()
def ghost_y(self):
dy = 0
while self.fits(self.piece.blocks(dy=dy + 1)):
dy += 1
return dy
def draw_cell(self, surface, x, y, color, outline=False):
rect = pygame.Rect(BOARD_X + x * CELL, BOARD_Y + y * CELL, CELL, CELL)
if outline:
pygame.draw.rect(surface, color, rect.inflate(-4, -4), 2, border_radius=3)
else:
pygame.draw.rect(surface, color, rect.inflate(-2, -2), border_radius=3)
pygame.draw.line(surface, (255, 255, 255), (rect.left + 3, rect.top + 3), (rect.right - 5, rect.top + 3))
def draw(self, surface):
surface.fill(BG)
well = pygame.Rect(BOARD_X, BOARD_Y, COLS * CELL, ROWS * CELL)
pygame.draw.rect(surface, WELL, well)
for c in range(1, COLS):
pygame.draw.line(surface, GRID, (well.x + c * CELL, well.top), (well.x + c * CELL, well.bottom))
for r in range(1, ROWS):
pygame.draw.line(surface, GRID, (well.left, well.y + r * CELL), (well.right, well.y + r * CELL))
for y, row in enumerate(self.board):
for x, kind in enumerate(row):
if kind:
self.draw_cell(surface, x, y, COLORS[kind])
if self.state in ("playing", "paused"):
g = self.ghost_y()
for x, y in self.piece.blocks(dy=g):
if y >= 0:
self.draw_cell(surface, x, y, COLORS[self.piece.kind], outline=True)
for x, y in self.piece.blocks():
if y >= 0:
self.draw_cell(surface, x, y, COLORS[self.piece.kind])
pygame.draw.rect(surface, (91, 147, 230), well.inflate(4, 4), 2)
panel_x = BOARD_X + COLS * CELL + 40
surface.blit(self.font.render("Next", True, WHITE), (panel_x, 30))
for x, y in self.next.cells:
r = pygame.Rect(panel_x + x * CELL, 64 + y * CELL, CELL - 2, CELL - 2)
pygame.draw.rect(surface, COLORS[self.next.kind], r, border_radius=3)
for i, (label, value) in enumerate((("Score", self.score), ("Lines", self.lines), ("Level", self.level))):
surface.blit(self.font.render(f"{label}: {value}", True, WHITE), (panel_x, 170 + i * 36))
help_lines = ["Left/Right move", "Up/X rotate", "Down soft drop", "Space hard drop", "P pause, R restart"]
for i, line in enumerate(help_lines):
surface.blit(self.font.render(line, True, (150, 165, 195)), (panel_x, 300 + i * 28))
if self.state in ("paused", "over"):
text = "Paused" if self.state == "paused" else "Game over"
t = self.big.render(text, True, (244, 197, 49))
box = t.get_rect(center=well.center).inflate(30, 20)
pygame.draw.rect(surface, WELL, box)
surface.blit(t, t.get_rect(center=well.center))
async def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Block Stacker - Pygame.net")
clock = pygame.time.Clock()
game = Game()
running = True
while running:
dt = clock.tick(FPS) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
game.handle_event(event)
game.update(dt)
game.draw(screen)
pygame.display.flip()
await asyncio.sleep(0)
pygame.quit()
if __name__ == "__main__":
asyncio.run(main())The code is released under the MIT license: use it, change it and build on it. See licenses.
Ideas to extend it#
- Add a hold slot: press C to swap the current piece with a stored one.
- Show the next three pieces instead of one.
- Flash full lines briefly before removing them.
- Add lock delay: a short grace period before a landed piece locks.
- Save a high score table with player initials.