C# Tutorial – Math’s Quiz Game in Windows Form Application and Visual Studio Version 1
- Subject: C# Tutorials
- Learning Time: 30 Minutes
In this tutorial we will make a classic math’s game. This tutorial will cover much more than just how to program. it will go over the visual studio environment again so hopefully it will be a good refresher on how to properly work with Visual Studio and Windows Form. We will be using C# programming language to make this program.
Lesson objective –
- Create a classic math’s game in Visual Studio using windows form application
- Generate random sums and ask the user to input the result
- Limit the result text box to only enter numbers and no letters are allowed as a input
- Click the check button to see if the answer is correct or incorrect
- Both correct and incorrect scores are saved and displayed on the form
Video Tutorial
Download The Math Quiz Game Tutorial on GitHub
Full Source Code –
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Maths_Quiz_01_MOOICT { public partial class Form1 : Form { Random rnd = new Random(); string[] Maths = {"Add", "Subtract", "Multiply" }; int total; int score; public Form1() { InitializeComponent(); SetUpGame(); } private void CheckAnswer(object sender, EventArgs e) { if (System.Text.RegularExpressions.Regex.IsMatch(txtAnswer.Text, "[^0-9]")) { MessageBox.Show("Please enter only numbers!"); txtAnswer.Text = txtAnswer.Text.Remove(txtAnswer.Text.Length - 1); } } private void CheckButtonClickEvent(object sender, EventArgs e) { int userEntered = Convert.ToInt32(txtAnswer.Text); if (userEntered == total) { lblAnswer.Text = "Correct"; lblAnswer.ForeColor = Color.Green; score += 1; lblScore.Text = "Score: " + score; SetUpGame(); } else { lblAnswer.Text = "Incorrect"; lblAnswer.ForeColor = Color.Red; } } private void SetUpGame() { int numA = rnd.Next(10, 20); int numB = rnd.Next(0, 9); txtAnswer.Text = null; switch (Maths[rnd.Next(0, Maths.Length)]) { case "Add": total = numA + numB; lblSymbol.Text = "+"; lblSymbol.ForeColor = Color.DarkGreen; break; case "Subtract": total = numA - numB; lblSymbol.Text = "-"; lblSymbol.ForeColor = Color.Maroon; break; case "Multiply": total = numA * numB; lblSymbol.Text = "x"; lblSymbol.ForeColor = Color.Purple; break; } lblNumA.Text = numA.ToString(); lblNumB.Text = numB.ToString(); } } }
Thanks sir, it was a nice tutorial.