2015-06-27 66 views
3

我正在嘗試製作一個簡單的井字遊戲Java遊戲,我即將完成,但我的程序沒有聲明一個贏家,也沒有聲明遊戲是否是平局即使在我的代碼中,我告訴它要聲明一個勝利者。在java中的基本井字遊戲腳本

這裏是我的代碼:

import java.util.*; 

public class TicTacToe { 

/** 
* @param args the command line arguments 
*/ 
public static int row, colm; 
public static char board[][] = new char [3][4]; 
public static Scanner console = new Scanner(System.in); 
public static char turn = 'X'; 

public static void main(String[] args) { 
    for(int i = 0; i < 3; i++) { 
     for(int j = 0; j < 4; j++){ 
      board[i][j] = '_'; 
     } 
    } 

    board(); 
    play(); 
    winner(row,colm); 
} 

public static void board() { 
    for(int i = 0; i < 3; i++) { 
     for(int j = 0; j < 4; j++) { 
      if(j == 0) { 
       System.out.print("|"); 
      } else { 
       System.out.print(board[i][j]+"|"); 
      } 

     } 
     System.out.println(); 
    } 
} 

public static void play() { 
    boolean playing = true; 
    while(playing) { 
     row = console.nextInt(); 
     colm = console.nextInt(); 
     board[row][colm] = turn; 
     if(winner(row,colm)) { 
      playing = false; 
      System.out.print("you win"); 
     } 
     board(); 
     if(turn == 'X') { 
      System.out.println("Player 2 your O"); 
      turn = 'O'; 
     } else 
      turn='X'; 
    } 
} 

public static boolean winner(int move1, int move2) { 
    if(board[0][move2] == board[1][move2] && board[0][move2] == board[2][move2]) 
     return true; 
    if(board[move1][0] == board[move1][1] && board[move1][0] == board[move1][2]) 
     return true; 
    if(board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[1][1] != '_') 
     return true; 
    if(board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[1][1] != '_') 
     return true; 
    return false; 
} 
+0

缺少'冠軍'功能的大括號 – CrakC

+0

在我的代碼中,我已經有了它,它仍然不起作用。 –

+0

至少讓代碼更具可讀性 – Pavel

回答

1

如果這樣做了,那麼turn都會有錯誤的值有人贏得了之後,你想在main來顯示它,這裏的更正:

public static void main(String[] args) { 
    ... 
    board(); 
    play(); 
    // remove winner(row,colm); it isn't doing anything here 
    // turn has the right value of the winner here if play() is modified 
} 

public static void play() { 
    // remove boolean playing = true; it is not needed 
    for (;;) { // I call it the 'forever', but you can also write while(true) 
     ... 
     board[row][colm] = turn; 
     board(); // move up unless you don't want to display the board on wins 
     if (winner(row,colm)) { 
      System.out.print(turn + " you win"); 
      return; // (or break) <-- otherwise turn has the wrong value in main 
     } 
     ... 
    } 
} 
+0

順便說一句。贏家()函數是正確的。 – maraca

+0

感謝您的幫助 –

+0

@AtifShah歡迎您,謝謝接受。 – maraca