static class Program
{
static void Main(string[] args)
{
using (StreamReader sr = new StreamReader(@"D:\1.txt"))
{
String s = null;
while ((s = sr.ReadUntil('-')) != null)
{
if (s.StartsWith("P"))
{
//crate object
}
if (s.StartsWith("B"))
{
//..
}
}
}
}
public static String ReadUntil(this StreamReader reader, char delimeter)
{
StringBuilder sb = new StringBuilder();
char c;
while ((c = (char)reader.Read()) != 0)
{
if (c == delimeter)
return sb.ToString();
else
sb.Append(c);
}
return sb.Length == 0 ? null:sb.ToString();
}
}
positioning objects from a text file
-
11-06-2023 - |
質問
Working with C# I have written the position of my game objects to a text file each frame, giving me a file looking like this
P,130,140,B,200,300,B,400,600-P,131,140,B,201,300,B,401,600-
above shows two frames and 3 objects positions adding 1 to each X coordinate on the second frame.
The P is for the player object and then the X and Y coordinate, then two Ball objects with their X and Y coordinates.
I am looking to replay saved gameplay by assigning positions of objects each frame as it reads through the file. Using a letter to determine the next visible object and the - to determine the end of the frame
I can't get my head around the syntax to read through the file, I was thinking something on the lines of
While (text != "-")
{ if (text = "P") Create Object player
player.X = nextText; player.Y = nextText;
if (text = "B") Create Object Ball
Ball.X = nextText; Ball.Y = nextText;
}
the nextText variable is to indicate I'm after the next bit of the text file after the comma , I am not sure how to work with multiple text delimiters. Any help would be greatly appreciated.
解決
他のヒント
By far the easiest way for you is to first Split()
your string on "-" character, to get an array of frames and then use a simple regex to split P, B and B objects. Something like this:
string WholeFile = System.IO.File.ReadAllText("YOUR PATH HERE");
var Frames[] = WholeFile.Split('-');
Regex rx = new Regex(@"P,(?<Px>\d+),(?<Py>\d+),B,(?<B1x>\d+),(?<B1y>\d+),B,(?<B2x>\d+),(?<B2y>\d+)", RegexOptions.ExplicitCapture | );
foreach(var frame in Frames)
{
var Captures = rx.Match(frame);
//now use Captures.Groups["Px"] etc. to get your values
}