gpt4 book ai didi

javascript - localStorage 无法运行 "save"游戏

转载 作者:行者123 更新时间:2023-11-28 18:58:25 24 4
gpt4 key购买 nike

美好的一天!

这里是完整的 JS 菜鸟。我正在关注本教程:http://dhmstark.co.uk/incrementals-part-2.html关于保存和加载游戏。然而,它根本不起作用。我希望你们这些好人能够轻松地告诉我代码的问题。浏览器控制台上根本没有出现任何错误。但是,当我重新加载页面时,它没有加载“保存的”数据。我尝试将 load() 函数放在 js 文件本身中,并包含在 HTML header 中。我还尝试在脚本本身中使用 window.onload 调用 load() 函数。

请帮忙。

HTML

<!DOCTYPE HTML>
<head>
<title> Game </title>
<link rel="stylesheet" type="text/css" href="interface.css" />
<script type="text/javascript">
function load() {
var savegame = JSON.parse(localStorage.getItem("save"));
if (typeof savegame.clicks !== "undefined") clicks = savegame.clicks;
}
</script>
</head>
<body onload="load()">
<button onClick="increment(1)"> Click </button>
<span id="clicks"></span><br /><br />

<button onClick="buyThing()"> Buy Thing </button><br />
Things: <span id="things">0</span><br />
Next Thing Cost: <span id="thingCost">10</span>

<script type="text/javascript" src="main.js"></script>
</body>

JS

//click tracker
var clicks = 0;

function increment(number){
clicks = clicks + number;
document.getElementById("clicks").innerHTML = clicks;
};

//cursor
var things = 0;

function buyThing(){
var thingCost = Math.floor(10 * Math.pow(1.1, things)); //works out cost of this cursor
if(clicks >= thingCost){ //check that player has enough clicks to afford cursor
things = things + 1; //increase number of cursors
clicks = clicks - thingCost; //remove clicks spent
document.getElementById('things').innerHTML = things; //update the number of cursors for the user
document.getElementById('clicks').innerHTML = clicks; //update the number of clicks for the user
};
var nextCost = Math.floor(10 * Math.pow(1.1,things)); //works out the cost of the next cursor
document.getElementById('thingCost').innerHTML = nextCost; //updates the cursor cost for user
};


var save = {
clicks: clicks,
things: things,
}

//loop
window.setInterval(function(){
increment(things);
localStorage.setItem("save",JSON.stringify(save));
}, 1000);

最佳答案

您的 save 对象将仅声明和定义一次,并且永远不会更改,因此您将一次又一次地保存进度的第一个初始值,您应该在每次保存一个新对象间隔:

window.setInterval(function(){
increment(things);
localStorage.setItem("save",JSON.stringify({clicks: clicks, things: things}));
}, 1000);

关于javascript - localStorage 无法运行 "save"游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33107193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com