Jump to content

Programming a simple tic tac toe program help!

- - - - -

  • Please log in to reply
10 replies to this topic

#1
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
I've seen the adv tic tac toe tutorial on this site, but that's a bit too advanced for me. I'm at the very basics and am trying to create a tic tac toe game without any object oriented programming (because I don't know it), even if it takes my a million if statements for each combination of the spaces on the board. It's a one player game, so I have to include an AI system that takes turns with the human. I'm trying to make it so the human can never win, but the computer can win if the human makes some stupid mistake. I've came up with some code, but I'm kinda stuck on how to continue. I would really appreciate it if someone could help me with the logic of this program.
My code:
import java.util.Scanner;

public class TikTakToe {


public static void main(String[] args) {


	Scanner scanner = new Scanner(System.in);

	String space1 = "1"; //these are just for visual coordinated. These will always be on the screen along with any Xs and Os.

	String space2 = "2";

	String space3 = "3";

	String space4 = "4";

	String space5 = "5";

	String space6 = "6";

	String space7 = "7";

	String space8 = "8";

	String space9 = "9";

	

	String board1 = "X"; //these actually keep track of the Xs and Os, they are printed along side of the char spaces that I have above. So

	String board2 = "O"; //for example, the grid will look like this when game is going on

	String board3 = "X"; //1 X 2 X 3 O

	String board4 = "O"; //4 O 5 X 6 O

	String board5 = "X"; //7 O 8 X 9 (as you can see, X has won, and space nine is empty. That is what I'm trying to achieve

	String board6 = "O";

	String board7 = " ";

	String board8 = " ";

	String board9 = "O";

	boolean x = false; //I don't know what I am doing with these, but I was thinking maybe 

	boolean o = false; //to see who wins. 

	String input = null;

	

	

	

	while //loop all this till all spaces are filled. Then to find who wins, I get more specific later.

	((board1 == " ") || (board2 == " ") || (board3 == " ") || (board4 == " ") || (board5 == " ")

	|| (board6 == " ") || (board7 == " ") || (board8 == " ") || (board9 == " ")){

	

	System.out.println(space1 +"|"+ board1+"\t"+space2 +"|"+ board2+"\t"+space3+"|"+board3);//I want to print out the board here and have it updated each time a user picks a space

	System.out.println(space4 +"|"+ board4+"\t"+space5 +"|"+ board5+"\t"+space6+"|"+board6);

	System.out.println(space7 +"|"+ board7+"\t"+space8 +"|"+ board8+"\t"+space9+"|"+board9);

	//everytime it goes through the loop, it will print the updated board to the screen.

	//I don't know if I should create a separate method for that (which I have tried, but ran into problems)

	

	

	

	//check the input in this loop		 

	do{

			System.out.print("Enter the number for the space you want to choose: ");

			input = scanner.nextLine();

			

				if (input.equals("1"))

				board1 = "X";

				

				if (input.equals("2"))

				board2 = "X";

				

				if (input.equals("3"))

				board3 = "X";

				

				if (input.equals("4"))

				board4 = "X";

				

				if (input.equals("5"))

				board5 = "X";

				

				if (input.equals("6"))

				board6 = "X";

				

				if (input.equals("7"))

				board7 = "X";

				

				if (input.equals("8"))

				board8 = "X";

				

				if (input.equals("9"))

				board9 = "X";

			

				else{System.out.print("The input is not 1-9, you just lost a turn");} //I don't wanna add any extra work to make my program robust for

																					//idiots who can't read or count.

				

System.out.println(space1 +"|"+ board1+"\t"+space2 +"|"+ board2+"\t"+space3+"|"+board3);//I want to print out the board here and have it updated each time a user picks a space

System.out.println(space4 +"|"+ board4+"\t"+space5 +"|"+ board5+"\t"+space6+"|"+board6);

System.out.println(space7 +"|"+ board7+"\t"+space8 +"|"+ board8+"\t"+space9+"|"+board9);


			} while(x = false);


	

	

		

		}

	

	

	

	

	

	}

} 

