Sure! Here's a simple Tetris-like game written in Python using Pygame. This version includes:
Basic tetromino shapes (I, O, T, L, J, S, Z)
Grid-based movement
Line clearing
Game over detection
🛠 Requirements
Make sure you have Python installed and install pygame via pip if you haven't already:
bash
pip install pygame
✅ Simple Tetris Clone in Python (Pygame)
python
import pygame
import random
# Initialize Pygame
pygame.init()
# Constants
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
COLUMNS = SCREEN_WIDTH // BLOCK_SIZE
ROWS = SCREEN_HEIGHT // BLOCK_SIZE
# Colors
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
WHITE = (255, 255, 255)
COLORS = [
(0, 255, 255), # I
(255, 255, 0), # O
(128, 0, 128), # T
(255, 165, 0), # L
(0, 0, 255), # J
(0, 255, 0), # S
(255, 0, 0) # Z
]
# Shapes
SHAPES = [
[[1, 1, 1, 1]], # I
[[1, 1], [1, 1]], # O
[[0, 1, 0], [1, 1, 1]], # T
[[1, 0, 0], [1, 1, 1]], # L
[[0, 0, 1], [1, 1, 1]], # J
[[0, 1, 1], [1, 1, 0]], # S
[[1, 1, 0], [0, 1, 1]] # Z
]
# Create grid
def create_grid(locked_positions={}):
grid = [[BLACK for _ in range(COLUMNS)] for _ in range(ROWS)]
for i in range(ROWS):
for j in range(COLUMNS):
if (j, i) in locked_positions:
grid[i][j] = locked_positions[(j, i)]
return grid
# Convert shape format to positions
def convert_shape_format(shape):
positions = []
format = shape.shape[shape.rotation]
for i, line in enumerate(format):
for j, column in enumerate(line):
if column == 1:
positions.append((shape.x + j, shape.y + i))
return positions
# Check valid space
def valid_space(shape, grid):
accepted_positions = [[(j, i) for j in range(COLUMNS) if grid[i][j] == BLACK] for i in range(ROWS)]
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] >= 0:
return False
return True
# Check if game over
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
# Clear full rows
def clear_rows(grid, locked):
cleared = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if BLACK not in row:
cleared += 1
ind = i
for j in range(COLUMNS):
try:
del locked[(j, i)]
except:
continue
if cleared > 0:
for key in sorted(list(locked.keys()), key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
newKey = (x, y + cleared)
locked[newKey] = locked.pop(key)
return cleared
# Draw grid lines
def draw_grid_lines(surface):
for i in range(ROWS):
pygame.draw.line(surface, GRAY, (0, i * BLOCK_SIZE), (SCREEN_WIDTH, i * BLOCK_SIZE))
for j in range(COLUMNS):
pygame.draw.line(surface, GRAY, (j * BLOCK_SIZE, 0), (j * BLOCK_SIZE, SCREEN_HEIGHT))
# Draw window
def draw_window(surface, grid):
surface.fill(BLACK)
for i in range(ROWS):
for j in range(COLUMNS):
pygame.draw.rect(surface, grid[i][j], (j*BLOCK_SIZE, i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
draw_grid_lines(surface)
pygame.display.update()
# Class for the tetromino
class Piece:
def __init__(self, x, y, shape):
self.x = x
self.y = y
self.shape = shape
self.color = COLORS[SHAPES.index(shape)]
self.rotation = 0
# Get a random piece
def get_shape():
return Piece(3, 0, random.choice(SHAPES))
# Main game loop
def main():
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Simple Tetris")
clock = pygame.time.Clock()
fall_time = 0
fall_speed = 0.5
locked_positions = {}
grid = create_grid(locked_positions)
current_piece = get_shape()
next_piece = get_shape()
running = True
while running:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
# Piece falls
if fall_time / 1000 >= fall_speed:
fall_time = 0
current_piece.y += 1
if not valid_space(current_piece, grid):
current_piece.y -= 1
# Lock the piece
for pos in convert_shape_format(current_piece):
locked_positions[(pos[0], pos[1])] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
clear_rows(grid, locked_positions)
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
current_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
elif keys[pygame.K_RIGHT]:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
elif keys[pygame.K_DOWN]:
current_piece.y += 1
if not valid_space(current_piece, grid):
current_piece.y -= 1
elif keys[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)
# Draw
draw_window(screen, grid)
# Check game over
if check_lost(locked_positions):
print("Game Over!")
running = False
pygame.quit()
if __name__ == "__main__":
main()
🕹 Controls
Arrow Left/Right: Move block left/right
Arrow Up: Rotate block
Arrow Down: Move block down faster
🧩 Features Implemented
✅ Falling blocks
✅ Rotation
✅ Collision detection
✅ Row clearing
✅ Game over detection
📦 Future Improvements (Optional)
Score system
Level progression
Preview of next piece
Hold piece feature
Sound effects
Would you like me to add any of these features or turn this into a standalone executable (.exe)?
User
and something in html?
Assistant
Absolutely! Here's a simple HTML + JavaScript version of Tetris that runs directly in your browser. It doesn't require any external libraries and uses just the <canvas> element for rendering.
🧱 Simple Tetris Game in HTML/JavaScript
You can copy and paste this into an .html file and open it in your browser:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Simple Tetris</title>
<style>
body {
background: #111;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
color: white;
font-family: sans-serif;
}
canvas {
border: 2px solid #fff;
background-color: #000;
}
</style>
</head>
<body>
<canvas id="tetris" width="300" height="600"></canvas>
<script>
const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.scale(30, 30); // Scale to block size (each block is 30x30 pixels)
// Tetromino shapes
const SHAPES = [
[[1, 1, 1, 1]], // I
[[1, 1], [1, 1]], // O
[[0, 1, 0], [1, 1, 1]], // T
[[1, 0, 0], [1, 1, 1]], // L
[[0, 0, 1], [1, 1, 1]], // J
[[0, 1, 1], [1, 1, 0]], // S
[[1, 1, 0], [0, 1, 1]] // Z
];
const COLORS = [
'#00ffff', // I
'#ffff00', // O
'#800080', // T
'#ffa500', // L
'#0000ff', // J
'#00ff00', // S
'#ff0000' // Z
];
// Create the grid
function createGrid() {
return Array.from({ length: 20 }, () => Array(10).fill(null));
}
let grid = createGrid();
let dropCounter = 0;
let dropInterval = 1000;
let lastTime = 0;
const piece = createPiece(SHAPES[randomIndex(SHAPES)]);
function createPiece(shape) {
return {
shape,
color: COLORS[SHAPES.indexOf(shape)],
pos: { x: 3, y: 0 },
rotation: 0
};
}
function randomIndex(arr) {
return Math.floor(Math.random() * arr.length);
}
function drawMatrix(matrix, offset) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
context.fillStyle = value;
context.fillRect(x + offset.x, y + offset.y, 1, 1);
}
});
});
}
function merge(grid, piece) {
piece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
grid[y + piece.pos.y][x + piece.pos.x] = piece.color;
}
});
});
}
function collide(grid, piece) {
const m = piece.shape;
const o = piece.pos;
for (let y = 0; y < m.length; ++y) {
for (let x = 0; x < m[y].length; ++x) {
if (
m[y][x] &&
(grid[y + o.y] && grid[y + o.y][x + o.x]) === undefined ||
(grid[y + o.y] && grid[y + o.y][x + o.x])
) {
return true;
}
}
}
return false;
}
function rotate(matrix) {
return matrix[0].map((_, i) => matrix.map(row => row[i]).reverse());
}
function playerDrop() {
piece.pos.y++;
if (collide(grid, piece)) {
piece.pos.y--;
merge(grid, piece);
pieceReset();
arenaSweep();
}
dropCounter = 0;
}
function playerMove(dir) {
piece.pos.x += dir;
if (collide(grid, piece)) {
piece.pos.x -= dir;
}
}
function playerRotate() {
const original = piece.shape;
piece.shape = rotate(piece.shape);
const offset = 1;
let collision = collide(grid, piece);
if (collision) {
piece.shape = original;
}
}
function pieceReset() {
const next = createPiece(SHAPES[randomIndex(SHAPES)]);
piece.shape = next.shape;
piece.color = next.color;
piece.pos.y = 0;
piece.pos.x = 3;
if (collide(grid, piece)) {
grid.forEach(row => row.fill(null));
alert("Game Over!");
}
}
function arenaSweep() {
outer: for (let y = grid.length - 1; y >= 0; --y) {
for (let x = 0; x < grid[y].length; ++x) {
if (!grid[y][x]) continue outer;
}
const row = grid.splice(y, 1)[0].fill(null);
grid.unshift(row);
y++;
}
}
function update(time = 0) {
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
playerDrop();
}
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
drawMatrix(grid, { x: 0, y: 0 });
drawMatrix(piece.shape.map(row => row.map(val => val ? piece.color : null)), piece.pos);
requestAnimationFrame(update);
}
document.addEventListener('keydown', event => {
if (event.key === 'ArrowLeft') {
playerMove(-1);
} else if (event.key === 'ArrowRight') {
playerMove(1);
} else if (event.key === 'ArrowDown') {
playerDrop();
} else if (event.key === 'ArrowUp') {
playerRotate();
}
});
update();
</script>
</body>
</html>