use the following code. It would work.
I have added an else for the textbox enabled check condition in BTn_Play_Click handler.
The problem was after player 1 plays you were setting the textbox for player 2 as enabled. which resulted in control going into the next "if" and the text box being empty threw a format exception.
int i_Play = 0;
int m_Total = 21;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
BTn_Play.Enabled = false;
TBx_P1.Enabled = false;
TBx_P2.Enabled = false;
LBl_msg.Text = string.Format("Press start to play");
}
private void BTn_Start_Click(object sender, EventArgs e)
{
BTn_Start.Enabled = false;
BTn_Play.Enabled = true;
TBx_P1.Enabled = !TBx_P1.Enabled;
TBx_P2.Enabled = !TBx_P1.Enabled;
if (TBx_P1.Enabled)
{
TBx_P1.Select();
LBl_msg.Text = string.Format("Player number 1 plays.");
}
else if (TBx_P2.Enabled)
{
TBx_P2.Select();
LBl_msg.Text = string.Format("Player number 2 plays.");
}
}
private void BTn_Play_Click(object sender, EventArgs e)
{
try
{
if (TBx_P1.Enabled == true)
{
i_Play = int.Parse(TBx_P1.Text);
if ((i_Play < 1) || (i_Play > 3) || (i_Play > m_Total))
{
MessageBox.Show("Error: You must play 1, 2, 3 or less than the total.",
"ICA 2 - Nim", MessageBoxButtons.OK, MessageBoxIcon.Error);
TBx_P1.Enabled = true;
TBx_P1.Focus();
TBx_P2.Enabled = false;
LBl_msg.Text = string.Format("Player number 1 plays.");
}
else
{
TBx_P1.Enabled = false;
TBx_P1.Focus();
TBx_P2.Enabled = true;
LBl_msg.Text = string.Format("Player number 2 plays.");
m_Total = m_Total - i_Play;
LBl_CNum.Text = m_Total.ToString();
}
if (m_Total == 0)
{
LBl_msg.Text = string.Format("Player number 1 wins");
}
}
else if (TBx_P2.Enabled == true)
{
i_Play = int.Parse(TBx_P2.Text);
if ((i_Play < 1) || (i_Play > 3) || (i_Play > m_Total))
{
MessageBox.Show("Error: You must play 1, 2, 3 or less than the total.",
"ICA 2 - Nim", MessageBoxButtons.OK, MessageBoxIcon.Error);
TBx_P2.Enabled = true;
TBx_P2.Focus();
TBx_P1.Enabled = false;
LBl_msg.Text = string.Format("Player number 2 plays.");
}
else
{
TBx_P2.Enabled = false;
TBx_P2.Focus();
TBx_P1.Enabled = true;
LBl_msg.Text = string.Format("Player number 1 plays.");
m_Total = m_Total - i_Play;
LBl_CNum.Text = m_Total.ToString();
}
if (m_Total == 0)
{
LBl_msg.Text = string.Format("Player number 2 wins");
}
}
}
catch (FormatException)
{
MessageBox.Show("Error: An invalid was entered.", "ICA 2 - Nim",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}