Edited by An Alien, 07 January 2011 - 02:56 PM.


#2
nicckk

nicckk

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 629 posts
Well, Strings are immutable, so using Strings to make your board wastes memory as you have to create a new String object for every change to the board. Using a primitive type, such as a char for each space could work much better. Also, for comparing objects- you should use the .equals() method; using == will check if the object variables reference the same object. You can learn more about comparing Strings and primitive types here Java: ==, .equals(), compareTo(), and compare(). Also if you're interested, I released a simple console tic tac toe program if you want to take a look. http://forum.codecal...ic-tac-toe.html

#3
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
Well originally I used chars but I ran into problems like I couldn't concatenate chars like strings would in println statements so I decided to use String. But now, you're telling me that Strings aren't changeable. I will look into the links you gave me and see if I can find that answer. And thanks for the help, I really appreciate it.:c-smile: +rep

EDIT: So you're saying, instead of "==", I should use input.equals(#) in my if statements?

Edited by An Alien, 05 January 2011 - 08:27 PM.


#4
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
all the ifs are the same, change them :D

#5
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
Oops, I didn't mean to post it with all the ifs the same. I was just doing some testing and forgot to change them back to 1-9.

#6
nicckk

nicckk

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 629 posts

An Alien said:

EDIT: So you're saying, instead of "==", I should use input.equals(#) in my if statements?

