2

我如何编写我的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);
        }    
    }
}
4

1 回答 1

0

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

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

但是,您还需要注意许多其他事项:

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

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

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

请注意,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;
    

就如此容易。

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

于 2012-11-01T07:33:22.713 回答