<!DOCTYPE html>
<html>
	<head>
		<title>Tetris</title>
		<style>
			#game-board {
				width: 200px;
				height: 400px;
				background-color: #000;
				border: 1px solid #000;
			}
			.block {
				width: 20px;
				height: 20px;
				background-color: #FFF;
				display: inline-block;
				margin: 0px;
				border: 1px solid #000;
			}
		</style>
	</head>
	<body>
<pre><code>	&lt;div id='game-board'&gt;
		
	&lt;/div&gt;
	
	&lt;script&gt;
		let board = document.querySelector('#game-board');
		let block;
		
		// Shapes
		let shapes = [
			[1, 1, 1, 1],
			[1, 1, 1, 0,
			 1],
			[1, 1, 1, 0,
			 0, 0, 1],
			[1, 1, 0, 0,
			 1, 1],
			[1, 1, 0, 0,
			 0, 1, 1],
			[0, 1, 1, 0,
			 1, 1],
			[0, 1, 0, 0,
			 1, 1, 1]
		];
		
		// Randomly Select Shape
		let shape = shapes[Math.floor(Math.random() * shapes.length)];
		
		// Position
		let x = 3;
		let y = 0;
		
		// Create Block
		function createBlock(x, y) {
			block = document.createElement('div');
			block.setAttribute('class', 'block');
			block.style.top = y * 20 + 'px';
			block.style.left = x * 20 + 'px';
			board.appendChild(block);
		}
		
		// Draw Shape
		function draw() {
			for (let i = 0; i &lt; shape.length; i++) {
				if (shape[i]) {
					createBlock(x + i % 2, y + Math.floor(i / 2));
				}
			}
		}
		
		// Move Right
		document.addEventListener('keydown', (e) =&gt; {
			if (e.keyCode == 39) {
				if (x &lt; 10 - shape.length % 2) {
					x++;
					draw();
				}
			}
			
			// Move Left
			if (e.keyCode == 37) {
				if (x &gt; 0) {
					x--;
					draw();
				}
			}
			
			// Move Down
			if (e.keyCode == 40) {
				if (y &lt; 20 - shape.length / 2) {
					y++;
					draw();
				}
			}
		});
		
		draw();
	&lt;/script&gt;
	
&lt;/body&gt;
</code></pre>
</html>
HTML Tetris Game: Build Your Own Classic Puzzle Game

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

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