JS贪吃蛇小游戏

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JS贪吃蛇小游戏

我莫得感情_   2022-05-23 我要评论

效果图:

完整代码如下:

HTML

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/index.css">
    <title>Document</title>
</head>
 
<body>
    <div class="content">
        <div class="btn startBtn"><button></button></div>
        <div class="btn pauseBtn"><button></button></div>
        <div id="snakeWrap">
            <!-- <div class="snakeHead"></div>
            <div class="snakeBody"></div>
            <div class="food"></div> -->
        </div>
    </div>
 
    <script src="js/index.js"></script>
</body>
 
</html>

CSS

.content {
    width: 640px;
    height: 640px;
    margin: 100px 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: 0;
    background-size: 100% 100%;
    cursor: pointer;
    outline: none;
    position: absolute;
    left: 50%;
    top: 50%;
}
 
.startBtn button {
    width: 200px;
    height: 130px;
    background-image: url(../imgs/startBtn.gif);
    margin-left: -100px;
    margin-top: -75px;
}
 
.pauseBtn {
    display: none;
}
 
.pauseBtn button {
    width: 70px;
    height: 70px;
    background-image: url(../imgs/pauseBtn.png);
    margin-left: -35px;
    margin-top: -35px;
}
 
#snakeWrap {
    position: relative;
    width: 600px;
    height: 600px;
    background: #225675;
    border: 20px solid #7dd9ff;
}
 
 
/* #snakeWrap div {
    width: 20px;
    height: 20px;
} */
 
.snakeHead {
    background-image: url(../imgs/snake.png);
    background-size: cover;
}
 
.snakeBody {
    background-color: #9ddbb1;
    border-radius: 50%;
}
 
.food {
    background-image: url(../imgs/food.png);
    background-size: cover;
}

JS

// 声明方块的宽高,行数和列数
var sw = 20,
    sh = 20,
    tr = 30,
    td = 30;
 
var snake = null, //蛇的实例
    food = null, //食物的实例
    game = null; //游戏的实例
 
function Square(x, y, classname) {
    this.x = sw * x;
    this.y = sh * y;
    this.class = classname;
 
    this.viewContent = document.createElement('div'); //方块对应的DOM元素
    this.viewContent.className = this.class;
    this.parent = document.getElementById('snakeWrap'); //方块的父级
}
//创建方块DOM,并添加到页面里
Square.prototype.create = function() {
    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);
};
//
      

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们