Clicker游戏本地存储

Clicker Game LocalStorage

本文关键字:存储 游戏 Clicker      更新时间:2023-09-26

我需要帮助我的点击游戏的保存功能。到目前为止,我的游戏非常小,但我想在我走得更远之前,我最好先把自动保存挡在一边。

这就是我目前所拥有的:

var cookies = 0;
var cursors = 0;
var workers = 0;
function cookieClick(number){
    cookies = cookies + number;
    document.getElementById("cookies").innerHTML = cookies;
};
function buyCursor(){
    var cursorCost = Math.floor(10 * Math.pow(1.1,cursors));     //works out the cost of this cursor
    if(cookies >= cursorCost){                                   //checks that the player can afford the cursor
        cursors = cursors + 1;                                   //increases number of cursors
    	cookies = cookies - cursorCost;                          //removes the cookies spent
        document.getElementById('cursors').innerHTML = cursors;  //updates the number of cursors for the user
        document.getElementById('cookies').innerHTML = cookies;  //updates the number of cookies for the user
    };
    var nextcursorCost = Math.floor(10 * Math.pow(1.1,cursors));       //works out the cost of the next cursor
    document.getElementById('cursorCost').innerHTML = nextcursorCost;  //updates the cursor cost for the user
};
function buyWorker(){
	var workerCost = Math.floor(200 * Math.pow(1.1,workers));
	if(cookies >= workerCost){
		workers = workers + 1;
		cookies = cookies - workerCost;
		document.getElementById('workers').innerHTML = workers;
	};
	var nextworkerCost = Math.floor(200 * Math.pow(1.1,workers));
	document.getElementById('workerCost').innerHTML = nextworkerCost;
}
window.setInterval(function(){
	cookieClick(cursors);
	}, 1000);
window.setInterval(function(){
	cookieClick(workers);
	}, 250);
//SAVE AND LOAD THE GAME
function saveGame(){
    printMessageLine("Saved.");
    localStorage['shittyInc_save'] = btoa(JSON.stringify(game));
}
function loadGame() {
    var save_data = localStorage['shittyInc_save']
    printMessageLine("Loaded.");
    console.log(save_data);
    if (!save_data) return;
    console.log(save_data);
    game = JSON.parse(atob(localStorage['shittyInc_save']))
}

注意:我当前的保存功能不起作用。

我不打算拥有和导入保存功能。自动保存是我所寻求的帮助,如果你愿意的话,我会很乐意将你的推特或其他内容包括在信用卡中。

我建议您制作一个字典并将其保存到localStorage,如下所示:

function saveGame() {
  var savedGame = {
    cookies: cookies,
    cursors: cursors,
    workers: workers
  }
  localStorage.setItem("savedGame", JSON.stringify(savedGame));
 }
  

对于负载,您使用以下内容:

function loadGame() {
  var savedGame = JSON.parse(localStorage.getItem("gameSave"))
}

要自动保存和自动加载,请执行以下操作:

// Save
setInterval(saveGame, 1000);
// Load
window.onload function() {
  loadGame();
  document.getElementById("cookies").innerHTML = cookies;
  document.getElementById("cursors").innerHTML = cursors;
  document.getElementById("cursorCost").innerHTML = cursorCost;
  document.getElementById("workers").innerHTML = workers;
  document.getElementById("workerCost").innerHTML = workerCost;
}

然后每秒钟,游戏都会保存,一旦你刷新,你的游戏就会加载。