带有For循环优胜者的TicTacToe代码...为什么找不到优胜者?

时间:2019-04-24 07:05:15

标签: java arrays function class multidimensional-array

    //I have been working on this code for the past week on and off... the main issue I have been having is finding a winner without listing down all the possibilities...

    //THIS IS MY METHODS CLASS
    import java.util.Scanner;
    import java.util.Arrays;

    public class TicTacToe1 {
        private String Player1Name;
        private String Player2Name;
        private char Pl1Choice;
        private char pl2Choice;
        private int row;
        private int column;
        private char board[][] = new char[4][4];

        public TicTacToe1() {

        }

        public TicTacToe1(String name1, String name2, char choice1, char choice2, int r, int c, char b[][]) {
            this.Player1Name = name1;
            this.Player2Name = name2;
            this.Pl1Choice = choice1;
            this.pl2Choice = choice2;
            this.row = r;
            this.column = c;
            this.board = b;
        }

        public void PlayerInfo(String name1, String name2, char choice1, char choice2) {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter The Name Of Player-1");
            this.Player1Name = sc.nextLine();
            System.out.println("\nEnter The Name Of Player-2");
            this.Player2Name = sc.nextLine();
        }// PlayerInfo Method

        public void InitializeBoard() {
            for (int l = 1; l < board.length; l++) {
                for (int g = 1; g < board[l].length; g++) {
                    board[l][g] = '*';
                }
            }
            System.out.println();
            System.out.println("--------------");
            for (int i = 1; i < board.length; i++) {
                for (int j = 1; j < board[i].length; j++) {
                    System.out.print("  ");
                    System.out.print(board[i][j] + "| ");
                }
                System.out.println();
                System.out.print("--------------");
                System.out.println();
            }
        }

    public void PrintBoard() {
    System.out.println();
    System.out.println("--------------");
    for (int i = 1; i < board.length; i++) {
    for (int j = 1; j < board[i].length; j++) {
        System.out.print("  ");
        System.out.print(board[i][j] + "| ");
        }
        System.out.println();
        System.out.print("--------------");
        System.out.println();
        }
        }

        public char WhoPlaysFirst() {
        Scanner sc = new Scanner(System.in);
        char secondplayer = ' ';
        while (true) {
            System.out.println("\nWho Would Like To Go First???");
            System.out.println(this.Player1Name + " - 1");
            System.out.println(this.Player2Name + " - 2");
            char firstplayer = sc.next().charAt(0);
            if (firstplayer == '1' || firstplayer == '2') {
                if (firstplayer == '1') {
                    return firstplayer = '1';
                } else if (firstplayer == '2') {
                    return firstplayer = '2';
                }
            } else {
                System.out.println("Enter A Valid Option Pls");
                continue;
            }
        }
        }
        public Boolean IsElementExist() {
        if (board[this.row][this.column] == '*') {
            if (board[this.row][this.column] == 'X' || board[this.row][this.column] == '0')
                return true;
            else
                return false;
        }
        return true;
    }
        public void AddElement1() {
        Scanner sc = new Scanner(System.in);
        boolean check;
        while (true) {
            System.out.println(this.Player1Name + " Plays...");
            System.out.println("\nEnter The Row You Would Like To Enter The Element");
            this.row = sc.nextInt();
            System.out.println("\nEnter The Column You Would Like To Enter The Element");
            this.column = sc.nextInt();
            if (this.row >= 1 && this.row <= 3) {
                if (this.column >= 1 && this.column <= 3) {
                    check = true;
                    break;
                }
            } else {
                System.out.println("Pls Enter Values Within The Board Size");
                System.out.println("\nEnter The Row You Would Like To Enter The Element");
                this.row = sc.nextInt();
                System.out.println("\nEnter The Column You Would Like To Enter The Element");
                this.column = sc.nextInt();
                continue;
            }
        }
        while (true) {
            boolean poscheck = true;
            if (board[this.row][this.column] == '*') {
                board[this.row][this.column] = 'X';
                break;
            } else if (board[this.row][this.column] == 'X' || board[this.row][this.column] == '0') {
            poscheck = false;
            }
            if (poscheck)
                break;
            else {
                System.out.println("This Spot Is Already Filled... Try Another Position Pls!")
                continue;
                }
            }
        }// AddElement1

        public void AddElement2() {
            Scanner sc = new Scanner(System.in);
            boolean check;
            while (true) {
                System.out.println(this.Player2Name + " Plays...");
                System.out.println("\nEnter The Row You Would Like To Enter The Element");
                this.row = sc.nextInt();
                System.out.println("\nEnter The Column You Would Like To Enter The Element");
                this.column = sc.nextInt();
                if (this.row >= 1 && this.row <= 3) {
                    if (this.column >= 1 && this.column <= 3) {
                        check = true;
                        break;
                    }
                } else {
                    System.out.println("Pls Enter Values Within The Board Size");
                    continue;
                }
            }
            board[this.row][this.column] = '0';
        }

        public Boolean HorizontalWin() {
            boolean won = false;
            /*
             * for (int i = 1; i < 4; i++) { if (board[i][1] == board[i][2] && board[i][2]
             * == board[i][3]) { won = true; break; } else continue; }
             */
            char start;
            for (int i = 1; i < board.length - 1 && !won; i++) {
                start = board[i][1];
                if (start != '*') {
                    for (int j = 2; j < board[i].length - 1; j++) {
                        if (board[i][j] != '*')
                            if (board[i][j] == start && board[i][j + 1] == start) {
                                won = true;
                                System.out.println("Horizontal");
                                break;
                            } else {
                                won = false;
                            }
                    }
                }
            }
            return won;
        }// HorizontalWin

        public Boolean VerticalWin() {
            boolean won = false;
            char start;
            for (int i = 1; i < board.length - 1 && !won; i++) {
                start = board[1][i];
                if (start != '*') {
                    for (int j = 2; j < board[i].length - 1; j++) {
                        if (board[j][i] != '*')
                            if (board[j][i] == start && board[j + 1][i] == start) {
                                won = true;
                                System.out.println("Vertical");
                                break;
                            } else {
                                won = false;
                            }
                    }
                }
            }

            /*
             * for (int i = 1; i < 4; i++) { if (board[1][i] == board[2][i] && board[2][i]
             * == board[3][i]) { won = true; break; } else continue; }
             */
            return won;
        }// VerticalWin

        public Boolean DiagnolWin() {
            boolean won = false;
            char start;
            for (int i = 1; i < board.length - 1 && !won; i++) {
                start = board[1][1];
                if (start != '*')
                    if (board[i][i] != '*')
                        if (board[2][2] == start && board[3][3] == start) {
                            won = true;
                            // System.out.println("check");
                        } else
                            won = false;
            }
            for (int j = 1; j < board.length - 1 && !won; j++) {
                start = board[3][1];
                if (start != '*')
                    if (board[j][board.length - j - 1] != '*')
                        if (board[2][2] == start && board[1][3] == start) {
                            won = true;
                            System.out.println("check");
                        } else
                            won = false;
            }
            return won;
        }// DiagnolWin

        public boolean winner() {
            return (VerticalWin() || HorizontalWin() || DiagnolWin());
        }

    }// class

