<!DOCTYPE html>
<html>
<head>
  <title>Simple Tetris Game</title>
  <style>
    #game-area {
      width: 500px;
      height: 500px;
      background-color: #EEE;
      position: relative;
      border: 2px solid #999;
    }
    .tetris-block {
      width: 25px;
      height: 25px;
      background-color: #000;
      position: absolute;
      left: 0;
      top: 0;
    }
  </style>
</head>
<body>
  <div id='game-area'></div>
  <script>
    var blockIndex = 0;
    var blocks = [
      {
        x: 0,
        y: 0
      },
      {
        x: 25,
        y: 0
      },
      {
        x: 25,
        y: 25
      },
      {
        x: 0,
        y: 25
      }
    ];
<pre><code>function moveBlockRight() {
  blocks.forEach(function(block) {
    block.x += 25;
  });

  drawBlock();
}

function moveBlockLeft() {
  blocks.forEach(function(block) {
    block.x -= 25;
  });

  drawBlock();
}

function moveBlockDown() {
  blocks.forEach(function(block) {
    block.y += 25;
  });

  drawBlock();
}

function rotateBlock() {
  blocks.forEach(function(block) {
    var x = block.x;
    var y = block.y;

    block.x = y;
    block.y = -x;
  });

  drawBlock();
}

function drawBlock() {
  var gameArea = document.getElementById('game-area');
  gameArea.innerHTML = '';

  blocks.forEach(function(block) {
    var div = document.createElement('div');
    div.className = 'tetris-block';
    div.style.left = block.x + 'px';
    div.style.top = block.y + 'px';
    gameArea.appendChild(div);
  });
}

document.onkeydown = function(e) {
  console.log(e.keyCode);
  switch(e.keyCode) {
    case 37:
      moveBlockLeft();
      break;
    case 38:
      rotateBlock();
      break;
    case 39:
      moveBlockRight();
      break;
    case 40:
      moveBlockDown();
      break;
  }
};

drawBlock();
</code></pre>
  </script>
</body>
</html>
Simple HTML Tetris Game - Build Your Own

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

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