Simple HTML Tetris Game - Play Now!
<html>
<head>
<title>Tetris</title>
<style>
body {
background-color: black;
}
<pre><code> canvas {
border: 1px solid red;
}
</style>
</code></pre>
</head>
<body>
<h1>Tetris</h1>
<p>Use the arrow keys to move the blocks.</p>
<canvas id='tetris' width='200' height='400'></canvas>
<script>
var canvas = document.getElementById('tetris');
var ctx = canvas.getContext('2d');
var score = 0;
<pre><code> // define the blocks
var block1 = {
x: 3,
y: 0,
color: 'cyan'
};
var block2 = {
x: 4,
y: 0,
color: 'cyan'
};
var block3 = {
x: 3,
y: 1,
color: 'cyan'
};
var block4 = {
x: 4,
y: 1,
color: 'cyan'
};
// draw the blocks
function drawBlock(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * 20, y * 20, 20, 20);
ctx.strokeStyle = 'black';
ctx.strokeRect(x * 20, y * 20, 20, 20);
}
// draw the blocks
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBlock(block1.x, block1.y, block1.color);
drawBlock(block2.x, block2.y, block2.color);
drawBlock(block3.x, block3.y, block3.color);
drawBlock(block4.x, block4.y, block4.color);
}
// move the blocks
document.addEventListener('keydown', move);
function move(e) {
if (e.keyCode == 37) {
block1.x -= 1;
block2.x -= 1;
block3.x -= 1;
block4.x -= 1;
} else if (e.keyCode == 38) {
block1.y -= 1;
block2.y -= 1;
block3.y -= 1;
block4.y -= 1;
} else if (e.keyCode == 39) {
block1.x += 1;
block2.x += 1;
block3.x += 1;
block4.x += 1;
} else if (e.keyCode == 40) {
block1.y += 1;
block2.y += 1;
block3.y += 1;
block4.y += 1;
}
draw();
}
// loop the game
setInterval(function() {
block1.y += 1;
block2.y += 1;
block3.y += 1;
block4.y += 1;
draw();
}, 1000);
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmoZ 著作权归作者所有。请勿转载和采集!