public class TicTacToe2 {//MAIN CLASS WHERE I CALL MY METHODS.
    public static void main(String[] args) {
        TicTacToe1 obj = new TicTacToe1();
        int counter = 1; int i = 1;
        boolean check = false;
        obj.PlayerInfo(null, null, ' ', ' ');
        obj.InitializeBoard();
        if (obj.WhoPlaysFirst()=='1')
        {
            while (i < 6)
            {
                obj.AddElement1();
                obj.PrintBoard();
                if (i >= 3)
                {
                    if (obj.winner())
                    {
                        check = true;
                        System.out.println("Winner");
                        break;
                    }
                    else
                        check = false;
                }
                obj.AddElement2();
                obj.PrintBoard();
                if (i >= 3)
                {
                    if (obj.winner())
                    {
                        check = true;
                        //System.out.println("Winner");
                        break;
                    }
                    else
                        check = false;
                }
                i++;
            }
        }
            else if (obj.WhoPlaysFirst()=='2')
            {
                while (i <= 9)
                {
                    obj.AddElement2();
                    obj.PrintBoard();
                    if (i >= 3)
                    {
                        if (obj.winner())
                        {
                            check = true;
                            break;
                        }
                        else
                            check = false;
                    }
                    obj.AddElement1();
                    obj.PrintBoard();
                    if (i >= 3)
                    {
                        if (obj.winner())
                        {
                            check = true;
                            break;
                        }
                        else
                            check = false;
                    }
                    i++;
                }

            }
        if (check) System.out.println("Game Over!");
        else
            System.out.println("It Is A Draw");

/ * //这是我无法获得的输出... 输入玩家1的名字 阿德南

输入Player-2的名称 汗


* | * | * |

* | * | * |

* | * | * |

谁想先走??? 阿德南-1 汗-2 1个 Adnan播放...

输入要输入元素的行 2

输入您要输入元素的列 2


* | * | * |

* | X | * |

* | * | * |

汗戏...

输入要输入元素的行 3

输入您要输入元素的列 1


* | * | * |

* | X | * |

0 | * | * |

Adnan播放...

输入要输入元素的行 1

输入您要输入元素的列 2


* | X | * |

* | X | * |

0 | * | * |

汗戏...

输入要输入元素的行 3

输入您要输入元素的列 2


* | X | * |

* | X | * |

0 | 0 | * |

Adnan播放...

输入要输入元素的行 1

输入您要输入元素的列 1


X | X | * |

* | X | * |

0 | 0 | * |

汗戏...

输入要输入元素的行 3

输入您要输入元素的列 3


X | X | * |

* | X | * |

0 | 0 | 0 |

Adnan播放...

输入要输入元素的行* /

2 个答案:

答案 0 :(得分:0)

尽管可以进行很多更改和优化,例如使用实际的0索引3 x 3板矩阵,而不是像现在使用的4 x 4那样,或更有效地使用for循环,不会涉及太多细节,只关注您当前的问题。

要解决您的问题,请在- 1HorizontalWin()方法的外部循环中删除VerticalWin()

for (int i = 1; i < board.length - 1 && !won; i++) {
                                 ^^^
                                 // This should be removed so it becomes:

for (int i = 1; i < board.length && !won; i++) {

然后您的winner()方法应该可以正常工作,并且游戏应该按预期完成,如this slightly modified code of yours to make it work online所示。

使用- 1时,您在[1, 4-1)范围内(从13进行循环,因此实际上只是迭代i=1和{{1 }})。通过删除i=2,您可以根据需要循环迭代- 1i=1i=2

答案 1 :(得分:0)

一种无循环检查获胜条件的简单方法是将行,列或对角线与由3个X或3 0组成的数组进行比较。如果您有更多的行和列,它的伸缩性就不好,但是对于一个井字游戏的问题,其中长度固定为3,就可以了。

private char[] xs = new char[] {'X', 'X', 'X'};
private char[] os = new char[] {'0', '0', '0'};

public boolean HorizontalWin() {
    char[] row1 = new char[] {board[1][1], board[1][2], board[1][3]};
    char[] row2 = new char[] {board[2][1], board[2][2], board[2][3]};
    char[] row3 = new char[] {board[3][1], board[3][2], board[3][3]};

    return Arrays.equals(row1, xs) || Arrays.equals(row1, os)
        || Arrays.equals(row2, xs) || Arrays.equals(row2, os)
        || Arrays.equals(row3, xs) || Arrays.equals(row3, os);

}// HorizontalWin

public boolean VerticalWin() {
    char[] col1 = new char[] {board[1][1], board[2][1], board[3][1]};
    char[] col2 = new char[] {board[1][2], board[2][2], board[3][2]};
    char[] col3 = new char[] {board[1][3], board[2][3], board[3][3]};

    return Arrays.equals(col1, xs) || Arrays.equals(col1, os)
        || Arrays.equals(col2, xs) || Arrays.equals(col2, os)
        || Arrays.equals(col3, xs) || Arrays.equals(col3, os);
}// VerticalWin

public boolean DiagnolWin() {
    char[] diag1 = new char[] {board[1][1], board[2][2], board[3][3]};
    char[] diag2 = new char[] {board[1][3], board[2][2], board[3][1]};

    return Arrays.equals(diag1, xs) || Arrays.equals(diag1, os)
        || Arrays.equals(diag2, xs) || Arrays.equals(diag2, os);
}// DiagnolWin

注释:

1-您应该使用3x3数组而不是4x4。拥有第一个空行和列很容易出错。起初我没有注意到,对循环有点困惑

2-Java约定是写以小写开头的方法名称,即horizontalWinverticalWindiagonalWin

3-没有意义返回Boolean,最好使用原始形式boolean