<!DOCTYPE html>
<html>
<head>
	<title>Simple HTML Tetris Game</title>
	<style type="text/css">
		#game{
			width: 200px;
			height: 400px;
			border: 1px solid black;
			background-color: lightgray;
			margin: 10px auto;
			position: relative;
		}
		#game div{
			position: absolute;
		}
		.block{
			width: 20px;
			height: 20px;
			border: 1px solid black;
			background-color: green;
		}
	</style>
</head>
<body>
	<div id="game"></div>
	<script type="text/javascript">
		// define the game board
		var board = document.getElementById('game');
<pre><code>	// define the blocks
	var block1 = document.createElement('div');
	block1.className = 'block';
	board.appendChild(block1);

	var block2 = document.createElement('div');
	block2.className = 'block';
	board.appendChild(block2);

	var block3 = document.createElement('div');
	block3.className = 'block';
	board.appendChild(block3);

	var block4 = document.createElement('div');
	block4.className = 'block';
	board.appendChild(block4);

	// define the initial position of the blocks
	var x = 0;
	var y = 0;
	block1.style.left = x + 'px';
	block1.style.top = y + 'px';

	block2.style.left = x + 20 + 'px';
	block2.style.top = y + 'px';

	block3.style.left = x + 'px';
	block3.style.top = y + 20 + 'px';

	block4.style.left = x + 20 + 'px';
	block4.style.top = y + 20 + 'px';

	// move the blocks with the arrow keys
	document.onkeydown = function(e){
		if(e.keyCode == 37){
			// left arrow key
			x -= 20;
			block1.style.left = x + 'px';
			block2.style.left = x + 20 + 'px';
			block3.style.left = x + 'px';
			block4.style.left = x + 20 + 'px';
		}
		if(e.keyCode == 38){
			// up arrow key
			y -= 20;
			block1.style.top = y + 'px';
			block2.style.top = y + 'px';
			block3.style.top = y + 20 + 'px';
			block4.style.top = y + 20 + 'px';
		}
		if(e.keyCode == 39){
			// right arrow key
			x += 20;
			block1.style.left = x + 'px';
			block2.style.left = x + 20 + 'px';
			block3.style.left = x + 'px';
			block4.style.left = x + 20 + 'px';
		}
		if(e.keyCode == 40){
			// down arrow key
			y += 20;
			block1.style.top = y + 'px';
			block2.style.top = y + 'px';
			block3.style.top = y + 20 + 'px';
			block4.style.top = y + 20 + 'px';
		}
	}
&lt;/script&gt;
</code></pre>
</body>
</html>
Simple HTML Tetris Game: Build Your Own Classic Game

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

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