Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop p

how to detect tic tac toe win or a draw

how to detect the win of tic tac toe game?


In this post I'm gonna tell you tic tac toe winning logic you will know the algorithm that is simple and clear you can implement it in any programming language of your interest.

Let's begin! 

The first thing you need to have is an array that indicates the state of the game for example how many places are left to put new mark out of  X or O and the length should be 9 (from 0 to 8).

  state_array = {0, 0, 0, 0, 0, 0, 0, 0, 0}   
 // 0 : empty,  1 :  X,  2 : O

In tic tac toe, there are a total of 8 possible conditions to win the game, when the three marks of the same kind connected in a line as shown bellow 



tic tac toe winning logic

tic tac toe



Again create another array of arrays (2-dimensional array) that contains the places for these win conditions.

win_condition_array = 
{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}}

you almost have done!

whenever in the program you want to check for win you can iterate over the win_condition_array by using for loop.

let's see how it can be done 

At the first iteration of the loop we get {0, 1, 2} and you can use these 3 value as an index of state_array, check if the value at 0, 1, and 2  of state_array is equal.
we are using 0 for empty places and because of it 0 = 0 = 0 will also get true to overcome this insert one more condition in if block that is first value shouldn't be 0. And these conditions are required to use and operator.

if (
state_array[innerArr[0]] == state_array[innerArr[1]] ==
state_array[innerArr[2]] and state_array[innerArr[0]] != 0
)          
    the current player won!

 do the same for each array of win_condition_array.


Thanks for reading the post If you have any suggestions please comment

No comments:

Post a Comment