This is what I have so far. This is a two player game. I need to make it a one player game (player vs. computer). I am also trying to make the computer smart.. for example, if there is an open corner, then it should take that spot. Basically, the computer should try to win. The computer's moves should not be random. Please help me! Here is my code:

import java.util.Scanner;

public class Game1 {
    public static void main(String[] arg) {
        Scanner keyboard = new Scanner(System.in);
        TicTacToe game = new TicTacToe();
        game.print();
        while ( !game.won() && !game.stalemate() ) {
            game.move(keyboard);
            game.print();
        }
        if ( game.won() ) System.out.println("You won!");
        if ( game.stalemate() ) System.out.println("Stalemate.");
    }
}

class TicTacToe {
    private char[][] board; // 3 x 3 board
    private char player;        // next player: either 'X' or 'O'

    //make a new game
    public TicTacToe() {
        player = 'X';                   //first player is 'X'
        board = new char[3][3];
        for (int i = 0; i < 3; ++i)
            for (int j = 0; j < 3; ++j)
                board[i][j] = ' ';          //board initially empty
    }

        //get the opposite player to the one given
    private static char opposite(char thePlayer) {
        if ( thePlayer == 'X' ) return 'O'; else return 'X';
    }

        //attempt play in position pos of the form "B2" etcetera,
        //return false if the move is not valid
    public boolean play(String pos) {
        if ( pos.length() != 2 ) return false;
        int row, col;
        switch ( pos.charAt(0) ) {
            case 'A': row = 0; break;
            case 'B': row = 1; break;
            case 'C': row = 2; break;
            default: return false;
        }
        switch ( pos.charAt(1) ) {
            case '1': col = 0; break;
            case '2': col = 1; break;
            case '3': col = 2; break;
            default: return false;
        }
        if ( board[row][col] != ' ' ) return false;
        board[row][col] = player;
        player = opposite(player);
        return true;
    }

        //prompt for a move and attempt to play it until this succeeds
    public void move(Scanner keyboard) {
            System.out.print(player+":");
            while ( !play( keyboard.nextLine() ) )
                System.out.print("Illegal move: try again.\n"+player+":");
            return;
    }

        //find out if the player who just played won the game
    public boolean won() {
        return playerWon( opposite(player) );
    }

        //find out if thePlayer has won the game
    private boolean playerWon(char thePlayer) {
        if ( check3(board[0][0], board[1][1], board[2][2], thePlayer) ) return true;
        if ( check3(board[0][2], board[1][1], board[2][0], thePlayer) ) return true;
        for (int i = 0; i < 3; ++i) {
            if ( check3(board[i][0], board[i][1], board[i][2], thePlayer) ) return true;
            if ( check3(board[0][i], board[1][i], board[2][i], thePlayer) ) return true;
        }
        return false;
    }

        //are p1, p2 and p3 which will come from three positions in a row
        //on the board, all equal to last (i.e. has last got three in a row)
    private static boolean check3(char p1, char p2, char p3, char last) {
        return p1==last && p2==last && p3==last;
    }

        //is the board full and no-one has won?
    public boolean stalemate() {
        if ( playerWon('X') || playerWon('O') ) return false;
        for (int i = 0; i < 3; ++i)
            for (int j = 0; j < 3; ++j)
                if ( board[i][j] == ' ' ) return false;
        return true;
    }

        //print the board to the console
    public void print() {
        String gap = "                 ";
        System.out.println(gap+"      1     2     3");
        System.out.println(gap+"         |     |");
        System.out.println(gap+"A     "+board[0][0]+"  |  "+board[0][1]+"  |  "+board[0][2]);
        System.out.println(gap+"    - - - - - - - - -");
        System.out.println(gap+"B     "+board[1][0]+"  |  "+board[1][1]+"  |  "+board[1][2]);
        System.out.println(gap+"    - - - - - - - - -");
        System.out.println(gap+"C     "+board[2][0]+"  |  "+board[2][1]+"  |  "+board[2][2]);
        System.out.println(gap+"         |     |");
    }
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Please use the (CODE) button to put your code here tags around your code: Preserves indentation, give line numbers and syntax colors: All good things. (Press the button, then paste between the tags, or paste, then highlight and press the button)

Edited 3 Years Ago by mike_2000_17: Fixed formatting

You need the [ code ] [ /code ] tag whenever you post codes... It is very difficult to read without the tag...

From scanning through, it could work, but what is your problem? Do you want to have a computer to play with a player? Then use a flag and flip it each time the while loop of the game is still running. If the flag is true, let player enter; otherwise, create another method for computer to return a valid input. If you really want a computer to be smart, you need to implement a search path for it. Tic Tac Toe game has finite step and can be determined the winner easily (whoever starts can win). You could search for min-max algorithm in AI to implement the way your computer select the next move.

import java.util.Scanner;

public class Game1 {
    public static void main(String[] arg) {
        Scanner keyboard = new Scanner(System.in);
        TicTacToe game = new TicTacToe();
        game.print();
        while ( !game.won() && !game.stalemate() ) {
            game.move(keyboard);
            game.print();
        }
        if ( game.won() ) System.out.println("You won!");
        if ( game.stalemate() ) System.out.println("Stalemate.");
    }
}

class TicTacToe {
    private char[][] board; // 3 x 3 board
    private char player;        // next player: either 'X' or 'O'

