我已经被指示制作一个简单的游戏,点击图片会增加你的分数并最终允许升级。当我单击图像时,它会显示第一次离开的点击量,但是,后续时间似乎不起作用。这是我的函数如何相互调用的问题吗?
的Javascript
//Variables
var clicks = 0;
var level = 2;
var clickInterval = 1;
var holdClick = 0;
function imgClicked() { //Activated by clicking on image
var clicks = clicks + clickInterval; //Increasing clicks
upgradeCheck();
if (holdClick === 1) { //If holding down the image activated
window.onmousedown = holding();
}
}
function upgradeCheck() { //Check if eligible for new level
if (clicks > Math.pow(level, 2)) { //If clicks more than current level^2
level = level + 1; //Next level
upgrade();
} else { //If not
var clicksLeft = Math.pow(level, 2) - clicks; //Determine clicks until eligible
document.getElementById("toUpgrade").innerHTML = clicksLeft + " clicks left until upgrade"; //Display
}
}
function upgrade() { //Upgrading
document.getElementById("clickImg").src = "level" + level + ".png"; //Change to new level
var clickInterval = clickInterval * 2; //Increase points per click
if (Math.pow(level, 2) / clickInterval > 400) { //If it take more than 400 clicks to get to next level
var holdClick = 1; //Activate hold clicking
document.getElementById("message").innerHTML = "You can now hold down the image";
}
}
function holding() {
var clicks = clicks + clickInterval; //Adding more clicks
}
HTML
<p id="toUpgrade"></p>
<img id="clickImg" src="level2.png" onclick="imgClicked()" />
<p> id="message"></p>
答案 0 :(得分:3)
我认为这不符合你的想法:
var clicks = clicks + clickInterval; //Adding more clicks
您没有修改全局clicks
变量,只是在该函数的范围内创建名为clicks
的全新变量。然后,当函数完成时,该变量就会消失。您永远不会实际修改现有的clicks
变量。我想你想要这个:
clicks = clicks + clickInterval; //Adding more clicks
其他地方也犯了同样的错误,例如:
var clickInterval = clickInterval * 2; //Increase points per click
和
var holdClick = 1; //Activate hold clicking
删除var
个关键字以防止声明新变量。