I'm working through a book and my code is exactly the same as the book but not working correctly. Basically it's a typing game. System adds letters to a listbox which should disappear when I type them. Instead they're highlighting as I type them but are not being removed. I've even copied and pasted the code from the book website (headfirst c#) and it's still misbehaving! I suspect it's to do with a property setting for the timer or form or something?
Anyway here's the code:Form code:
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;
namespace Ch4_TypingGame
{
public partial class Form1 : Form
{
Random random = new Random();
Stats stats = new Stats();
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
// Add a random key to the ListBox
listBox1.Items.Add((Keys)random.Next(65, 90));
if (listBox1.Items.Count > 7)
{
listBox1.Items.Clear();
listBox1.Items.Add("Game over");
timer1.Stop();
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// If the user pressed a key that's in the ListBox, remove it
// and then make the game a little faster
if (listBox1.Items.Contains(e.KeyCode))
{
listBox1.Items.Remove(e.KeyCode);
listBox1.Refresh();
if (timer1.Interval > 400)
timer1.Interval -= 10;
if (timer1.Interval > 250)
timer1.Interval -= 7;
if (timer1.Interval > 100)
timer1.Interval -= 2;
difficultyProgressBar.Value = 800 - timer1.Interval;
// The user pressed a correct key, so update the Stats object
// by calling its Update() method with the argument true
stats.Update(true);
}
else
{
// The user pressed an incorrect key, so update the Stats object
// by calling its Update() method with the argument false
stats.Update(false);
}
// Update the labels on the StatusStrip
correctLabel.Text = "Correct: " + stats.Correct;
missedLabel.Text = "Missed: " + stats.Missed;
totalLabel.Text = "Total: " + stats.Total;
accuracyLabel.Text = "Accuracy: " + stats.Accuracy + "%";
}
}
}
Stats class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch4_TypingGame
{
class Stats
{
public int Total = 0;
public int Missed = 0;
public int Correct = 0;
public int Accuracy = 0;
public void Update(bool correctKey)
{
Total++;
if (!correctKey)
{
Missed++;
}
else
{
Correct++;
}
Accuracy = 100 * Correct / (Missed + Correct);
}
}
}