We need to know when the game is over: either by a victory of any of the player or where there’s simply no empty cell where a move can be made.
there’s simply no empty cell where a move can be made.
Finding the Winner
To determine, if a player managed to form a line of 3 cells, we use simply check if the @verification
string contains a XXX
or OOO
substring:
IF
IndexOf(@verification,'OOO') > 0
THEN
set @state = "Os Win!"
set @stateClass = "o"
set @firstPlayer = 'X'
ELSEIF
IndexOf(@verification,'XXX') > 0
THEN
set @state = "Xs Win!"
set @stateClass = "x"
set @firstPlayer = 'O'
Drawing Conclusions
To see if a draw occurred, we replace all instances X
s and O
s with nothing. If the resulting string is empty, we know that the game can’t continue as there are no cells that weren’t taken by any of the player.
ELSEIF
Replace(Replace(@fields, "O"), "X") == ""
THEN
set @state = "Draw!"
set @stateClass = "d"
set @firstPlayer = IIF(@firstPlayer == "X", "O", "X")
Examples
Player X Wins
For this board our variables would get the following values:
set @fields = "X2OOO6XXX"
/* ... */
set @verification = 'XEO^OOE^XXX^XOX^EOX^OEX^XOX^XOO^'
/* 'XXX' found at position 9 which is bigger than 0 */
IF
IndexOf(@verification,'XXX') > 0
THEN
set @state = "Xs Win!"
set @stateClass = "x"
set @firstPlayer = 'O'
A draw occurs
For this board our variables would get the following values:
set @fields = 'XOXXOOOXX'
/* If we replace all X's and O's, the resulting string is empty*/
ELSEIF
Replace(Replace(@fields, "O"), "X") == ""
THEN
set @state = "Draw!"
set @stateClass = "d"
set @firstPlayer = IIF(@firstPlayer == "X", "O", "X")
The game continues
This is neither a draw nor a victory, so the game can continue.
For this board our variables would get the following values:
set @fields = 'X234O678X'
/* ... */
set @verification = 'X23^4O6^78X^X47^2O8^36X^XOX^7O3^'
/* No player has won and there are moves possible */
ELSE
set @state = Concat("Local Multiplayer:<br>", @playerTurn, "s turn")
Next moves
As you can see in the last example, new variables have appeared:
@state
will be displayed to the player and show:- who won the game
- that the game concluded in a draw
- which player’s turn it is
@stateClass
is the name of the CSS class for a box displaying the@state
@firstPlayer
tells us which player started the game
Speaking of CSS classes, let’s build the interface.