贪吃蛇小游戏

🔸有一个请求就是大家自己有什么想玩的但是很简单的游戏可以私信我或者发在评论里🔞

1. 游戏介绍

最近闲来无事就写了个解压小游戏,供自己娱乐

1. 演示

地址长期有效(不出意外的话): 演示地址

2. 封面

效果图

2. 源码

新建个index.html

<!DOCTYPE html>
<html lang="en">
<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;
        }
        canvas {
            border: 1px solid black;
        }
        #score{
            color: rgb(39, 66, 236);
        }
    </style>
</head>
<body>
    <div style="text-align: center;">
        <h3>贪吃蛇游戏</h3><br>
        <p>您的得分是: <span id="score">0</span></p>
        <canvas id="gameCanvas" width="600" height="450"></canvas>
        <p>按空格或回车开始/暂停游戏</p>
        <p>按方向键控制贪吃蛇,吃到食物加分,撞到自己或撞到边界游戏结束。</p>
    </div>
    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const gridSize = 15;
        const formWidth = canvas.width / gridSize;
        const formHeight = canvas.height / gridSize;
        let snake = [{ x: 10, y: 10 }];
        let food = {};
        let direction = 0;
        let score = 0;
        let gameInterval;
        let isPaused = false;
		
		// 重置游戏
        function resetGame(resetScoreAndLength = true) {
            if (resetScoreAndLength) {
                snake = [{ x: 10, y: 10 }];
                direction = 0;
                score = 0;
            } else {
                let newHead = { x: Math.floor(formWidth / 2), y: Math.floor(formHeight / 2) };
                for (let i = snake.length - 1; i > 0; i--) {
                    snake[i] = snake[i - 1];
                }
                snake[0] = newHead;
                direction = 0;
            }
            generateFood();
        }
		
		// 随机新食物
        function generateFood() {
            food = {
                x: Math.floor(Math.random() * formWidth),
                y: Math.floor(Math.random() * formHeight)
            };
        }
		
		// 主角移动
        function moveSnake() {
            for (let i = snake.length - 1; i > 0; i--) {
                snake[i] = { ...snake[i - 1] };
            }
            switch (direction) {
                case 0: snake[0].x += 1; break;
                case 1: snake[0].y += 1; break;
                case 2: snake[0].x -= 1; break;
                case 3: snake[0].y -= 1; break;
            }
        }
		
		// 得分及碰撞检测
        function checkCollision() {
            if (snake[0].x < 0 || snake[0].x >= formWidth || snake[0].y < 0 || snake[0].y >= formHeight) {
                gameOver();
            }
            for (let i = 1; i < snake.length; i++) {
                if (snake[0].x === snake[i].x && snake[0].y === snake[i].y) {
                    gameOver();
                }
            }
            if (snake[0].x === food.x && snake[0].y === food.y) {
                snake.push({ ...food });
                score += 10;
                generateFood();
                document.getElementById('score').innerText = score;
                if (snake.length >= formWidth * formHeight * 0.3) {
                    alert('You win!');
                    resetGame(true);
                }
            }
        }
		
		// 结束游戏
        function gameOver() {
            clearInterval(gameInterval);
            if (confirm(`游戏结束!您的得分是 ${score}。是否选择复活?`)) {
                let input = prompt('请输入复活指令:', '');
                if (input === '哥') {
                    resetGame(false);
                    startGame();
                } else {
                    alert('输入不正确,无法复活。');
                    resetGame(true);
                    startGame();
                }
            } else {
                resetGame(true);
                startGame();
            }
            document.getElementById('score').innerText = score;
        }

		// 开始游戏
        function startGame() {
            gameInterval = setInterval(() => {
                if (!isPaused) {
                    moveSnake();
                    checkCollision();
                    draw();
                }
            }, 200); // 蛇的移动速度: 数字越小移动越快
        }

        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            for (let segment of snake) {
                ctx.fillStyle = 'green';
                ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
            }
            ctx.fillStyle = 'red';
            ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
        }
        
		// 键盘事件
        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowRight': if (direction !== 2) direction = 0; break;
                case 'ArrowDown': if (direction !== 3) direction = 1; break;
                case 'ArrowLeft': if (direction !== 0) direction = 2; break;
                case 'ArrowUp': if (direction !== 1) direction = 3; break;
                case ' ':
                case 'Enter':
                    isPaused = !isPaused;
                    if (isPaused) {
                        clearInterval(gameInterval);
                    } else {
                        startGame();
                    }
                    break;
            }
        });

        resetGame(true);
        startGame();
    </script>
</body>
</html>

可以自己改一下样式什么的,我实在是懒得一个一个调

  • 12
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值