1. 程式人生 > >javascript 彈彈球小遊戲

javascript 彈彈球小遊戲

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>單機版彈球遊戲</title>
		<link rel="stylesheet" type="text/css" href="css/util.css" />
		<script type="text/javascript">
			var step = 20;
			var qiuXFlag = true;
			var qiuYFlag = true;
			var intervalId = 0;

			function qiuMove() {
				intervalId = window.setInterval(function() {
					//根據按鍵的值移動板
					var ban = document.getElementById("showBan");
					var banX = parseInt(ban.style.left);
					var banH3 = document.getElementById("banH3");
					//接球的範圍是
					banH3.innerHTML = "板的接球範圍[min=" + banX + "][max=" + (banX + 100) + "]";
					//獲取小球
					var qiu = document.getElementById("showQiu");
					var ban = document.getElementById("showBan");
					var qiuH3 = document.getElementById("qiuH3");
					//獲取板的left的值
					var banX = parseInt(ban.style.left);
					//改變座標
					var x = parseInt(qiu.style.left);
					var y = parseInt(qiu.style.top);
					//實現座標資訊
					qiuH3.innerHTML = "球的座標為[x=" + x + "][y=" + y + "]";
					//判斷X的大小
					if (qiuXFlag) {
						qiu.style.left = x + step + "px";
						if (x >= 380) {
							qiuXFlag = false;
						}
					} else {
						qiu.style.left = x - step + "px";
						if (x <= 20) {
							qiuXFlag = true;
						}
					}
					//判斷Y的大小
					if (qiuYFlag) {
						qiu.style.top = y + step + "px";
						if (y == 420 && (x >= banX && x <= banX + 100)) {
							qiuYFlag = false;
						}
						if (y > 440) {
							window.clearInterval(intervalId);
							alert("Game Over");
						}
					} else {
						qiu.style.top = y - step + "px";
						if (y <= 20) {
							qiuYFlag = true;
						}
					}
				}, 100);
			}
			window.onkeydown = function(event) {
				//根據按鍵的值移動板
				var ban = document.getElementById("showBan");
				var banX = parseInt(ban.style.left);
				var banH3 = document.getElementById("banH3");
				//接球的範圍是
				banH3.innerHTML = "板的接球範圍[min=" + banX + "][max=" + (banX + 100) + "]";
				//獲取事件
				var eve = event || window.event;
				//獲取按鍵的值
				var code = eve.keyCode;
				//判斷左右
				if (code == 37) {
					if (banX > 20) {
						ban.style.left = banX - step + "px";
					}
				} else if (code == 39) {
					if (banX < 300) {
						ban.style.left = banX + step + "px";
					}
				}
			}
			
		</script>
	</head>

	<body onload="qiuMove();">
		<div id="showDiv">
			<img id="showQiu" src="img/shz.gif" style="height: 20px;position: absolute;left: 200px;top: 0px;" />
			<input type="button" id="showBan" value=" " style="width: 100px;position: absolute;top: 460px;left: 150px;" />
		</div>
		<div id="">
			<h3 id="qiuH3"></h3>
			<h3 id="banH3"></h3>
		</div>
	</body>
</html>