    //make a new game
    public TicTacToe() {
        player = 'X';                   //first player is 'X'
        board = new char[3][3];
        for (int i = 0; i < 3; ++i)
            for (int j = 0; j < 3; ++j)
                board[i][j] = ' ';          //board initially empty
    }

        //get the opposite player to the one given
    private static char opposite(char thePlayer) {
        if ( thePlayer == 'X' ) return 'O'; else return 'X';
    }

        //attempt play in position pos of the form "B2" etcetera,
        //return false if the move is not valid
    public boolean play(String pos) {
        if ( pos.length() != 2 ) return false;
        int row, col;
        switch ( pos.charAt(0) ) {
            case 'A': row = 0; break;
            case 'B': row = 1; break;
            case 'C': row = 2; break;
            default: return false;
        }
        switch ( pos.charAt(1) ) {
            case '1': col = 0; break;
            case '2': col = 1; break;
            case '3': col = 2; break;
            default: return false;
        }
        if ( board[row][col] != ' ' ) return false;
        board[row][col] = player;
        player = opposite(player);
        return true;
    }

        //prompt for a move and attempt to play it until this succeeds
    public void move(Scanner keyboard) {
            System.out.print(player+":");
            while ( !play( keyboard.nextLine() ) )
                System.out.print("Illegal move: try again.\n"+player+":");
            return;
    }

        //find out if the player who just played won the game
    public boolean won() {
        return playerWon( opposite(player) );
    }

        //find out if thePlayer has won the game
    private boolean playerWon(char thePlayer) {
        if ( check3(board[0][0], board[1][1], board[2][2], thePlayer) ) return true;
        if ( check3(board[0][2], board[1][1], board[2][0], thePlayer) ) return true;
        for (int i = 0; i < 3; ++i) {
            if ( check3(board[i][0], board[i][1], board[i][2], thePlayer) ) return true;
            if ( check3(board[0][i], board[1][i], board[2][i], thePlayer) ) return true;
        }
        return false;
    }

        //are p1, p2 and p3 which will come from three positions in a row
        //on the board, all equal to last (i.e. has last got three in a row)
    private static boolean check3(char p1, char p2, char p3, char last) {
        return p1==last && p2==last && p3==last;
    }

        //is the board full and no-one has won?
    public boolean stalemate() {
        if ( playerWon('X') || playerWon('O') ) return false;
        for (int i = 0; i < 3; ++i)
            for (int j = 0; j < 3; ++j)
                if ( board[i][j] == ' ' ) return false;
        return true;
    }

        //print the board to the console
    public void print() {
        String gap = "                 ";
        System.out.println(gap+"      1     2     3");
        System.out.println(gap+"         |     |");
        System.out.println(gap+"A     "+board[0][0]+"  |  "+board[0][1]+"  |  "+board[0][2]);
        System.out.println(gap+"    - - - - - - - - -");
        System.out.println(gap+"B     "+board[1][0]+"  |  "+board[1][1]+"  |  "+board[1][2]);
        System.out.println(gap+"    - - - - - - - - -");
        System.out.println(gap+"C     "+board[2][0]+"  |  "+board[2][1]+"  |  "+board[2][2]);
        System.out.println(gap+"         |     |");
    }
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

import java.util.Scanner;

public class Game1 {
	public static void main(String[] arg) {
		Scanner keyboard = new Scanner(System.in);
		TicTacToe game = new TicTacToe();
		game.print();
		while ( !game.won() && !game.stalemate() ) {
			game.move(keyboard);
			game.print();
		}
		if ( game.won() ) System.out.println("You won!");
		if ( game.stalemate() ) System.out.println("Stalemate.");
	}
}

class TicTacToe {
	private char[][] board;	// 3 x 3 board
	private char player;		// next player: either 'X' or 'O'

