Simple HTML Game of Tetris

Tetris is a classic game that's been enjoyed by millions. This tutorial will guide you through creating a simple Tetris game using HTML, CSS, and JavaScript.

Step 1: Setting up the HTML File

First, create a basic HTML file. Create a new file and add the following code:

<!DOCTYPE html>
<html>
<head>
	<title>Tetris</title>
	<style>
		#game-board {
			width: 200px;
			height: 400px;
			border: 1px solid #000;
			position: relative;
			margin: 0 auto;
		}

		.block {
			position: absolute;
			width: 20px;
			height: 20px;
			border: 1px solid #000;
		}
	</style>
</head>
<body>
	<div id='game-board'></div>

	<script>
		// JavaScript code goes here
	</script>
</body>
</html>

This sets up the HTML structure and basic styles for the game board and blocks.

Step 2: Adding JavaScript Code

Now, let's add the JavaScript to create the game logic. Add this code inside the <script> tags:

var gameBoard = document.getElementById('game-board');
var blocks = [];
var currentBlock = null;

function createBlock() {
	// Create a new block and add it to the game board
	var block = document.createElement('div');
	block.className = 'block';
	block.style.left = '90px'; // Start in the middle of the game board
	gameBoard.appendChild(block);
	
	// Add the block to the blocks array
	blocks.push(block);
	
	// Set the current block to the newly created block
	currentBlock = block;
}

function moveBlockDown() {
	var top = parseInt(currentBlock.style.top) || 0;
	currentBlock.style.top = (top + 20) + 'px';
}

// Move the block down every 500ms
setInterval(moveBlockDown, 500);

// Create a new block every 2 seconds
setInterval(createBlock, 2000);

This code generates new blocks every 2 seconds and makes the current block move down every 500 milliseconds.

Step 3: Adding Keyboard Controls

Finally, let's add keyboard controls to let the player move the blocks left and right. Add this code to the JavaScript section:

document.addEventListener('keydown', function(event) {
	switch (event.keyCode) {
		case 37: // left arrow
			var left = parseInt(currentBlock.style.left) || 0;
			currentBlock.style.left = (left - 20) + 'px';
			break;
			
		case 39: // right arrow
			var left = parseInt(currentBlock.style.left) || 0;
			currentBlock.style.left = (left + 20) + 'px';
			break;
	}
});

This code listens for key presses and moves the current block left or right when the left or right arrow keys are pressed.

Conclusion

Congratulations! You've now created a simple Tetris game. This is just the beginning. You can add more features and complexity as you learn more about HTML, CSS, and JavaScript.

Simple HTML Tetris Game Tutorial: Build Your Own Classic Game

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

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