1

I recently had a problem with saving my game, and after some further fiddling around, I successfully got localStorage(); to work! Unfortunately, when you do refresh or reopen the game, a nasty bug occurs. The game I am trying to recreate is Cookie Clicker. The bug is as follows: if you have a structure purchased (I.E. Auto Clicker which is +1 cookie every 2 seconds) it does not add a cookie to your total. Instead it adds a 1 to the end of your cookie total. For example, if you have 1004 cookies, instead of bringing you to 1005 cookies, it is making your total 10041 cookies. And this just keeps going and going. The same thing happens to the cost of structures. For example, (Note my formula for increasing cost is: cost += cost*.3) if you purchase your first auto clicker for 50 cookies, the next auto clicker cost 5015 cookies instead of 65 cookies. I have no idea why this is happening. Any explanations are appreciated.

<!DOCTYPE html>
<html>

<head>
    <title>Cookie Clickers!</title>
    <link type="stylesheet/css" rel="stylesheet" href="style.css" />
    <script language="javascript">
    </script>
</head>

<body>

    <h1>Cookie Clickers By: Michael</h1>
    <h3>Original Idea By: Orteil</h3>
    <br>
    <br>
    <h1 id="CookieAmount"></h1>
    <h2 id="CookiePerSecond"></h2>
    <div id="cookie" style="cursor:pointer" onclick="cookieClicked();">
        <img src="http://img1.wikia.nocookie.net/__cb20130827014912/cookieclicker/images/thumb/5/5a/PerfectCookie.png/250px-PerfectCookie.png">
    </div>
    <!--Tells player how much Auto Clicker Costs-->
<button onclick="getAutoClicker();">Purchase Auto Clicker for <span id="AutoClickCookieCost"></span>
	<br><span id="AutoClickTotal"></span> owned</button>
	
	<br>
    <button onclick="saveGame();">Save Game</button>
	<button onclick="resetConfirm();">Reset Game</button>
    <div>
        <script language="javascript">
            //Checks if variables are defined
           
if(typeof cookieClicks === "undefined"){
		//If no variables are defined, the variables are defined and given a default value.
			var cookieClicks = 0;
			} 
			var cookieClicks = localStorage.cookieClicks;
if(typeof clckValue === "undefined"){
		//If no variable is defined, variable is given value.
			var clickValue = 1;
}
			var clickValue = localStorage.clickValue;
if(typeof AutoClickers === "undefined"){
		//If no Auto Clickers defined, defaul value given.
			var AutoClickers = 0;
}
			var AutoClickers = localStorage.AutoClickers;
if(typeof AutoClickerCost === "undefined"){
		//If no Auto Clicker Cost defined, default value given.
			var AutoClickerCost = 50;
}
			var AutoClickerCost=localStorage.AutoClickerCost;
			
//==================================End of Variables========================================================================================
//==================================Begin Compute Structure CPS=============================================================================
             //Purchases Auto Clicker for Player and removes Cookies.
function getAutoClicker() {
	if (cookieClicks >= AutoClickerCost) {
		AutoClickers++;
		cookieClicks -= AutoClickerCost;
		AutoClickerCost += Math.floor(AutoClickerCost *.3);
			} else {
				alert("Oh No! It appears you do not have enough cookies to purchase an Auto Clicker. An Auto Clicker currently costs " + AutoClickerCost + " which is " + (AutoClickerCost - cookieClicks) + " more cookies than you have.")
					}
				} 
			
			
			
			//Rests Game
			function resetConfirm(){
				var answer = confirm("Are you sure you wish to reset?  ALL progress will be lost FOREVER.");
				if(answer){
					 cookieClicks = 0;
					 clickValue = 0;
					 AutoClickers = 0;
					 AutoClickerCost = 50;
				}
			}
			//Processes cookie click and adds it to total.
       function cookieClicked(){
		   cookieClicks++;
	   }
				//Main Game loop updating Cookie Totals from AUTOCLICKER ONLY!
			var AutoClickTimer = setInterval(function() {
			AutoClickCookie()
			}, 2000);
				function AutoClickCookie() {
				cookieClicks = cookieClicks+parseInt((AutoClickers*1),10);
				}
                //Side Loop updating button costs and CPS
            var CookieClickTimer = setInterval(function() {
                updateCookie()
            }, 100);

            function updateCookie() {
                //Calculate CPS

                document.getElementById("CookieAmount").innerHTML = cookieClicks + " cookies.";
				//CPS PlaceHolder;
				document.getElementById("AutoClickCookieCost").innerHTML = AutoClickerCost;
				document.getElementById("AutoClickTotal").innerHTML = AutoClickers;
            }
        var saveGameLoop = setInterval(function(){saveGame()}, 100);
            function saveGame(){
                localStorage.cookieClicks = cookieClicks;
				localStorage.clickValue = clickValue;
				localStorage.AutoClickers = AutoClickers;
				localStorage.AutoClickerCost = AutoClickerCost;
            };
        </script>
    </div>
</body>

</html>

Thanks, Michael

2
  • 1
    A simple way to force a value that might be a string to be treated as a number is to use the unary + operator: var total = total + +maybe_a_string; for example. Commented Feb 22, 2015 at 3:59
  • Also there's no need to declare any particular variable with var more than once. The var statement establishes the symbol as a local variable, and it's redundant to do it more than once in a function. Commented Feb 22, 2015 at 4:00

3 Answers 3

2

I didn't sift through all of your code, but after reading your description, I imagine that your problem is that you are not converting the string data to a number. Remember that localStorage only stores string values. So, when you need a number, I suggest you use the built-in parseInt function.

var cost = parseInt(localStorage.AutoClickerCost, 10); 
// 10 means base 10 here (optional, but helpful)
Sign up to request clarification or add additional context in comments.

5 Comments

You dont need to use a function. You can do +localStorage.AutoClickerCost (as per a comment to the question), localStorage.AutoClickerCost * 1, localStorage.AutoClickerCost + 0, localStorage.AutoClickerCost / 1, localStorage.AutoClickerCost << 0 or localStorage.AutoClickerCost >> 0. All of them are faster than your example.
Very true. But should be careful with some of those, as String might take precedence in the cast. eg: "5" + 0 = "50". parseInt might also be a little more readable when trying to debug 6 months after writing the code.
That is very true indeed. But the most seem method, in my opinion is localStorage.AutoClickerCost / 1, which anyone can recognise easily and will always work. And we all know that dividing by 1 will always give the same number.
Yea, I like that. I think I'll start using it.
You should add that to your answer then. Also, remember that if you forget to specify the base with parseInt(), numbers starting with 0 (like '09') will be interpreted as if written in octal, returning 0 or NaN instead of 9. But this is more for older browsers.
0

try this AutoClickCookie() instead of your AutoClickCookie() function :

function AutoClickCookie() {
                cookieClicks = parseInt(cookieClicks)+parseInt((AutoClickers*1),10);
                }

Comments

0

add the Number(); tag aroundwhere you get the bigger number (1004)

Number(<code for getting number>) + <other number> = variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.