打气球游戏,面向对象

这篇博客介绍了一个使用JavaScript编写的气球游戏。游戏中,气球从屏幕左侧动态生成并沿水平方向移动,用户可以通过键盘操作消除与气球上显示的字母相匹配的气球。博客内容涉及DOM操作、对象创建、事件监听等JavaScript核心技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>面向对象</title>
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}

			.box {
				width: 1200px;
				height: 500px;
				border: solid 1px red;
				margin: 0 auto;
				position: relative;
				overflow: hidden;
			}

			.qi {
				width: 38px;
				height: 60px;
				border: solid 1px #000;
				border-radius: 100%;
				text-align: center;
				line-height: 60px;
				font-size: 24px;
				position: absolute;
			}
		</style>
	</head>
	<body>
		<div id="box" class="box">

		</div>
		<script type="text/javascript">
			// 获取它爹
			var box = document.getElementById('box');
			// 创建对象
			function Ballon(className, width, height, x, y) {
				// 考虑这个气球对象应当拥有什么样的属性和方法
				// 属性:文字属性  移动速度、元素属性、样式类属性、宽度、高度、位置属性(x、y)
				// 方法:移动方法、出现方法、消失方法
				this.text = Ballon.textwb[Ballon.sj(0, Ballon.textwb.length - 1)].toUpperCase()
				this.className = className;
				this.speed = Ballon.sj(10, 20);
				this.dom = document.createElement('div');
				this.width = width;
				this.height = height;
				this.x = x;
				this.y = y;
				// 方法 气球能不能动
				// 将属性赋值给气球属性
				this.render = function() {
					this.dom.className = this.className;
					this.dom.innerHTML = this.text;
					this.dom.style.top = this.y + 'px';
				}
				// 移动
				this.move = function() {
					this.x += this.speed;
					this.dom.style.left = this.x + 'px'
				}
				// 显示
				this.show = function(parent) {
					parent.appendChild(this.dom)
				}
				this.hide = function() {
					this.dom.remove()
				}
			}
			// 静态属性
			Ballon.textwb = 'abcdefghijklmnopqrstuvwxyz'
			// 静态方法
			Ballon.sj = function(min, max) {
				return parseInt(Math.random() * (max - min + 1)) + min;
			}
			var arr = []
			setInterval(() => {
				var sun = new Ballon('qi', 38, 60, 0, Ballon.sj(0, box.clientHeight - 62))
				arr.push(sun)
				// 渲染
				sun.render()
				// 显示
				sun.show(box)
				// 移动
				sun.move()
			}, 1000)
			setInterval(() => {
				arr.forEach(function(value, idx) {
					value.move()
				})
			}, 50)
			// 键盘删除
			document.onkeydown = function(e) {
				arr.forEach(function(value,idx) {
					// console.log(value)
					if(value.text == e.key.toUpperCase()){
						value.hide()
						arr.splice(idx,1)
					}
				})
				// console.log(e.key)
			}
		</script>
	</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值