【问题标题】:Tic Tac Toe Winner Checker Issue井字游戏获胜者检查器问题
【发布时间】:2019-11-10 22:28:39
【问题描述】:

我对编码和 Java 比较陌生,对于我的 CS-173 课程,我的任务是创建一个井字游戏。但是,在创建确定获胜者的方法时,每当我获得“胜利”时,代码都不会运行说我赢了。我确实有检查每种获胜方式的代码,但是,我从代码中提取了它以进行一些个人故障排除。另外,我为糟糕的代码道歉。

     public static void playGame(char[][] board, int size){
    Scanner input = new Scanner(System.in);

    int turn = 0;
    int spaces = board.length * board.length;
    boolean valid = false;
    boolean winner = false;

    for (int i = 0; i<spaces; i++){
      int startchecker = 3;
      int xcord = 0;
      int ycord = 0;

      do{      
        do{

          System.out.println("Player 1 please type your coordinates with a space");
            xcord = input.nextInt();
            ycord = input.nextInt();


           valid = isValid (board, xcord, ycord);

         if(i >= spaces){

         }   


        }while(!valid);      
          board[xcord][ycord] = 'X';
        printBoard(board);
         winner = isWinner(board);

        do{
            System.out.println("Player 2 please type your coordinates with a space");
            xcord = input.nextInt();
            ycord = input.nextInt();
             valid = isValid (board, xcord, ycord);

            winner = isWinner(board);

          }while(!valid);
         board[xcord][ycord] = 'O';
         printBoard(board);



        if(i >= spaces){
          winner = true;
          System.out.println("It is a tie!");


        } 
      }while(!winner);

      }
    }


    public static boolean isWinner (char[][] board){
     boolean determiner = false;
     int XCounter = 0;
     int OCounter = 0;
     int size = board.length-1;
     int winner = 3;


   //Check Horizontal
    for(int j = 0; j > size; j++){
         for(int i = 0; i > size; i++){
          if(board[i][j]=='X'){
               XCounter++;

              }
          else if(board[i][j]=='O'){
               OCounter++;

           }
             if(XCounter == winner){
                determiner = true;
                 System.out.println("Player 1 Wins!");
             }
              else if(OCounter == winner){
                System.out.println("Player 2 Wins!");
                determiner = true;
              }
          }
    }

    return determiner; 
    } 

【问题讨论】:

  • for(int j = 0; j &gt; size; j++){ 应该是&lt;?简单的调试(例如添加打印以查看正在执行的代码位)会在几秒钟内找到它。

标签: java tic-tac-toe


【解决方案1】:

您的isWinner 方法不会检查所有获胜方式。

为了清晰起见,我建议使用 2 个 for 循环(一个用于水平线,另一个用于垂直线),并使用 2 个 if 语句(循环之外)来检查对角线。

例如,

for(int i=0; i<size; i++){
    boolean flag = true; // Assume this line is a winning line
    for(int j=0; j<size; j++){ // Check each tile to see if it has a tile
        // Set the flag to false when it is not the tile you're looking for
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多