新 C#er 在这里。我正在制作基于控制台的 RPG。进展顺利,但我需要找出如何保存游戏。我猜想有一种方法可以将我的应用程序中的变量保存到文本文件中,该文件可用于在应用程序再次运行时加载变量。不幸的是,我不知道从哪里开始。
另外,我需要一种在加载保存文件时转到代码中某个点的方法。
我的一些变量包括:
int xCoordinate, yCoordinate, hp, hpmax, level;
Run Code Online (Sandbox Code Playgroud)
任何示例代码将不胜感激。
将一些变量写入文本文件很简单:
TextWriter tw = new StreamWriter("SavedGame.txt");
// write lines of text to the file
tw.WriteLine(xCoordinate);
tw.WriteLine(yCoordinate);
// close the stream
tw.Close();
Run Code Online (Sandbox Code Playgroud)
并将它们读回:
// create reader & open file
TextReader tr = new StreamReader("SavedGame.txt");
// read lines of text
string xCoordString = tr.ReadLine();
string yCoordString = tr.ReadLine();
//Convert the strings to int
xCoordinate = Convert.ToInt32(xCoordString);
yCoordinate = Convert.ToInt32(yCoordString);
// close the stream
tr.Close();
Run Code Online (Sandbox Code Playgroud)