<html>
<head>
  <title>Tetris Game</title>
  <style>
    #board {
      width: 400px;
      height: 600px;
      background-color: #ccc;
    }
  </style>
</head>
<body>
  <h1>Tetris Game</h1>
  <div id='board'></div>
  <script>
    // Board configuration
    let board = [
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    ];
<pre><code>// Generate new piece
let piece = {
  x: 5,
  y: 0,
  shape: [
    [1, 1],
    [1, 1],
  ]
};

// Update board
function draw() {
  for(let r = 0; r &lt; board.length; r++) {
    for(let c = 0; c &lt; board[0].length; c++) {
      if(board[r][c] === 0) {
        document.getElementById('board').innerHTML += '&amp;nbsp;';
      } else {
        document.getElementById('board').innerHTML += '&amp;#9632;';
      }
    }
    document.getElementById('board').innerHTML += '&lt;br&gt;';
  }
}

// Move piece
document.onkeydown = function(e) {
  if(e.keyCode == 37) {
    piece.x -= 1;
  } else if(e.keyCode == 39) {
    piece.x += 1;
  }
}

// Game loop
function loop() {
  // Update board
  board[piece.y][piece.x] = 1;

  // Clear board
  document.getElementById('board').innerHTML = '';

  // Draw board
  draw();

  // Move piece
  piece.y += 1;

  // Check for collision
  if(board[piece.y][piece.x] === 1) {
    piece.y -= 1;
  }
}

// Run game loop every second
setInterval(loop, 1000);
</code></pre>
  </script>
</body>
</html>
Simple HTML Tetris Game - Code Tutorial

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

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