You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在p5.js中实现游戏存档:数组的文件存储与修改?

Hey there! Let's break down your problem step by step—since you're working with p5.js, the approach to saving game data depends a lot on whether you're running your game in a web browser (the most common use case) or as a desktop app. First, let's cover why saveStrings()/loadStrings() didn't work for you, then dive into the right tools for the job.

Why saveStrings()/loadStrings() Failed

In most p5.js web environments, these functions don't modify files in your game's package directly:

  • saveStrings() triggers a download prompt for the user to save the file to their local device, not your game's bundled files.
  • loadStrings() can only load files hosted with your game (like assets) or files the user explicitly uploads, not arbitrary local files.

If you're using the p5.js desktop mode in the Processing Editor, it does save to your sketch folder—but you might have been looking for the file in the wrong location (check the folder where your sketch.js lives).


Solutions by Environment

1. Web Browser (Most Common p5.js Use Case)

Browser security rules block direct file modification, so use browser storage APIs to persist data locally on the user's device.

Option A: localStorage (Simple Key-Value Storage)

Perfect for small-to-medium game state arrays—it persists even after the browser closes.

Saving Data:
Convert your array to a JSON string (since localStorage only stores strings) and save it:

// Assume your game state array is called gameStateArray
function saveGame() {
  const savedData = JSON.stringify(gameStateArray);
  localStorage.setItem("p5GameSave", savedData);
  alert("Game saved successfully!"); // Optional user feedback
}

Loading Data:
Pull the saved data on game startup and parse it back to an array:

let gameStateArray;

function setup() {
  createCanvas(800, 600);
  // Initialize with default values first
  gameStateArray = [100, 50, "player1", true];
  
  // Check for saved data
  const savedData = localStorage.getItem("p5GameSave");
  if (savedData) {
    gameStateArray = JSON.parse(savedData);
    console.log("Loaded saved game state!");
  }
}

Option B: IndexedDB (For Larger/Complex Data)

If your array is huge or you need advanced features (like querying), use IndexedDB. It’s more complex but handles larger datasets better than localStorage.


2. Desktop App (Electron or p5.js Desktop)

If you’re packaging your game as a desktop app (e.g., with Electron), you can use Node.js’s fs (file system) module to modify files directly in your game package.

Saving Data:

const fs = require('fs');
const path = require('path');

function saveGame() {
  // Path to your save file inside the game package
  const savePath = path.join(__dirname, 'saveData.json');
  // Convert array to formatted JSON
  const savedData = JSON.stringify(gameStateArray, null, 2);
  
  fs.writeFile(savePath, savedData, (err) => {
    if (err) {
      console.error("Save failed:", err);
      alert("Couldn't save your game!");
    } else {
      console.log("Game saved to package!");
      alert("Game saved!");
    }
  });
}

Loading Data:

let gameStateArray;

function setup() {
  createCanvas(800, 600);
  const savePath = path.join(__dirname, 'saveData.json');
  
  if (fs.existsSync(savePath)) {
    const savedData = fs.readFileSync(savePath, 'utf8');
    gameStateArray = JSON.parse(savedData);
    console.log("Loaded saved game!");
  } else {
    gameStateArray = [/* default values */];
    console.log("No save file found—using default state.");
  }
}

3. p5.js Desktop (Processing Editor)

If you’re using the Processing Desktop Editor’s p5.js mode, saveStrings() works but saves to your sketch folder. Here’s how to make it work:

Saving Data:

function saveGame() {
  // Convert array elements to strings (each becomes a line in the file)
  const stringifiedArray = gameStateArray.map(item => String(item));
  saveStrings('saveData.txt', stringifiedArray);
  println("Game saved to your sketch folder!");
}

Loading Data:

let gameStateArray;

function setup() {
  createCanvas(800, 600);
  try {
    const loadedLines = loadStrings('saveData.txt');
    // Convert back to your original data type (e.g., numbers)
    gameStateArray = loadedLines.map(item => Number(item));
    println("Loaded saved game!");
  } catch (err) {
    gameStateArray = [/* default values */];
    println("No save file found—using default state.");
  }
}

Quick Tips

  • For web games, don’t rely on localStorage for critical data—users can clear their browser storage. For cloud saves, you’d need a backend server (but that’s more complex).
  • Ensure your array elements are JSON-serializable (no functions, circular references, etc.).
  • In desktop apps, double-check file permissions to make sure your game can write to the save location.

内容的提问来源于stack exchange,提问作者Coding King2

火山引擎 最新活动