在学校,我们使用名为code.org的编码网站。它非常方便,并且似乎能够执行普通编码软件可以执行的任何操作,对于像我这样的初学者而言,它更容易理解。我在问一个我不确定是否可以回答的问题。在游戏中,我试图找出如何向计数器添加cps(每秒cookie)。我的问题是,这可以循环执行,但是其他事情需要在循环之外进行。因此,我不确定如何添加它们,但是仍然能够运行其他代码,而不会陷入循环中。该代码将发布在底部。这个项目只是为了娱乐,我不打算把这项工作当做我自己的事。感谢您的帮助!
(请注意,这是我到目前为止的全部代码...)
var cookies = 0;
var incriment = 1;
var cps = 0;
var autoClickers = 0;
var autoClickerCost = 1;
var autoClickerAdd = 0.50;
var upgradeClickCost = 100;
setText("upgradeClickCostText","cost: "+ upgradeClickCost);
setText("autoClickerCostText", "cost: " + autoClickerCost);
onEvent("image1", "click", function() {
cookies = cookies + incriment;
console.log("you have: "+cookies+" cookies");
setText("cookieNumber", "Cookies: " + cookies);
});
onEvent("upgradeClick", "click", function() {
if(cookies >= upgradeClickCost){
cookies = cookies - upgradeClickCost;
console.log("you have: "+cookies+" cookies");
setText("cookieNumber", "Cookies: " + cookies);
incriment = incriment * 2;
upgradeClickCost = upgradeClickCost * 2;
setText("upgradeClickCostText", "cost: "+ upgradeClickCost);
}
});
onEvent("shopScrnBtn", "click", function() {
setScreen("shop_screen");
console.log("went to shop!");
});
onEvent("gameScrnBtn", "click", function() {
setScreen("game_screen");
console.log("went to cookie!");
});
function addCookies(){
cookies = cookies + cps;
}
onEvent("buyAutoClicker", "click", function() {
if(cookies >= autoClickerCost){
cookies = cookies - autoClickerCost;
autoClickers++;
console.log("you have: "+cookies+" cookies");
setText("cookieNumber", "Cookies: " + cookies);
autoClickerAdd = autoClickerAdd * autoClickers;
cps = cps + autoClickerAdd;
}
console.log("auto clicker purchased");
});
(还请注意,此代码段无法正常运行,因为您将不在code.org上,也没有适当的按钮来处理事件。)
答案 0 :(得分:0)
我在这里没有看到任何循环,只是单击事件。我想念什么吗?如果有一个循环,我们可以看到里面到底是什么。通常,您在循环中使用条件if
语句处理变量更改(而不更改它们)。
答案 1 :(得分:0)
您正在寻找的功能可能是setInterval
,它每 n 毫秒运行一次功能。
function runAutoClicker() {
cookies = cookies + cps;
}
// Run auto-clicker every second (every 1000 milliseconds)
setInterval(runAutoClicker, 1000);