basic tic tac toe game help

Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last
• 04-22-2011, 02:38 AM
java157
basic tic tac toe game help
Here are the requirements and description of my assignment:

* Write a program that allows the user to play a game of "tic-tac-toe"
against the computer.

* For ease, you can assume that the user will make the first move.

* For ease, you can assume that the user will be the "X" in the game.

* When it is the user's turn to move, the program should output the
game board, and should ask the user which square he/she wants to move into.
The user will enter a number from 1 to 9, representing
one of the nine squares. (The top row is 1, 2, 3,
the next row is 4, 5, 6, the bottom row is 7, 8, 9.)

* If the user chooses a square that was already taken, the program
should again ask the user to choose a square.

* When the computer makes a move, it must (of course) only move into
an empty square. Do not let the computer move into a square that is

* For ease, you can assume that when the computer moves, it moves randomly.

* As soon as somebody (user or computer) wins, by putting 3 marks
in a row or column or diagonal, the program should announce the winner
(user or computer), and should output the game board, and
should immediately stop.

* If all 9 squares get filled, but nobody has won (i.e., a cat's game),
the program should announce a "cat's game", output the game board, and
should immediately stop.

* Right before the user is asked to make a move, the program should
output the current game board. It should use X's and O's.
The board MUST have this game board output pattern (of course, the X's and O's
should get based on the current player/computer game, this is sample X's O's):

X | O |
---+---+---
O | X | O
---+---+---
X | O |

---------------------------------------------------------------------

HINTS:
======

* You could use String or int variables or array, to keep track of the moves.

* If you use String comparisons, recall that Java Strings compare with
.equals instead of the usual ==.

Example:
if (s.equals("X"))
if (s=="X")

* For functions, "return ____;" sets the function's return (i.e. answer) value,
and also immediately ends the function.

* For subroutines (including "main"), "return;" immediately ends
the subroutine.

* Code to generate a random integer from 1 to 9, including 1 and 9:
int r = (int) (Math.random() * 9) + 1;

* Code to generate a random integer from 0 to 8, including 0 and 8:
int r = (int) (Math.random() * 9);

---------------------------------------------------------------------

Here is my code (so far):
Code:

``` import java.io.*; public class ttt { public static void main (String args[]) throws IOException { BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in)); int n; System.out.println (" 1 | 2 | 3"); System.out.println ("---+---+---"); System.out.println (" 4 | 5 | 6"); System.out.println ("---+---+---"); System.out.println (" 7 | 8 | 9"); System.out.print("Enter a number to place an X on the board above: "); n = Integer.parseInt(keybd.readLine()); turnX1(n); } public static void turnX1(int n) { {                 if (n==1)         {                 System.out.println (" X | 2 | 3");                 System.out.println ("---+---+---");                 System.out.println (" 4 | 5 | 6");                 System.out.println ("---+---+---");                 System.out.println (" 7 | 8 | 9");         }         else if (n==2)         {                 System.out.println (" 1 | X | 3");                 System.out.println ("---+---+---");                 System.out.println (" 4 | 5 | 6");                 System.out.println ("---+---+---");                 System.out.println (" 7 | 8 | 9");         }         else if (n==3)         {                 System.out.println (" 1 | 2 | X");                 System.out.println ("---+---+---");                 System.out.println (" 4 | 5 | 6");                 System.out.println ("---+---+---");                 System.out.println (" 7 | 8 | 9");         }         else if (n==4)         {                 System.out.println (" 1 | 2 | 3");                 System.out.println ("---+---+---");                 System.out.println (" X | 5 | 6");                 System.out.println ("---+---+---");                 System.out.println (" 7 | 8 | 9");         }         else if (n==5)         {                 System.out.println (" 1 | 2 | 3");                 System.out.println ("---+---+---");                 System.out.println (" 4 | X | 6");                 System.out.println ("---+---+---");                 System.out.println (" 7 | 8 | 9");         }         else if (n==6)         {                 System.out.println (" 1 | X | 3");                 System.out.println ("---+---+---");                 System.out.println (" 4 | 5 | 6");                 System.out.println ("---+---+---");                 System.out.println (" 7 | 8 | 9");         }         else if (n==7)         {                 System.out.println (" 1 | 2 | 3");                 System.out.println ("---+---+---");                 System.out.println (" 4 | 5 | 6");                 System.out.println ("---+---+---");                 System.out.println (" X | 8 | 9");         }         else if (n==8)         {                 System.out.println (" 1 | 2 | 3");                 System.out.println ("---+---+---");                 System.out.println (" 4 | 5 | 6");                 System.out.println ("---+---+---");                 System.out.println (" 7 | X | 9");         }         else         {                 System.out.println (" 1 | 2 | 3");                 System.out.println ("---+---+---");                 System.out.println (" 4 | 5 | 6");                 System.out.println ("---+---+---");                 System.out.println (" 7 | 8 | X");         } } } public static void turnO1(int r) { r = (int) (Math.random() * 9) + 1;         if () // I didn't finish because this is where I felt like I was doing something wrong         } }```
Somehow I feel like I am doing something wrong (or I am doing it the tedious long way). Any assistance would be greatly appreciated thanks!
• 04-22-2011, 04:49 AM
Fubarable
Quote:

Originally Posted by java157
Somehow I feel like I am doing something wrong (or I am doing it the tedious long way). Any assistance would be greatly appreciated thanks!

Yeah, your way will cause your program to get huge and redundant fast. Better is to heed the suggestion to use an array to store the current board state and then display the board based on this state. For instance you could use an array of 10 Strings, the first item or 0th item being ignored, and fill it with empty Strings "". Then if the user selects number 3, fill the [3] item with an "X". Then I'd create a method to display the board, and it would loop through the array from i = 1 to i < 10. If it encounters an "X" or an "O" you put show that in the board, but if it encounters an "", you display the array index instead.

Good luck!
• 04-22-2011, 06:21 AM
java157
Quote:

Originally Posted by Fubarable
Yeah, your way will cause your program to get huge and redundant fast. Better is to heed the suggestion to use an array to store the current board state and then display the board based on this state. For instance you could use an array of 10 Strings, the first item or 0th item being ignored, and fill it with empty Strings "". Then if the user selects number 3, fill the [3] item with an "X". Then I'd create a method to display the board, and it would loop through the array from i = 1 to i < 10. If it encounters an "X" or an "O" you put show that in the board, but if it encounters an "", you display the array index instead.

Good luck!

Am I on the right track for the for the game board:

Code:

``` String[] a={"1","2","3","4","5","6","7","8","9"};                                 System.out.print (" "); // I wanted the whole thing to be on the same line: a[0]) "|"  a[1]  "|"  a[2] , but I get a weird error and tried to fix it but decided to do it this way                 System.out.print (a[0]);                 System.out.print (" | ");                 System.out.print (a[1]);                 System.out.print (" | ");                 System.out.println (a[2]);                                 System.out.println ("---+---+---");                                 System.out.print (" ");                 System.out.print (a[3]);                 System.out.print (" | ");                 System.out.print (a[4]);                 System.out.print (" | ");                 System.out.println (a[5]);                                 System.out.println ("---+---+---");                                 System.out.print (" ");                 System.out.print (a[6]);                 System.out.print (" | ");                 System.out.print (a[7]);                 System.out.print (" | ");                 System.out.print (a[8]);         }         }```
it outputs the board, but I don't know where to go from here
• 04-22-2011, 06:26 AM
sunde887
Not quite, but getting closer. Why not take advantage of a loop, since you are doing lots of repetition a loop would be very helpful.

Code:

```public void printBoard(){   loop     loop       print 1 value and a |     end loop     print seperator +---+---+---   end loop }```
This will make the code much quicker to type and a smaller amount of code. Whenever you perform a very repetitive task, think loops.

Try creating this method with loops and see what you come up with, then post the code here and ask more questions if you have any.
• 04-22-2011, 07:17 AM
sarevok9
Just to give you a bit more of a nudge in the right direction, I have a topic open where I show how I create a player grid (battleship rather than tic - tac- toe) with a 2 dimensional array that might benefit you open in another thread. If you look at the other thread my 'Arrays.java' class in the 'DisplayMap' method.
• 04-22-2011, 08:31 AM
sarevok9
Quote:

Originally Posted by mahoomerry
here's a good place to read up on the algorithm.

Pretty sure you didn't link anything there...
• 04-22-2011, 03:19 PM
java157
Quote:

Originally Posted by sarevok9
Just to give you a bit more of a nudge in the right direction, I have a topic open where I show how I create a player grid (battleship rather than tic - tac- toe) with a 2 dimensional array that might benefit you open in another thread. If you look at the other thread my 'Arrays.java' class in the 'DisplayMap' method.

I did not learn dimensional arrays in our programming class, so I am assuming that we are not allowed to use them, especially since the directions say (focus on the bold part):

Quote:

Originally Posted by sarevok9
The board MUST have this game board output pattern (of course, the X's and O's
should get based on the current player/computer game, this is sample X's O's):

X | O |
---+---+---
O | X | O
---+---+---
X | O |

• 04-22-2011, 03:33 PM
sunde887
Have you tried using a loop as I suggested to print the board?
• 04-22-2011, 04:39 PM
java157
Quote:

Originally Posted by sunde887
Have you tried using a loop as I suggested to print the board?

Not yet. I was going to last night, but it was getting late and I was tired so I went to bed. I will try the loop method though.
• 04-22-2011, 04:53 PM
java157
Quote:

Originally Posted by java157
Am I on the right track for the for the game board:

Code:

``` String[] a={"1","2","3","4","5","6","7","8","9"};                                 System.out.print (" "); // I wanted the whole thing to be on the same line: a[0]) "|"  a[1]  "|"  a[2] , but I get a weird error and tried to fix it```

LOL I figured out why I couldn't print it on the same line. It's because I forgot the plus sign between quoted and unquoted text (ie System.out.println (a[0] + "|" + a[1] + "... etc.");

Wow I feel so dumb.

Code:

```public static void board (String args[]) {         String[] a={"1","2","3","4","5","6","7","8","9"};                 System.out.println (a[0] + " | " + a[1] + " | " + a[2]);                 System.out.println ("---+---+---");                 System.out.println (a[3] + " | " + a[4] + " | " + a[5]);                 System.out.println ("---+---+---");                 System.out.println (a[6] + " | " + a[7] + " | " + a[8]); }```
• 04-22-2011, 05:18 PM
sunde887
You could do this much nicer with a loop. Using an instance variable for the string array would be nice too.
• 04-22-2011, 05:30 PM
java157
Quote:

Originally Posted by sunde887
Have you tried using a loop as I suggested to print the board?

Code:

```public static void board (String args[]) {         int[] a = new int[4];         for (int i=1; i<=3; i++)         {                                 System.out.print (i + " | ");                         }         System.out.println ("");         System.out.println ("---+---+---");                 int[] b = new int[7];         for (int i=4; i<=6; i++)         {                                 System.out.print (i + " | ");                         }                 System.out.println ("");         System.out.println ("---+---+---");                 int[] c = new int[10];         for (int i=7; i<=9; i++)         {                                 System.out.print (i + " | ");                         }                 } }```
The code outputs:

1 | 2 | 3 |
--+--+---
4 | 5 | 6 |
--+--+---
7 | 8 | 9 |

1 | 2 | 3
--+--+---
4 | 5 | 6
--+--+----
7 | 8 | 9
• 04-22-2011, 05:53 PM
JosAH
Quote:

Originally Posted by java157
The code outputs:

1 | 2 | 3 |
--+--+---
4 | 5 | 6 |
--+--+---
7 | 8 | 9 |

1 | 2 | 3
--+--+---
4 | 5 | 6
--+--+----
7 | 8 | 9

For now, don't think about it but change all those System.out.print( ... ) calls to:

Code:

`System.out.print (i + ((i%3 == 0)?"":" | "));`
kind regards,

Jos
• 04-22-2011, 07:28 PM
sunde887
Also, consider a nested loop, you shouldn't be creating 3 individual loops. Have one loop run the other loop 3 times.
• 04-23-2011, 04:24 PM
java157
Quote:

Originally Posted by sunde887
Also, consider a nested loop, you shouldn't be creating 3 individual loops. Have one loop run the other loop 3 times.

The professor posted extra hints yesterday, but it's really confusing me:

Code:

```public class HW7 { public static void main(String args[]) { int[] a = new int[9];  //create elements a[0] to a[8]   //encoding: a[#] = 0 means empty square   //          a[#] = 1 means player moved "X" there   //          a[#] = 2 means computer moved "O" there   //   //          board is:  a[0], a[1], a[2]   //                    a[3], a[4], a[5]   //                    a[6], a[7], a[8] int nummoves=0;  //tracks current number of game moves, as game progresses while (true)  //infinite loop, until winner or cat's game ends the program {   drawBoard(a);  //calling subroutine, to draw the game board   //HERE: PUT CODE TO LET PLAYER INPUT A SQUARE NUMBER, ASSUME 1-9 OR 0-8,   //      BUT KEEP LOOPING UNTIL PLAYER CHOOSES AN EMPTY SQUARE.   //HERE: SET APPROPRIATE ARRAY ELEMENT, TO TRACK USER'S MOVE.   //HERE: INCREASE NUMMOVES BY 1.   //HERE: IF PLAYER WINS, SAY "PLAYER WINS!", DRAW BOARD, END PROGRAM.   //HERE: IF NUMBER OF MOVES SO FAR IS 9,   //      THEN OUTPUT "CAT'S GAME!", DRAW BOARD, END PROGRAM.   //HERE: PUT CODE TO LET COMPUTER RANDOMLY CHOOSE A SQUARE NUMBER,   //      BUT KEEP LOOPING UNTIL COMPUTER CHOOSES AN EMPTY SQUARE.   //HERE: SET APPROPRIATE ARRAY ELEMENT, TO TRACK COMPUTER'S MOVE.   //HERE: INCREASE NUMMOVES BY 1.   //HERE: IF COMPUTER WINS, SAY "COMPUTER WINS!", DRAW BOARD, END PROGRAM. } //end while } //end main public static boolean XWins(int[] a) {   //HERE: EXAMINE THE ARRAY ELEMENTS, TO SEE IF PLAYER WINS.   //      IF PLAYER HAS MOVED IN AN ENTIRE ROW OR COLUMN OR DIAGONAL   //      (8 POSSIBILITIES), THEN "return true;".  BUT IF NOT, "return false;" } public static boolean OWins(int[] a) {   //SIMILAR TO THE PREVIOUS XWINS FUNCTION, EXCEPT SEE IF COMPUTER WINS. } public static void drawBoard(int[] a) {   String[] s = new String[9];  // since moves were tracked with int array a   for (int i=0; i<=8; i++)      // instead of String array a, we must now   {                            // create extra array with X's and O's       if (a[i]==0)              // instead of 1's and 2's, for nicer output.         s[i]=" ";              // (Instead, you could have tracked moves       else if (a[i]==1)          // with String array a, instead of int array a.         s[i]="X";              // But, that would make the XWins and OWins       else                      // routines much more complex.)         s[i]="O";   }   System.out.println(" "+s[0]+" | "+s[1]+" | "+s[2]);   System.out.println("---+---+---");   System.out.println(" "+s[3]+" | "+s[4]+" | "+s[5]);   System.out.println("---+---+---");   System.out.println(" "+s[6]+" | "+s[7]+" | "+s[8]); } } //end class```
• 04-23-2011, 04:34 PM
java157
This is what I came up with using the professor's extra hints. Read the // comments for where I need help with errors:
Code:

```import java.io.*; public class HW7 {         public static void main(String args[]) throws IOException         {                 BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in));                         int[] a = new int[9];         int nummoves=0;                 while (true)          {           drawBoard(a);           System.out.print("Enter a number to place an X on the board above: ");           int n = Integer.parseInt(keybd.readLine());           int[] b = new int[9];           nummoves +=1;           XWins(a);           if (nummoves==9)           {                   System.out.println ("CAT'S GAME!");                   drawBoard(a);                   return;           }                     int r = (int) (Math.random() * 9); [COLOR="Red"][B]// Error: "Duplicate local variable r"[/B][/COLOR]           int[] r = new int[9];           nummoves +=1;                 }         }         public static boolean XWins(int[] a) [COLOR="red"][B]// Error: This method must return a result of type boolean[/B][/COLOR]         {           if (a[0]==1 && a[1]==1 && a[2]==1)           {                                                                System.out.println ("X WINS!");           }                            else if (a[3]==1 && a[4]==1 && a[5]==1)           {                   System.out.println ("X WINS!");           }                     else if (a[6]==1 && a[7]==1 && a[8]==1)           {                   System.out.println ("X WINS!");           }                     else if (a[0]==1 && a[3]==1 && a[6]==1)           {                   System.out.println ("X WINS!");           }                     else if (a[1]==1 && a[4]==1 && a[7]==1)           {                   System.out.println ("X WINS!");           }                     else if (a[2]==1 && a[5]==1 && a[8]==1)           {                   System.out.println ("X WINS!");           }                     else if (a[0]==1 && a[4]==1 && a[8]==1)           {                   System.out.println ("X WINS!");           }                     else if (a[2]==1 && a[4]==1 && a[6]==1)           {                   System.out.println ("X WINS!");           }                 }         public static boolean OWins(int[] a) [COLOR="red"][B]// Error: This method must return a result of type boolean[/B][/COLOR]         {                 if (a[0]==2 && a[1]==2 && a[2]==2)                   {                                                                        System.out.println ("O WINS!");                                                          }                                            else if (a[3]==2 && a[4]==2 && a[5]==2)                   {                           System.out.println ("O WINS!");                   }                                     else if (a[6]==2 && a[7]==2 && a[8]==2)                   {                           System.out.println ("O WINS!");                   }                                     else if (a[0]==2 && a[3]==2 && a[6]==2)                   {                           System.out.println ("O WINS!");                   }                                     else if (a[1]==2 && a[4]==2 && a[7]==2)                   {                           System.out.println ("O WINS!");                   }                                     else if (a[2]==2 && a[5]==2 && a[8]==2)                   {                           System.out.println ("O WINS!");                   }                                     else if (a[0]==2 && a[4]==2 && a[8]==2)                   {                           System.out.println ("O WINS!");                   }                                     else if (a[2]==2 && a[4]==2 && a[6]==2)                   {                           System.out.println ("O WINS!");                   }           }         public static void drawBoard(int[] a)         {           String[] s = new String[9];            for (int i=0; i<=8; i++)                {                                          if (a[i]==0)                              s[i]=" ";                            else if (a[i]==1)                        s[i]="X";                            else                                      s[i]="O";           }           System.out.println(" "+s[0]+" | "+s[1]+" | "+s[2]);           System.out.println("---+---+---");           System.out.println(" "+s[3]+" | "+s[4]+" | "+s[5]);           System.out.println("---+---+---");           System.out.println(" "+s[6]+" | "+s[7]+" | "+s[8]);         } }```
• 04-23-2011, 05:21 PM
Fubarable
The error messages are telling you exactly what's wrong. The first one is due to your declaring the "r" variable twice, and it's quite obvious that you're doing this here by declaring r as an int and then one line below as an array:

Code:

```          int r = (int) (Math.random() * 9); // r declared as an int           int[] r = new int[9]; // r declared [b]again[/b] as an int array```

The next two state that your methods have been declared as returning a boolean but instead you're trying to return Strings, and again, the error messages are pretty clear cut about what's wrong. What is confusing to you?
• 04-23-2011, 05:43 PM
java157
Quote:

Originally Posted by Fubarable
The error messages are telling you exactly what's wrong, I'm not sure how you're not understanding them. The first one is due to your declaring the "r" variable twice, and it's quite obvious that you're doing this here by declaring r as an int and then one line below as an array:

Code:

```          int r = (int) (Math.random() * 9); // Error: "Duplicate local variable r"           int[] r = new int[9];```

The next two state that your methods have been declared as returning a boolean but you're returning Strings. Again, the error messages are pretty clear cut. What is confusing you about them?

Ok when i change the variable
Code:

```          int r = (int) (Math.random() * 9); // Error: "Duplicate local variable r"           int[] c = new int[9];```
neither r or c gets read

I don't understand boolean

edit: I just changed boolean to void for both subroutines and now the error is now gone
• 04-23-2011, 05:49 PM
Fubarable
Quote:

Originally Posted by java157
Ok when i change the variable
Code:

```          int r = (int) (Math.random() * 9); // Error: "Duplicate local variable r"           int[] c = new int[9];```
neither r or c gets read

Your code only does what you tell it to do. I'm not even sure what you are using c for, what its purpose is.

Quote:

I don't understand boolean
boolean is true/false. So if you declare a method to return boolean, it must return either true or false, not a String. You can read about it here: Primitive Data Types (The Java™ Tutorials > Learning the Java Language > Language Basics)

Heck, your instructor even spelled this out for you :rolleyes::
Quote:

THEN "return true;". BUT IF NOT, "return false;"
• 04-23-2011, 07:03 PM
Fubarable
My suggestion to you is to first fix your methods so that they return boolean.

Next, you should do try to do each recommendation of your instructor one at a time. Test and modify the resulting code until it works, and don't work on the next instruction until the one you're working on is done and bullet proof. Don't try to do the whole thing at once. Then if you have a problem, you can ask about that specific instruction, your code and your problem, and we'll all have an easier time with this.
Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last