Implementera High-score lista i C#

Permalänk

Implementera High-score lista i C#

Går första året med spelprogrammering på gymnasiet.

Vi har fått i uppgift att implementera en high-score lista i ett färdigt spel gjort av en lärare.

Jag har gjort metoden som läser in resultatet i "score.txt".

Kvar är sorteringen och inläsningen samt att visa resultatet i en MessageBox.

koden är följande:
MainForm.cs

/* TypeFast - challenge yourself and test your typing skills!
*
*
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace TypeFast
{
public partial class MainForm : Form
{
// The big list of words
List<string> words = new List<string>();

// words to test
string testWord;
string inputWord;
int testLength;

// score
List<double> wordStats = new List<double>();

// timer
DateTime startTime;

public MainForm()
{
// read word list
try
{
string word = null;
StreamReader wordsFile = new StreamReader("words.txt");
while ((word = wordsFile.ReadLine()) != null)
words.Add(word);
wordsFile.Close();
}
catch (FileNotFoundException fe)
{
MessageBox.Show(fe.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

InitializeComponent();
}

/**
* Return the elapsed time in seconds since startTime.
*/
double ElapsedTime()
{
return (DateTime.Now - startTime).TotalSeconds;
}

/**
* At each timer tick, update the timer display.
*/
private void timer_Tick(object sender, EventArgs e)
{
timerLabel.Text = (wordStats.Count + 1) + "/" + testLength +
" " + ElapsedTime().ToString("F2");
}

/**
* Update the progress (delay) bar while the user is waiting for the next word.
*/
private void delay_Tick(object sender, EventArgs e)
{
// have to use a hack to bypass the progress bar animation
// (windows vista/7)
if (waitIndicator.Value < 9)
{
waitIndicator.Value += 2;
--waitIndicator.Value;
}
else if (waitIndicator.Value == 9)
{
waitIndicator.Maximum = 1000;
waitIndicator.Value = 1000;
waitIndicator.Value = 999;
waitIndicator.Maximum = 10;
}
else
{
// show the next word
delay.Stop();
startTime = DateTime.Now;
waitIndicator.Visible = false;
inputWord = "";
inputLabel.Text = "";
inputLabel.ForeColor = Color.Black;
timer.Start();
}
}

/**
* Reset the test display and pick a new word to test.
*/
void NewWord()
{
// pick a new word at random
Random r = new Random();
testWord = words[r.Next(words.Count)];
wordLabel.Text = testWord;

// start delayed timer
waitIndicator.Value = 0;
waitIndicator.Visible = true;
delay.Start();
}

/**
* Complete the word. Stops timer and updates stats.
*/
void WordComplete()
{
wordStats.Add(testWord.Length / ElapsedTime());
timer.Stop();
avgTimerLabel.Text = wordStats.Average().ToString("F3");
inputLabel.ForeColor = Color.Green;
string s = avgTimerLabel.Text;

// pick a new word if the test round is incomplete
if (wordStats.Count < testLength)
{
Update(); // refresh window
NewWord();
}
else
{
// done!
WriteToFile(wordStats.Average().ToString("F3"));
MessageBox.Show();
wordStats.Clear();
startButton.Enabled = true;
wordsPerRound.Enabled = true;

startButton.Focus();

}
}

public string LoadFromFile()
{
string results = "";
TextReader reader = new StreamReader("score.txt");
string[] lines = reader.ReadToEnd().Split('\n');
while (lines != null)
{

results += lines;

}

return results;
}

private void startButton_Click(object sender, EventArgs e)
{
// begin a new test round
wordsPerRound.Enabled = false;
startButton.Enabled = false;
this.Focus(); // prevent button stealing key presses bug
testLength = (int) wordsPerRound.Value;
NewWord();
}

/**
* User keyboard input is handled here. Each character is compared
* against the current test word.
* When a word is typed in correctly we pick a new word to test if
* the round is incomplete.
*/
private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
{
if (!timer.Enabled) return;
// check for input and correct words
string tempWord = inputWord + e.KeyChar;
if (tempWord == testWord.Substring(0, tempWord.Length))
{
inputWord = tempWord;
inputLabel.Text = tempWord;
if (inputWord.Length == testWord.Length)
WordComplete();
}
else
{
// wrong character
Console.Beep();
}
}
public void WriteToFile(string points)
{
StreamWriter writer = new StreamWriter("score.txt", true);
writer.WriteLine(points);
writer.Close();
}
private void MainForm_Load(object sender, EventArgs e)
{
// exit program when word list is empty
if (words.Count == 0)
Close();
}
}
}
_________________________________________________________________

MainForm.Designer.cs:

