我对编程非常陌生,对Javascript也非常陌生。教授没有任何帮助,我正在和一个朋友(也是一个初学者)一起做这件事,我们都被困住了。
我们正在尝试制作一个简单的游戏,并被告知必须使用localStorage的保存和加载功能。
我的朋友在处理游戏逻辑的同时,我正在进行保存和加载。
问题是,我无法弄清楚如何获取需要放入对象文字中的游戏和玩家数据,我可以将其字符串化并保存到localStorage中。
每次检查firefox中的元素时,都会显示所选主机没有数据。
这是我朋友的代码:
class Game {
constructor(level, score)
{
// game logic truncated to not clutter..
this.levelNum = level;
this.total = score;
this.hits = 0;
this.misses = 0;
this.time = 0;
}
// Game methods
// truncated...
}
class Player
{
constructor(fName, playerAge)
{
this.firstName = fName;
this.age = playerAge;
}
displayInfo()
{
return `${this.firstName}, AGE ${this.age}`;
}
}
// Creating player one
function createPlayer ()
{
let playerName = document.querySelector("#textbox").value;
let playerAge = parseInt(document.querySelector("#selectBox").value);
return new Player(playerName, playerAge);
}
let playerOne = createPlayer();
clickPlay.addEventListener("click", createPlayer());
var playGame;
var gameLevel = 1;
function showLevel()
{
playGame = new Game(gameLevel);
let currentLevel = document.querySelector("#levelNum");
let levelName = document.querySelector("#mathType");
let playerID = document.querySelector("#playerName");
let ageID = document.querySelector("#playerAge");
currentLevel.innerHTML = `${playGame.levelNum}`;
levelName.innerHTML = `${playGame.mathType}`;
playerID.innerHTML = `${playerOne.firstName}`;
ageID.innerHTML = `${playerOne.age}`;
}
clickPlay.addEventListener("click", showLevel());
这是我尝试过的方法,我在上面的代码结尾处插入了此代码:
let save_button = document.querySelector("#savBut");
function createUserData(){
var userData =
{
nName: playerOne.firstName,
nAge: playerOne.age,
nLevel: playGame.levelNum,
nMisses: playGame.misses,
nHits: playGame.hits,
nSecs: playgame.time
};
}
clickPlay.addEventListener("click", createUserData();
function saving() {
// stringify first before storing to userInfo
localStorage.setItem("userInfo", JSON.stringify(userData));
}
save_button.addEventListener("click", saving);
答案 0 :(得分:1)
您应该定期创建它,而不是在游戏开始时创建userData。为了进行测试,我将在您单击保存按钮时创建它,并在保存之前控制台出userData来查看数据是否在对象中。我还建议将键命名为与来自它们的对象相同的名称,以使加载数据更容易。
function saving() {
// stringify first before storing to userInfo
const userData =
{
firstName: playerOne.firstName,
age: playerOne.age,
levelNum: playGame.levelNum,
misses: playGame.misses,
hits: playGame.hits,
time: playgame.time
};
console.log(userData);
localStorage.setItem("userData", JSON.stringify(userData));
}
您可能已经正确保存了数据,数据将显示在开发人员控制台的本地存储列表主标签Application
下。