Right, if you have a String input, you could use if(input.equals("whatever");

#7
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
I got a compiling error from eclipse say that cannot invoke equals(int) with primative type int so I changed the input to a string instead of an int. And now input.equals is working fine.

Also, Is there any more object oriented/better way to figure out how to make the AI moves instead of typing out the code for EVERY SINGLE combination on the board that the user and AI can make?

#8
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
Would it be better to use case statements rather than ifs? What should I do about the strings being immutable.
Edit: Updated code, check first post, I used the boolean for X to keep continuing the do while loop while X has not won the game. To determine, I'll probably have to list all the combinations for winning and if they are winning combination, then x = true which will stop the do while loop.

Edited by An Alien, 07 January 2011 - 02:55 PM.


#9
GabryelFall

GabryelFall

    Learning Programmer

  • Members
  • PipPipPip
  • 74 posts
So.. I got it working with a little bit of OOP. Two classes, a main and a TicTacBoard class.

No AI yet.. and the if..else block for checking combinations isn't pretty... If anyone has a better way to do that part I'd love to hear it.

otherwise.. here's the code. Hope this helps. As with all code posted, take it apart and let me know what I did right and wrong.. I'm still in the learning process for Java as well.

first is the Main.class
package tictactoe;

import java.util.Scanner;
public class Main {
    public static TicTacBoard tic = new TicTacBoard();

    public static void main(String[] args) {
        int playerNum=1;
        tic.paintBoard();
   
        int gameOver=1;
        while (gameOver != 0){
            placeInput(getInput(), playerNum);
            tic.paintBoard();
            playerNum=setPlayer(playerNum);
            gameOver=checkGameover(gameOver, playerNum);
        }


    }
    public static int getInput(){
        Scanner scan = new Scanner(System.in);
        int input=0;
        int count=1;
        while (count != 0){
            input = scan.nextInt();
            if (input > 9){
                System.out.println("Invalid selection.");
            } else {
              count = 0;
            }
        }
        return input;
    }
    public static void placeInput(int input, int playerNum){
        int cell=input;
        int play=playerNum;
        if(tic.cells[cell-1].equals(" ")){
            if(play == 1){
                tic.cells[cell-1]="x";
            } else tic.cells[cell-1]="o";
        } else System.out.println("Invalid selection.");

    }
    public static int setPlayer(int playerNum){
        int player=playerNum;
        if(player==1){
            player=0;
        } else player=1;
        
        return player;
    }
    public static int checkGameover(int gameOver, int playerNum){
        int game = gameOver;
        int player = playerNum;
        int win = tic.checkCombination();

        if (win == 1){
            game = 0;
            System.out.println("X has won the game!");
            return game;
        } else if(win == 2){
            game = 0;
            System.out.println("O has won the game!");
            return game;
        }

        return game;
    }
    
    

}
Next is the TicTacBoard.class
package tictactoe;

import java.lang.String;

public class TicTacBoard {
    String[] cells = new String[] {" "," "," "," "," "," "," "," "," "};

    public void testArray(){
        int num;
        for(num=0;num<=8;num++){
            System.out.println(cells[num]);
        }            
    }
    public void paintBoard(){
        System.out.println("[" + cells[0] + "]" + "[" + cells[1] + "]" + "[" + cells[2] + "]");
        System.out.println("[" + cells[3] + "]" + "[" + cells[4] + "]" + "[" + cells[5] + "]");
        System.out.println("[" + cells[6] + "]" + "[" + cells[7] + "]" + "[" + cells[8] + "]");
    }
    public int checkCombination(){
        int player=0;
        if(this.cells[0].equals("x") && this.cells[1].equals("x") && this.cells[2].equals("x")){
            player =1;
            return player;
        }else if(this.cells[3].equals("x") && this.cells[4].equals("x") && this.cells[5].equals("x")){
            player =1;
            return player;
        }else if (this.cells[6].equals("x") && this.cells[7].equals("x") && this.cells[8].equals("x")){
            player =1;
            return player;
        }else if(this.cells[0].equals("x") && this.cells[3].equals("x") && this.cells[6].equals("x")){
            player =1;
            return player;
        }else if(this.cells[1].equals("x") && this.cells[4].equals("x") && this.cells[7].equals("x")){
            player =1;
            return player;
        }else if(this.cells[2].equals("x") && this.cells[5].equals("x") && this.cells[8].equals("x")){
            player =1;
            return player;
        }else if(this.cells[0].equals("x") && this.cells[4].equals("x") && this.cells[6].equals("x")){
            player =1;
            return player;
        }else if(this.cells[6].equals("x") && this.cells[4].equals("x") && this.cells[2].equals("x")){
            player =1;
            return player;
        }else if(this.cells[0].equals("o") && this.cells[1].equals("o") && this.cells[2].equals("o")){
            player =2;
            return player;
        }else if(this.cells[3].equals("o") && this.cells[4].equals("o") && this.cells[5].equals("o")){
            player =2;
            return player;
        }else if (this.cells[6].equals("o") && this.cells[7].equals("o") && this.cells[8].equals("o")){
            player =2;
            return player;
        }else if(this.cells[0].equals("o") && this.cells[3].equals("o") && this.cells[6].equals("o")){
            player =2;
            return player;
        }else if(this.cells[1].equals("o") && this.cells[4].equals("o") && this.cells[7].equals("o")){
            player =2;
            return player;
        }else if(this.cells[2].equals("o") && this.cells[5].equals("o") && this.cells[8].equals("o")){
            player =2;
            return player;
        }else if(this.cells[0].equals("o") && this.cells[4].equals("o") && this.cells[6].equals("o")){
            player =2;
            return player;
        }else if(this.cells[6].equals("o") && this.cells[4].equals("o") && this.cells[2].equals("o")){
            player =2;
            return player;
        }

        return player;
    }

}

~~~~>>>><<<<~~~~
Cook to live; Live to cook. Code is poetry. Chef and code-monkey,
Gabe

#10
GabryelFall

GabryelFall

    Learning Programmer

  • Members
  • PipPipPip
  • 74 posts
Credit where credit is due nicckk. I used your board layout and a form of your combination check. thanks for posting :)
~~~~>>>><<<<~~~~
Cook to live; Live to cook. Code is poetry. Chef and code-monkey,
Gabe

#11
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
Thanks A LOT man! +rep. I will study that. Also, I would really appreciate it if you could help me get the AI working here too. But I don't really understand the idea of packages yet. I've always just used the default eclipse package so I don't really know what that means.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users