So for my school computer science class I have to write a web page in HTML and Javascript, and decided to make a game where you explore different locations and collect the money there while trying to beat your record time.
My problem is with using cookies. I cannot seem to make them ever work, and don't even know how to use the js cookie library- nor do I have time this week to find out. I will also need to eventually figure out how to store the final time variable, check if it is a high score, and save it as a cookie. The current web page code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Treasure Hunter
</title>
<script type="text/javascript">
var c_time = 0
var c_coins = 0
function countUP () {
c_time = c_time + 1;//increment the counter by 1
//display the new value in the div
document.getElementById("timer_container").innerHTML = "Seconds ellapsed: " + c_time;
}
function incCoins () {
c_coins = c_coins + 1;
document.getElementById("coin_counter").innerHTML = "Coins collected: " + c_coins;
}
function changeImg(img, nocoins) {
img.src = nocoins;
}
function setCookie(c_coins,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_coins + "=" + c_value;
}
function getCookie(c_coins)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_coins)
{
return unescape(y);
}
}
}
</script>
</head>
<body onload='timer=setInterval("countUP()", 1000 );'>
<img src="courtyardbackground.png">
<a href="garden.html">
<img style="position:absolute; TOP:450px; LEFT:170px" src="courtyardgardensign.png">
</a>
<div onclick="incCoins()">
<img onclick="changeImg(this, 'nocoins.png')" style="position:absolute; TOP:550px; LEFT:470px" src="coins.png">
</div>
<div id="timer_container" style="position:absolute; TOP:780px; LEFT:50px">Seconds ellapsed: 0</div>
<div id="coin_counter" style="position:absolute; TOP:780px; LEFT:400px">Coins collected: 0</div>
</body>
</html>
Note that this code does not include my attempt at loading a cookie, but merely modifies the variables. Any help with this cookie business would be greatly appreciated.
No, you will not get a cookie for your help.