writing a test "cookie clicker" game

1k Views Asked by At

In school we use this coding website called code.org. It's pretty handy and seems to be able to do anything that normal coding software can, just a bit more digestible for beginners such as myself. I'm asking a question that I'm not sure is even possible to answer. In the game I'm trying to figure out how to add cps (cookies per second) to the counter. My issue is that this could be done in a loop, but other things need to happen outside of the loop. So I'm not sure how to add them, but still be able to run other bits of code without it getting stuck in a loop. The code will be posted at the bottom. This project is just for fun and I do not intend to pass this work off as my own. Thanks for the help!

(please note that this IS the entirety of the code i have so far...)

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");
});

(also note that this code snippet does not work properly as you won't be on code.org or have the proper buttons to handle the events.)

2

There are 2 best solutions below

2
On

I'm not seeing any loops here, just click events. Am I missing something? If there was a loop, we could see what's inside vs. what's out. Typically you handle variables changes (and not changing them) within loops with conditional if statements.

0
On

The feature you are looking for is probably setInterval which runs a function every n milliseconds.

function runAutoClicker() {
  cookies = cookies + cps;
}

// Run auto-clicker every second (every 1000 milliseconds)
setInterval(runAutoClicker, 1000);