游戏高分与名字

时间:2012-01-26 07:52:19

标签: c# winforms streamreader streamwriter

有人会如何制作高分读取代码,其中包括C#中Windows窗体中的名称? 例如:史蒂夫600 我可以使用StreamReader / Streamwriter获取数字部分,但我无法找到包含该名称的方法。有什么建议吗?

4 个答案:

答案 0 :(得分:1)

最简单的方法是将每个值写在自己的行上,这样你就可以:

  

史蒂夫
  600个
  乔治
  500个
  彼得
  200

然后在你的循环中,你只需读取一行,即名称,然后读取另一行,并将其解析为int。然后,如果您不在文件的末尾,请再次执行相同操作。

答案 1 :(得分:1)

您可以使用特殊分隔符(例如 $ )将它们分开。也不要让用户在名称中使用分隔符,所以您将拥有:

<强>史蒂夫$ 600

然后,您可以使用StreamReader.ReadLine方法获取此行字符串,然后使用string.Split拆分分隔符。

答案 2 :(得分:0)

您可能想要使用固定格式从其他游戏加载分数?

如果格式为NAME SCORE,我们搜索最后一个空格,因为名称可能也包含空格并将字符串拆分为名称和得分部分。

    private List<Score> ReadScores(string filename) {
        List<Score> scores = new List<Score>();

        using (var sr = new StreamReader(filename)) {
            string line = "";
            while (!string.IsNullOrEmpty((line = sr.ReadLine()))) {
                int lastspace = line.LastIndexOf(' ');
                string name = line.Substring(0, lastspace);
                string pointstring = line.Substring(lastspace + 1, line.Length - lastspace - 1);

                int points = 0;
                if (!int.TryParse(pointstring, out points))
                    throw new Exception("Wrong format");

                scores.Add(new Score(name, points);

            }
        }

        return scores;
    }

    class Score {
        public string Name { get; set; }
        public int Points { get; set; }

        public Score(string name, int points) {
            this.Name = name;
            this.Points = points;
        }
    }

答案 3 :(得分:0)

如果您无法使用StreamReader或StreamWriter,则可以使用输入框为用户输入自己的名称。例如:

string sName;


            //asks user to input their name before the game begins
            sName = Microsoft.VisualBasic.Interaction.InputBox("Please enter your name:", "What is Your Name?", "");
            //if no name is entered, they are asked again

                   while (sName == "")
                    {
                    MessageBox.Show("Please enter your name.");
                    sName = Microsoft.VisualBasic.Interaction.InputBox("Please enter your name:", "What is Your Name?", "");
                     }

除了声明变量外,还需要包含

using Microsoft.VisualBasic;

位于页面顶部。此外,您还需要添加对页面的引用。在解决方案资源管理器的右侧,如果右键单击引用,在.NET中添加引用,您将找到'Microsoft.VisualBasic'

您可以将实际的Inpuxbox代码放在代码中的任何位置,您可以轻松地重复使用和编辑它。