o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
write a tetris game
- User
write a tetris game
- Assistant
write a tetris game
Sure! Below is a simple Tetris game implemented in JavaScript using HTML5 Canvas. You can run this code by creating an index.html file and copying the code into it. Then, open the file in a web browser to play the game.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tetris Game</title>
<style>
canvas {
background: #000;
display: block;
margin: 0 auto;
}
body {
text-align: center;
color: #fff;
background-color: #222;
font-family: Arial, sans-serif;
}
h1 {
margin-top: 20px;
}
</style>
</head>
<body>
<h1>JavaScript Tetris</h1>
<canvas id="tetris" width="240" height="400"></canvas>
<script>
const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.scale(20, 20);
// Create the matrix for each Tetris piece
function createPiece(type) {
if (type === 'T') {
return [
[0, 0, 0],
[1, 1, 1],
[0, 1, 0],
];
} else if (type === 'O') {
return [
[2, 2],
[2, 2],
];
} else if (type === 'L') {
return [
[0, 0, 3],
[3, 3, 3],
[0, 0, 0],
];
} else if (type === 'J') {
return [
[4, 0, 0],
[4, 4, 4],
[0, 0, 0],
];
} else if (type === 'I') {
return [
[0, 5, 0, 0],
[0, 5, 0, 0],
[0, 5, 0, 0],
[0, 5, 0, 0],
];
} else if (type === 'S') {
return [
[0, 6, 6],
[6, 6, 0],
[0, 0, 0],
];
} else if (type === 'Z') {
return [
[7, 7, 0],
[0, 7, 7],
[0, 0, 0],
];
}
}
// Function to create the game arena
function createMatrix(w, h) {
const matrix = [];
while (h--) {
matrix.push(new Array(w).fill(0));
}
return matrix;
}
// Function to check for 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 merge the 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 rotate the piece
function rotate(matrix, dir) {
for (let y = 0; y < matrix.length; ++y) {
for (let x = 0; x < y; ++x) {
[
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 draw the game arena and the player piece
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 draw a matrix (game arena or piece)
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 clear completed rows
function arenaSweep() {
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;
player.score += 10;
updateScore();
}
}
// 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 reset the player piece after it lands
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)) {
arena.forEach(row => row.fill(0));
player.score = 0;
updateScore();
}
}
// Function to rotate the player piece
function playerRotate(dir) {
const pos = player.pos.x;
let offset = 1;
rotate(player.matrix, dir);
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;
}
}
}
let dropCounter = 0;
let dropInterval = 1000;
let lastTime = 0;
// Update function to control game loop
function update(time = 0) {
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
playerDrop();
}
draw();
requestAnimationFrame(update);
}
// Update the player's score display
function updateScore() {
document.getElementById('score').innerText = `Score: ${player.score}`;
}
// Colors for each piece
const colors = [
null,
'#FF0D72', // T
'#0DC2FF', // O
'#0DFF72', // L
'#F538FF', // J
'#FF8E0D', // I
'#FFE138', // S
'#3877FF', // Z
];
const arena = createMatrix(12, 20);
const player = {
pos: {x: 0, y: 0},
matrix: null,
score: 0,
};
document.addEventListener('keydown', event => {
if (event.keyCode === 37) {
playerMove(-1);
} else if (event.keyCode === 39) {
playerMove(1);
} else if (event.keyCode === 40) {
playerDrop();
} else if (event.keyCode === 81) {
playerRotate(-1);
} else if (event.keyCode === 87) {
playerRotate(1);
}
});
playerReset();
updateScore();
update();
</script>
<h2 id="score">Score: 0</h2>
</body>
</html>
Create a New File:
Save the File:
index.html.Open the Game:
index.html in a modern web browser (Chrome, Firefox, Edge).Play Tetris:
←): Move piece left.→): Move piece right.↓): Soft drop the piece.Q Key: Rotate piece counter-clockwise.W Key: Rotate piece clockwise.Canvas Setup:
<canvas> element is used to draw the game graphics.context.scale(20, 20); line scales up the drawing by 20, so each block is 20x20 pixels.Game Mechanics:
createPiece function generates the shape of each Tetris piece as a matrix.arena represents the game board where pieces stack up.collide function.arena using the merge function.arenaSweep function checks for completed rows and clears them, increasing the score.Player Controls:
playerDrop, playerMove, and playerRotate functions handle the player's actions.Game Loop:
update function is called recursively using requestAnimationFrame to create the game loop.Scoring:
You can customize the game by modifying various parts of the code:
Speed Adjustment:
dropInterval value to adjust the speed at which pieces fall.Colors:
colors array to change the colors of the Tetris pieces.Controls:
document.addEventListener('keydown', ...) section to change the controls.Game Board Size:
createMatrix(12, 20); call to change the size of the game board.Have fun playing the Tetris game! Feel free to enhance it further by adding new features like level progression, hard drop, hold piece, or sound effects.
Not yet included in a published release.