Simple HTML Tetris Game

Here's a simple HTML Tetris game that you can play right in your browser!

HTML

First, let's set up the basic HTML structure of the game:

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <title>Simple HTML Tetris Game</title>
    <link rel='stylesheet' href='style.css'>
  </head>
  <body>
    <div id='game-board'></div>
    <script src='script.js'></script>
  </body>
</html>

Here, we have a basic HTML structure with a 'game-board' div that we'll use to hold our game. We've also linked to a 'style.css' file and a 'script.js' file that we'll create next.

CSS

Next, let's add some basic CSS to the 'style.css' file to style our game board:

#game-board {
  width: 200px;
  height: 400px;
  border: 2px solid black;
  position: relative;
}

Here, we've set the width and height of our game board and given it a black border. We've also positioned it relatively to allow us to position our game pieces later.

JavaScript

Finally, let's add some JavaScript to the 'script.js' file to create the game logic:

const gameBoard = document.querySelector('#game-board');

let gamePieces = [
  [1, 1, 1],
  [0, 1, 0],
  [0, 1, 0],
];

function draw() {
  gameBoard.innerHTML = '';
  for (let i = 0; i < gamePieces.length; i++) {
    for (let j = 0; j < gamePieces[i].length; j++) {
      if (gamePieces[i][j] === 1) {
        const block = document.createElement('div');
        block.classList.add('block');
        block.style.top = i * 20 + 'px';
        block.style.left = j * 20 + 'px';
        gameBoard.appendChild(block);
      }
    }
  }
}

draw();

Here, we've selected our 'game-board' div using 'document.querySelector' and created a 'gamePieces' array with a basic T-shaped game piece. We've then created a 'draw' function that loops through our 'gamePieces' array and creates and positions a 'block' div for each square in the game piece. Finally, we call 'draw' to render our game piece on the game board.

Play the Game

To play the game, simply open the HTML file in your browser and use the arrow keys to move the game piece around the board. You can continue to add more game pieces and game logic to create a full Tetris game!

Enjoy!

Simple HTML Tetris Game - Build Your Own Classic Game in Your Browser

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

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