StreamReader文件如何在列表框中达到高分时才更新?

时间:2012-11-01 05:51:27

标签: c# streamreader streamwriter

我如何编写我的StreamReader文件,如果超过目前的高分,它只能覆盖游戏的高分?目前,所有分数都将更新到列表框,而不仅仅是超过当前分数/ txt文件的分数。

先谢谢

public partial class Form1 : Form
{
    int Dice;
    int RunningTotal;
    int MaxRolls;
    int RollCount;
    Random rand = new Random();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        RollDiebutton.Enabled = true;
        StartOverbutton.Enabled = true;
        ClickBeginGametoStartlabel.Visible = false;
        int beginTotal = 0;
        TotalMoneyEarnedlabel.Text = beginTotal.ToString("c");

        MaxRolls = rand.Next(3) + 2;
    }

    private void button4_Click(object sender, EventArgs e)         
    {
        try
        {
            string highScore;
            StreamReader inputFile; 

            inputFile = File.OpenText("Highscore.txt"); 
            HighscoreBox.Items.Clear();

            while (!inputFile.EndOfStream)
            {
                highScore = inputFile.ReadLine();   
                HighscoreBox.Items.Add(highScore);
            }

            inputFile.Close();
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        RollDiebutton.Enabled = false;
        BeginGamebutton.Enabled = true;
        StartOverbutton.Enabled = false;
        TotalMoneyEarnedlabel.Text = "";

        BeginpictureBox.Image = P2Kbembow.Properties.Resources.Begin;
        Pressyourluckandrollagainlabel.Visible = false;
        ClickBeginGametoStartlabel.Visible = true;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        //Close Form
        this.Close();
    }

    private void RollDiebutton_Click(object sender, EventArgs e)
    {
        Random rand = new Random();
        Dice = rand.Next(6) + 1;

        RunningTotal += 0;
        int DollarAmount = 100;
        int Sum = (Dice * DollarAmount);

        BeginGamebutton.Enabled = false;
        Pressyourluckandrollagainlabel.Visible = true;

        RunningTotal += Sum;
        TotalMoneyEarnedlabel.Text = RunningTotal.ToString("c");
        RollCount += 1;

        if (MaxRolls == 0)
        {
            Random getMax = new Random();
            TotalMoneyEarnedlabel.Text = ""; 
        }
        else
            if (RollCount >= MaxRolls)
            {
                MaxRolls = 6;
                RollCount = 0;
                RunningTotal = 0;

                TotalMoneyEarnedlabel.Text = "$0.0";
                Show(); MessageBox.Show("Sorry! You lose!");

                RollDiebutton.Enabled = false;
                BeginGamebutton.Enabled = true;

                TotalMoneyEarnedlabel.Text = "";

                BeginpictureBox.Image = P2Kbembow.Properties.Resources.Begin;
                Pressyourluckandrollagainlabel.Visible = false;
                ClickBeginGametoStartlabel.Visible = true;
                StartOverbutton.Enabled = false;

                return;
            }

        StreamWriter outputFile;
        outputFile = File.CreateText("HighScore.txt");

        outputFile.WriteLine(TotalMoneyEarnedlabel.Text);
        outputFile.Close();

        if (Dice == 1)
        {
            //shows Image of dice 1
            BeginpictureBox.Image = P2Kbembow.Properties.Resources._1Die;
        }

        if (Dice == 2)
        {
            //shows Image of dice 2
            BeginpictureBox.Image = P2Kbembow.Properties.Resources._2Die;
        }

        if (Dice == 3)
        {
            //shows Image of dice 3
            BeginpictureBox.Image = P2Kbembow.Properties.Resources._3Die;
        }
        if (Dice == 4)
        {
            //shows Image of dice 4
            BeginpictureBox.Image = P2Kbembow.Properties.Resources._4Die;
        }

        if (Dice == 5)
        {
            //shows Image of dice 5
            BeginpictureBox.Image = P2Kbembow.Properties.Resources._5Die;
        }

        if (Dice == 6)
        {
            //shows Image of dice 6
            BeginpictureBox.Image = P2Kbembow.Properties.Resources._6Die;
        }

        //Display Message Box of dice rolled 
        Show(); MessageBox.Show(" You rolled a  " + Dice + "!");
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            string highScore;
            StreamReader inputFile;

            inputFile = File.OpenText("Highscore.txt");
            HighscoreBox.Items.Clear();

            while (!inputFile.EndOfStream)
            {
                highScore = inputFile.ReadLine();
                HighscoreBox.Items.Add(highScore);

            }

            inputFile.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }    
    }
}

1 个答案:

答案 0 :(得分:0)

代码中有问题的部分非常简单。要将文件中的最高分数添加到列表框,您只需使用:

var highScore = File.ReadAllLines("Highscore.txt").Max(score => decimal.Parse(score));
HighscoreBox.Items.Clear();
HighscoreBox.Items.Add(highScore);

但是还有很多其他事情你需要照顾:

  1. 您必须确保有可用的有效高分榜。因此,请检查表单加载(,并且可能不需要每次滚动模具时创建和覆盖现有文件)。

  2. DRY您的代码可以将高分从文件加载到列表框。

    string _fileName = "Highscore.txt";
    
    private void Form1_Load(object sender, EventArgs e)
    {
        if (!File.Exists(_fileName))
        {
            File.Create(_fileName);
            return; 
        }
    
        LoadHighestScore();
    }
    
    private void LoadHighestScore()
    {
        HighscoreBox.Items.Clear();
    
        var highestScore = GetHighestScore();
        HighscoreBox.Items.Add(highestScore);
    }
    
    private decimal GetHighestScore()
    {
        var scores = File.ReadAllLines(_fileName);
        if (scores.Length == 0)
            return 0;
    
        return scores.Max(score => decimal.Parse(score));
    }
    
  3. 每次滚动模具时,您都可以将分数写入您的文件:

    private void RollDiebutton_Click(object sender, EventArgs e)
    {
        //-------------------------
        //-------------------------
    
        WriteScore(score);
    
        //-------------------------
        //-------------------------
    }
    
    private void WriteScore(string score)
    {
        File.AppendAllLines(sd, new string[]{ score });
    }
    
  4. 每次都记住你的appends分数。如果你只需要在分数高于现有的最高分(你的问题不是很清楚)时才需要写,你可以这样做:

        private void WriteScore(string score)
        {
            if (int.Parse(score) > GetHighestScore())
                File.AppendAllLines(sd, new string[]{ score });
        }
    
    1. 请将您的大部分代码分解为不同的方法,以便它可以帮助重用代码。如果你可以将逻辑移到另一个类别,那就更好了。

    2. 要做这种事情,最好使用像SQLite这样的小型轻量级客户端数据库。将来如果您需要更复杂的操作,例如“每个用户的最高分”,该怎么办?要获得最高分,您可以这样做:

      SELECT MAX(score) FROM highscores;
      
    3. 就这么简单。

      最后,请发布代码中有问题的部分,而不是一大堆不相关的行。