Time for action – code consolidation
We've chosen the square that the computer player will take. What are the next steps? Well, we need to increment the moves variable. We need to instantiate a piece Prefab. We need to update the Square with the player who claimed it. We need to check for a win or a stalemate, and update the player number.
By golly, all these steps are identical to the steps we already take when the human player places a piece! We should encapsulate those steps in a function that both the human and computer player can call.
Take all of the lines that are bolded below in the ClickSquare function, and move them into a new function called PlacePiece():
function ClickSquare(square:GameObject)
{
if(gameIsOver) return;
var piece:GameObject;
if(currentPlayer == 1)
{
piece = XPiece;
} else {
piece = OPiece;
}
moves ++;
Instantiate(piece, square.transform.position, Quaternion.identity);
square.GetComponent.<Square>().player = currentPlayer;
...