88public class TicTacToe {
99 private static final Logger logger = LoggerFactory .getLogger ("TicTacToe" );
1010
11+ /* State is a string with one character that indicates the current turn
12+ * (X or O), or win state (A or B). The remaining 9 characters map to spaces
13+ * on the game board.
14+ * 1 2 3
15+ * 4 5 6
16+ * 7 8 9
17+ * A move is a two character string that indicates the moving player (X or O)
18+ * and the space on the game board. After applying the move, the function
19+ * converts the game state of the current player into an integer and compares
20+ * it against known win states to check for victory.
21+ */
1122 public static String move (String oldState , String moveText ) {
12- // 0: user, 1-9: board
13- // String old = "XNNNNNNNNN";
14- // 0: turn, 1: space
15- // String mov = "X3";
23+ // current state in char[]
1624 char [] oldchar = oldState .toCharArray ();
25+ // move in char[]
1726 char [] movchar = moveText .toCharArray ();
27+ // validate move and update state
1828 if ( movchar [0 ] == oldchar [0 ] ) {
1929 oldchar [Character .getNumericValue (movchar [1 ])] = movchar [0 ];
2030 if ( movchar [0 ] == 'X' ) {
@@ -25,12 +35,10 @@ public static String move(String oldState, String moveText) {
2535 } else {
2636 logger .error ("Not your turn" );
2737 }
28- // new = "ONNXNNNNNN"
29- // check for victory
30- // - convert state to integer
38+ // convert state to integer
3139 int stateInt = toInt (oldchar , movchar [0 ]);
3240 logger .info ("state int: " + stateInt );
33- // - compare
41+ // check for victory
3442 boolean win = checkWin (stateInt );
3543 if ( win ) {
3644 if ( movchar [0 ] == 'X' ) {
@@ -43,6 +51,10 @@ public static String move(String oldState, String moveText) {
4351 return newState ;
4452 }
4553
54+ /* Convert a string game state to an integer by treating it as a binary
55+ * number where spaces occupied by the player are '1' and all other spaces
56+ * are '0'.
57+ */
4658 public static int toInt (char [] state , char turn ) {
4759 int out = 0 ;
4860 int len = state .length ;
@@ -54,6 +66,14 @@ public static int toInt(char[] state, char turn) {
5466 return out ;
5567 }
5668
69+ /* Compare an integer game state against known winning states for tic tac
70+ * toe. For example, X can win with three Xs on the bottom row:
71+ * 0 X 0
72+ * O
73+ * X X X
74+ * Xs state in binary is 010000111, 135 in decimal. 135 is a bitwise match
75+ * for 000000111, 7 in decimal, one of the 8 winning states.
76+ */
5777 public static boolean checkWin (int state ) {
5878 int [] winningStates = {7 ,56 ,73 ,84 ,146 ,273 ,292 ,448 };
5979 for ( int i = 0 ; i < 8 ; i ++ ){
0 commit comments