<!DOCTYPE html>
<html>
  <head>
    <title>Tetris</title>
    <style>
      #game {
        width: 250px;
        height: 400px;
        margin: 0 auto;
        border: 1px solid black;
        position: relative;
      }
      .block {
        width: 20px;
        height: 20px;
        position: absolute;
        background-color: #000;
      }
    </style>
  </head>
  <body>
    <h1>Tetris</h1>
<pre><code>&lt;div id='game'&gt;&lt;/div&gt;

&lt;script&gt;
  // game parameters
  var x = 0;
  var y = 0;
  var blockSize = 20;
  var boardWidth = 250;
  var boardHeight = 400;
  var game = document.getElementById('game');
  
  // create the game board
  for (var i = 0; i &lt; boardWidth; i += blockSize) {
    for (var j = 0; j &lt; boardHeight; j += blockSize) {
      var block = document.createElement('div');
      block.classList.add('block');
      block.style.left = i + 'px';
      block.style.top = j + 'px';
      game.appendChild(block);
    }
  }
  
  // create blocks
  document.addEventListener('keydown', function(event) {
    if (event.keyCode === 37) {
      x -= blockSize;
    }
    if (event.keyCode === 39) {
      x += blockSize;
    }
    if (event.keyCode === 40) {
      y += blockSize;
    }
    if (x &lt; 0) {
      x = 0;
    }
    if (x &gt; (boardWidth - blockSize)) {
      x = boardWidth - blockSize;
    }
    if (y &gt; (boardHeight - blockSize)) {
      y = boardHeight - blockSize;
    }
    var block = document.createElement('div');
    block.classList.add('block');
    block.style.left = x + 'px';
    block.style.top = y + 'px';
    game.appendChild(block);
  });
&lt;/script&gt;
</code></pre>
  </body>
</html>
Simple HTML Tetris Game - Build Your Own

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

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