Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public partial class Form1 : Form
- {
- bool whosTurn = true; //true - X, false - O
- int stalemateCounter = 0;
- public Form1()
- {
- InitializeComponent();
- lblWhosTorn.Text = "X";
- }
- private void InsertSymbol(object button)
- {
- Button pressedButton = (Button)button;
- if (whosTurn)
- {
- pressedButton.Text = "X";
- }
- else
- {
- pressedButton.Text = "O";
- }
- pressedButton.Enabled = false;
- bool wynik = checkIfSomeoneWon();
- if (wynik == true)
- {
- string winText;
- if (whosTurn == true)
- {
- winText = "Player X won! Replay?";
- }
- else
- {
- winText = "Player 0 won! Replay?";
- }
- //We check if players want to replay the match.
- DialogResult answer = MessageBox.Show(winText, "Win", MessageBoxButtons.YesNo);
- if (answer == DialogResult.Yes)
- {
- TurnOnAllButtonsAndReset();
- return;
- }
- else
- {
- Close();
- }
- }
- // We check stalemate
- if (stalemateCounter == 9)
- {
- DialogResult answer = MessageBox.Show("Stalemate, replay?", "Stalemate", MessageBoxButtons.YesNo);
- if (answer == DialogResult.Yes)
- {
- TurnOnAllButtonsAndReset();
- return;
- }
- else
- {
- Close();
- }
- }
- whosTurn = !whosTurn; //player switch
- if (whosTurn == true)
- {
- lblWhosTorn.Text = "X";
- }
- else
- {
- lblWhosTorn.Text = "O";
- }
- }
- private void TurnOnAllButtonsAndReset()
- {
- btn1.Enabled = true;
- btn2.Enabled = true;
- btn3.Enabled = true;
- btn4.Enabled = true;
- btn5.Enabled = true;
- btn6.Enabled = true;
- btn7.Enabled = true;
- btn8.Enabled = true;
- btn9.Enabled = true;
- btn1.Text = "";
- btn2.Text = "";
- btn3.Text = "";
- btn4.Text = "";
- btn5.Text = "";
- btn6.Text = "";
- btn7.Text = "";
- btn8.Text = "";
- btn9.Text = "";
- stalemateCounter = 0;
- whosTurn = true;
- lblWhosTorn.Text = "X";
- }
- private bool checkIfSomeoneWon()
- {
- if (btn1.Text == btn2.Text && btn2.Text == btn3.Text && btn1.Text != "")
- {
- return true;
- }
- else if (btn4.Text == btn5.Text && btn5.Text == btn6.Text && btn4.Text != "")
- {
- return true;
- }
- else if (btn7.Text == btn8.Text && btn8.Text == btn9.Text && btn7.Text != "")
- {
- return true;
- }
- else if (btn1.Text == btn4.Text && btn4.Text == btn7.Text && btn1.Text != "")
- {
- return true;
- }
- else if (btn2.Text == btn5.Text && btn5.Text == btn8.Text && btn2.Text != "")
- {
- return true;
- }
- else if (btn3.Text == btn6.Text && btn6.Text == btn9.Text && btn3.Text != "")
- {
- return true;
- }
- else if (btn1.Text == btn5.Text && btn5.Text == btn9.Text && btn1.Text != "")
- {
- return true;
- }
- else if (btn3.Text == btn5.Text && btn5.Text == btn7.Text && btn3.Text != "")
- {
- return true;
- }
- else
- {
- stalemateCounter++;
- return false;
- }
- }
- private void btn_click(object sender, EventArgs e)
- {
- InsertSymbol(sender);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement