2016-10-06 6 views
-4

私は4つの方法で勝つ方法を見つける方法を理解していない、私は何を考えて、どのように接続four.Howで勝者を見つけることができます私はthem.Howを見つけるためにforループを使用する必要があります勝者を見つける方法を使用しますか?短いものの後My Connect 4のJavaコードで勝者を確認するにはどうすればよいですか?

import java.util.Scanner; 
public class Connect4{ 
    public static int[][] arrayboard(){ 
     int [][] board = new int[6][7]; 
     for (int i=0;i<board.length;i++){ 
      for(int j=0;j<board[i].length;j++){ 
       } 
      } 
      return board;  
     } 
    public static void printboard(int[][] board){ 
      int k=5; 
      for (int i = 0; i < board.length; i++) { 
       for (int j = 0; j < board[i].length; j++) { 
       System.out.print(board[i][j] + " "); 
       } 
      System.out.print("|"+k); 
      k--; 
      System.out.println(); 
      } 
      System.out.println("--------------+"); 
      System.out.println("0 1 2 3 4 5 6"); 
     } 
    public static void player1(int[][] board){ 
     System.out.print("player 1 type a column(0-6) or 9 to quit current game:"); 
     Scanner input = new Scanner(System.in); 
     int column=input.nextInt(); 
     for (int i=5;i>=0;i--){ 
      if(board[i][column]==0){ 
       board[i][column]=1; 
       break; 
      } 
      } 
     } 
    public static void player2 (int[][] board){ 
     System.out.print("player 2 type a column(0-6) or 9 to quit current game:"); 
     Scanner input = new Scanner(System.in); 
     int column=input.nextInt(); 
     for (int i=5;i>=0;i--){ 
      if (board[i][column]==0){ 
       board[i][column]=2; 
       break; 
      } 
     } 
    } 
    public static void main(String[] args) { 
     int [][] board=arrayboard(); 
      printboard(board); 
     boolean loop= true; 
       int count=0; 
     while(loop){ 
      if (count % 2 == 0) 
       player1(board); 
      else player2(board); 
      count++; 
      printboard(board); 
     } 
    } 
} 

答えて

0

次のコードをグーグルポップアップ表示: https://codereview.stackexchange.com/questions/100917/connect-four-game-in-javaまたはhttp://www.lazylab.org/152/java/connect-four-game-coding-puzzle-algorithm-in-java/またはConnect4 game with 2D arrays diagonal check

見つけることはその非常に簡単。 同じことをするScalaの実装もあります。だけにして、別の言語で:

  1. 水平方向(行):https://github.com/Green7izard/AP-ASE/blob/master/Scala/src/Day1.scala

    基本的に勝つために3つの方法があります。プレーヤーが4列に並んでいるかどうかを調べるために、すべてのボード[i]を確認します。ただし、アレイの端に注意してください。

  2. 垂直(列)。すべてのボード[currentRow] [i]を調べて、4つの「currentRow」が同じIが存在するかどうかを確認します。

最後のオプションは斜めです。これはあなたが確認すべき2方向もあるのでより難しいです。

これは、一度に完了を確認できないことを意味します。 しかし、あなたのようなすべての値をチェックする関数加えることができます。

public void int GetWinner() 
{ 
    int result = 0; 
    result= CheckHorizontal(); 
    if(result>0) return result; 
    result= CheckVertical(); 
    if(result>0) return result; 
    result= CheckDiagonalTopLeftBotRight(); 
    if(result>0) return result; 
    result= CheckDiagonalBotLeftTopRight(); 
    return result; 
} 

は、すべての移動後に実行し、結果が0でない場合は、あなたが勝者を持っているでしょうが! しかし、この偉業をプリフォームするにはより良い方法があります!

関連する問題