最近一直刷题,偶尔换个方式,让脑子休息一下。把前几天写的贪吃蛇demo分享一下。主要用的是html,css基础知识,加上一些js的键盘交互时间,鼠标点击事件以及一些页面元素创建函数,最重要的是使用DOM。使用的全是原生javascript。只要学过一点js都可以看懂。
目录
用到的方法:
键盘事件
keydown:按键按下
keyup:按键抬起
keypress:按键按下抬起
鼠标事件
click:单击
dblclick:双击
mousedown:鼠标按下
mouseup:鼠标抬起
mouseover:鼠标悬浮
mouseout:鼠标离开
mousemove:鼠标移动
mouseenter:鼠标进入
mouseleave:鼠标离开
DOM事件:(这个就不多说了,js和html以及css交互时必须会用的,实在不会就去啃文档吧 滑稽.jpg)
HTML页面
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>贪吃蛇</title>
<link rel="stylesheet" href="css/demo.css">
</head>
<body>
<div class="startPage" id="startPage">
<div class="startBtn" id="startBtn"></div>
</div>
<div class="wrapper">
<div class="left-side">
<img src="./images/start.png" width = "100" height="90"id = "startPaush">
</div>
<div class="main">
<div class="header">
<div class="score">
Score :
<span id = "score"></span>
</div>
</div>
<!-- <div>
<img src="./images/smallMap.jpg" class="smallMap">
</div> -->
<div class="content" id="content"></div>
</div>
</div>
<div class="loser" id = 'loser'>
<div class="con">
<div class="close" id="close"></div>
<span class = "txt">Final Score:</span>
<span class="loserScore" id="loserScore"></span>
</div>
</div>
<script src="js/demo.js"></script>
</body>
</html>
贪吃蛇大概思路:
//点击开始游戏--> stratpage消失-->游戏开始
//随机出现食物,出现三节蛇开始运动
//上下左右 --> 控制蛇的运动
//判断是否吃到食物--> 食物消失 --> 蛇加一
//判断游戏结束,弹出game over
模块分析
初始游戏
这个模块主要是初始化蛇的属性,DOM事件获取html元素。确定蛇的初始位置(数组)。
var startBtn = document.getElementById('startBtn');
var startPage = document.getElementById('startPage');
var startPaush = document.getElementById('startPaush');
var loser = document.getElementById('loser');
var scoreBox = document.getElementById('score');
var content = document.getElementById('content');
var loserScore = document.getElementById('loserScore');
var close = document.getElementById('close');
var snakeMove; //蛇的运动
var speed = 200; //蛇的速度
var startGameBool = true;
var startPaushBool = true;
initGame();
function initGame() {
//Map
this.mapW = parseInt(getComputedStyle(content).width);
this.mapH = parseInt(getComputedStyle(content).height);
this.mapDiv = content;
//Food
this.foodW = 20;
this.foodH = 20;
this.foodX = 0;
this.foodY = 0;
//snake
this.snakeW = 20;
this.snakeH = 20;
this.snakeBody = [[3, 1, 'head'], [2, 1, 'body'], [1, 1, 'body']]
//游戏属性
this.direct = 'right';
this.left = false;
this.right = false;
this.up = true;
this.down = true;
this.score = 0;
scoreBox.innerHTML = this.score;
bindEvent();
}
蛇,食物
创建蛇的身体,随机出现食物(个人设置屏幕一次只有一个食物)
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'); //吃掉食物 appendChild增加蛇的体长
//转向
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();
}
开始/暂停游戏
//开始暂停游戏
function startAndPaush() {
if (startPaushBool) {
if (startGameBool) {
startGame();
startGameBool = false;
}
startPaush.setAttribute('src', './images/pause.png');
snakeMove = setInterval(function () {
move();
}, speed);
document.onkeydown = function (e) {
var code = e.keyCode;
setDirect(code);
};
startPaushBool = false;
} else {
//pause
startPaush.setAttribute('src', './images/start.png');
clearInterval(snakeMove); //停止蛇的运动
document.onkeydown = function (e) {
e.returnValue = false;
return false;
};
startPaushBool = true;
}
}
重新加载游戏
function reloadGame() {
removeClass('snake');
removeClass('food');
clearInterval(snakeMove);
startPaush.setAttribute('src', './images/start.png');
this.snakeBody = [[3, 1, 'head'], [2, 1, 'body'], [1, 1, 'body']]; //设置初始位置
this.direct = 'right';
this.left = false;
this.right = false;
this.up = true;
this.down = true;
loser.style.display = 'block';
loserScore.innerHTML = this.score;
this.score = 0;
scoreBox.innerHTML = this.score;
startGameBool = true;
startPaushBool = true;
}
碰撞问题
蛇碰到设置的边框,立即中止游戏
// 如果蛇头和食物x y同时相等 代表吃到食物
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 += 1;
scoreBox.innerHTML = this.score;
removeClass('food'); //吃掉食物后,移除食物
food(); //再次随机生成食物
}
//撞到设置的边框
if (this.snakeBody[0][0] < 0 || this.snakeBody[0][0] >= this.mapW / this.snakeW) {
// console.log(123);
this.reloadGame();
}
if (this.snakeBody[0][1] < 0 || this.snakeBody[0][1] >= this.mapH / this.snakeH) {
// console.log(124);
this.reloadGame();
}
var snakeHX = this.snakeBody[0][0];
var snakeHY = this.snakeBody[0][1];
for (var i = 1; i < this.snakeBody.length; i++) {
var snakeBodyX = this.snakeBody[i][0];
var snakeBodyY = this.snakeBody[i][1];
//蛇头和蛇尾相撞
if (snakeHX == snakeBodyX && snakeHY == snakeBodyY) {
// console.log(126);
this.reloadGame();
}
}
Style
css style demo
*{
margin: 0;
padding: 0;
}
.startPage{
width: 100%;
z-index: 999;
height: 960px;
position: absolute;
top:0;
left:0;
}
.startBtn{
background-image:url('../images/startGame.jpg');
height: 60px;
width: 170px;
background-size: 100% 100%;
cursor: pointer;
position: absolute;
top: 0;
right: 0;
bottom:0;
left:0;
margin: auto;
/* display: none; */
}
.wrapper{
width: 100%;
height: 960px;
background-image:url('../images/Map.jpg');
background-size: 100% 100%;
position: relative;
}
.left-side{
width: 24%;
position: absolute;
height: 960px;
/* border-right: 1px solid aqua; */
}
.left-side img{
display: none;
margin-left: 50px;
margin-top: 50px;
}
.main{
position: absolute;
left: 25%;
width: 50%;
height: 90%;
/* border: 1px solid white; */
}
.header{
width: 100%;
height: 80px;
text-align: center;
}
.score{
line-height: 80px;
color: aqua;
font-size: 20;
font-weight: bolder;
}
/* .smallMap{
position: inherit;
width: 812px;
height: 478px;
background-size: 100% 100%;
left: 7.6%;
top:28%;
} */
.content{
position: absolute;
/* background-image: url('../images/smallMap.jpg'); */
background-size: 100% 100%;
width: 85%;
height:55%;
left: 7.6%;
top:28%;
border: 2px solid green;
}
.loser{
display: none;
position: 100%;
height: 960px;
top: 0;
left: 0;
}
.con{
background-image:url('../images/gameover.jpg');
background-size: 100% 100%;
height: 170px;
width: 280px;
position: absolute;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
border-radius: 20px;
}
.loserScore{
display: block;
height: 20px;
width: 150px;
position: absolute;
top: 71%;
left: 60%;
color:aqua;
font-size: 18px;
font-weight: bolder;
}
.close{
position: absolute;
top:0;
right:0;
height: 20px;
width: 20px;
border-radius: 60%;
background-image: url('../images/close.jpg');
background-size: 100% 100%;
cursor: pointer;
}
.food{
background-image: url('../images/food.jpg');
background-size: 100% 100%;
width: 50px;
height: 50px;
border-radius: 75%;
}
.head{
background-image: url('../images/SnakeHead.jpg');
background-size: 100% 100%;
width: 50px;
height: 50px;
border-radius: 85%;
}
.body{
background-image: url('../images/SnakeBody.jpg');
background-size: 100% 100%;
width: 50px;
height: 50px;
border-radius: 65%;
}
.txt{
color: aqua;
font-weight: bolder;
font-size: 18px;
top:70%;
left: 17.5%;
position: relative;
}
贪吃蛇,扫雷,2048一般都做为js原生的一个练手demo。
结语
使用一些DOM方法,js,html,css三者交互实现一个小demo,说难也不难。懂得页面布局,函数块写demo,个人美工不是很好,页面美化不是很好。过段时间用bootstrap渲染一下。
源码下载
链接:https://pan.baidu.com/s/1UlUG-ZN82Bo-JQa_Tqjmew
提取码:zkm5
(失效的话私我)