o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
make a tetris game using css javascript and html, separate the programming languages
- User
make a tetris game using css javascript and html, separate the programming languages
- Assistant
make a tetris game using css javascript and html, separate the programming languages
Certainly! Below is a simple Tetris game implemented using HTML, CSS, and JavaScript. The code is separated by language for clarity.
index.html)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Tetris Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="tetris" width="240" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
style.css)body {
background-color: #000;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
#tetris {
border: 2px solid #fff;
box-shadow: 0 0 10px #fff;
}
script.js)const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
// Scale the canvas up by a factor for better visibility
context.scale(20, 20);
// Create the arena (game board)
const arena = createMatrix(12, 20);
// Player object to hold position and piece matrix
const player = {
pos: {x: 0, y: 0},
matrix: null,
score: 0,
};
// Piece colors
const colors = [
null,
'#FF0D72', // T
'#0DC2FF', // O
'#0DFF72', // S
'#F538FF', // Z
'#FF8E0D', // L
'#FFE138', // J
'#3877FF', // I
];
// Functions for game logic (collisions, rotations, etc.)
function createMatrix(width, height) {
const matrix = [];
while (height--) {
matrix.push(new Array(width).fill(0));
}
return matrix;
}
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 'S':
return [
[0, 3, 3],
[3, 3, 0],
[0, 0, 0],
];
case 'Z':
return [
[4, 4, 0],
[0, 4, 4],
[0, 0, 0],
];
case 'L':
return [
[0, 5, 0],
[0, 5, 0],
[0, 5, 5],
];
case 'J':
return [
[0, 6, 0],
[0, 6, 0],
[6, 6, 0],
];
case 'I':
return [
[0, 7, 0, 0],
[0, 7, 0, 0],
[0, 7, 0, 0],
[0, 7, 0, 0],
];
}
}
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 draw() {
// Clear the canvas
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
// Draw the arena and the player piece
drawMatrix(arena, {x: 0, y: 0});
drawMatrix(player.matrix, player.pos);
}
function merge(arena, player) {
// Merge the player's piece into the arena when it lands
player.matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
arena[y + player.pos.y][x + player.pos.x] = value;
}
});
});
}
function rotate(matrix, dir) {
// Transpose the matrix
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],
];
}
}
// Reverse the rows for the rotation direction
if (dir > 0){
matrix.forEach(row => row.reverse());
} else {
matrix.reverse();
}
}
function playerReset() {
// Reset the player position and create a new random piece
const pieces = 'ILJOTSZ';
player.matrix = createPiece(pieces[Math.floor(Math.random() * pieces.length)]);
player.pos.y = 0;
player.pos.x = (arena[0].length / 2 | 0) -
(player.matrix[0].length / 2 | 0);
// Check if the new piece collides immediately (game over)
if (collide(arena, player)) {
arena.forEach(row => row.fill(0));
player.score = 0;
updateScore();
}
}
function playerMove(dir) {
// Move the player left or right
player.pos.x += dir;
if (collide(arena, player)) {
player.pos.x -= dir;
}
}
function playerDrop() {
// Move the player piece down
player.pos.y++;
if (collide(arena, player)) {
player.pos.y--;
merge(arena, player);
playerReset();
arenaSweep();
updateScore();
}
dropCounter = 0;
}
function playerRotate(dir) {
// Rotate the player piece
const pos = player.pos.x;
let offset = 1;
rotate(player.matrix, dir);
// Adjust position if collision occurs after rotation
while (collide(arena, player)) {
player.pos.x += offset;
offset = -(offset + (offset > 0 ? 1 : -1));
if (offset > player.matrix[0].length) {
// Rotate back if no valid position found
rotate(player.matrix, -dir);
player.pos.x = pos;
return;
}
}
}
function collide(arena, player) {
// Check for collisions with the arena
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 arenaSweep() {
// Clear complete rows and update score
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;
}
}
// Remove the complete row
const row = arena.splice(y, 1)[0].fill(0);
// Add a new empty row on top
arena.unshift(row);
++y;
player.score += rowCount * 10;
rowCount *= 2;
}
}
function update(time = 0) {
// Update game state and render
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if (dropCounter > dropInterval){
playerDrop();
}
draw();
requestAnimationFrame(update);
}
function updateScore() {
// Display the player's score (implement as needed)
console.log('Score:', player.score);
}
// Game variables for timing
let dropCounter = 0;
let dropInterval = 1000;
let lastTime = 0;
// Event listeners for keyboard controls
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);
}
});
// Start the game
playerReset();
updateScore();
update();
Create the Files:
index.html: Copy the HTML code into a new file named index.html.style.css: Copy the CSS code into a new file named style.css.script.js: Copy the JavaScript code into a new file named script.js.Set Up the Project Structure:
Ensure all files are in the same directory, or adjust the paths in the HTML <link> and <script> tags if you organize them into subdirectories.
Run the Game:
Open index.html in a modern web browser (e.g., Chrome, Firefox, Edge) to start the game.
←): Move the falling piece left.→): Move the falling piece right.↓): Move the piece down faster.Q Key: Rotate the piece counterclockwise.W Key: Rotate the piece clockwise.Feel free to enhance the game further by adding new features or improving the design to suit your preferences. Enjoy coding your own Tetris game!
Not yet included in a published release.