HTML+js实现贪吃蛇小游戏(内含完整代码)

案例分析

看图拆解游戏

首先我们根据图片上的内容把这个游戏拆解成几个部分去单独看:

  1. 最外面的大盒子包裹着内容加边框限制蛇的活动范围,整个范围可以看成由许多小方格排列构成的,例如这样子的:
  2. 两个按钮,一个控制开始游戏,一个控制游戏中途的暂停继续功能;
  3. 盒子里面有可以移动的蛇,最开始状态的蛇分为蛇头、蛇身、蛇尾三个部分,蛇只能走直线,通过上下左右的功能键去控制蛇的走向;
  4. 还有一个随机产生在限制区域内的食物;

这个游戏是当点击开始游戏按钮才显示蛇和食物的,所以最开始我们不在结构里面书写,后面通过js构造函数来生成,但是可以先把样式写了来,由此可知:我们的结构代码可以这么去写:

<body>
    <!-- 最外面盒子 -->
    <div class="content">
        <!-- 开始按钮 -->
        <div class="btn startBtn">
            <button></button>
        </div>
        <!-- 暂停按钮 -->
        <div class="btn pauseBtn">
            <button></button>
        </div>
        <!-- 蛇的活动范围 -->
        <div id="snakeWrap">
        </div>
    </div>
</body>

CSS样式代码是这样的:

.content {
    width: 640px;
    height: 640px;
    margin: 35px auto;
    position: relative;
}

.btn {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background-color: rgba(0, 0, 0, .3);
    z-index: 2;
}

.btn button {
    background: none;
    border: none;
    background-size: 100% 100%;
    cursor: pointer;
    outline: none;
    position: absolute;
    left: 50%;
    top: 50%;
}

.startBtn button {
    width: 200px;
    height: 80px;
    background-image: url(../images/start.gif);
    margin-left: -100px;
    margin-top: -40px;
}

.pauseBtn {
    display: none;
}

.pauseBtn button {
    width: 70px;
    height: 70px;
    background-image: url(../images/pause.png);
    margin-left: -35px;
    margin-top: -35px;
}


/* snakeWrap */

#snakeWrap {
    position: relative;
    width: 600px;
    height: 600px;
    background-color: greenyellow;
    border: 20px solid green;
}

#snakeWrap div {
    width: 20px;
    height: 20px;
}

.snakeHead {
    background-image: url(../images/蛇头.png);
    background-size: cover;
}

.snakeBody {
    background-color: #808ca5;
    border-radius: 50%;
}

.food {
    background-image: url(../images/食物.png);
    background-size: cover;
}

蛇的活动范围分析:

下面的代码方块构造函数就是创建一个一个的方格,给每个方格设置了宽高,这个大小是经过计算的可以正好铺满整个蛇的活动范围的地砖,就好比我准备了一整个房间需要的地砖,但是只是准备了并没有拿出来;给原型添加或删除的函数是我具备了铺地装这样子的技术;现在就是人和了,坐等天时地利的时候使用。

js代码:

  var sw = 20, //一个方格的宽
        sh = 20, //一个方格的高
        tr = 30, //行数
        td = 30; //列数
    //方块构造函数
    function Square(x, y, classname) {
        //0,0    0,0
        //20,0   1,0
        //40,0   2,0
        this.x = x * sw;
        this.y = y * sh;
        this.class = classname;
        this.viewContent = document.createElement('div'); //方块对应的DOM元素
        this.viewContent.className = this.class; //方块所指元素
        this.parent = document.getElementById('snakeWrap'); //方块的父级
    }

    //单词prototype指的是原型
    //给原型添加
    Square.prototype.create = function() { //创建方块DOM,并添加到页面里
        this.viewContent.style.position = 'absolute';
        this.viewContent.style.width = sw + 'px';
        this.viewContent.style.height = sh + 'px';
        this.viewContent.style.left = this.x + 'px';
        this.viewContent.style.top = this.y + 'px';
        this.parent.appendChild(this.viewContent);
    };
    //删除
    Square.prototype.remove = function() {
        this.parent.removeChild(this.viewContent);
    };

创建对象——蛇的分析:

下面的代码看蛇的部分,想要蛇移动,必须先有蛇,开始的时候就说了蛇又分为三个部分蛇头、蛇身和蛇尾,蛇需要移动,蛇移动又分为上下左右四个方向,所以我们需要根据x和y的正负来判断它走的方向,当蛇转向的时候需要蛇头跟着转向,所以要添加一个rotate属性来确定蛇头的方向。

js代码:

    //蛇
    var snake = null;
    function Snake() {
        this.head = null; //存一下蛇头信息
        this.tail = null; //存一下蛇尾信息
        this.pos = []; //存蛇身上每一个方块的位置

        this.directionNum = { //存储蛇走的方向,用一个对象来表示
            left: {
                x: -1,
                y: 0,
                rotate: 180 // 蛇头在不同方向中应该进行旋转
            },
            right: {
                x: 1,
                y: 0
            },
            up: {
                x: 0,
                y: -1,
                rotate: -90
            },
            down: {
                x: 0,
         
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
编写一个完整的贪吃蛇JS小游戏涉及到多个部分,包括游戏循环、键盘控制、蛇的移动、食物生成、碰撞检测等。以下是一个简化的版本,你可以根据这个基础进行扩展: ```javascript // 创建游戏元素 const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; let snake = [{ x: canvas.width / 2, y: canvas.height / 2 }, { x: canvas.width / 2 - 10, y: canvas.height / 2 }]; let food = { x: Math.floor(Math.random() * canvas.width), y: Math.floor(Math.random() * canvas.height) }; let direction = { x: 1, y: 0 }; // 初始方向为右 function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 绘制蛇和食物 snake.forEach(s => ctx.fillRect(s.x, s.y, 10, 10)); ctx.fillRect(food.x, food.y, 10, 10); } function move() { let newHead = { x: snake.x + direction.x * 10, y: snake.y + direction.y * 10 }; // 检查边界和碰撞 if (newHead.x < 0 || newHead.x >= canvas.width || newHead.y < 0 || newHead.y >= canvas.height) { gameOver(); } else { if (newHead.x === food.x && newHead.y === food.y) { // 吃到食物,增长蛇身 snake.push(newHead); food = { x: Math.floor(Math.random() * canvas.width), y: Math.floor(Math.random() * canvas.height) }; } else { // 移除蛇尾 snake.shift(); } // 更新蛇头位置 snake.unshift(newHead); } } function gameLoop() { draw(); move(); requestAnimationFrame(gameLoop); } document.addEventListener('keydown', e => { switch (e.key) { case 'ArrowUp': direction.y = -1; break; case 'ArrowDown': direction.y = 1; break; case 'ArrowLeft': direction.x = -1; break; case 'ArrowRight': direction.x = 1; break; } }); gameLoop(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值