TicTacToe Java - winner check

Here is my code. I'm trying to check the winner. I'm just a beginner, so please do it easily. I wanted the board to resize. So, I want the check for the winner to be able to use its size, it will not just check 9 blocks.

import java.util.*;

public class TicTacToe {

    private String[][] board;
    private Scanner console;

    public TicTacToe(String[][] table, Scanner console) {
        this.board = table;
        this.console = console;
    }

    public void makeTable() {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                board[i][j] = "_";
            }
        }
    }

    public void printTable() {
        System.out.print(" ");
        for (int i = 0; i < board.length; i++) {
            System.out.print(" " + i);
        }
        System.out.println();
        for (int i = 0; i < board.length; i++) {
            System.out.print(i + "│");
            for (int j = 0; j < board[i].length; j++) {
                System.out.print(board[i][j] + "│");
            }
            System.out.println();
        }
    }

    public void play(Scanner console) {
        int turn = 0;
        String player = "_";
        makeTable();
        printTable();
        while (turn != 9) {
            int x = console.nextInt();
            int y = console.nextInt();

            while (x >= board.length || y >= board[1].length) {
                System.out.println("Out of bounce, try again!!!");
                x = console.nextInt();
                y = console.nextInt();
            }

            while (board[y][x] != "_") {
                System.out.println("Occupied, try again!!!");
                x = console.nextInt();
                y = console.nextInt();
            }

            if (turn % 2 == 0) {
                player = "X";
            } else {
                player = "O";
            }
            board[y][x] = player;
            turn++;
            printTable();
        }
    }

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        String[][] board = new String[3][3];
        TicTacToe ttt = new TicTacToe(board, console);
        ttt.play(console);
    }
}
+4
source share
5 answers

A winning move can only happen when a piece is on the board, so you only need to check the winning combinations in which the piece that was just installed on the board participates.

For example, if the current state of the board:

O X O
X   X
    O

And Oputs part of them in the middle of the board:

O X O
X O X
    O

, , , (4 ) (8 ).

, , .

+5

, , , , . , , , - .

, , , ( ), , , .

// Takes the row and column coordinates of the last move made
// and checks to see if that move causes the player to win
public boolean isWinner(int row, int col){
    String Player = board[row][col];

    int r = row;
    int c = col;

    boolean onDiagonal = (row == col) || (col == -1 * row + (board.length-1));
    boolean HorizontalWin = true, VerticalWin = true;
    boolean DiagonalWinOne = true; DiagonalWinTwo = true;

    // Check the rows and columns
    for(int n = 0; n < board.length; n++){
        if(!board[r][n].equals(Player))
            HorizontalWin = false;
        if(!board[n][c].equals(Player))
            VerticalWin = false;
    }

    // Only check diagonals if the move is on a diagonal
    if(onDiagonal){
        // Check the diagonals
        for(int n = 0; n < board.length; n++){
            if(!board[n][n].equals(Player))
                DiagonalWinOne = false;
            if(!board[n][-1*n+(board.length-1)].equals(Player))
                DiagonalWinTwo = false;
        }
    }
    else{
        DiagonalWinOne = false;
        DiagonalWinTwo = false;
    }

    boolean hasWon = (HorizontalWin || VerticalWin || DiagonalWinOne || DiagonalWinTwo);

    return hasWon;

}

, .

, while , , , , , , . , , , , ArrayOutOfBoundsException.

public boolean isWinner(String player){
    // Check for N-in-a-row on the rows and columns
    for(int i = 0; i < board.length; i++){
        boolean verticalWin = true, horizontalWin = true;
        for(int j = 0; j < board.length; j++){
            if(!board[i][j].equals(player)))
                horizontalWin = false;
            if(!board[j][i].equals(player))
                verticalWin = false;
            if(!(horizontalWin || verticalWin))
                break;
        }
        if(horizontalWin || verticalWin)
            return true;
    }

    // If there was a N-in-a-row on the rows or columns
    // the method would have returned by now, so we're
    // going to check the diagonals

    // Check for N-in-a-row on both the diagonals
    boolean diagonalWinOne = true, diagonalWinTwo = true;
    for(int n = 0; n < board.length; n++){
        diagonalWinOne = true;
        diagonalWinTwo = true;
        int row = board.length - 1 - n;
        if(!board[n][n].equals(player))
            diagonalWinOne = false;
        if(!board[row][n].equals(player))
            diagonalWinTwo = false;
        if(!(diagonalOne || diagonalTwo))
            break;
    }

    // If either one of the diagonals has N-in-a-row, then there a winner
    if(diagonalWinOne || diagonalWinTwo)
        return true;
    // Otherwise, no one has won yet
    else
        return false;   
} 
+1

, , tic-tac-toc. String

  • 2D-,
  • String, .
  • 1 9, .
  • , , String

, :
 6. 2d. , -:

String[][] winningCombo = ... initialization ...
for( int i = 0 ; i < winningCombo.length; i++){
    for(j = 0; j < winningCombo[i].length; j ++){
        char c1 = winningCombo[i][j].charAt(0);
        char c2 = winningCombo[i][j].charAt(1);
        char c3 = winningCombo[i][j].charAt(2);
        if(currentPlayerString.contains(c1) && currentPlayerString.contains(c2) && currentPlayerString.contains(c3)){
            // currentPlayer has won if he has all the 3 positions of a winning combo
        }
    }
}  

