javascript 개발 뱀 탐식 게임 실현
이 예 에서 snake 배열 의 0 번 째 요소 와 direction 대상 의 x 값 과 y 값 을 덧셈 하여 뱀의 다음 위 치 를 계산 합 니 다.간격 함 수 를 이용 하여 클래스 이름 을 끊임없이 수정 하여 렌 더 링 작업 을 하 는 것 은 매우 유연 한 예 라 고 생각 합 니 다.
style.css
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.page{
width: 100vw;
height: 100vh;
position: absolute;
left: 0;
top: 0;
}
body{
font-size: 0.16rem;
}
.startGame{
/* display: none; */
background: purple;
display: flex;
justify-content: center;
align-items: center;
}
.startBtn,.reStartBtn{
width:2rem;
height: 0.5rem;
text-align: center;
line-height: 0.5rem;
background: deepskyblue;
color: #fff;
}
.endGame{
display: none;
/* display:flex; */
flex-direction: column;
justify-content: center;
align-items: center;
background: lightsalmon;
}
.endGame h1{
margin: 1rem 0;
color: #fff;
}
.gaming{
display: none;
background: black;
color: #fff;
}
.gaming .score{
display: flex;
justify-content: space-between;
height: 0.5rem;
align-items: center;
width: 100vw;
padding: 0 0.25rem;
}
.gaming .score .pauseBtn{
width: 0.8rem;
height: 0.3rem;
line-height: 0.3rem;
background: #999;
text-align: center;
}
.gaming .mainGame{
/* 15*20 */
width: 3.45rem;
height:4.6rem ;
background: #555;
margin: 0.3rem auto;
display: flex;
flex-wrap: wrap;
border-top: 1px solid #ccc;
border-left: 1px solid #ccc;
box-sizing: content-box;
}
.gaming .mainGame .gezi{
width: 0.23rem;
height: 0.23rem;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
}
.gaming .mainGame .gezi.snake{
width: 0.23rem;
height: 0.23rem;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
background-color: #fff;
}
.gaming .mainGame .gezi.food{
width: 0.23rem;
height: 0.23rem;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
/* background-color: orangered; */
}
.gaming .mainGame .gezi.food:before{
width: 100%;
height: 100%;
content: "";
display: block;
background:yellow;
animation: food 1s alternate infinite ;
box-shadow: 0 0 10px #ffffcc;
}
.gaming .mainGame .gezi.food[data-food=redStar]:before{
background:deeppink;
}
@keyframes food{
from{
transform: scale(1) rotate(0deg);
}
to{
transform: scale(0.5) rotate(360deg);
}
}
.gaming .mainGame .gezi.snake:before{
content:"" ;
display: block;
width: 100%;
height: 100%;
background: #ccc;
animation: snake 0.4s;
box-sizing: border-box;
}
@keyframes snake{
from{
background: #fff;
box-shadow:0 0 15px rgba(255,255,255,1);
}
to{
background: #ccc;
box-shadow:0 0 15px rgba(255,255,255,0.5);
}
}
index.js 는 주로 모든 뱀 을 게 걸 스 럽 게 먹 는 페이지 의 각종 조작 을 실현 했다.
var startBtn = document.querySelector(".startBtn")
var startPage = document.querySelector(".page.startGame")
var gamingPage = document.querySelector(".gaming")
var endGamePage = document.querySelector(".endGame")
var mainGame = document.querySelector(".mainGame")
var numDom = document.querySelector(".score .left .num")
var endGameScore = document.querySelector(".endGame .num")
var reStartBtn = document.querySelector('.reStartBtn');
var pauseBtn=document.querySelector(".pauseBtn");
var snake = [{x:0,y:1},{x:1,y:1},{x:2,y:1}];
var snakeFood = {
x:10,y:10
}
//
var score = 0;
var interId;
var ispaused=false;
//
// {x:-1,y:0}
// {x:1,y:0}
// {x:0,y:1}
// {x:0,y:-1}
var direction = {x:-1,y:0}
startBtn.onclick = function(){
startPage.style.display = "none"
gamingPage.style.display = "block"
gameIng()
}
function renderGezi(){
for(var i=0;i<20;i++){
for(var j=0;j<15;j++){
var gezi = document.createElement("div");
gezi.className = "gezi";
gezi.id = 'x'+j+'y'+i;
mainGame.appendChild(gezi)
}
}
}
renderGezi()
// ,
function createSnake(){
var randomX = parseInt(Math.random()*13)
var randomY = parseInt(Math.random()*20)
snake = [];
for(var i= 0;i<3;i++){
snake.push({x:randomX+i,y:randomY})
}
}
function renderSnake(){
snake.forEach(function(item,i){
var snakeBody = document.querySelector("#x"+item.x+"y"+item.y);
snakeBody.className = "gezi snake";
})
}
//
function renderFood(){
var randomX = parseInt(Math.random()*15)
var randomY = parseInt(Math.random()*20)
var foodDiv = document.querySelector("#x"+randomX+"y"+randomY)
if(foodDiv.className == "gezi snake"){
renderFood()
}else{
foodDiv.className = "gezi food"
}
}
createSnake()
renderFood()
renderSnake()
function gameIng(){
interId = setInterval(function(){
var headerX = snake[0].x + direction.x;
var headerY = snake[0].y + direction.y;
if(headerX<0){
headerX = 14;
}
if(headerX>14){
headerX = 0;
}
if(headerY<0){
headerY = 19;
}
if(headerY>19){
headerY = 0;
}
var snakeHeader = {x:headerX,y:headerY};
isSnake(snakeHeader)
if(!isFood(snakeHeader)) {
// , dom, class gezi
var snakeFooter = snake.pop()//
var snakeFooterDiv = document.querySelector("#x"+snakeFooter.x+"y"+snakeFooter.y);
snakeFooterDiv.className = "gezi";
}
snake.unshift(snakeHeader)//
renderSnake()
},100)
}
function isSnake(snakeHeader){
var newHeader = document.querySelector("#x"+snakeHeader.x+"y"+snakeHeader.y)
if(newHeader.className == "gezi snake"){
clearInterval(interId);
gamingPage.style.display = "none"
endGamePage.style.display = "flex"
endGameScore.innerHTML = score;
return true;
}else{
return false;
}
}
function isFood(snakeHeader){
var newHeader = document.querySelector("#x"+snakeHeader.x+"y"+snakeHeader.y)
if(newHeader.className == "gezi food"){
score ++;
numDom.innerHTML = score;
renderFood()
return true;
}else{
return false;
}
}
var body = document.body
body.addEventListener("keydown",function(e){
console.log(e)
// 。
if(e.key == "ArrowUp"&&direction.y!=1){
direction = {x:0,y:-1}
}
if(e.key=="ArrowRight"&&direction.x!=-1){
direction = {x:1,y:0}
}
if(e.key == "ArrowDown"&&direction.y!=-1){
direction = {x:0,y:1}
}
if(e.key=="ArrowLeft"&&direction.x!=1){
direction = {x:-1,y:0}
}
})
ylEvent.init(body);
body.addEvent("swiperLeft",function(){
if(direction.x!=1){
direction = {x:-1,y:0}
}
})
body.addEvent("swiperRight",function(){
if(direction.x!=-1){
direction = {x:1,y:0}
}
})
body.addEvent("swiperTop",function(){
if(direction.y!=1){
direction = {x:0,y:-1}
}
})
body.addEvent("swiperBottom",function(){
if(direction.y!=-1){
direction = {x:0,y:1}
}
})
reStartBtn.onclick = function(){
location.reload();
}
pauseBtn.onclick=function(){
if(ispaused){
ispaused=false;
gameIng();
}else{
ispaused=true;
clearInterval(interId);
}
}
js 보조 응답
(function(){
function xys(){
var userAgent=navigator.userAgent
var html=document.querySelector("html");
//userAgent.indexOf("iPhone") iPhone ( )
// -1
html.className="";
if((userAgent.indexOf("iPhone"))!=-1){
html.classList.add("iphone");
}else if((userAgent.indexOf("Android"))!=-1)
{
html.classList.add("android");
}else if((userAgent.indexOf("iPad"))!=-1){
html.classList.add("ipad");
}else{
html.classList.add("pc");
}
if(window.innerWidth<640){
html.classList.add('lt640');
html.classList.add('lt960');
html.classList.add('lt1200');
}else if(window.innerWidth<960){
html.classList.add('lt960');
html.classList.add('lt1200');
html.classList.add('gt640');
}else if(window.innerWidth<1200){
html.classList.add('lt1200');
html.classList.add('gt640');
html.classList.add('gt960');
}else{
html.classList.add('gt640');
html.classList.add('gt960');
html.classList.add('gt1200');
}
var screenWidth = window.innerWidth;
var danwei = screenWidth/3.75;// / rem
var html = document.querySelector("html")
html.style.fontSize = danwei + 'px';
}
xys();
window.onresize=function(){
xys();
}
})()
swiperEvent.js
var ylEvent = {
eventAll:{
//" ":[' 1',' 2',' 3']
},
init:function(dom){
dom.eventAll = {},
dom.addEvent = this.addEvent;
dom.emit = this.emit;
dom.removeEvent = this.removeEvent
dom.touchData = {};
//body.emit('swiperLeft',"msg")
dom.addEventListener("touchstart",function(e){
//console.log(e)
this.touchData.startX = e.touches[0].pageX;
this.touchData.startY = e.touches[0].pageY
})
dom.addEventListener('touchmove',function(e){
this.touchData.endX = e.touches[0].pageX;
this.touchData.endY = e.touches[0].pageY;
})
dom.addEventListener("touchend",function(e){
//console.log(e)
var x = this.touchData.endX - this.touchData.startX;
var y = this.touchData.endY - this.touchData.startY
if( (Math.abs(x) > Math.abs(y)) && Math.abs(x)>100){
if(x>0){
//console.log(' ')
e.swiperDir = 'swiperRight'
body.emit('swiperRight',e)
}else{
//console.log(' ')
e.swiperDir = 'swiperLeft'
body.emit('swiperLeft',e)
}
}else if((Math.abs(x) < Math.abs(y)) && Math.abs(y)>100){
if(y>0){
//console.log(' ')
e.swiperDir = 'swiperBottom'
body.emit('swiperBottom',e)
}else{
//console.log(' ')
e.swiperDir = 'swiperTop'
body.emit('swiperTop',e)
}
}
})
},
addEvent:function(eventName,callBackFn){
if(this.eventAll[eventName]==undefined){
this.eventAll[eventName] = []
}
this.eventAll[eventName].push(callBackFn)
},
emit:function(eventName,eventMsg){
if(this.eventAll[eventName]!=undefined){
this.eventAll[eventName].forEach(function(item,i){
item(eventMsg)
})
}
},
removeEvent:function(eventName,callBackFn){
var that = this
this.eventAll[eventName].forEach(function(item,i){
if(item==callBackFn){
that.eventAll[eventName].splice(i,1)
}
})
},
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<script src="js/js .js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<!--
1、
2、
3、
4、
5、
6、
-->
<div class="page startGame">
<div class="startBtn"> </div>
</div>
<div class="page gaming">
<div class="score">
<div class="left">
score:<span class="num">0</span>
</div>
<div class="pauseBtn">
</div>
</div>
<div class="mainGame">
</div>
</div>
<div class="page endGame">
<h1> <span class="num">0</span> </h1>
<div class="reStartBtn"> </div>
</div>
<script src="js/swiperEvent.js" type="text/javascript" charset="utf-8"></script>
<script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
결과:이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[2022.04.19] 자바스크립트 this - 생성자 함수와 이벤트리스너에서의 this18일에 this에 대해 공부하면서 적었던 일반적인 함수나 객체에서의 this가 아닌 오늘은 이벤트리스너와 생성자 함수 안에서의 this를 살펴보기로 했다. new 키워드를 붙여 함수를 생성자로 사용할 때 this는...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.