当前位置: 首页 > article >正文

贪吃蛇游戏:增加暂停按钮,每次增加10分蛇会变化

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
</head>
<style>
    body {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100vh;
        background: #0b1b2c;
        color: antiquewhite;
        margin: 0;
    }
    #score {
        font-size: 24px;
        color: #319403;
    }
    #gameCanvas {
        border: 1px solid rgb(165, 165, 165);
    }
</style>
<body>
    <div id="score">得分: 0</div>
    <p>(方向键开始游戏,方向键左、上、右、下控制,碰壁不会结束。每次增加10分蛇会变化)</p>
    <button id="pauseButton">暂停</button>
    <canvas id="gameCanvas" width="600" height="600"></canvas>
</body>
<script>
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const box = 20;
    let snake = [{ x: 10 * box, y: 10 * box }];
    let food = {
        x: Math.floor(Math.random() * 20) * box,
        y: Math.floor(Math.random() * 20) * box
    };
    let d;
    let score = 0; // 初始化得分
    const scoreElement = document.getElementById('score'); // 获取得分显示元素
    document.addEventListener('keydown', direction);
    function direction(event) {
        const keyMap = {
            37: 'LEFT',
            38: 'UP',
            39: 'RIGHT',
            40: 'DOWN'
        };
        const newDirection = keyMap[event.keyCode];
        if (newDirection && newDirection !== oppositeDirection(d)) {
            d = newDirection;
        }
    }
    function oppositeDirection(dir) {
        return {
            'LEFT': 'RIGHT',
            'UP': 'DOWN',
            'RIGHT': 'LEFT',
            'DOWN': 'UP'
        }[dir];
    }
    let game = setInterval(draw, 200);
    let isPaused = false;
    const pauseButton = document.getElementById('pauseButton');
    pauseButton.addEventListener('click', () => {
        isPaused = !isPaused;
        pauseButton.textContent = isPaused ? '继续' : '暂停';
        if (isPaused) {
            clearInterval(game);
        } else {
            game = setInterval(draw, 200);
        }
    });
    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        snake.forEach((segment, index) => {
            if (index === 0) {
                drawHead(segment.x, segment.y);
            } else {
                ctx.fillStyle = 'white';
                ctx.fillRect(segment.x, segment.y, box, box);
                ctx.strokeStyle = 'black';
                ctx.strokeRect(segment.x, segment.y, box, box);
            }
        });
        ctx.fillStyle = 'red';
        ctx.fillRect(food.x, food.y, box, box);
        let snakeX = snake[0].x;
        let snakeY = snake[0].y;
        const moveMap = {
            'LEFT': () => snakeX -= box,
            'UP': () => snakeY -= box,
            'RIGHT': () => snakeX += box,
            'DOWN': () => snakeY += box
        };
        moveMap[d]();
        if (snakeX === food.x && snakeY === food.y) {
            food = {
                x: Math.floor(Math.random() * 20) * box,
                y: Math.floor(Math.random() * 20) * box
            };
            score += 1; // 每次吃到食物得分增加
            scoreElement.textContent = '得分: ' + score; // 更新得分显示
        } else {
            snake.pop();
        }
        snakeX = (snakeX < 0) ? canvas.width - box : (snakeX >= canvas.width) ? 0 : snakeX;
        snakeY = (snakeY < 0) ? canvas.height - box : (snakeY >= canvas.height) ? 0 : snakeY;
        const newHead = { x: snakeX, y: snakeY };
        snake.unshift(newHead);
        console.log(score); // 打印当前得分
        // 美化蛇身
        if (score >= 60) {
            beautifySnake();
            // 重新绘制蛇头部
            drawHead(snake[0].x, snake[0].y);
        }
    }
