1

I am trying to develop a game.

However my math is a problem. Every time the total profit value goes into negative value.

How can i fix it?

var gameProfit = 10000;
var tinyOwned = 0;
var tinyCost = 10000;
var tinyIncome = 0;

function buyTiny(){
 if (gameProfit >= tinyCost){
  
  tinyOwned += 1;
  document.getElementById('tiny-owned').innerHTML = tinyOwned;
  document.getElementById('current-profit').innerHTML = "Profit : $ " + (gameProfit -= tinyCost * tinyOwned);
  document.getElementById('tiny-cost').innerHTML = "Next Cost : $ " + (tinyCost * tinyOwned + 10000);
  document.getElementById('tiny-income').innerHTML = "Income : $ " + (tinyIncome = 15000 * tinyOwned); 
 }
}

var timer = 0;
var timeInterval = 10;

window.setInterval(function gameTimer() {
 if (timer >= 0) {
  timer++;
  document.getElementById('timer-value').style.width = timer + "px";
 }
 if (timer >= 600) {
  timer = 0 + 1;
  document.getElementById('timer-value').style.width = "0px";
  
  tinyIncome = 15000 * tinyOwned;
  gameProfit += tinyIncome;
  
  document.getElementById('current-profit').innerHTML = "Profit : $ " + (gameProfit);
  
 }
}, timeInterval);

Can anyone see the problem in my code? gameProfit Variable goes into negative how to fix this?

Claire
  • 3,146
  • 6
  • 22
  • 37

1 Answers1

4

You allow someone to buy when: gameProfit >= tinyCost

But you reduce gameProfit like: gameProfit -= tinyCost * tinyOwned

So you take more then you initially check! to fix:

if (gameProfit >= tinyCost * tinyOwned){

The math looks really messy especially since it is mixed up with setting InnerHtml. I strongly advice to first do the math and then update the Html.InnerHTML

Offtopic: make sure you escape your data if you are ever going to make it to a multiplayer game, else people can crosside script it (Can I escape html special chars in javascript?) but this is something you don't really have to worry about at this stage.

Joel Harkes
  • 10,975
  • 3
  • 46
  • 65