原生js编写贪吃蛇小游戏
作者:你想变强嘛 发布时间:2023-07-02 05:19:17
标签:js,贪吃蛇
本文实例为大家分享了js编写贪吃蛇小游戏的具体代码,供大家参考,具体内容如下
刚学完js模仿着教程,把自己写的js原生小程序。
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">
<title>Document</title>
<link rel="stylesheet" href="./css/index.css" >
</head>
<body>
<div class="content">
<!-- 游戏开启按钮 -->
<div class="btn startBtn"><button></button></div>
<!-- 蛇身 -->
<div id="snakeWrap"></div>
</div>
<!-- 引入外部js文件 -->
<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, 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: url(../images/Snipaste_2021-05-08_08-52-45.png) no-repeat;
background-size: contain;
margin-left: -100px;
margin-top: 222px;
}
#snakeWrap{
width: 600px;
height: 600px;
background: #73aad4;
border: 20px solid #13649c;
position: relative;
}
.snakeHead{
background-color: yellowgreen;
border-radius: 50%;
}
.snakeBody{
background-color: black;
border-radius: 50%;
}
.food{
background-color: red;
border-radius: 50%;
}
js部分
var sw = 20, //一个方块的宽
sh = 20, //一个方块的宽
tr = 30, //行数
td = 30; //列数
var snake = null, //生成蛇的实例
food = null; //生成食物的实例
game = null; //创建游戏实例
//把整体看成是一个一个小方块 移动的的时候创建和删除方块(后续所有方块的生成都会调用)
// 方块构造函数
function Square(x,y,classname){ //对应css中三种蛇的样式(蛇头 蛇身 蛇尾)
this.x = x * sw;
this.y = y * sh;
this.class = classname;
this.viewContent = document.createElement('div');
this.viewContent.className = this.class; //将创建出来的div添加对应css样式
this.parent = document.getElementById('snakeWrap');
}
//在方块构造函数的 原型链 上创建create方法 确定新div的具体信息
//this指向Square
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); //把新创建的div添加到页面
}
//在方块构造函数的 原型链 上创建remove方法 用于移动时删除方块
Square.prototype.remove = function(){
this.parent.removeChild(this.viewContent);
}
// 蛇
function Snake(){
this.head = null; //存储蛇头信息
this.tail = null; //存储蛇尾信息
this.pos = []; //存储蛇身上的每一个方块的位置
this.directionNum = { //存储蛇走的方向
left : {
x : -1,
y : 0
},
right : {
x : 1,
y : 0
},
up : {
x : 0,
y : -1
},
down : {
x : 0,
y : 1
}
}
}
//this 指向 Snake
Snake.prototype.init = function(){ //初始化
// 创建蛇头
var snakeHead = new Square(2,0,'snakeHead');
snakeHead.create();
this.head = snakeHead;
this.pos.push([2,0]); //储存蛇头信息
// 创建蛇身1
var snakeBody1 = new Square(1,0,'snakeBody');
snakeBody1.create();
this.pos.push([1,0]); //储存蛇身信息
// 创建蛇尾
var snakeBody2 = new Square(0,0,'snakeBody');
snakeBody2.create();
this.tail = snakeBody2;
this.pos.push([0,0]); /储存蛇尾信心
//形成链表关系
//蛇头 蛇身 蛇尾的前后关系
snakeHead.last = null;
snakeHead.next = snakeBody1;
snakeBody1.last = snakeHead;
snakeBody1.next = snakeBody2;
snakeBody2.last = snakeBody1;
snakeBody2.next = null;
//给蛇 添加一个默认方向 向右
this.direction = this.directionNum.right;
}
// 获取蛇头的下一个位置对应的元素(this指向Snake)
// 获取下一个点的坐标并储存到nextPos数组
Snake.prototype.getNextPos = function(){
var nextPos = [
this.head.x/sw + this.direction.x, //this.direction.x、y 下面会将方向与键盘事件绑定 来确定下一个点生成的位置
this.head.y/sh + this.direction.y
]
// 下个点是自己,撞到了自己 游戏结束
var selfCollied = false;
this.pos.forEach(function(value){ //forEach遍历数组 两数组比较看是否有重复坐标
if (value[0] == nextPos[0] && value[1] == nextPos[1]){
selfCollied = true;
}
})
//撞到了自己 游戏结束
if(selfCollied){
this.、
.die.call(this);
return;
}
// 下个点是围墙 游戏结束
if(nextPos[0] > 29 || nextPos[0] < 0 || nextPos[1] > 29 || nextPos[1] < 0){
this.strategies.die.call(this);
return;
}
// 下个点是食物 吃
if(food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]){
this.strategies.eat.call(this);
return;
}
// 下个点什么都不是 走
this.strategies.move.call(this);
}
// 碰撞后要做的事
Snake.prototype.strategies = {
move : function(format){ //参数用于判断是否删除蛇尾
// 创建一个newbody,删掉蛇头
var newBody = new Square(this.head.x/sw,this.head.y/sh,'snakeBody')
newBody.next = this.head.next;
newBody.next.last = newBody;
newBody.last = null;
this.head.remove();
newBody.create();
// 创建一个新蛇头
var newx = this.head.x/sw + this.direction.x;
var newy = this.head.y/sh + this.direction.y;
var newHead = new Square(newx,newy,'snakeHead')
newHead.next = newBody;
newBody.last = newHead;
newHead.last = null;
newHead.create();
// 更新蛇身的坐标
this.pos.splice(0,0,[newx,newy]);
this.head = newHead;
//如果为false 则吃
if(!format){
this.tail.remove();
this.tail = this.tail.last;
this.pos.pop();
}
},
eat : function(){
this.strategies.move.call(this,true);
game.score ++;
createFood();
},
die : function(){
game.over();
}
}
snake = new Snake();
// 创建食物
function createFood(){
// 食物小方块坐标
var x = null;
var y = null;
var include = true;
while(include){
x = Math.round(Math.random()*(td - 1));
y = Math.round(Math.random()*(tr - 1));
snake.pos.forEach(function(value){
if(x != value[0] && y != value[1]){
include = false;
}
});
}
// 生成食物
food = new Square(x,y,'food');
food.pos = [x,y];
var foodDom = document.querySelector('.food');
if(foodDom){
foodDom.style.left = x * sw + 'px';
foodDom.style.top = y * sh + 'px';
}else{
food.create();
}
}
// 创建游戏逻辑
function Game(){
this.timer = null;
this.score = 0;
}
Game.prototype.init = function(){
snake.init();
createFood();
//这里曾经的e.keycode e.which 都已禁用 使用e.key
window.addEventListener('keydown',function(e){
if(e.key == 'ArrowLeft' && snake.direction != snake.directionNum.right){
snake.direction = snake.directionNum.left;
}else if(e.key == 'ArrowUp' && snake.direction != snake.directionNum.down){
snake.direction = snake.directionNum.up;
}else if(e.key == 'ArrowRight' && snake.direction != snake.directionNum.left){
snake.direction = snake.directionNum.right;
}else if(e.key == 'ArrowDown' && snake.direction != snake.directionNum.up){
snake.direction = snake.directionNum.down;
}
});
this.start();
}
Game.prototype.start = function(){
this.timer = setInterval(function(){
snake.getNextPos();
},0.0000000000000001)
}
Game.prototype.over = function(){
clearInterval(this.timer);
alert('你的得分为' + this.score);
// 游戏回到最初始状态
var snakeWrap = document.getElementById('snakeWrap');
snakeWrap.innerHTML = '';
snake = new Snake();
game = new Game();
var startBtnWrap = document.querySelector('.startBtn');
startBtnWrap.style.display = 'block';
}
// 开启游戏
game = new Game();
var startBtn = document.querySelector('.startBtn button');
startBtn.onclick = function(){
startBtn.parentNode.style.display = 'none';
game.init();
}
简单的一个小游戏,如有问题请大佬指正。
来源:https://blog.csdn.net/weixin_56330639/article/details/116569204


