A Tetris game in Python with a nice UI design! That's a great project. I'll guide you through the implementation using the Pygame library, which is perfect for creating games with a simple and intuitive API.
Game Requirements
Before we dive into the code, let's outline the basic requirements:
- Gameplay: Rotate, move, and drop Tetrominoes (the Tetris blocks) to create solid lines without gaps.
- Scoring: Award points for clearing lines (1 line = 100 points, 2 lines = 300 points, 3 lines = 500 points, 4 lines = 800 points).
- Game Over: When the stack of Tetrominoes reaches the top of the grid.
- UI:
- Grid display (10x20 cells) with border.
- Score display at the top.
- Next Tetromino preview.
- Game Over screen with final score.
Code Structure
We'll break the code into sections:
tetris.py: The main game logic and Pygame setup.
tetrominoes.py: Defines the 7 Tetromino shapes and their rotations.
settings.py: Constants for colors, grid size, font, and other game settings.
Let's start with settings.py:
# settings.py
# Colors (RGB)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
RED = (255, 0, 0)
# Grid dimensions
GRID_WIDTH = 10
GRID_HEIGHT = 20
CELL_SIZE = 30
# Font
FONT_NAME = 'Arial'
FONT_SIZE = 24
# Score values
SCORE_VALUES = {
1: 100,
2: 300,
3: 500,
4: 800
}
# Tetromino colors
TETROMINO_COLORS = {
'I': (0, 255, 255), # Cyan
'J': (0, 0, 255), # Blue
'L': (255, 165, 0), # Orange
'O': (255, 255, 0), # Yellow
'S': (0, 128, 0), # Green
'T': (75, 0, 130), # Indigo
'Z': (255, 0, 0) # Red
}
Next, tetrominoes.py defines the 7 Tetromino shapes as 2D lists, along with their rotations:
# tetrominoes.py
TETROMINOES = {
'I': [
[[1, 1, 1, 1]], # 0°
[[1], [1], [1], [1]] # 90°
],
'J': [
[[1, 0, 0], [1, 1, 1]], # 0°
[[1, 1], [1, 0], [1, 0]], # 90°
[[1, 1, 1], [0, 0, 1]], # 180°
[[0, 1], [0, 1], [1, 1]] # 270°
],
'L': [
[[0, 0, 1], [1, 1, 1]], # 0°
[[1, 1], [0, 1], [0, 1]], # 90°
[[1, 1, 1], [1, 0, 0]], # 180°
[[1, 0], [1, 0], [1, 1]] # 270°
],
'O': [
[[1, 1], [1, 1]] # all rotations are the same
],
'S': [
[[0, 1, 1], [1, 1, 0]], # 0°
[[1, 0], [1, 1], [0, 1]] # 90°
],
'T': [
[[0, 1, 0], [1, 1, 1]], # 0°
[[1, 1], [0, 1], [0, 1]], # 90°
[[1, 1, 1], [0, 1, 0]], # 180°
[[1, 0], [1, 1], [1, 0]] # 270°
],
'Z': [
[[1, 1, 0], [0, 1, 1]], # 0°
[[0, 1], [1, 1], [1, 0]] # 90°
]
}
Now, the main tetris.py file:
# tetris.py
import pygame
import random
from tetrominoes import TETROMINOES
from settings import *
class Tetris:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((GRID_WIDTH * CELL_SIZE + 200, GRID_HEIGHT * CELL_SIZE + 100))
pygame.display.set_caption('Tetris')
self.clock = pygame.time.Clock()
self.font = pygame.font.SysFont(FONT_NAME, FONT_SIZE)
self.reset_game()
def reset_game(self):
self.grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
self.score = 0
self.tetromino = self.get_random_tetromino()
self.next_tetromino = self.get_random_tetromino()
self.tetromino_x, self.tetromino_y = GRID_WIDTH // 2, 0
self.rotation = 0
def get_random_tetromino(self):
return random.choice(list(TETROMINOES.keys()))
def run(self):
running = True
while running:
self.clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.move_tetromino(-1, 0)
elif event.key == pygame.K_RIGHT:
self.move_tetromino(1, 0)
elif event.key == pygame.K_DOWN:
self.move_tetromino(0, 1)
elif event.key == pygame.K_UP:
self.rotate_tetromino()
elif event.key == pygame.K_SPACE:
self.drop_tetromino()
self.update()
self.draw()
pygame.display.flip()
pygame.quit()
def update(self):
if self.check_collision(0, 1):
self.lock_tetromino()
self.clear_lines()
self.tetromino = self.next_tetromino
self.next_tetromino = self.get_random_tetromino()
self.tetromino_x, self.tetromino_y = GRID_WIDTH // 2, 0
self.rotation = 0
if self.check_collision(0, 0):
self.game_over()
else:
self.tetromino_y += 1
def draw(self):
self.screen.fill(BLACK)
self.draw_grid()
self.draw_tetromino()
self.draw_next_tetromino()
self.draw_score()
if self.game_over_flag:
self.draw_game_over()
def draw_grid(self):
for y in range(GRID_HEIGHT):
for x in range(GRID_WIDTH):
pygame.draw.rect(self.screen, GRAY, (x * CELL_SIZE, y * CELL_SIZE + 50, CELL_SIZE, CELL_SIZE), 1)
if self.grid[y][x] == 1:
pygame.draw.rect(self.screen, WHITE, (x * CELL_SIZE + 1, y * CELL_SIZE + 51, CELL_SIZE - 2, CELL_SIZE - 2))
def draw_tetromino(self):
shape = TETROMINOES[self.tetromino][self.rotation]
color = TETROMINO_COLORS[self.tetromino]
for y, row in enumerate(shape):
for x, val in enumerate(row):
if val == 1:
pygame.draw.rect(self.screen, color, ((self.tetromino_x + x) * CELL_SIZE + 1, (self.tetromino_y + y) * CELL_SIZE + 51, CELL_SIZE - 2, CELL_SIZE - 2))
def draw_next_tetromino(self):
shape = TETROMINOES[self.next_tetromino][0]
color = TETROMINO_COLORS[self.next_tetromino]
for y, row in enumerate(shape):
for x, val in enumerate(row):
if val == 1:
pygame.draw.rect(self.screen, color, (GRID_WIDTH * CELL_SIZE + 50 + x * CELL_SIZE, 100 + y * CELL_SIZE, CELL_SIZE - 2, CELL_SIZE - 2))
text = self.font.render('Next:', True, WHITE)
self.screen.blit(text, (GRID_WIDTH * CELL_SIZE + 50, 50))
def draw_score(self):
text = self.font.render(f'Score: {self.score}', True, WHITE)
self.screen.blit(text, (10, 10))
def draw_game_over(self):
text = self.font.render('Game Over!', True, RED)
self.screen.blit(text, (GRID_WIDTH * CELL_SIZE // 2 - 50, GRID_HEIGHT * CELL_SIZE // 2 - 25))
text = self.font.render(f'Final Score: {self.score}', True, WHITE)
self.screen.blit(text, (GRID_WIDTH * CELL_SIZE // 2 - 75, GRID_HEIGHT * CELL_SIZE // 2 + 25))
def move_tetromino(self, dx, dy):
if not self.check_collision(dx, dy):
self.tetromino_x += dx
self.tetromino_y += dy
def rotate_tetromino(self):
new_rotation = (self.rotation + 1) % len(TETROMINOES[self.tetromino])
if not self.check_collision(0, 0, new_rotation):
self.rotation = new_rotation
def drop_tetromino(self):
while not self.check_collision(0, 1):
self.tetromino_y += 1
self.lock_tetromino()
def lock_tetromino(self):
shape = TETROMINOES[self.tetromino][self.rotation]
for y, row in enumerate(shape):
for x, val in enumerate(row):
if val == 1:
self.grid[self.tetromino_y + y][self.tetromino_x + x] = 1
def clear_lines(self):
lines_cleared = 0
for y in range(GRID_HEIGHT):
if all(cell == 1 for cell in self.grid[y]):
del self.grid[y]
self.grid.insert(0, [0 for _ in range(GRID_WIDTH)])
lines_cleared += 1
self.score += SCORE_VALUES.get(lines_cleared, 0)
def check_collision(self, dx, dy, rotation=None):
shape = TETROMINOES[self.tetromino][rotation if rotation is not None else self.rotation]
for y, row in enumerate(shape):
for x, val in enumerate(row):
if val == 1:
nx, ny = self.tetromino_x + x + dx, self.tetromino_y + y + dy
if nx < 0 or nx >= GRID_WIDTH or ny >= GRID_HEIGHT or (ny >= 0 and self.grid[ny][nx] == 1):
return True
return False
def game_over(self):
self.game_over_flag = True
def run_game_over_screen(self):
self.screen.fill(BLACK)
self.draw_game_over()
pygame.display.flip()
pygame.time.wait(2000)
if __name__ == '__main__':
game = Tetris()
game.run()
game.run_game_over_screen()
How it works
- The
Tetris class initializes Pygame, sets up the display, and defines the game logic.
- The
reset_game method initializes the grid, score, and Tetrominoes.
- The
run method is the main game loop, handling events, updating game state, and drawing the UI.
update checks for collisions, moves the Tetromino down, and locks it in place when necessary.
draw renders the grid, Tetrominoes, score, and next Tetromino preview.
- The
move_tetromino, rotate_tetromino, and drop_tetromino methods handle user input.
lock_tetromino adds the Tetromino to the grid, and clear_lines removes completed lines and updates the score.
check_collision verifies if a Tetromino movement or rotation is valid.
game_over sets the game over flag, and run_game_over_screen displays the final score screen.
Run the game
Save all three files (settings.py, tetrominoes.py, and tetris.py) in the same directory. Run python tetris.py to start the game!
UI Design
The UI features:
- A 10x20 grid with gray borders and white filled cells.
- The current Tetromino is colored according to its type (see
TETROMINO_COLORS).
- The next Tetromino preview is displayed on the right side.
- The score is shown at the top-left corner.
- When the game ends, a "Game Over!" message appears with the final score.
Feel free to adjust colors, font sizes, and grid dimensions in settings.py to customize the UI.
Enjoy playing Tetris!