Advanced HTML Code Tetris

To create a Tetris game using HTML and JavaScript, we need to break down the game into its basic elements and functionality. Here's a possible implementation:

HTML Structure

The first step is to create the HTML structure of the game. We need a container to hold the game board and a sidebar to display the score and other information. Here's the HTML code:

<!DOCTYPE html>
<html>
  <head>
    <title>Tetris Game</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="container">
      <div class="game-board"></div>
      <div class="sidebar">
        <div class="score">Score: <span id="score">0</span></div>
        <button id="start-button">Start Game</button>
        <div class="next-piece">
          <div class="label">Next Piece:</div>
          <div class="piece"></div>
        </div>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

CSS Styling

Next, we need to style the game board and sidebar using CSS. Here's the CSS code:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f2f2f2;
}

.game-board {
  width: 300px;
  height: 600px;
  border: 2px solid #333;
}

.sidebar {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  width: 200px;
  height: 600px;
  margin-left: 20px;
  padding: 20px;
  border: 2px solid #333;
  background-color: #ddd;
}

.score {
  font-size: 24px;
  font-weight: bold;
}

.next-piece {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.label {
  font-size: 18px;
  font-weight: bold;
}

.piece {
  width: 80px;
  height: 80px;
  border: 2px solid #333;
}

JavaScript Functionality

Finally, we need to add JavaScript functionality to the game. We need to create a game board, generate random tetrominoes, move the tetrominoes down the board, rotate the tetrominoes, check for collisions, clear completed lines, and update the score. Here's the JavaScript code:

const gameBoard = document.querySelector('.game-board');
const scoreDisplay = document.querySelector('#score');
const startButton = document.querySelector('#start-button');
const nextPiece = document.querySelector('.piece');

const ROWS = 20;
const COLS = 10;
const CELL_SIZE = 30;

const shapes = [
  [[1, 1, 1], [0, 1, 0]],
  [[0, 2, 2], [2, 2, 0]],
  [[3, 3, 0], [0, 3, 3]],
  [[4, 0, 0], [4, 4, 4]],
  [[0, 0, 5, 0], [0, 5, 5, 5]],
  [[6, 6], [6, 6]],
  [[0, 7, 0, 0], [0, 7, 7, 7]]
];

let board = [];
let tetromino = null;
let intervalId = null;
let score = 0;

function createBoard() {
  for (let row = 0; row < ROWS; row++) {
    board[row] = [];
    for (let col = 0; col < COLS; col++) {
      board[row][col] = 0;
    }
  }
}

function drawBoard() {
  let html = '';
  for (let row = 0; row < ROWS; row++) {
    for (let col = 0; col < COLS; col++) {
      if (board[row][col] !== 0) {
        html += `<div class="cell color-${board[row][col]}"></div>`;
      } else {
        html += `<div class="cell"></div>`;
      }
    }
  }
  gameBoard.innerHTML = html;
}

function drawPiece() {
  let html = '';
  for (let row = 0; row < tetromino.shape.length; row++) {
    for (let col = 0; col < tetromino.shape[row].length; col++) {
      if (tetromino.shape[row][col] !== 0) {
        html += `<div class="cell color-${tetromino.color}"></div>`;
      } else {
        html += `<div class="cell"></div>`;
      }
    }
  }
  const pieceTop = tetromino.row * CELL_SIZE;
  const pieceLeft = tetromino.col * CELL_SIZE;
  html = `<div class="piece" style="top:${pieceTop}px;left:${pieceLeft}px">${html}</div>`;
  gameBoard.innerHTML += html;
}

function clearPiece() {
  const piece = document.querySelector('.piece');
  if (piece) piece.remove();
}

function generateTetromino() {
  const index = Math.floor(Math.random() * shapes.length);
  const shape = shapes[index];
  const color = index + 1;
  const row = 0;
  const col = Math.floor(COLS / 2) - 1;
  return { shape, color, row, col };
}

function moveDown() {
  tetromino.row++;
  if (collides(tetromino)) {
    tetromino.row--;
    merge(tetromino);
    tetromino = generateTetromino();
    clearLines();
    updateScore();
    drawNextPiece();
    if (collides(tetromino)) {
      clearInterval(intervalId);
      gameOver();
    }
  }
  clearPiece();
  drawPiece();
}

function rotate() {
  const originalShape = tetromino.shape;
  const rotatedShape = [];
  for (let col = 0; col < originalShape[0].length; col++) {
    const newRow = [];
    for (let row = originalShape.length - 1; row >= 0; row--) {
      newRow.push(originalShape[row][col]);
    }
    rotatedShape.push(newRow);
  }
  tetromino.shape = rotatedShape;
  if (collides(tetromino)) {
    tetromino.shape = originalShape;
  }
  clearPiece();
  drawPiece();
}

function collides(piece) {
  for (let row = 0; row < piece.shape.length; row++) {
    for (let col = 0; col < piece.shape[row].length; col++) {
      if (piece.shape[row][col] !== 0) {
        const newRow = piece.row + row;
        const newCol = piece.col + col;
        if (newRow < 0 || newRow >= ROWS || newCol < 0 || newCol >= COLS || board[newRow][newCol] !== 0) {
          return true;
        }
      }
    }
  }
  return false;
}

function merge(piece) {
  for (let row = 0; row < piece.shape.length; row++) {
    for (let col = 0; col < piece.shape[row].length; col++) {
      if (piece.shape[row][col] !== 0) {
        const newRow = piece.row + row;
        const newCol = piece.col + col;
        board[newRow][newCol] = piece.color;
      }
    }
  }
}

function clearLines() {
  let linesCleared = 0;
  for (let row = ROWS - 1; row >= 0; row--) {
    if (board[row].every(cell => cell !== 0)) {
      linesCleared++;
      board.splice(row, 1);
      board.unshift(new Array(COLS).fill(0));
      row++;
    }
  }
  if (linesCleared === 1) {
    score += 40;
  } else if (linesCleared === 2) {
    score += 100;
  } else if (linesCleared === 3) {
    score += 300;
  } else if (linesCleared === 4) {
    score += 1200;
  }
}

function updateScore() {
  scoreDisplay.innerText = score;
}

function drawNextPiece() {
  const html = '';
  for (let row = 0; row < tetromino.shape.length; row++) {
    for (let col = 0; col < tetromino.shape[row].length; col++) {
      if (tetromino.shape[row][col] !== 0) {
        html += `<div class="cell color-${tetromino.color}"></div>`;
      } else {
        html += `<div class="cell"></div>`;
      }
    }
  }
  nextPiece.innerHTML = html;
}

function gameOver() {
  alert(`Game Over! Your score is ${score}`);
}

function startGame() {
  createBoard();
  drawBoard();
  tetromino = generateTetromino();
  drawPiece();
  intervalId = setInterval(moveDown, 500);
}

startButton.addEventListener('click', startGame);

Conclusion

With this HTML, CSS, and JavaScript code, you can create an advanced Tetris game that includes all the basic functionality of the classic game. You can customize the game by adjusting the colors, shapes, and scoring system. Have fun playing and creating new variations of this classic game!

Advanced HTML Tetris Game: Build Your Own Tetris Experience

原文地址: https://www.cveoy.top/t/topic/lnQy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录