TicTacToe Game (Java Code).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.*;
public class Tictactoe {
    private static final int ROWS = 3;
    private static final int COLUMNS = 3;
    private String[][] board;
    //construct an empty board
    public Tictactoe()
    {
        board = new String[ROWS][COLUMNS];
        //Fill with spaces
        for(int i = 0; i < ROWS; i++)
        {
            for(int j = 0; j < COLUMNS; j++)
            {
                board[i][j] = " ";
            }
        }
    }
    //set the fields in the board
    public void set(int i, int j, String player)
    {
        if(board[i][j].equals(" "))
        {
            board[i][j] = player;
        }
    }
    /**creates a string representation of the board
     * @return the string representation
     */
    public String toString()
    {
        String r = "";
        for(int i = 0; i < ROWS; i++)
        {
          r += "|";
            for(int j = 0; j < COLUMNS; j++)
            {
                r += board[i][j];
            }
          r += "|\n";
        }
      return r;
    }
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        String player = "x";
        Tictactoe game = new Tictactoe();
        boolean done = false;
        while(!done)
        {
            System.out.println(game.toString());
            System.out.println("Row for "+player+" (-1 to exit): ");
            int row = in.nextInt();
            if(row < 0) done = true;
            else
            {
                System.out.println("Column for "+player+": ");
                int column = in.nextInt();
                game.set(row, column, player);
                if(player.equals("x")) player = "o";
                else player = "x";
            }
        }
    }
}
Share This!

Leave a Reply

Your email address will not be published.