热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

原生JS实现贪吃蛇

HTML

  

 

HTML



"
en">

"UTF-8">
"X-UA-Compatible" cOntent="IE=edge">
"viewport" cOntent=">







"text" value=0 class=score disabled>

class="popup">popup

class="map">






 

greedysnake.js


import Food from ./food.js
import Snake
from ./snake.js
export
default class GreedySnake{
constructor(elem,score,popup){
this.map=document.querySelector(elem)
this.timer=null
this.level=1
this.food=new Food(this.map)
this.snake=new Snake(this.map)
this.score=document.querySelector(score)
this.count=0
this.steer()
this.popup=document.querySelector(popup)
this.flag=true
}
start(){
this.timer=setInterval(()=>{
this.alert()
this.snake.motion()
let flag
=this.snake.achieve(this.food)
// console.log(‘this.food‘,this.food,this.food.food.offsetLeft,this.food.food.offsetTop)
if(flag){
this.updateScore()
this.snake.defineHead()
this.food.generator()
}
if(this.snake.termination()){
clearInterval(
this.timer)
// window.alert(‘Game Over!!!‘)
if(window.confirm(Oops! Game Over! Do you want to restart ?)){
this.restart()
}
}
},
400-this.level*50)
}
stop(){
window.clearInterval(
this.timer)
}
restart(){
window.location.reload()
}
steer(){
document.addEventListener(
keydown,e=>{
e.preventDefault()
// console.log(e.key)
switch(e.key){
case ArrowUp: this.snake.bearing=top;break
case ArrowDown: this.snake.bearing=bottom;break
case ArrowLeft: this.snake.bearing=left;break
case ArrowRight: this.snake.bearing=right;break
}
})
}
alert(){
if(this.count%1===0 && this.flag){
if(this.count !== 0){
this.popup.innerHTML=`^_^ Congratulations, promote to level: ${this.level}`
}
else{
this.popup.innerHTML=`^_^ level: ${this.level}`
}
this.popup.style.display=block;
this.flag=false
setTimeout(()
=>{
this.popup.style.display=none
},
1500)
}
}
updateScore(){
this.count++
// console.log(‘count: ‘,this.count,typeof this.score.value,this.score.value)
this.score.value=parseInt(this.score.value)+this.level*10
if(this.count%1===0){
this.flag=true
this.level++
this.stop()
this.start()
}
}
}

 

snake.js


export default class Snake{
constructor(map){
this.map=map
this.snake=[]
this.bearing=right
this.initialize()
}
getBearing(){
const head=this.snake[0]
if(!head) return {left:0,right:0}
const bearing={left:head.offsetLeft,top:head.offsetTop}
switch(this.bearing){
case top: bearing.top-=20;break
case right: bearing.left+=20;break
case bottom: bearing.top+=20;break
case left: bearing.left-=20;break
}
// console.log(‘getBearing‘,bearing)
return bearing
}
defineHead(){
const position=this.getBearing()
// console.log(‘defineHead‘,position)
const head=this.snake[0]
if(head) head.className=body
const div=document.createElement(div)
div.className
=head
div.style.left
=position.left+px
div.style.top
=position.top+px
this.snake.unshift(div)
this.map.appendChild(div)
}
initialize(){
const num=3;
for(let i=0;ii){
this.defineHead()
}
}
motion(){
const body=this.snake.pop()
body.remove()
this.defineHead()
}
termination(){
const head=this.snake[0]
const x=head.offsetLeft
const y=head.offsetTop
if(x<0 || y<0 || x>this.map.clientWidth || y>this.map.clientHeight){
return true
}
else{
let flag
=false
const body=this.snake.slice(1)
body.forEach((value,index,array)
=>{
if(value.offsetLeft === x && value.offsetTop === y) flag=true
})
return flag
}
}
achieve(food){
const x=this.snake[0].offsetLeft
const y=this.snake[0].offsetTop
if(x === food.food.offsetLeft && y === food.food.offsetTop) return true
return false
}
}

 

food.js


export default class Food{
constructor(map){
this.map=map
this.food=document.createElement(div)
this.food.className=food
this.map.appendChild(this.food)
this.x=0
this.y=0
this.generator()
}
generator(){
const numberX=this.map.clientWidth/this.food.clientWidth
const numberY=this.map.clientHeight/this.food.clientHeight
const x=Math.floor(Math.random()*numberX)
const y=Math.floor(Math.random()*numberY)
this.food.style.left=x*20+px
this.food.style.top=y*20+px
// console.log(‘food‘,x,y,this.food.offsetLeft,this.food.offsetTop)
}
}

 

main.js


import GreedySnake from ./greedysnake.js
const pastime=new GreedySnake(.map,.score,.popup)
const startButton=document.querySelector(.start)
startButton.addEventListener(
click,()=>pastime.start())
const stopButton=document.querySelector(.stop)
stopButton.addEventListener(
click,()=>pastime.stop())
const restartButton=document.querySelector(.restart)
restartButton.addEventListener(
click,()=>pastime.restart())

 

body.png

技术分享图片

 

 

head.png

技术分享图片

 

 

bg.png

技术分享图片

 

 

food.png

技术分享图片

 

 


推荐阅读
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 高质量SQL书写的30条建议
    本文提供了30条关于优化SQL的建议,包括避免使用select *,使用具体字段,以及使用limit 1等。这些建议是基于实际开发经验总结出来的,旨在帮助读者优化SQL查询。 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 动态规划算法的基本步骤及最长递增子序列问题详解
    本文详细介绍了动态规划算法的基本步骤,包括划分阶段、选择状态、决策和状态转移方程,并以最长递增子序列问题为例进行了详细解析。动态规划算法的有效性依赖于问题本身所具有的最优子结构性质和子问题重叠性质。通过将子问题的解保存在一个表中,在以后尽可能多地利用这些子问题的解,从而提高算法的效率。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • 在project.properties添加#Projecttarget.targetandroid-19android.library.reference.1..Sliding ... [详细]
author-avatar
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有