, , . Swing GridLayout JPanel.

0

, :

import java.util.Scanner;

public class TTT {

private String[][] board;
private Scanner console;
private int size;

public TTT(String[][] table, Scanner console, int size) {
    this.board = table;
    this.console = console;
    this.size = size;
}

public void makeTable() {
    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i].length; j++) {
            board[i][j] = "_";
        }
    }
}

public void printTable() {
    System.out.print(" ");
    for (int i = 0; i < board.length; i++) {
        System.out.print(" " + i);
    }
    System.out.println();
    for (int i = 0; i < board.length; i++) {
        System.out.print(i + "│");
        for (int j = 0; j < board[i].length; j++) {
            System.out.print(board[i][j] + "│");
        }
        System.out.println();
    }
}

public void play(Scanner console) {
    int turn = 0;
    String player = "_";
    makeTable();
    printTable();
    while (turn != 9) {
        int x = console.nextInt();
        int y = console.nextInt();

        while (x >= board.length || y >= board[1].length) {
            System.out.println("Out of bounce, try again!!!");
            x = console.nextInt();
            y = console.nextInt();
        }

        while (board[y][x] != "_") {
            System.out.println("Occupied, try again!!!");
            x = console.nextInt();
            y = console.nextInt();
        }

        if (turn % 2 == 0) {
            player = "X";
        } else {
            player = "O";
        }
        board[y][x] = player;
        turn++;
        printTable();
        if(check()){
            System.out.println("Player "+player+" won!");
            break;
        }
    }
}
public boolean check(){
    //check diagonals
    if(check00ToNN()){
        return true;
    }
    if(check0NToN0()){
        return true;
    }
    for(int i = 0 ; i< size ; i++){

        if(checkCol(i)){
            return true;
        }
        if(checkRow(i)){
            return true;
        }
    }
    return false;

}

public boolean checkRow(int index){

    for(int i = 1 ; i< size ; i++){
        if(board[i-1][index]!=board[i][index]||board[i][index]=="_"){
            return false;
        }
    }
    return true;


    }
public boolean checkCol(int index){
    for(int i = 1 ; i< size ; i++){
        if(board[index][i-1]!=board[index][i]||board[index][i]=="_"){
            return false;
        }
    }
    return true;


    }
public boolean check00ToNN(){
    for(int i = 1 ; i< size ; i++){

            if(board[i-1][i-1]!=board[i][i]||board[i][i]=="_"){
                return false;

        }
    }
    return true;
    }

public boolean check0NToN0(){ //diagonal
    for(int i = 1 ; i< size ; i++){

            if(board[i-1][size-i-1]!=board[i][size-i]||board[i][size-i]=="_"){
                return false;
            }

    }
    return true;
    }




public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    int size = 3;
    String[][] board = new String[size][size];
    TTT ttt = new TTT(board, console,size);
    ttt.play(console);
}

}

, , , , , .

check() checkmethods.

i size, .

0

( ) , 8.

, . , 2D-

static final class WinCombos {

    /* 3 combos shown are
     *
     * X X X
     *
     * X
     *   X
     *     X
     *
     * and
     *
     * X
     * X
     * X
     *
     */

    int[][][] positions = {
        { {0, 0}, {0, 1}, {0, 2} },
        { {0, 0}, {1, 1}, {2, 2} },
        { {0, 0}, {1, 0}, {2, 0} },
        { {....}, {....}, {....} }
    };
}

, , . , .

, , , :

boolean xWon = false;
boolean oWon = false;

for (int[][] combo : WinCombos.positions) {
    xWon = oWon = true;

    for (int[] coord : combo) {

        if (!"X".equals(board[coord[0]][coord[1]])) {
            xWon = false;
        }

        if (!"O".equals(board[coord[0]][coord[1]])) {
            oWon = false;
        }
    }

    // if all three coordinates were either X or O
    // otherwise xWon/oWon would have been set to false

    if (oWon || xWon) break;
}

if (xWon) {
    System.out.println("X won!");
} else if (oWon) {
    System.out.println("O won!");
}

Now, if you want the board to resize, you need to reset the winning coordinates every time the board size changes. Tic-tac-toe will be relatively simple, because winning combinations should always be the length of the board.

So you need some loops:

public final class WinCombos {

    public int[][][] positions;

    static {
        findCombos(3);
    }

    public static final void findCombos(int blen) {

        int combos = blen * 2 + 2;
        positions = new int[combos][blen][];

        for (int i = 0; i < blen; i++) {
            for (int k = 0; k < blen; k++) {

                positions[i][k] = new int[] { i, k };
                positions[i + blen][k] = new int[] { k, i };

            }
        }

        // now diagonals

        for (int i = blen - 2; i < blen; i++) {
            for (int k = 0; k < blen; k++) {

                positions[i][k] = new int[] { k, k };

            }
        }
    }
}

And you go there. I have not tested this.

0
source

All Articles