【发布时间】:2012-04-13 22:46:02
【问题描述】:
文本文件用于描述网络浏览器上的游戏状态。所以我需要格式化我的 nameWriter.WriteLine 看起来像。
Output to text file:
playerOneName, playerTwoName, _ , _ , _ , _ , _ , _ , _ , _
我知道这听起来像是“哦,就这样写吧!”但是不,下划线是一个空字段,将由我的 StreamWriter 替换,它跟踪玩家在井字游戏中的移动。我可以使用什么来代替下划线来使该空间可供我读写?
这是我的 StreamWriter,现在我只有添加播放器名称。
你能告诉我如何将输出格式化为文本吗?
也许将它分开在一个数组中?并使用数组 DelimiterList 来键入逗号?
string[] lineParts... and reference the linePart[0-11]
and then do a lineParts = line.Split(delimiterList)?
这是我写的代码。
private void WriteGame(string playerOneName, string playerTwoName, string[] cells)
{
StreamWriter gameStateWriter = null;
StringBuilder sb = new StringBuilder();
try
{
gameStateWriter = new StreamWriter(filepath, true);
gameStateWriter.WriteLine(playerOneName + " , " + playerTwoName);
string[] gameState = { playerOneName,
playerTwoName, null, null, null, null,
null, null, null, null, null };//I cannot use null, they will give me errors
foreach (string GameState in gameState)
{
sb.Append(GameState);
sb.Append(",");
}
gameStateWriter.WriteLine(sb.ToString());
}
catch (Exception ex)
{
txtOutcome.Text = "The following problem ocurred when writing to the file:\n"
+ ex.Message;
}
finally
{
if (gameStateWriter != null)
gameStateWriter.Close();
}
}
最后,如果 playerOneName 已经在文本文件中,我如何专门在它后面写 playerTwoName 并检查它是否存在?
使用 Visual Studio '08 ASP.NET 网站和表单
【问题讨论】:
-
仅供参考:您的流作家应该在
using块中。它将负责在其范围结束时处理流。 -
另外,为什么您的网站需要创建一个文本文件来存储信息?
-
文本文件是服务器文件,我正在练习如何读写服务器上的文件到浏览器。对于玩家在井字游戏的 9 个按钮中所做的每一步,它都会记录在玩家二共享的服务器文本文件中。所以他们在同一个文件上玩同一个游戏。但是可以进行多场比赛。这意味着我需要使用不同的线路来跟踪每个游戏的进度。
-
是的,代码还有许多其他问题(为什么游戏状态是一组字符串而不是一个对象?这是最大的问题)。
-
事实是,我正在做一个 3 人项目,而我的同龄人无济于事。哎呀,如果我知道什么是真正应该去那里。如果您有任何建议,我很想听听,我只是通过反复试验来完成这个项目。两个玩家共享文件,一个数组将为我提供 11 个展示位置。 2 代表正在玩的玩家,9 代表井字游戏场上的按钮数量。因此,如果他们按下按钮 5,我的球员姓名后的第 5 个字段将变为“X”。因此,在检查获胜者时,我正在该数组中寻找不同的组合以找到获胜者。