【发布时间】:2020-04-15 07:05:22
【问题描述】:
我正在开发这款游戏,并终于想出了如何将我的代码重写为一个最小的示例,我为我为这个示例删减了多少代码而感到自豪。所以我的代码在点击屏幕时开始运行,点击后,我的 createShape1() 函数运行,创建一个灰色矩形。它开始下拉屏幕,当它到达底部时,再次调用 CreateShape1() 重新开始整个过程。但是,第二个形状应该与第一个形状在同一位置,但它向左移动了 150 像素,最终重置并向下移动。 这是我的 HTML:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tetris</title>
<link rel="stylesheet" href="styleSheets/main.css">
<script src = "js/jquery.js"></script>
<script src = "js/main.js"></script>
</head>
<body>
<div id="container" style= "height: 650px; width: 500px; background: black; position: relative">
<div class= "grid">
</div>
</div>
</body>
</html>
CSS:
.grid {
background-image: repeating-linear-gradient(0deg,transparent,transparent 49px,#88F 49px,#88F 50px),
repeating-linear-gradient(-90deg,transparent,transparent 49px,#88F 49px,#88F 50px);
background-size: 50px 50px;
top: 0px;
height: 651px;
position: absolute;
width: 501px;
}
JS:
var svgNS = "http://www.w3.org/2000/svg";
countO = 0;
function createShape1() {
var endB1 = 650;
var newEndB = endB1; //used to set boundaries bottom
var elem = document.getElementById("container");
var outer = document.createElementNS(svgNS, "svg"); //creates full transparent shape
countO++;
elem.append(outer);
outer.id = "outer" + countO;
outer.style.background = "grey";
outer.style.height = "100px";
outer.style.width = "150px";
outer.style.left = "150px";
outer.style.top = "0px";
outer.style.position = "relative";
outer.style.transform = "rotate(0deg)"
var t = setInterval(down, 100); // calls down() function every second
var yPos = parseInt(outer.style.top);
var h = parseInt(outer.style.height);
var ymath = yPos + h;
function down() { // moves shape down by 50px
if (ymath < newEndB) {
yPos += 50;
ymath = yPos + h;
outer.style.top = yPos +'px';
} else {
clearInterval(t);
}
}
};
var shapes = [createShape1];
function randShape() {
shapes[0]();
};
window.addEventListener("click", startGame, {once: true})
function startGame() {
randShape()
var t = setInterval(randShape, 1200)
}
【问题讨论】:
标签: javascript function attributes setinterval createelement