我的loadgame/savegame方法出现严重问题



我正在尝试用C#开发一个基于文本的游戏。我真的很难让我的加载游戏让我加载玩家,让我的保存游戏保存不止一次。

它也不会保存玩家名称。我调试了大约5个小时,但没有成功。。。这是代码:

public static void saveGame()
{
PlayerClass p = new PlayerClass();
//creates bin folder named textadsaves with player id
BinaryFormatter binForm = new BinaryFormatter();
string path = "textgameSaves/" + p.id + ".sf";
//creates file in bin folder with player name or id and closes file
FileStream file = File.Open(path, FileMode.OpenOrCreate);
binForm.Serialize(file,p);
file.Close();
}
public static PlayerClass loadGame( out bool newP)
{
newP = false;
string gameSaves = "textgameSaves";
Console.Clear();
Console.WriteLine("Choose your Save Game.");
//to select from a list of saves
string[] paths = Directory.GetFiles(gameSaves);
//convert paths into a player instance(file)
List<PlayerClass> players = new List<PlayerClass>();
int idCount = 0;
BinaryFormatter binForm = new BinaryFormatter();
//check every path 
foreach (string p in paths)
{
FileStream file = File.Open(p, FileMode.Open);
PlayerClass player = (PlayerClass)binForm.Deserialize(file);
file.Close();
players.Add(player);
}
//check for player save
idCount = players.Count;
while (true)
{
Console.Clear();
Console.WriteLine("Choose your player");
foreach (PlayerClass p in players)
{
Console.WriteLine(p.id + ": " + p.name);
}
Console.WriteLine("Please enter player name or id. (id:# or playername).n Additionally 'Create' will start a new save.");
string[] data = Console.ReadLine().Split(':');
try
{
if (data[0]== "id")
{
if (int.TryParse(data[1], out int id))
{
foreach(PlayerClass player in players)
{
if(player.id == id)
{
return player;
}
}
Console.Clear();
Console.WriteLine("not finding the character in file.n press enter");
Console.ReadKey();
}
else
{
Console.WriteLine("Your id needs a numbern press enter to continue");
Console.ReadKey();
}
}
else if (data[0] =="create")
{
PlayerClass newPlayer = startFun(idCount);
newP = true;
return newPlayer;
}
else
{
foreach(PlayerClass player in players)
{
if(player.name == data[0])
{
return player;
}
}
Console.Clear();
Console.WriteLine("Not finding player in file.n press enter");
Console.ReadKey();
}
}
catch(IndexOutOfRangeException)
{
Console.WriteLine("Your id needs a numbern press enter to continue");
Console.ReadKey();
}
}

您最大的问题就在SaveGame方法的顶部:

PlayerClass p = new PlayerClass();

你正在实例化一个新玩家,然后试图保存它。你实际上并没有保存游戏中的玩家

相反,你想做的是获得游戏中每个玩家的列表,并保存每个玩家,类似于加载这些玩家时所做的操作。

相关内容

  • 没有找到相关文章

最新更新