I have this Tic Tac Toe Game, it works fine, however I am player 1 and player 2, I am playing with myself. I have been trying to make the computer to be player2, and to be smart enough to block if player 1 (me) has two Xs or two Os in a row, but I haven't been unsuccessful. Any ideas, please? Thanks.
This is the Code in C#
using System;
using Xamarin.Forms;
namespace TicTACTOE
{
public partial class MainPage : ContentPage
{
private Button[] buttons = new Button[9];
private GameDriver game = new GameDriver();
private GameState gameState= new GameState();
public MainPage()
{
InitializeComponent();
buttons[0] = button1;
buttons[1] = button2;
buttons[2] = button3;
buttons[3] = button4;
buttons[4] = button5;
buttons[5] = button6;
buttons[6] = button7;
buttons[7] = button8;
buttons[8] = button9;
}
private void Button_Clicked(object sender, EventArgs e)
{
game.SetButton((Button)sender, this.gameState);
if (game.CheckWinner(buttons))
{
gameOverStackLayout.IsVisible = true;
}
}
private void PlayAgain_Clicked(Object sender, EventArgs e)
{
game.ResetGame(buttons);
gameOverStackLayout.IsVisible = false;
}
}
}
and this is the other namespace
namespace TicTACTOE
{
using Xamarin.Forms;
internal class GameDriver
{
private PlayerType player = PlayerType.Human;
private readonly int[,] Winners = new int[,]
{
{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6}
};
public bool CheckWinner(Button[] buttons)
{
bool gameOver = false;
for (int i = 0; i < 8; i++)
{
Button b1 = buttons[Winners[i, 0]];
Button b2 = buttons[Winners[i, 1]];
Button b3 = buttons[Winners[i, 2]];
if (b1.Text == "" || b2.Text == "" || b3.Text == "")
{
continue;
}
if (b1.Text == b2.Text && b2.Text == b3.Text)
{
b1.BackgroundColor = b2.BackgroundColor = b3.BackgroundColor = Color.Aqua;
gameOver = true;
break;
}
}
bool isTie = true;
if (!gameOver)
{
foreach (Button b in buttons)
{
if (b.Text == "")
{
isTie = false;
break;
}
}
if (isTie)
{
gameOver = true;
}
}
return gameOver;
}
public void SetButton(Button b, GameState gameState)
{
if (b.Text == "")
{
b.Text = player == PlayerType.Human ? "X" : "O";
player = player == PlayerType.Human ? PlayerType.AI : PlayerType.Human;
}
}
public void ResetGame(Button[] buttons)
{
player = PlayerType.Human;
foreach (Button b in buttons)
{
b.Text = "";
b.BackgroundColor = Color.Gray;
}
}
}
}
What I have tried:
I have tried
-to do this for each one of the buttons
-
But, it doesn't work, either. Thanks