HTML Tetris Game Example Code: Beginner's Guide
<!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 < width; x++) {
for(var y = 0; y < 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 > 0) {
currentX--;
}
break;
// right arrow
case 39:
if(currentX < width - 1) {
currentX++;
}
break;
// up arrow
case 38:
if(currentY > 0) {
currentY--;
}
break;
// down arrow
case 40:
if(currentY < 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>
原文地址: https://www.cveoy.top/t/topic/losL 著作权归作者所有。请勿转载和采集!