<!DOCTYPE html>
<html>
<head>
  <title>Tetris</title>
  <style>
    canvas {
      border:1px solid #d3d3d3;
      background-color: #f1f1f1;
    }
  </style>
</head>
<body onload='startGame()'>
  <script>
    var canvas;
    var canvasContext;
    var blockSize = 20;
    var width = 10;
    var height = 20;
    var currentX = 0;
    var currentY = 0;
<pre><code>window.onload = function() {
  canvas = document.getElementById('gameCanvas');
  canvasContext = canvas.getContext('2d');
  
  document.addEventListener('keydown', keyPressed);
}

function startGame() {
  drawBoard();
  var interval = setInterval(update, 500);
}

function drawBoard() {
  for(var x = 0; x &lt; width; x++) {
    for(var y = 0; y &lt; height; y++) {
      canvasContext.fillStyle = 'black';
      canvasContext.fillRect(x*blockSize, y*blockSize, blockSize, blockSize);
    }
  }
}

function keyPressed(evt) {
  switch(evt.keyCode) {
    // left arrow
    case 37:
      if(currentX &gt; 0) {
        currentX--;
      }
      break;
    // right arrow
    case 39:
      if(currentX &lt; width - 1) {
        currentX++;
      }
      break;
    // up arrow
    case 38:
      if(currentY &gt; 0) {
        currentY--;
      }
      break;
    // down arrow
    case 40:
      if(currentY &lt; height - 1) {
        currentY++;
      }
      break;
  }
}

function update() {
  canvasContext.fillStyle = 'white';
  canvasContext.fillRect(currentX*blockSize, currentY*blockSize, blockSize, blockSize);
}
</code></pre>
  </script>
  <canvas id='gameCanvas' width='200' height='400'></canvas>
</body>
</html>
HTML Tetris Game Example Code: Beginner's Guide

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

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