原生js练习:”贪吃蛇“小项目(附视频解析,图片素材,源码免费下载)

原生js练习:”贪吃蛇“小项目

内含贪吃蛇素材,标准的 html, css, js, 适合使用原生JavaScript进行小项目练习,有一点JavaScript基础的同学练习使用

成品展示:在这里插入图片描述在这里插入图片描述在这里插入图片描述

HTML:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>贪吃蛇</title>
    <link rel="stylesheet" href="snake.css">
</head>

<body>
    <div class="startPage" id="startPage">
        <div class="startBtn" id="startBtn"></div>
    </div>
    <div class="wrapper">
        <div class="left-side">
            <img id="startP" src="img/start.png" alt="">
        </div>
        <div class="main">
            <div class="header">
                <div class="score">
                    分数:
                    <span id="scoreBox"></span>
                </div>
            </div>
           <div id="content" class="content"></div>
        </div>
    </div>
    <div class="loser" id="lose">
        <div class="con">
            <div class="close" id="close"></div>
            <span class="loserScore" id="loserScore"></span>
        </div>
    </div>
    <script src="snake.js"></script>
</body>
</html>

CSS:

*{
    margin: 0;
    padding: 0;
}
.startPage{
    width: 100%;
    z-index: 999;
    height: 1000px;
    position: absolute;
    top: 0;
    left: 0;
}
.startBtn{
    background-image: url(img/startGame.png);
    height: 170px;
    width: 200px;
    background-size: 100% 100%;
    cursor: pointer;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}
.wrapper{
    width:100%;
    height: 1000px;
    background-image: url(img/bg.jpg);
    background-size:100% 100%;
    position: relative; 
}
.left-side{
    width:24%;
    position: absolute;
    height: 1000px;
}
.left-side img{
    display: none;
    margin-left: 50px;
    margin-top: 50px;
}
.main{
    position: absolute;
    left: 25%;
    width: 50%;
    height: 90%;
}
.header{
    width:100%;
    height: 80px;
    text-align: center;
}
.score{
    line-height: 80px;
    color: #ddd;
    font-size: 20px;
    font-weight: bolder;
}
.content{
    position: absolute;
    width:79.5%;
    height: 36.5%;
    left: 10%;
    top:34%;
}
.loser{
    display: none;
    width: 100%;
    height: 1000px;
    top:0;
    left:0;
}
.con{
    background-image: url(img/startP.jpg);
    background-size: 100% 100%;
    height: 300px;
    width: 400px;
    position: absolute;
    margin: auto;
    left:0;
    top: 0;
    right: 0;
    bottom: 0;
    border-radius: 20%;
}
.loserScore{
    display: block;
    height: 30px;
    width: 40px;
    position: absolute;
    top: 42%;
    left: 40%;
    color: #222;
    font-size: 30px;
    font-weight: bolder;
}
.close{
    position: absolute;
    top: 0;
    right: 0;
    height: 40px;
    width: 40px;
    background-image: url(img/closeBtn.png);
    background-size: 100% 100%;
    cursor: pointer;
}
.food{
    background-image: url(img/apple.png);
    background-size: 100% 100%;
}
.head{
    background-image: url(img/head.png);
    background-size: 100% 100%;
}
.body{
    background-image: url(img/body.png);
    background-size: 100% 100%;
}

JS:

