简体中文简体中文
EnglishEnglish
简体中文简体中文

轻松上手!JS小游戏源码分享,助你打造属于自己的

2024-12-28 07:32:49

随着互联网的快速发展,JavaScript(简称JS)已经成为前端开发中不可或缺的编程语言。利用JS,我们可以轻松地制作出各种有趣的小游戏,让网页焕发活力。今天,就为大家分享一些JS小游戏的源码,让你轻松上手,打造属于自己的游戏世界。

一、贪吃蛇游戏

贪吃蛇游戏是一款经典的街机游戏,下面是贪吃蛇游戏的源码:

`html <!DOCTYPE html> <html> <head> <title>贪吃蛇游戏</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="snakeCanvas" width="400" height="400"></canvas> <script> var canvas = document.getElementById('snakeCanvas'); var ctx = canvas.getContext('2d'); var snake = [{x: 50, y: 50}]; var food = {x: Math.floor(Math.random() 20) 20, y: Math.floor(Math.random() 20) 20}; var dx = 20; var dy = 0; var score = 0;

    function draw() {
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.strokeStyle = 'black';
        ctx.strokeRect(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < snake.length; i++) {
            ctx.fillStyle = (i === 0) ? 'green' : 'blue';
            ctx.fillRect(snake[i].x, snake[i].y, 20, 20);
            ctx.strokeStyle = 'red';
            ctx.strokeRect(snake[i].x, snake[i].y, 20, 20);
        }
        ctx.fillStyle = 'red';
        ctx.fillRect(food.x, food.y, 20, 20);
        var head = {x: snake[0].x + dx, y: snake[0].y + dy};
        snake.unshift(head);
        if (head.x === food.x && head.y === food.y) {
            score++;
            food = {x: Math.floor(Math.random() * 20) * 20, y: Math.floor(Math.random() * 20) * 20};
        } else {
            snake.pop();
        }
        if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
            alert('Game Over!');
            return;
        }
        for (var i = 0; i < snake.length; i++) {
            if (head.x === snake[i].x && head.y === snake[i].y) {
                alert('Game Over!');
                return;
            }
        }
        setTimeout(draw, 100);
    }
    document.addEventListener('keydown', function (e) {
        var key = e.keyCode;
        if (key === 37 && dx === 0) {
            dx = -20;
            dy = 0;
        } else if (key === 38 && dy === 0) {
            dx = 0;
            dy = -20;
        } else if (key === 39 && dx === 0) {
            dx = 20;
            dy = 0;
        } else if (key === 40 && dy === 0) {
            dx = 0;
            dy = 20;
        }
    });
    draw();
</script>

</body> </html> `

二、俄罗斯方块游戏

俄罗斯方块游戏是一款经典的游戏,下面是俄罗斯方块游戏的源码:

`html <!DOCTYPE html> <html> <head> <title>俄罗斯方块游戏</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="tetrisCanvas" width="400" height="600"></canvas> <script> var canvas = document.getElementById('tetrisCanvas'); var ctx = canvas.getContext('2d'); var board = []; var pieces = [ [[1, 1, 1, 1]], [[1, 1], [1, 1]], [[0, 1, 0], [1, 1, 1], [0, 1, 0]], [[0, 0, 1], [1, 1, 1], [0, 0, 1]], [[1, 1, 0], [0, 1, 1], [0, 0, 0]], [[0, 1, 1], [1, 1, 0], [0, 0, 0]], [[0, 0, 0], [1, 1, 1], [0, 1, 0]] ]; var currentPiece = null; var x = 0; var y = 0; var timer = null;

    function drawBoard() {
        for (var i = 0; i < 20; i++) {
            for (var j = 0; j < 10; j++) {
                var color = (board[i][j] === 0) ? 'white' : 'blue';
                ctx.fillStyle = color;
                ctx.fillRect(j * 20, i * 20, 20, 20);
                ctx.strokeStyle = 'black';
                ctx.strokeRect(j * 20, i * 20, 20, 20);
            }
        }
    }
    function drawPiece() {
        ctx.fillStyle = 'red';
        for (var i = 0; i < currentPiece.length; i++) {
            for (var j = 0; j < currentPiece[i].length; j++) {
                if (currentPiece[i][j]) {
                    ctx.fillRect(x + j * 20, y + i * 20, 20, 20);
                    ctx.strokeStyle = 'black';
                    ctx.strokeRect(x + j * 20, y + i * 20, 20, 20);
                }
            }
        }
    }
    function moveDown() {
        if (!canMoveDown()) {
            drop();
            resetTimer();
            return;
        }
        y++;
    }
    function canMoveDown() {
        for (var i = 0; i < currentPiece.length; i++) {
            for (var j = 0; j < currentPiece[i].length; j++) {
                if (currentPiece[i][j]) {
                    if (y + i >= 20 || board[y + i][x + j]) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
    function drop() {
        while (canMoveDown()) {
            y++;
        }
        placePiece();
    }
    function placePiece() {
        for (var i = 0; i < currentPiece.length; i++) {
            for (var j = 0; j < currentPiece[i].length; j++) {
                if (currentPiece[i][j]) {
                    board[y + i][x + j] = currentPiece[i][j];
                }
            }
        }
        newPiece();
    }
    function newPiece() {
        currentPiece = pieces[Math.floor(Math.random() * pieces.length)];
        x = Math.floor((canvas.width - currentPiece[0].length * 20) / 2);
        y = 0;
    }
    function resetTimer() {
        clearTimeout(timer);
        timer = setTimeout(drop, 1000);
    }
    drawBoard();
    newPiece();
    timer = setTimeout(drop, 1000);
    document.addEventListener('keydown', function (e) {
        var key = e.keyCode;
        if (key === 37 && canMoveLeft()) {
            x -= 20;
        } else if (key === 38) {
            rotate();
        } else if (key === 39 && canMoveRight()) {
            x += 20;
        } else if (key === 40) {
            moveDown();
        }
    });
    function canMoveLeft() {
        for (var i = 0; i < currentPiece.length; i++) {
            for (var j = 0; j < currentPiece[i].length; j++) {
                if (currentPiece[i][j]) {
                    if (x + j < 0 || board[y + i][x + j - 1]) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
    function canMoveRight() {
        for (var i = 0; i < currentPiece.length; i++) {
            for (var j = 0; j < currentPiece[i].length; j++) {
                if (currentPiece[i][j]) {
                    if (x + j >= canvas.width - 20 || board[y + i][x + j + 1]) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
    function rotate() {
        var rotatedPiece = [];
        for (var i = currentPiece[0].length - 1; i >= 0; i--) {
            rotatedPiece.push(currentPiece.map(function (row) {
                return row[i];
            }));
        }
        if (canRotate(rotatedPiece)) {
            currentPiece = rotatedPiece;
        }
    }
    function canRotate(rotatedPiece) {
        for (var i = 0; i < rotatedPiece.length; i++) {
            for (var j = 0; j < rotatedPiece[i].length; j++) {
                if (rotatedPiece[i][j]) {
                    if (x + j < 0 || x + j >= canvas.width - 20 || y + i < 0 || y + i >= 20) {
                        return false;
                    }
                    if (board[y + i][x + j]) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
</script>

</body> </html> `

