JavaScript实现气球打字游戏

Posted 公众号_前端每日技巧

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript实现气球打字游戏相关的知识,希望对你有一定的参考价值。

实现效果

JavaScript实现气球打字游戏_javascript

定义球的类

气球类中我们需要对26个字符进行处理

this.arr = "abcdefghijklmnopqrstuvwxyz".split("");

生成一个随机字母

this.index = parseInt(Math.random() * this.arr.length);
// 定义随机字符
this.str = this.arr[this.index];

生成一个div标签并对图片进行处理

// 元素属性
this.dom = document.createElement("div");
// 图片属性
this.img = img;
// 图片的宽
this.width = this.img.width / 4;
// 图片的高
this.height = this.img.height / 3;
// 图片的背景定位X
this.positionX = parseInt(Math.random() * 4);
// 图片的背景定位Y
this.positionY = parseInt(Math.random() * 3);

关于样式的处理操作

// 设置样式
this.setStyle = function()
// 设置元素定位
this.dom.style.position = "absolute";
this.dom.style.left = 0;
// 设置元素的内部文本
this.dom.innerhtml = this.str;
// 设置文本样式
this.dom.style.lineHeight = this.height * 2 / 3+ "px";
this.dom.style.textAlign = "center";
this.dom.style.fontSize = "20px";
this.dom.style.fontWeight = "bold";
this.dom.style.top = parseInt(Math.random() * (document.documentElement.clientHeight - this.height)) + "px";
// 设置元素的宽度和高度
this.dom.style.width = this.width + "px";
this.dom.style.height = this.height + "px";
// 设置元素背景图片
this.dom.style.backgroundImage = "url(" + this.img.src + ")";
// 设置元素的背景定位
this.dom.style.backgroundPositionX = -this.width * this.positionX + "px";
this.dom.style.backgroundPositionY = -this.height * this.positionY + "px";

定义一个上树的方法

// 上树方法
this.upTree = function()
document.body.appendChild(this.dom);

我们需要检测气球是否到达浏览器边缘

// 检测气球是否到达边界
this.check = function()
// 判断定位left值值是否到达别界
if (this.dom.offsetLeft >= document.documentElement.clientWidth - this.width)
// 设置定位值
this.dom.style.left = document.documentElement.clientWidth - this.width + "px";
return true;

return false;

定义一个下树的方法

// 下树方法
this.boom = function()
this.dom.parentNode.removeChild(this.dom);

定义一个移动的方法,其中的数字表示气球移动的速度

// 移动方法
this.move = function()
this.dom.style.left = this.dom.offsetLeft + 5 + "px";

定义初始化的方法并执行

// 定义初始化方法
this.init = function()
this.setStyle();
this.upTree();

// 执行init
this.init();

创建图片元素

// 创建图片元素
var img = document.createElement("img");
// 设置路径
img.src = "images/balloon.jpg";

气球每隔多少时间生成一个,我们需要设置定时器以及气球到达边界的处理,其中代码中的​​70​​表示每移动70次创建一个气球。

// 定义数组
var arr = [];
// 定义定时器
var timer = null;
// 定义一个信号量
var count = 0;
// 添加事件
img.onload = function()
// 初始化气球对象
var balloon = new Balloon(img);
// 第一个气球也要放入数组中
arr.push(balloon);
// 赋值定时器
timer js实现点气球小游戏

C语言项目实战:《气球射击》游戏项目,200行代码轻松实现

jQuery 打气球小游戏 点击气球爆炸效果

Scratch投球游戏 2020蓝桥杯STEMA考试Scratch编程题真题和答案解析

腾讯2019 暑期实习提前批笔试 —— AcWing 570. 气球游戏

腾讯2019 暑期实习提前批笔试 —— AcWing 570. 气球游戏