//1.点击开始游戏》》startpage消失 》》游戏开始
//2.随机随机出现食物,出现三节蛇,开始运动
//3.上下左右》》改变运动方向
//4.判断吃到食物
//5.判断结束
window.onload = function () {
    var startP = document.getElementById('startP');
    var startPage = document.getElementById('startPage');
    var lose = document.getElementById('lose');
    var content = document.getElementById('content');
    var scoreBox = document.getElementById('scoreBox');
    var close = document.getElementById('close');
    var loserScore = document.getElementById('loserScore');
    var startBtn = document.getElementById('startBtn');
    var snakeMove;
    var speed = 200;
    var startGameBool = true;
    var startPaushBool = true;
    init();

    function init() {
        //地图 
        this.mapW = parseInt(getComputedStyle(content).width);
        this.mapH = parseInt(getComputedStyle(content).height);
        this.mapDiv = content;

        //食物
        this.foodW = 20;
        this.foodH = 20;
        this.foodX = 0;
        this.foodY = 0;

        //蛇
        this.snakeW = 20;
        this.snakeH = 20;
        this.snakeBody = [
            [4, 2, "head"],
            [3, 2, 'body'],
            [2, 2, 'body']
        ]

        //游戏属性
        this.direct = 'right';
        this.right = false;
        this.left = false;
        this.up = true;
        this.down = true;
        this.score = 0;
        bindEvent();
    }

    function startGame() {
        startP.style.display = 'block';
        startPage.style.display = 'none';
        food();
        snake();
    }

    function food() {
        var food = document.createElement('div');
        food.style.width = this.foodW + 'px';
        food.style.height = this.foodH + 'px';
        food.style.position = 'absolute';
        this.foodX = Math.floor(Math.random() * (this.mapW / 20));
        this.foodY = Math.floor(Math.random() * (this.mapH / 20));
        food.style.left = this.foodX * 20 + 'px';
        food.style.top = this.foodY * 20 + 'px';
        this.mapDiv.appendChild(food).setAttribute("class", "food")
    }

    function snake() {
        for (var i = 0; i < this.snakeBody.length; i++) {
            var snake = document.createElement('div');
            snake.style.width = this.snakeW + 'px';
            snake.style.height = this.snakeH + 'px';
            snake.style.position = 'absolute';
            snake.style.left = this.snakeBody[i][0] * 20 + 'px';
            snake.style.top = this.snakeBody[i][1] * 20 + 'px';
            snake.classList.add(this.snakeBody[i][2]);
            this.mapDiv.appendChild(snake).classList.add('snake');
           
            switch (this.direct) {
                case 'right':
                    break;
                case 'up':
                    snake.style.transform = 'rotate(270deg)';
                    break;
                case 'left':
                    snake.style.transform = 'rotate(180deg)';
                    break;
                case 'down':
                    snake.style.transform = 'rotate(90deg)';
                    break;
                default:
                    break;
            }
        }
    }

    function move() {
        for (var i = this.snakeBody.length - 1; i > 0; i--) {
            this.snakeBody[i][0] = this.snakeBody[i - 1][0];
            this.snakeBody[i][1] = this.snakeBody[i - 1][1];
        }
        switch (this.direct) {
            case 'right':
                this.snakeBody[0][0] += 1;
                break;
            case 'up':
                this.snakeBody[0][1] -= 1;
                break;
            case 'left':
                this.snakeBody[0][0] -= 1;
                break;
            case 'down':
                this.snakeBody[0][1] += 1;
                break;
            default:
                break;
        }
        removeClass('snake');
        snake();
     
        if (this.snakeBody[0][0] == this.foodX && this.snakeBody[0][1] == this.foodY) {
            var snakeEndX = this.snakeBody[this.snakeBody.length - 1][0];
            var snakeEndY = this.snakeBody[this.snakeBody.length - 1][1];
            switch (this.direct) {
                case 'right':
                    this.snakeBody.push([snakeEndX + 1, snakeEndY, "body"]);
                    break;
                case 'up':
                    this.snakeBody.push([snakeEndX, snakeEndY - 1, "body"]);
                    break;
                case 'left':
                    this.snakeBody.push([snakeEndX - 1, snakeEndY, "body"]);
                    break;
                case 'down':
                    this.snakeBody.push([snakeEndX, snakeEndY + 1, "body"]);
                    break;
                default:
                    break;
            }
            this.score++;    
            scoreBox.innerHTML = this.score;
            removeClass('food');
            food();
        }
        if (this.snakeBody[0][0] < 0 || this.snakeBody[0][0] >= this.mapW / 20) {
            reloadGame();
        }
        if (this.snakeBody[0][1] < 0 || this.snakeBody[0][1] >= this.mapH / 20) {
            reloadGame();
        }
        var snakeHX = this.snakeBody[0][0];
        var snakeHY = this.snakeBody[0][1];
        for (var i = 1; i < this.snakeBody.length; i++) {
            if (snakeHX == snakeBody[i][0] && snakeHY == snakeBody[i][1]) {
                reloadGame();
            }
        }
    }

    function reloadGame() {
        removeClass('snake');
        removeClass('food');
        clearInterval(snakeMove);
        this.snakeBody = [
            [4, 2, "head"],
            [3, 2, 'body'],
            [2, 2, 'body']
        ]
        this.direct = 'right';
        this.right = false;
        this.left = false;
        this.up = true;
        this.down = true;

        lose.style.display = 'block';
        loserScore.innerHTML = this.score;
        this.score = 0;
        startGameBool = true;
        startPaushBool = true;
        startP.setAttribute('src', "img/start.png")
    }

    function removeClass(className) {
        var ele = document.getElementsByClassName(className);
        while (ele.length > 0) {
            ele[0].parentNode.removeChild(ele[0]);
        }
    }

    function setDerict(code) {
        switch (code) {
            case 37:
                if (this.left) {
                    this.direct = 'left';
                    this.left = false;
                    this.right = false;
                    this.up = true;
                    this.down = true;
                }
                break;
            case 38:
                if (this.up) {
                    this.direct = 'up';
                    this.left = true;
                    this.right = true;
                    this.up = false;
                    this.down = false;
                }
                break;
            case 39:
                if (this.right) {
                    this.direct = 'right';
                    this.left = false;
                    this.right = false;
                    this.up = true;
                    this.down = true;
                }
                break;
            case 40:
                if (this.down) {
                    this.direct = 'down';
                    this.left = true;
                    this.right = true;
                    this.up = false;
                    this.down = false;
                }
                break;
            default:
                break;
        }
    }

    function bindEvent() {
        document.onkeydown = function (e) {
            var code = e.keyCode;
            setDerict(code);
        }
        close.onclick = function () {
            lose.style.display = 'none';
        }
        startBtn.onclick = function () {
            startAndPaush();
        }
        startP.onclick = function () {
            startAndPaush();
        }
    }

    function startAndPaush() {
        if (startPaushBool) {
            if (startGameBool) {
                startGame();
                startGameBool = false;
            }
            startP.setAttribute('src', 'img/pause.png');
            document.onkeydown = function (e) {
                var code = e.keyCode;
                setDerict(code);
            }
            snakeMove = setInterval(function () {
                move()
            }, speed);
            bindEvent();
            startPaushBool = false;
        } else {
            startP.setAttribute('src', "img/start.png");
            clearInterval(snakeMove);
            document.onkeydown = function (e) {
                e.returnValue = false;
                return false;
            };
            startPaushBool = true;
        }
    }
}

图片素材及代码下载:

CSDN(奖励作者1积分):
https://download.csdn.net/download/weixin_43436925/10935740

百度网盘(免费下载):
https://pan.baidu.com/s/1_OdhHPAvuTKCu3hUgnc7DA

视频讲解(渡一教育免费提供):
https://ke.qq.com/course/276537

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值