三、拼图游戏

拼图游戏是一款益智类游戏,下面是拼图游戏的源码:

`html <!DOCTYPE html> <html> <head> <title>拼图游戏</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="puzzleCanvas" width="400" height="400"></canvas> <script> var canvas = document.getElementById('puzzleCanvas'); var ctx = canvas.getContext('2d'); var puzzle = []; var puzzleSize = 4; var pieces = []; var currentPiece = null; var x = 0; var y = 0;

    function drawBoard() {
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.strokeStyle = 'black';
        ctx.strokeRect(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < puzzle.length; i++) {
            for (var j = 0; j < puzzle[i].length; j++) {
                if (puzzle[i][j]) {
                    ctx.fillStyle = 'red';
                    ctx.fillRect(j * puzzleSize, i * puzzleSize, puzzleSize, puzzleSize);
                    ctx.strokeStyle = 'black';
                    ctx.strokeRect(j * puzzleSize, i * puzzleSize, puzzleSize, puzzleSize);
                }
            }
        }
    }
    function drawPiece() {
        ctx.fillStyle = 'blue';
        ctx.fillRect(x, y, puzzleSize, puzzleSize);
        ctx.strokeStyle = 'black';
        ctx.strokeRect(x, y, puzzleSize, puzzleSize);
    }
    function shufflePuzzle() {
        puzzle = [];
        for (var i = 0; i < puzzleSize; i++) {
            puzzle[i] = [];
            for (var j = 0; j < puzzleSize; j++) {
                puzzle[i][j] = Math.floor(Math.random() * puzzleSize);
            }
        }
        puzzle[puzzleSize - 1][puzzleSize - 1] = 0;
    }
    function newPiece() {
        currentPiece = Math.floor(Math.random() * puzzleSize);
        x = Math.floor((canvas.width - puzzleSize * puzzleSize) / 2);
        y = Math.floor((canvas.height - puzzleSize * puzzleSize) / 2);
    }
    function checkWin() {
        for (var i = 0; i < puzzle.length; i++) {
            for (var j = 0; j < puzzle[i].length; j++) {
                if (puzzle[i][j] !== j) {
                    return false;
                }
            }
        }
        return true;
    }
    drawBoard();
    shufflePuzzle();
    newPiece();
    document.addEventListener('keydown', function (e) {
        var key = e.keyCode;
        if (key === 37 && canMoveLeft()) {
            x -= puzzleSize;
        } else if (key === 38 && canMoveUp()) {
            y -= puzzleSize;
        } else if (key === 39 && canMoveRight()) {
            x += puzzleSize;
        } else if (key === 40 && canMoveDown()) {
            y += puzzleSize;
        }
    });
    function canMoveLeft() {
        return (x - puzzleSize >= 0 && puzzle[Math.floor(y / puzzleSize)][Math.floor(x / puzzleSize) - 1] !== 0);
    }
    function canMoveUp() {
        return (y - puzzleSize >= 0 && puzzle[Math.floor(y / puzzleSize) - 1][Math.floor(x / puzzleSize)] !== 0);
    }
    function canMoveRight() {
        return (x + puzzleSize < canvas.width && puzzle[Math.floor(y / puzzleSize)][Math.floor(x / puzzleSize) + 1] !== 0);
    }
    function canMoveDown() {
        return (y + puzzleSize < canvas.height && puzzle[Math.floor(y / puzzleSize) + 1][Math.floor(x / puzzleSize)] !== 0);
    }
    function movePiece() {
        if (canMoveLeft()) {
            x -= puzzleSize;
        } else if (canMoveUp()) {
            y -= puzzleSize;
        } else if (canMoveRight()) {
            x += puzzleSize;
        } else if (canMoveDown()) {
            y += puzzleSize;
        }
        drawBoard();
        drawPiece();
        if (checkWin()) {
            alert('Congratulations! You solved the puzzle!');
        }
    }
    setInterval(movePiece, 1000);
</script>

</body> </html> `

通过以上三个小游戏源码的分享,相信大家对JS小游戏的制作有了更深入的了解。希望这些源码能对你有所帮助,让你在游戏开发的道路上越走越远。在学习和实践过程中,不断积累经验,相信你一定能打造出属于自己的游戏世界!