Form1の全コード
using System;using System;
using System.Windows.Forms;
namespace Math_Quiz
{
public partial class Form1 : Form
{
Random randomizer = new Random();
int addend1;
int addend2;
int minuend;
int subtrahend;
int multiplicand;
int multiplier;
int dividend;
int divisor;
int timeLeft;
public Form1()
{
InitializeComponent();
}
public void StartTheQuiz()
{
// Fill in the addition problem.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();
sum.Value = 0;
// Fill in the subtraction problem.
minuend = randomizer.Next(1, 101);
subtrahend = randomizer.Next(1, minuend);
minusLeftLabel.Text = minuend.ToString();
minusRightLabel.Text = subtrahend.ToString();
difference.Value = 0;
// Fill in the multiplication problem.
multiplicand = randomizer.Next(2, 11);
multiplier = randomizer.Next(2, 11);
timesLeftLabel.Text = multiplicand.ToString();
timesRightLabel.Text = multiplier.ToString();
product.Value = 0;
// Fill in the division problem.
divisor = randomizer.Next(2, 11);
int temporaryQuotient = randomizer.Next(2, 11);
dividend = divisor * temporaryQuotient;
dividedLeftLabel.Text = dividend.ToString();
dividedRightLabel.Text = divisor.ToString();
quotient.Value = 0;
// Start the timer.
timeLeft = 30;
timeLabel.Text = "30 seconds";
Timer1.Start();
}
private void startButton_Click(object sender, EventArgs e)
{
StartTheQuiz();
startButton.Enabled = false;
}
private void Timer1_Tick(object sender, EventArgs e)
{
if (CheckTheAnswer())
{
// If the user got the answer right, stop the timer
// and show a MessageBox.
Timer1.Stop();
MessageBox.Show("You got all the answers right!",
"Congratulations");
startButton.Enabled = true;
}
else if (timeLeft > 0)
{
// Decrease the time left by one second and display
// the new time left by updating the Time Left label.
timeLeft--;
timeLabel.Text = timeLeft + " seconds";
}
else
{
// If the user ran out of time, stop the timer, show
// a MessageBox, and fill in the answers.
Timer1.Stop();
timeLabel.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry");
sum.Value = addend1 + addend2;
difference.Value = minuend - subtrahend;
product.Value = multiplicand * multiplier;
quotient.Value = dividend / divisor;
startButton.Enabled = true;
}
}
private bool CheckTheAnswer()
{
if ((addend1 + addend2 == sum.Value)
&& (minuend - subtrahend == difference.Value)
&& (multiplicand * multiplier == product.Value)
&& (dividend / divisor == quotient.Value))
return true;
else
return false;
}
private void answer_Enter(object sender, EventArgs e)
{
NumericUpDown answerBox = sender as NumericUpDown;
if (answerBox != null)
{
int lengthOfAnswer = answerBox.Value.ToString().Length;
answerBox.Select(0, lengthOfAnswer);
}
}
}
}