猜你喜欢
- Anaconda安装:anaconda官方下载地址https://www.anaconda.com/products/individual注
- 在 JavaScript 中对象和数组是引用类型,指向同一个内存空间,如果 prop 是一个对象或数组,在子组件内部改变它会影响父组件的状态
- 本文实例讲述了mysql 数据库备份的多种实现方式。分享给大家供大家参考,具体如下:一、使用mysqldump进行备份1、完整备份所有数据库
- 一、85%的广告没人看解读:如何挤进那15%的成功广告中去,吸引了读者就是成功了一半。Quester视角:反过来讲,只有不到1/5的广告能吸
- -------------- 函数检索 --------------trim函数: trim() lTrim() rTrim()校验字符串是
- 前言:接口自动化是指模拟程序接口层面的自动化,由于接口不易变更,维护成本更小,所以深受各大公司的喜爱。接口自动化包含2个部分,功能性的接口自
- hash//从井号 (#) 开始的 URL(锚)host//主机名和当前 URL 的端口号hostname//当前 URL 的主机名href
- 如下所示:a = int(input("请输入菱形行数:"))m = a #空格d = a #倒三角for i in r
- 有时候需要一次性将SQL Server中的数据导出给其他部门的也许进行关联或分析,这种需求对于SSIS
- FlaskFlask是什么?Flask是一个使用 Python 编写的轻量级 Web 应用框架, 让我们可以使用Python语言快速搭建We
- Create PROC P_viewPage
- 工作中会遇到这样的需求,有多个Excel的格式一样,都有多个sheet,且每个sheet的名字和格式一样,我们需要按照sheet 合并,就是
- 以前在windows下一直用的idel带的功能调试python程序,在linux下没调试过。(很多时候只是print)就从网上查找一下~方法
- 这个分页使用的是0游标,也就是Rs.Open Sql,Conn,0,1。但是感觉也快不了多少,10万条数据的分页时间300多豪秒之间。风格A
- 1.添加新用户只允许本地IP访问create user 'test'@'localhost' identif
- pyecharts产生背景Echarts是由百度开源的数据可视化,凭借良好的交互性和精巧的图表设计,得到众多开发者的认可,而python很适
- 切片是 Python 中最迷人最强大最 Amazing 的语言特性(几乎没有之一),在《Python进阶:切片的误区与高级用法》中,我介绍了
- pycharm中光标变粗,如下:原因:光标进入了改写状态。解决方法:按一下键盘中的Insert键就好了。
- asp上传的时候出现这种 错误:Server 对象 错误 'ASP 0177 800401f3'Server.CreateO
- 通信信息包是发送至MySQL服务器的单个SQL语句,或发送至客户端的单一行。在MySQL 5.1服务器和客户端之间最大能发送的可能信息包为1