JavaScript—面向对象 贪吃蛇_3 蛇对象
2024-10-08 17:31:19
蛇对象
function Snake(element) {
this.width = 20
this.height = 20 //蛇身 位置 颜色
this.body = [
{x: 6, y: 4, bc: 'red'},
{x: 5, y: 4, bc: 'blue'},
{x: 4, y: 4, bc: 'blue'},
]
this.direction = 'right'
this.elemen = element
//保存当前蛇
this.arr = []
} //吃食物
Snake.prototype.feed = function (food) { // 遇到食物 复制最后一个蛇身
if (this.body[0].x * this.width === food.x && this.body[0].y * this.height === food.y) {
let o = this.body[this.body.length - 1]
let pro = {x: o.x, y: o.y, bc: o.bc}
this.body.push(pro)
}
} Snake.prototype.remove = function () {
for (let i = 0; i < this.arr.length; i++) {
this.arr[i].parentNode.removeChild(this.arr[i])
}
this.arr = []
}
//蛇出现
Snake.prototype.show = function () {
this.remove()
//console.log(this.arr)
for (let i = 0; i < this.body.length; i++) {
let div = document.createElement('div')
this.elemen.appendChild(div)
div.style.width = this.width + 'px';
div.style.height = this.height + 'px'
div.style.position = 'absolute'
div.style.backgroundColor = this.body[i].bc
div.style.left = this.body[i].x * this.width + 'px'
div.style.top = this.body[i].y * this.height + 'px'
this.arr.push(div)
} }
//移动方法
Snake.prototype.udlr = function () {
//蛇身移动 根据最后一个的位置等于上一个的位置
for (let i = this.body.length - 1; i > 0; i--) {
this.body[i].x = this.body[i - 1].x
this.body[i].y = this.body[i - 1].y
}
// 边界
let herfX = this.body[0].x * this.width >= this.elemen.offsetWidth - this.width || this.body[0].x * this.width <= 0
let herfY = this.body[0].y * this.height >= this.elemen.offsetHeight - this.height || this.body[0].y * this.height <= 0
if (herfX || herfY) {
alert('完蛋')
return
}
switch (this.direction) {
case "right": {
this.body[0].x += 1
break;
}
case "letf": {
this.body[0].x -= 1
break;
}
case "up": {
this.body[0].y -= 1
break;
}
case "down": {
this.body[0].y += 1
break;
}
}
}
最新文章
- PHP+mysql数据库开发搜索功能:中英文分词+全文检索(MySQL全文检索+中文分词(SCWS))
- DNS劫持和DNS污染的区别
- 2014多校第十场1004 || HDU 4974 A simple water problem
- Adobe Photoshop CC 14.0简体中文特别版32位和64位下载
- iOS开发中关于UIImage的知识点总结
- POJ 3061 Subsequence(Two Pointers)
- Git Command Summary (Updated)
- 【C++继承与派生之二】有子对象的派生类的构造函数
- Jenkins安装plugin
- CodeForces 721B
- 细心!SQL语句进行运算时使用字符串时缺失精度的细节!
- 玩玩 Nginx 2-----给Nginx添加第三方模块(动态更新upstream)
- openssl命令
- 【SSH系列】Hibernate映射-- 多对一单向关联映射
- [Swift]LeetCode173. 二叉搜索树迭代器 | Binary Search Tree Iterator
- IDF-简单题目writeup
- xlwt模块的使用
- JavaScript最后的课程笔记
- vue中的指令v-model
- Django之WSGI 和MVC/MTV