-1

I made a "Dodge Game" that adds charaters to a canvas, and a button "save". When i press the "Save: button, I want to save all the objects location, game settings ( timer current form),etc'. Then i would like to make a button that reload the game (the canvas with the save products) and run from "the same spot". I need a way to save and upload the game.

I will appriciate every single help / direction.

1 Answers1

0

There are multiple ways of achieving what you want. Here are some guidelines that could help.

1. Game State Objects

Represent your game state using entities (classes that represents data).

Example:

public class GameState
{
   public CharacterData[] Characters { get; set; }
   public TimeSpan GameTime { get; set; }
}

public class CharacterData
{
   public string Name { get; set; }
   public double PositionX { get; set; }
   public double PositionY { get; set; }
}

2. Serialization

Once you have a class that represents your game state, you can use serialization to convert that object and its content to a single string. There are various serialization formats. JSON and XML are popular ones.

Example using System.Text.Json.

using System.Text.Json;
// ...
GameState myState;
// ...
string jsonString = JsonSerializer.Serialize(myState);

3. Write File

Once your data is serialized, you can easily write it in a file.

Example:

StorageFile sampleFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, jsonString));

At this point, you have the steps to save your game state.

Next steps are about going from the file back to a game state.


4. Read File

First step is to read the file.

Example:

StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file = await folder.GetFileAsync(fileName);
var fileContent = await FileIO.ReadTextAsync(file);

5. Deserialization

Once you have the raw file content, you need to parse it to re-obtain a GameState object. Since we used JSON serialization, we want to do the opposite and do JSON deserialization.

Example (again using System.Text.Json):

GameState gameState = JsonSerializer.Deserialize<GameState>(fileContent);

Next Steps

  1. You need to customize the GameState object structure based on your actual needs (so that all information is captured).
  2. You need to instantiate a GameState based on your current implementation (when you save the game).
  3. You need to be able to bootstrap your game based on a GameState object (put the objects in the canvas when you load the game).
Batesias
  • 1,914
  • 1
  • 12
  • 22