	//make a new game
	public TicTacToe() {
		player = 'X';                   //first player is 'X'
		board = new char[3][3];
		for (int i = 0; i < 3; ++i)
			for (int j = 0; j < 3; ++j)
				board[i][j] = ' ';          //board initially empty
	}

		//get the opposite player to the one given
	private static char opposite(char thePlayer) {
		if ( thePlayer == 'X' ) return 'O'; else return 'X';
	}

		//attempt play in position pos of the form "B2" etcetera,
		//return false if the move is not valid
	public boolean play(String pos) {
		if ( pos.length() != 2 ) return false;
		int row, col;
		switch ( pos.charAt(0) ) {
			case 'A': row = 0; break;
			case 'B': row = 1; break;
			case 'C': row = 2; break;
			default: return false;
		}
		switch ( pos.charAt(1) ) {
			case '1': col = 0; break;
			case '2': col = 1; break;
			case '3': col = 2; break;
			default: return false;
		}
		if ( board[row][col] != ' ' ) return false;
		board[row][col] = player;
		player = opposite(player);
		return true;
	}

		//prompt for a move and attempt to play it until this succeeds
	public void move(Scanner keyboard) {
			System.out.print(player+":");
			while ( !play( keyboard.nextLine() ) )
				System.out.print("Illegal move: try again.\n"+player+":");
			return;
	}

		//find out if the player who just played won the game
	public boolean won() {
		return playerWon( opposite(player) );
	}

		//find out if thePlayer has won the game
	private boolean playerWon(char thePlayer) {
		if ( check3(board[0][0], board[1][1], board[2][2], thePlayer) ) return true;
		if ( check3(board[0][2], board[1][1], board[2][0], thePlayer) ) return true;
		for (int i = 0; i < 3; ++i) {
			if ( check3(board[i][0], board[i][1], board[i][2], thePlayer) ) return true;
			if ( check3(board[0][i], board[1][i], board[2][i], thePlayer) ) return true;
		}
		return false;
	}

		//are p1, p2 and p3 which will come from three positions in a row
		//on the board, all equal to last (i.e. has last got three in a row)
	private static boolean check3(char p1, char p2, char p3, char last) {
		return p1==last && p2==last && p3==last;
	}

		//is the board full and no-one has won?
	public boolean stalemate() {
		if ( playerWon('X') || playerWon('O') ) return false;
		for (int i = 0; i < 3; ++i)
			for (int j = 0; j < 3; ++j)
				if ( board[i][j] == ' ' ) return false;
		return true;
	}

		//print the board to the console
	public void print() {
		String gap = "                 ";
		System.out.println(gap+"      1     2     3");
		System.out.println(gap+"         |     |");
		System.out.println(gap+"A     "+board[0][0]+"  |  "+board[0][1]+"  |  "+board[0][2]);
		System.out.println(gap+"    - - - - - - - - -");
		System.out.println(gap+"B     "+board[1][0]+"  |  "+board[1][1]+"  |  "+board[1][2]);
		System.out.println(gap+"    - - - - - - - - -");
		System.out.println(gap+"C     "+board[2][0]+"  |  "+board[2][1]+"  |  "+board[2][2]);
		System.out.println(gap+"         |     |");
	}
}

Here is the good code. Yes I want a player to play with the computer. This helps a little

In an initial contact with the user, choose whether the computer is X or O. Then at line 60.5 (if you understand what I mean), check whether the player the X or O, and if it is the one that is a human, run the existing code. Else, call a new method getComputerMove() which does whatever you can think would be smart to do. (I usually play for a draw, so I try to avoid letting my opponent get two intersecting lines with none of my pieces in them). All the information the computer needs is in the board array, though you might make it easier (or not?) if you remember all the 'good' moves from last time and base your next set of 'good' moves on that and the last move by the opponent. There are only about 600 possible arrangements of naught, X and O on the board, counting symmetries, so the job isn't very big.

This article has been dead for over six months. Start a new discussion instead.