Here's an example of Tetris with physics implemented using HTML and JavaScript in a single file. This version simulates basic physics, allowing blocks to fall, stack, and respond to simple collision detection.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tetris with Physics</title>
<style>
canvas {
background: #111;
display: block;
margin: 0 auto;
border: 1px solid #fff;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="300" height="600"></canvas>
<script>
// Tetris with Physics
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30;
const gravity = 0.001; // Acceleration due to gravity (pixels/ms^2)
const shapes = [
// I
[
[1],
[1],
[1],
[1]
],
// J
[
[0, 2],
[0, 2],
[2, 2]
],
// L
[
[3, 0],
[3, 0],
[3, 3]
],
// O
[
[4, 4],
[4, 4]
],
// S
[
[0, 5, 5],
[5, 5, 0]
],
// T
[
[0, 6, 0],
[6, 6, 6]
],
// Z
[
[7, 7, 0],
[0, 7, 7]
]
];
const colors = [
null,
'cyan',
'blue',
'orange',
'yellow',
'green',
'purple',
'red'
];
class Block {
constructor(x, y, color) {
this.x = x * BLOCK_SIZE;
this.y = y * BLOCK_SIZE;
this.vx = 0;
this.vy = 0;
this.color = color;
this.size = BLOCK_SIZE;
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.size, this.size);
}
update(deltaTime) {
// Apply gravity
this.vy += gravity * deltaTime;
// Update position
this.x += this.vx * deltaTime;
this.y += this.vy * deltaTime;
// Collision with floor
if (this.y + this.size > canvas.height) {
this.y = canvas.height - this.size;
this.vy = 0;
}
// Collision with walls
if (this.x < 0) {
this.x = 0;
this.vx = 0;
} else if (this.x + this.size > canvas.width) {
this.x = canvas.width - this.size;
this.vx = 0;
}
}
}
class Piece {
constructor(shape) {
this.shape = shape;
this.color = colors[shape[0][0]];
this.blocks = [];
this.x = 4;
this.y = 0;
}
createBlocks() {
for (let y = 0; y < this.shape.length; y++) {
for (let x = 0; x < this.shape[y].length; x++) {
if (this.shape[y][x]) {
let block = new Block(this.x + x, this.y + y, this.color);
this.blocks.push(block);
}
}
}
}
draw() {
this.blocks.forEach(block => block.draw());
}
move(dx) {
this.blocks.forEach(block => {
block.x += dx * BLOCK_SIZE;
});
if (this.collides()) {
this.blocks.forEach(block => {
block.x -= dx * BLOCK_SIZE;
});
}
}
drop(deltaTime) {
this.blocks.forEach(block => {
block.vy += gravity * deltaTime;
block.y += block.vy * deltaTime;
});
if (this.collides()) {
this.blocks.forEach(block => {
block.y -= block.vy * deltaTime;
block.vy = 0;
});
merge(this.blocks);
resetPiece();
}
}
rotate() {
// Rotation logic (optional for physics simulation)
}
collides() {
let collision = false;
this.blocks.forEach(block => {
// Collision with floor
if (block.y + block.size > canvas.height) {
collision = true;
}
// Collision with existing blocks
blocks.forEach(other => {
if (block !== other && isColliding(block, other)) {
collision = true;
}
});
});
return collision;
}
}
const blocks = []; // All settled blocks on the board
let currentPiece = null;
function resetPiece() {
const shape = shapes[Math.floor(Math.random() * shapes.length)];
currentPiece = new Piece(shape);
currentPiece.createBlocks();
}
function merge(pieceBlocks) {
blocks.push(...pieceBlocks);
}
function isColliding(a, b) {
return (
a.x < b.x + b.size &&
a.x + a.size > b.x &&
a.y < b.y + b.size &&
a.y + a.size > b.y
);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw existing blocks
blocks.forEach(block => {
block.draw();
});
// Draw current piece
if (currentPiece) {
currentPiece.draw();
}
}
function update(time = 0) {
const deltaTime = time - lastTime;
lastTime = time;
// Update current piece
if (currentPiece) {
currentPiece.drop(deltaTime);
}
// Update all blocks
blocks.forEach(block => {
block.update(deltaTime);
// Check for collisions with other blocks
blocks.forEach(other => {
if (block !== other && isColliding(block, other)) {
// Simple collision response
if (block.y < other.y) {
block.y = other.y - block.size;
block.vy = 0;
}
}
});
});
draw();
requestAnimationFrame(update);
}
let lastTime = 0;
document.addEventListener('keydown', event => {
if (currentPiece) {
if (event.keyCode === 37) {
// Left arrow
currentPiece.move(-1);
} else if (event.keyCode === 39) {
// Right arrow
currentPiece.move(1);
} else if (event.keyCode === 40) {
// Down arrow
// Accelerate drop
currentPiece.blocks.forEach(block => {
block.vy += 0.05;
});
} else if (event.keyCode === 38) {
// Up arrow
// Rotate piece (optional)
// currentPiece.rotate();
}
}
});
resetPiece();
update();
</script>
</body>
</html>
Explanation:
Note: This is a simplified physics simulation. Collisions are handled in a basic way, and the rotation functionality is optional and can be complex to implement with physics. For a more advanced physics simulation, integrating a physics engine like Matter.js would be recommended, but it would increase the complexity and size of the code.
Usage:
- Copy the code into a file with an
.html extension (e.g., tetris_with_physics.html).
- Open the file in a modern web browser.
- Use the left and right arrow keys to move the falling pieces.
- Press the down arrow key to accelerate the fall.
- The pieces will break into individual blocks upon landing and will stack with basic physics simulation.
Limitations:
- Rotation is not implemented in this version due to the complexity of applying physics to rotated shapes.
- Collision detection is rudimentary and may not handle all edge cases.
- Clearing full lines is not implemented, as blocks stack based on physics rather than a grid.
This example demonstrates how to create a basic Tetris game with simple physics simulation using only HTML and JavaScript in a single file.