c# - StreamReader 文件如何仅在列表框中达到高分时更新?

标签 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);
        }    
    }
}

最佳答案

您的代码中有问题的部分非常微不足道。要仅将文件中的最高分添加到列表框,您可以使用:

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 });
    }
    

请注意,这每次都会将分数附加到您的文件中。如果你只需要在分数超过现有的最高分数(你的问题不是很清楚)时才写,你可以这样做:

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

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

    SELECT MAX(score) FROM highscores;
    

就这么简单。

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

关于c# - StreamReader 文件如何仅在列表框中达到高分时更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13171656/

相关文章:

C# 流阅读器 : Handling of special characters \"\' etc

c# - EntityFramework ToListAsync() 不起作用

c# - 如何避免看似自动引用 "parent"命名空间?

c# - StreamReader.EndOfStream产生IOException

c# - 为什么写入文件比附加字符串更快?

c# - StreamWriter 追加随机数据

c# - WPF 切换面板可见性

c# - 如何在.net core WebApi 上获取请求字符串

c# - StreamReader 与 BinaryReader?

java - 尽管我有一个关闭最外层流的 finally block ,但 Eclipse 警告潜在的资源泄漏,我错过了什么?