const colors = ['orange', 'blue', 'green', 'purple', 'yellow', 'cyan']; 
function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
function beautifySnake() {
    snake.forEach((segment, index) => {
        ctx.fillStyle = getRandomColor(); // 使用随机颜色
        ctx.fillRect(segment.x, segment.y, box, box);
        ctx.strokeStyle = 'black';
        ctx.strokeRect(segment.x, segment.y, box, box);
    });
}
    function drawHead(x, y) {
        ctx.fillStyle = 'green';
        if (score >= 10) {
            ctx.beginPath();
            ctx.arc(x + box / 2, y + box / 2, box / 2, 0, Math.PI * 2);
            ctx.fill();
            ctx.stroke();
        } else {
            ctx.fillRect(x, y, box, box);
            ctx.strokeRect(x, y, box, box);
        }
        if (score >= 20) {
            ctx.fillStyle = 'black';
            ctx.fillRect(x + box / 4, y + box / 4, box / 8, box / 8);
            ctx.fillRect(x + box * 3 / 4 - box / 8, y + box / 4, box / 8, box / 8);
        }
        if (score >= 30) {
            ctx.fillStyle = 'black';
            ctx.beginPath();
            ctx.arc(x + box / 2, y + box * 3 / 4, box / 4, 0, Math.PI);
            ctx.fill();
        }
        if (score >= 40) {
            ctx.fillStyle = 'yellow';
            ctx.beginPath();
            ctx.arc(x + box / 2, y + box * 3 / 4, box / 4, 0, Math.PI);
            ctx.fill();
            ctx.stroke();
        }
        if (score >= 50) {
            ctx.fillStyle = 'purple';
            ctx.beginPath();
            ctx.moveTo(x, y);
            ctx.lineTo(x + box, y);
            ctx.lineTo(x + box / 2, y + box);
            ctx.closePath();
            ctx.fill();
        }
    }
    function collision(head, array) {
        return array.some(segment => head.x === segment.x && head.y === segment.y);
    }
</script>
</html>


http://www.kler.cn/news/294083.html

相关文章:

  • 199页Word智慧水务平台建设方案
  • Centos 7离线部署jenkins 2.346.3
  • 【网络安全】Jenkins任意文件读取漏洞及检测工具(CVE-2024-23897)
  • log4j 多classloader重复加载配置问题解决
  • uni-app流式接受消息/文件
  • 【Java 学习】:抽象类接口
  • 未来出行:高效智能的汽车充电桩
  • CUB-200-2011数据集及该格式自己数据集制作
  • 好用的AI编程助手MarsCode[豆包]
  • 分类预测|基于CNN-LSTM-Attention卷积-长短时记忆-注意力数据分类Matlab程序 直接运行程序或替换数据集运行程序
  • 基于IMX6ULL的Cortex-A中断原理讲解,以及编写其中断向量表
  • 算法图解(8~10贪心,动态规划,K最近邻算法)
  • 代码随想录训练营day36|1049.最后一块石头的重量II,494.目标和,474.一和零
  • WEB服务与虚拟主机/IIS中间件部署
  • 【kafka】在Linux系统中部署配置Kafka的详细用法教程分享
  • Leetcode面试经典150题-210.课程表II
  • 如何让linux程序在后台执行
  • CSP-J 之C++常用英文缩写
  • 【亲测有效】nginx负载均衡指定ip端口转发,做自动切换
  • 用Python实现时间序列模型实战——Day 13: 自回归条件异方差模型 (ARCH/GARCH)
  • 《深度学习》OpenCV轮廓检测 轮廓近似 解析及实现
  • Linux date命令 日期格式化与计算
  • VScode 的下载安装及常见插件 + Git的下载和安装
  • 2024年四川省安全员A证证考试题库及四川省安全员A证试题解析
  • 数据结构(1)数据结构基础(单向链表)
  • 双雄并肩:Tesla P40 GTX 1650 AI工作站搭建指南
  • redis之缓存淘汰策略
  • Keysight U8031A DC power supply
  • MySQL表操作及约束
  • WSL 在 Windows 上删除已经安装的 Ubuntu | WSL 再次重装 Ubuntu | cv2.imshow() 弹窗支持