在这里插入图片描述
以下是一个使用 HTML5 和 JavaScript 实现的简单俄罗斯方块小游戏的代码示例:

<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>俄罗斯方块小游戏</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }

        #game-board {
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <canvas id="game-board" width="300" height="600"></canvas>
    <script>
        // 获取画布元素和上下文
        const canvas = document.getElementById('game-board');
        const ctx = canvas.getContext('2d');

        // 定义方块大小
        const BLOCK_SIZE = 30;
        const COLS = canvas.width / BLOCK_SIZE;
        const ROWS = canvas.height / BLOCK_SIZE;

        // 定义方块形状
        const SHAPES = [
            [[1, 1, 1, 1]],
            [[1, 1], [1, 1]],
            [[1, 1, 0], [0, 1, 1]],
            [[0, 1, 1], [1, 1, 0]],
            [[1, 1, 1], [0, 1, 0]],
            [[1, 1, 1], [1, 0, 0]],
            [[1, 1, 1], [0, 0, 1]]
        ];

        // 方块类
        class Block {
            constructor() {
                this.shape = SHAPES[Math.floor(Math.random() * SHAPES.length)];
                this.x = Math.floor(COLS / 2) - Math.floor(this.shape[0].length / 2);
                this.y = 0;
                this.color = getRandomColor();
            }

            moveDown() {
                this.y++;
            }

            moveLeft() {
                this.x--;
            }

            moveRight() {
                this.x++;
            }

            rotate() {
                this.shape = this.shape[0].map((_, index) => this.shape.map(row => row[index]).reverse());
            }

            draw() {
                for (let i = 0; i < this.shape.length; i++) {
                    for (let j = 0; j < this.shape[0].length; j++) {
                        if (this.shape[i][j] === 1) {
                            ctx.fillStyle = this.color;
                            ctx.fillRect((this.x + j) * BLOCK_SIZE, (this.y + i) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
                            ctx.strokeStyle = 'black';
                            ctx.strokeRect((this.x + j) * BLOCK_SIZE, (this.y + i) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
                        }
                    }
                }
            }
        }

        // 生成随机颜色
        function getRandomColor() {
            const letters = '0123456789ABCDEF';
            let color = '#';
            for (let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }

        // 初始化游戏板
        const board = Array.from({ length: ROWS }, () => Array(COLS).fill(0));

        // 生成新方块
        function newBlock() {
            return new Block();
        }

        // 检查方块是否可以移动
        function canMove(block, dx, dy) {
            for (let i = 0; i < block.shape.length; i++) {
                for (let j = 0; j < block.shape[0].length; j++) {
                    if (block.shape[i][j] === 1) {
                        const newX = block.x + j + dx;
                        const newY = block.y + i + dy;
                        if (newX < 0 || newX >= COLS || newY >= ROWS || (newY >= 0 && board[newY][newX]!== 0)) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        // 合并方块到游戏板
        function mergeBlock(block) {
            for (let i = 0; i < block.shape.length; i++) {
                for (let j = 0; j < block.shape[0].length; j++) {
                    if (block.shape[i][j] === 1) {
                        board[block.y + i][block.x + j] = 1;
                    }
                }
            }
        }

        // 检查并消除满行
        function checkLines() {
            let linesCleared = 0;
            for (let i = 0; i < ROWS; i++) {
                if (board[i].every(cell => cell === 1)) {
                    board.splice(i, 1);
                    board.unshift(Array(COLS).fill(0));
                    linesCleared++;
                }
            }
            return linesCleared;
        }

        // 绘制游戏板
        function drawBoard() {
            for (let i = 0; i < ROWS; i++) {
                for (let j = 0; j < COLS; j++) {
                    if (board[i][j] === 1) {
                        ctx.fillStyle = 'gray';
                        ctx.fillRect(j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
                        ctx.strokeStyle = 'black';
                        ctx.strokeRect(j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
                    }
                }
            }
        }

        // 主游戏循环
        let currentBlock = newBlock();
        let score = 0;
        let gameOver = false;

        function gameLoop() {
            if (gameOver) return;

            ctx.clearRect(0, 0, canvas.width, canvas.height);
            drawBoard();
            currentBlock.draw();

            if (canMove(currentBlock, 0, 1)) {
                currentBlock.moveDown();
            } else {
                mergeBlock(currentBlock);
                const linesCleared = checkLines();
                score += linesCleared * 100;
                currentBlock = newBlock();
                if (!canMove(currentBlock, 0, 0)) {
                    gameOver = true;
                    alert(`游戏结束!得分: ${score}`);
                }
            }

            setTimeout(gameLoop, 300);
        }

        // 处理键盘事件
        document.addEventListener('keydown', function (event) {
            if (gameOver) return;
            if (event.key === 'ArrowLeft' && canMove(currentBlock, -1, 0)) {
                currentBlock.moveLeft();
            } else if (event.key === 'ArrowRight' && canMove(currentBlock, 1, 0)) {
                currentBlock.moveRight();
            } else if (event.key === 'ArrowDown' && canMove(currentBlock, 0, 1)) {
                currentBlock.moveDown();
            } else if (event.key === 'ArrowUp') {
                const newShape = currentBlock.shape[0].map((_, index) => currentBlock.shape.map(row => row[index]).reverse());
                const tempBlock = { shape: newShape, x: currentBlock.x, y: currentBlock.y };
                if (canMove(tempBlock, 0, 0)) {
                    currentBlock.rotate();
                }
            }
        });

        // 启动游戏循环
        gameLoop();
    </script>
</body>

</html>

代码说明

  1. HTML 部分:创建了一个画布元素用于显示游戏界面,并设置了基本的样式。
  2. JavaScript 部分
    • 方块类Block类表示当前下落的方块,包含移动、旋转和绘制的方法。
    • 游戏板管理:使用二维数组board表示游戏板,提供生成新方块、检查方块是否可以移动、合并方块到游戏板和检查并消除满行的功能。
    • 主游戏循环:使用setTimeout实现游戏循环,处理方块的下落和碰撞检测。
    • 键盘事件处理:监听键盘事件,处理用户的移动和旋转操作。

运行步骤

  1. 将上述代码保存为game.html文件。
  2. 用浏览器打开game.html文件,即可开始游戏。
    在这里插入图片描述

通过这个代码,你可以在网页上玩一个简单的俄罗斯方块小游戏。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