Sure! I can provide you with the code for a simple Tetris game written in HTML, CSS, and JavaScript. You can paste this code into an online editor like CodePen, JSFiddle, or JS Bin to play the game directly in your web browser.
Step 1: HTML Code
HTML (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Tetris Game</title>
<style>
body {
background: #000;
margin: 0;
overflow: hidden;
}
canvas {
display: block;
margin: auto;
background: #111;
}
</style>
</head>
<body>
<canvas id="tetris" width="240" height="400"></canvas>
<script src="tetris.js"></script>
</body>
</html>
Step 2: JavaScript Code
JavaScript (tetris.js):
const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
// Scale the canvas to make the blocks larger
context.scale(20, 20);
// Create the arena (game board)
const arena = createMatrix(12, 20);
// Function to create a matrix for the pieces and arena
function createMatrix(width, height) {
const matrix = [];
while (height--) {
matrix.push(new Array(width).fill(0));
}
return matrix;
}
// Function to create different tetris pieces
function createPiece(type) {
switch (type) {
case 'T':
return [
[0, 0, 0],
[1, 1, 1],
[0, 1, 0],
];
case 'O':
return [
[2, 2],
[2, 2],
];
case 'L':
return [
[0, 0, 3],
[3, 3, 3],
[0, 0, 0],
];
case 'J':
return [
[4, 0, 0],
[4, 4, 4],
[0, 0, 0],
];
case 'I':
return [
[0, 5, 0, 0],
[0, 5, 0, 0],
[0, 5, 0, 0],
[0, 5, 0, 0],
];
case 'S':
return [
[0, 6, 6],
[6, 6, 0],
[0, 0, 0],
];
case 'Z':
return [
[7, 7, 0],
[0, 7, 7],
[0, 0, 0],
];
}
}
// Function to draw the matrix
function drawMatrix(matrix, offset) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
context.fillStyle = colors[value];
context.fillRect(
x + offset.x,
y + offset.y,
1,
1
);
}
});
});
}
// Function to draw the game
function draw() {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
drawMatrix(arena, { x: 0, y: 0 });
drawMatrix(player.matrix, player.pos);
}
// Function to merge player piece into the arena
function merge(arena, player) {
player.matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
arena[y + player.pos.y][x + player.pos.x] = value;
}
});
});
}
// Function to check collision
function collide(arena, player) {
const [m, o] = [player.matrix, player.pos];
for (let y = 0; y < m.length; ++y) {
for (let x = 0; x < m[y].length; ++x) {
if (
m[y][x] !== 0 &&
(arena[y + o.y] && arena[y + o.y][x + o.x]) !== 0
) {
return true;
}
}
}
return false;
}
// Function to drop the player piece
function playerDrop() {
player.pos.y++;
if (collide(arena, player)) {
player.pos.y--;
merge(arena, player);
playerReset();
arenaSweep();
}
dropCounter = 0;
}
// Function to move the player piece
function playerMove(dir) {
player.pos.x += dir;
if (collide(arena, player)) {
player.pos.x -= dir;
}
}
// Function to rotate the player piece
function playerRotate(dir) {
rotate(player.matrix, dir);
const pos = player.pos.x;
let offset = 1;
while (collide(arena, player)) {
player.pos.x += offset;
offset = -(offset + (offset > 0 ? 1 : -1));
if (offset > player.matrix[0].length) {
rotate(player.matrix, -dir);
player.pos.x = pos;
return;
}
}
}
// Function to rotate the matrix
function rotate(matrix, dir) {
for (let y = 0; y < matrix.length; ++y) {
for (let x = 0; x < y; ++x) {
// Swap
[matrix[x][y], matrix[y][x]] = [
matrix[y][x],
matrix[x][y],
];
}
}
if (dir > 0) {
matrix.forEach(row => row.reverse());
} else {
matrix.reverse();
}
}
// Function to reset the player position and piece
function playerReset() {
const pieces = 'ILJOTSZ';
player.matrix = createPiece(
pieces[(pieces.length * Math.random()) | 0]
);
player.pos.y = 0;
player.pos.x =
((arena[0].length / 2) | 0) -
((player.matrix[0].length / 2) | 0);
if (collide(arena, player)) {
// Game over, clear arena
arena.forEach(row => row.fill(0));
}
}
// Function to clear filled rows
function arenaSweep() {
let rowCount = 1;
outer: for (let y = arena.length - 1; y >= 0; --y) {
for (let x = 0; x < arena[y].length; ++x) {
if (arena[y][x] === 0) {
continue outer;
}
}
const row = arena.splice(y, 1)[0].fill(0);
arena.unshift(row);
++y;
}
}
// Update function for animation and timing
let dropCounter = 0;
let dropInterval = 1000;
let lastTime = 0;
function update(time = 0) {
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
playerDrop();
}
draw();
requestAnimationFrame(update);
}
// Handle keyboard input
document.addEventListener('keydown', event => {
if (event.keyCode === 37) {
// Left arrow
playerMove(-1);
} else if (event.keyCode === 39) {
// Right arrow
playerMove(1);
} else if (event.keyCode === 40) {
// Down arrow
playerDrop();
} else if (event.keyCode === 81) {
// Q key
playerRotate(-1);
} else if (event.keyCode === 87) {
// W key
playerRotate(1);
}
});
// Define colors for the pieces
const colors = [
null,
'#FF0D72', // T
'#0DC2FF', // O
'#0DFF72', // L
'#F538FF', // J
'#FF8E0D', // I
'#FFE138', // S
'#3877FF', // Z
];
// Player object
const player = {
pos: { x: 0, y: 0 },
matrix: null,
};
// Start the game
playerReset();
update();
Step 3: Instructions to Play
-
Open an Online Code Editor:
-
Paste the Code:
- CodePen:
- In the HTML panel, paste the HTML code.
- In the JavaScript panel, paste the JavaScript code.
- You can ignore the CSS panel, as the CSS is included in the
<style> tag in the HTML code.
- JSFiddle/JS Bin:
- Paste the HTML code into the HTML section.
- Paste the JavaScript code into the JavaScript section.
-
Run the Code:
- CodePen: The game should load automatically. If not, click on the "Run" button.
- JSFiddle: Click on the "Run" button to execute the code.
- JS Bin: The game should display automatically; if not, click "Run" or reload the preview.
-
Play the Game:
- Controls:
- Left Arrow (
←): Move piece left.
- Right Arrow (
→): Move piece right.
- Down Arrow (
↓): Faster drop.
Q Key: Rotate piece counterclockwise.
W Key: Rotate piece clockwise.
-
Enjoy Playing Tetris!
Additional Notes
-
Game Mechanics:
- The game will automatically generate random Tetris pieces.
- When a row is completely filled, it will be cleared, and the blocks above will move down.
-
Restarting the Game:
- If the pieces stack up to the top of the arena, the game will reset, and you can continue playing.
-
Customization:
- You can customize colors and speeds by modifying the
colors array and dropInterval variable in the JavaScript code.
Feel free to experiment with the code and make improvements or add new features. Have fun coding and playing Tetris!