namespace TypeFast
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.timer = new System.Windows.Forms.Timer(this.components);
this.startButton = new System.Windows.Forms.Button();
this.wordLabel = new System.Windows.Forms.Label();
this.inputLabel = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.avgTimerLabel = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.timerLabel = new System.Windows.Forms.Label();
this.wordsPerRound = new System.Windows.Forms.NumericUpDown();
this.label3 = new System.Windows.Forms.Label();
this.waitIndicator = new System.Windows.Forms.ProgressBar();
this.delay = new System.Windows.Forms.Timer(this.components);
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.wordsPerRound)).BeginInit();
this.SuspendLayout();
//
// timer
//
this.timer.Tick += new System.EventHandler(this.timer_Tick);
//
// startButton
//
this.startButton.Location = new System.Drawing.Point(235, 123);
this.startButton.Name = "startButton";
this.startButton.Size = new System.Drawing.Size(75, 23);
this.startButton.TabIndex = 0;
this.startButton.Text = "START";
this.startButton.UseVisualStyleBackColor = true;
this.startButton.Click += new System.EventHandler(this.startButton_Click);
//
// wordLabel
//
this.wordLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.wordLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.wordLabel.Location = new System.Drawing.Point(12, 114);
this.wordLabel.Name = "wordLabel";
this.wordLabel.Size = new System.Drawing.Size(200, 37);
this.wordLabel.TabIndex = 3;
this.wordLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// inputLabel
//
this.inputLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.inputLabel.Location = new System.Drawing.Point(12, 165);
this.inputLabel.Name = "inputLabel";
this.inputLabel.Size = new System.Drawing.Size(200, 35);
this.inputLabel.TabIndex = 4;
this.inputLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.avgTimerLabel);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.timerLabel);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 82);
this.groupBox1.TabIndex = 6;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Time";
//
// avgTimerLabel
//
this.avgTimerLabel.Location = new System.Drawing.Point(80, 49);
this.avgTimerLabel.Name = "avgTimerLabel";
this.avgTimerLabel.Size = new System.Drawing.Size(99, 23);
this.avgTimerLabel.TabIndex = 9;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(10, 49);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(31, 13);
this.label2.TabIndex = 8;
this.label2.Text = "CPS:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(10, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(70, 13);
this.label1.TabIndex = 7;
this.label1.Text = "Current word:";
//
// timerLabel
//
this.timerLabel.Location = new System.Drawing.Point(80, 24);
this.timerLabel.Name = "timerLabel";
this.timerLabel.Size = new System.Drawing.Size(99, 21);
this.timerLabel.TabIndex = 6;
//
// wordsPerRound
//
this.wordsPerRound.Location = new System.Drawing.Point(235, 59);
this.wordsPerRound.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.wordsPerRound.Name = "wordsPerRound";
this.wordsPerRound.Size = new System.Drawing.Size(75, 20);
this.wordsPerRound.TabIndex = 7;
this.wordsPerRound.Value = new decimal(new int[] {
10,
0,
0,
0});
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(232, 36);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(89, 13);
this.label3.TabIndex = 8;
this.label3.Text = "Words per round:";
//
// waitIndicator
//
this.waitIndicator.Location = new System.Drawing.Point(12, 114);
this.waitIndicator.Maximum = 10;
this.waitIndicator.Name = "waitIndicator";
this.waitIndicator.Size = new System.Drawing.Size(200, 37);
this.waitIndicator.Step = 1;
this.waitIndicator.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
this.waitIndicator.TabIndex = 100;
this.waitIndicator.Visible = false;
//
// delay
//
this.delay.Tick += new System.EventHandler(this.delay_Tick);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(331, 224);
this.Controls.Add(this.waitIndicator);
this.Controls.Add(this.label3);
this.Controls.Add(this.wordsPerRound);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.inputLabel);
this.Controls.Add(this.startButton);
this.Controls.Add(this.wordLabel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.Name = "MainForm";
this.Text = "TypeFast";
this.Load += new System.EventHandler(this.MainForm_Load);
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MainForm_KeyPress);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.wordsPerRound)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();

}

#endregion

private System.Windows.Forms.Timer timer;
private System.Windows.Forms.Button startButton;
private System.Windows.Forms.Label wordLabel;
private System.Windows.Forms.Label inputLabel;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label avgTimerLabel;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label timerLabel;
private System.Windows.Forms.NumericUpDown wordsPerRound;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ProgressBar waitIndicator;
private System.Windows.Forms.Timer delay;
}
}

______________________________________________________

Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace TypeFast
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}

_________________________________________

sorry för långt inlägg, all hjälp uppskattas.

Kod för att utföra en enkel Bubblesort.
Hjälp med att färdigställa LoadFromFile()
Visa resultatet i en MessageBox.

tack på förhand !!!

// NikkEpikkE

Visa signatur

"It is not enough that i should succed, others should fail."
- Unkown

Permalänk
Medlem

Så vad exakt är det du har fastnat på? Att hitta en bubblesortimplementation i läsbart språk som är lätt att fälja lär ju gå att hitta på någon minut.

Permalänk
Skrivet av iXam:

Så vad exakt är det du har fastnat på? Att hitta en bubblesortimplementation i läsbart språk som är lätt att fälja lär ju gå att hitta på någon minut.

Det löste sig. Jag la in raderna i score.txt i en vektor och sorterade den...

tack för visat intresse...

Visa signatur

"It is not enough that i should succed, others should fail."
- Unkown