This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Tic Tac Toe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Tic Tac Toe" Watch "Tic Tac Toe" New topic
Author

Tic Tac Toe

Shyam Prasad Murarka
Ranch Hand

Joined: May 02, 2005
Posts: 209
Dear Readers,
I just learnt how to use binary operators from here.
I then took a look at the TicTacToe game that comes in with JDK. Nearly everywhere they used left-shift operators or right-shift operators. I really can't understand it. Can anyone please explain the logic of the game in a synopsis or pseudocode. Please I can't get it through my thich brains.


With Best Regards,
Shyam Prasad Murarka
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Consider the 3x3 square board as binary "switches" that can be turned on or off...

000
000
000

There are a total of 8 winning patterns -- since there are 3 rows, 3 columns, and 2 diagonals. For example, one way of winning is the bottom row...

000
000
111

If you string all of these switches together, you have a binary quantity, 000000111. One way to represent this quantity is using the bitwise "or" operator. In binary, 000000111 = 000000001 | 000000010 | 000000100. A convenient way to express this is to use left-shift operators, (1<<0) | (1<<1) | (1<<2).

In the same manner, the middle row could be expressed as (1<<3) | (1<<4) | (1<<5). And the first column would be expressed as (1<<2) | (1<<5) | (1<<8).

Each of these 8 winning patterns is initialized to "true" in the boolean array called "won." This array has an element representing each possible pattern. The number of theoretical possibilities is 2^9 (two choices for each of the nine squares). 2^9 is equivalent to 1<<9 (binary), which is 512. So the boolean array of size 512 is created with "new boolean[1<<9]."
[ May 12, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Shyam Prasad Murarka
Ranch Hand

Joined: May 02, 2005
Posts: 209
Dear marc,
Thank you very much for explaining the logic to me. Now i will be going to spend some time with the sample to understand better.
 
 
subject: Tic Tac Toe