gpt-4o-2024-11-20· OpenAI
WildChat-4.8M (AI2)
напиши на HTML тетрис
- User
напиши на HTML тетрис
- Assistant
- User
добавь счётчик очков и разные цвета фигурам
- Assistant
напиши на HTML тетрис
добавь счётчик очков и разные цвета фигурам
Конечно! Вот простой пример HTML и JavaScript для создания базовой версии тетриса. Это пример описывает создание игрового поля и элементов управления, а также базовую механику игры:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Тетрис</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #111;
color: white;
font-family: Arial, sans-serif;
}
canvas {
background: #333;
display: block;
border: 4px solid #fff;
}
</style>
</head>
<body>
<canvas id="tetris" width="240" height="400"></canvas>
<script>
const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.scale(20, 20);
// Создаем игровое поле
function createMatrix(w, h) {
const matrix = [];
while (h--) {
matrix.push(new Array(w).fill(0));
}
return matrix;
}
// Создаем фигуры (Тетромино)
function createPiece(type) {
if (type === 'T') {
return [
[0, 1, 0],
[1, 1, 1],
[0, 0, 0],
];
} else if (type === 'O') {
return [
[1, 1],
[1, 1],
];
} else if (type === 'L') {
return [
[0, 0, 1],
[1, 1, 1],
[0, 0, 0],
];
} else if (type === 'J') {
return [
[1, 0, 0],
[1, 1, 1],
[0, 0, 0],
];
} else if (type === 'I') {
return [
[0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0],
];
} else if (type === 'S') {
return [
[0, 1, 1],
[1, 1, 0],
[0, 0, 0],
];
} else if (type === 'Z') {
return [
[1, 1, 0],
[0, 1, 1],
[0, 0, 0],
];
}
}
// Рендеринг игровой сетки
function drawMatrix(matrix, offset) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
context.fillStyle = 'red';
context.fillRect(x + offset.x, y + offset.y, 1, 1);
}
});
});
}
// Очистка экрана
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 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 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 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++;
}
}
// Движение фигуры вниз
function playerDrop() {
player.pos.y++;
if (collide(arena, player)) {
player.pos.y--;
merge(arena, player);
playerReset();
arenaSweep();
}
dropCounter = 0;
}
// Перемещение игрока влево/вправо
function playerMove(dir) {
player.pos.x += dir;
if (collide(arena, player)) {
player.pos.x -= dir;
}
}
// Сброс игрока при столкновении
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));
}
}
// Поворот фигуры
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 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;
function update(time = 0) {
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
playerDrop();
}
draw();
requestAnimationFrame(update);
}
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);
}
});
const arena = createMatrix(12, 20);
const player = {
pos: { x: 0, y: 0 },
matrix: null,
};
playerReset();
update();
</script>
</body>
</html>
Это базовый пример, который можно улучшать. Например, можно добавить:
Вот обновленный пример, где добавлен счетчик очков и разные цвета для фигур. Я аккуратно оптимизировал код, чтобы учет очков работал при очистке линий, а фигуры были окрашены в разные цвета.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Тетрис с очками и цветами</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
background: #111;
color: #fff;
font-family: Arial, sans-serif;
margin: 0;
}
canvas {
background: #333;
display: block;
border: 4px solid #fff;
}
.score {
margin-bottom: 20px;
font-size: 20px;
}
</style>
</head>
<body>
<div class="score">Очки: <span id="score">0</span></div>
<canvas id="tetris" width="240" height="400"></canvas>
<script>
const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.scale(20, 20);
const scoreElement = document.getElementById('score');
let score = 0;
function createMatrix(w, h) {
const matrix = [];
while (h--) {
matrix.push(new Array(w).fill(0));
}
return matrix;
}
function createPiece(type) {
if (type === 'T') {
return [
[0, 'T', 0],
['T', 'T', 'T'],
[0, 0, 0],
];
} else if (type === 'O') {
return [
['O', 'O'],
['O', 'O'],
];
} else if (type === 'L') {
return [
[0, 0, 'L'],
['L', 'L', 'L'],
[0, 0, 0],
];
} else if (type === 'J') {
return [
['J', 0, 0],
['J', 'J', 'J'],
[0, 0, 0],
];
} else if (type === 'I') {
return [
[0, 0, 0, 0],
['I', 'I', 'I', 'I'],
[0, 0, 0, 0],
];
} else if (type === 'S') {
return [
[0, 'S', 'S'],
['S', 'S', 0],
[0, 0, 0],
];
} else if (type === 'Z') {
return [
['Z', 'Z', 0],
[0, 'Z', 'Z'],
[0, 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() {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
drawMatrix(arena, { x: 0, y: 0 });
drawMatrix(player.matrix, player.pos);
}
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 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++;
score += rowCount * 10;
rowCount *= 2;
}
scoreElement.innerText = score;
}
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 playerDrop() {
player.pos.y++;
if (collide(arena, player)) {
player.pos.y--;
merge(arena, player);
playerReset();
arenaSweep();
}
dropCounter = 0;
}
function playerMove(dir) {
player.pos.x += dir;
if (collide(arena, player)) {
player.pos.x -= dir;
}
}
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));
score = 0;
scoreElement.innerText = score;
}
}
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 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;
function update(time = 0) {
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
playerDrop();
}
draw();
requestAnimationFrame(update);
}
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);
}
});
const colors = {
T: 'purple',
O: 'yellow',
L: 'orange',
J: 'blue',
I: 'cyan',
S: 'green',
Z: 'red',
};
const arena = createMatrix(12, 20);
const player = {
pos: { x: 0, y: 0 },
matrix: null,
};
playerReset();
update();
</script>
</body>
</html>
colors.Теперь фигуры выглядят ярче, и вы можете наблюдать прогресс игрока за счет обновлений счета.
Not yet included in a published release.