Question

So, this is for an assignment, it's coming along quite well, i just can't seem to get past this part where i have to set it to only add 4 X's and 5 O's. i've been trying some options but i figured i would dump the code that actually works so far on here, if anybody would like to assist that would be appreciated.

"Write a program that simulates a game of tic-tac-toe and indicates whether a player wins, and which. The program should: • Declare and use an array of int of size [3,3] to represent the tic-tac-toe grid

• Fill each position in the array with either a -1 or +1 as follows

• 4 ‘X’s represented by -1

• 5 ‘O’s represented by +1

• Display the grid

• Evaluate and indicate if the player that uses ‘X’ won.

• Evaluate and indicate if the player that uses ‘O’ won.

Program must implement and use at least the following methods:

• public static void fillGridWithRandomValues(int[][] grid) o Receives an array and fills is with -1 and 1 chosen randomly

• public static void printGrid(int[][] grid) o Displays the grid on the screen

• public static boolean evaluateWinner(int[][] grid, int value) o Returns true when there is at least 3 positions in the same row, or the same column or the same diagonal that contain the parameter ‘value’. Returns false otherwise"

And here's the actual code.

package 123456;

/** * * @author 123456 */ public class 123456 {

/**
 * @param args the command line arguments
 */
public static void fillGridWithRandomValues(int[][] grid) {
    for (int row=0; row < grid.length; row++) {
        for (int column=0; column < grid[row].length; column++) {
            grid[row][column] = (int) (((Math.random()*2)*2)-2);
                            if (grid[row][column] == 0) grid[row][column]++;

                    }
    };
}

public static boolean evaluateWinner(int[][] grid, int value) {

        return false;

}

public static void printGrid(int[] row) {
    for (int i : row) {
        String str = null;
        if (i == 1) str = "X";
        else if (i == -1) str = "O";
        else str = null ;
        System.out.print(str + " ");
        System.out.print(" ");
    }
    System.out.println();
    }

public static void main(String[] args) {

    // creating array for the grid

    int[][] grid ;//= { { 1, -1, 1 }, { -1, 1, -1 }, { 1, -1, } };
    grid = new int[3][3];

    fillGridWithRandomValues(grid);

    for(int[] row : grid) {
        printGrid(row);
    }




    }   

}

Was it helpful?

Solution

No, Math.random() is specifically designed to give unpredictable results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top