2016-12-19 1 views
-3

어떤 플레이어가 움직이는지를 확인하는 while/while 루프를 만들려고합니다. 지금은 for 루프에서 어떤 플레이가 움직이는 지 확인합니다. 내 코드를 좀 더 명확하고 간결하게 만들려고 노력하고있다.네 명의 게임을 연결하는 플레이어의 움직임을 확인하려면 어떻게합니까?

public static void main(String[] args) { 


      try (Scanner input = new Scanner(System.in)) { 
       int height = 6, width = 8, moves = height * width; 
       ConnectFour board = new ConnectFour(width, height); 
       System.out.println("Use 0-" + (width - 1) + " to choose a column."); 
       System.out.println(board); 



       for (int player = 0; moves-- > 0; player = 1 - player) { // Here is where i check to see who plays 
        char symbol = players[player]; 
        board.chooseAndDrop(symbol, input); 
        System.out.println(board); 
        if (board.isWinningPlay()) { 
         System.out.println("Player " + symbol + " wins!"); 
         return; 
        } 
       } 
       System.out.println("Game over, no winner."); 
      } 


     } 

내가의 라인을 따라 더 생각 : : 아래

    int playerNb = 0; 
        while (thegamestarted) 
        { 
         if (playerNb == 0) 
          // Get user input 
         else 
          // Get second player input 

         // Process the input 
         // Change playerNb to 1 or 0 
        } 

전체 코드입니다 : 여기에 주요 방법이다

import java.util.Arrays; 
    import java.util.Scanner; 
    import java.util.stream.Collectors; 
    import java.util.stream.IntStream; 

    public class ConnectFour { 
     private static final char[] players = new char[] { 'X', 'O' }; 

     private final int width, height; 
     private final char[][] grid; 
     private int lastCol = -1, lastTop = -1; 

     public ConnectFour(int width, int height) { 
      this.width = width; 
      this.height = height; 
      this.grid = new char[height][]; 
      for (int h = 0; h < height; h++) { 
       Arrays.fill(this.grid[h] = new char[width], '.'); 
      } 
     } 

     public String toString() { 
      return IntStream.range(0, this.width) 
          .mapToObj(Integer::toString) 
          .collect(Collectors.joining()) + "\n" + 
        Arrays.stream(this.grid) 
         .map(String::new) 
         .collect(Collectors.joining("\n")); 
     } 

     /** 
     * Prompts the user for a column, repeating until a valid 
     * choice is made. 
     */ 
     public void chooseAndDrop(char symbol, Scanner input) { 
      do { 
       System.out.print("\nPlayer " + symbol + " turn: "); 
       int col = input.nextInt(); 

       if (! (0 <= col && col < this.width)) { 
        System.out.println("Column must be between 0 and " + 
             (this.width - 1)); 
        continue; 
       } 
       for (int h = this.height - 1; h >= 0; h--) { 
        if (this.grid[h][col] == '.') { 
         this.grid[this.lastTop=h][this.lastCol=col] = symbol; 
         return; 
        } 
       } 

       System.out.println("Column " + col + " is full."); 
      } while (true); 
     } 

     /** 
     * Detects whether the last chip played was a winning move. 
     */ 
     public boolean isWinningPlay() { 
      if (this.lastCol == -1) { 
       throw new IllegalStateException("No move has been made yet"); 
      } 
      char sym = this.grid[this.lastTop][this.lastCol]; 
      String streak = String.format("%c%c%c%c", sym, sym, sym, sym); 
      return contains(this.horizontal(), streak) || 
        contains(this.vertical(), streak) || 
        contains(this.slashDiagonal(), streak) || 
        contains(this.backslashDiagonal(), streak); 
     } 

     /** 
     * The contents of the row containing the last played chip. 
     */ 
     private String horizontal() { 
      return new String(this.grid[this.lastTop]); 
     } 

     /** 
     * The contents of the column containing the last played chip. 
     */ 
     private String vertical() { 
      StringBuilder sb = new StringBuilder(this.height); 
      for (int h = 0; h < this.height; h++) { 
       sb.append(this.grid[h][this.lastCol]); 
      } 
      return sb.toString(); 
     } 

     /** 
     * The contents of the "/" diagonal containing the last played chip 
     * (coordinates have a constant sum). 
     */ 
     private String slashDiagonal() { 
      StringBuilder sb = new StringBuilder(this.height); 
      for (int h = 0; h < this.height; h++) { 
       int w = this.lastCol + this.lastTop - h; 
       if (0 <= w && w < this.width) { 
        sb.append(this.grid[h][w]); 
       } 
      } 
      return sb.toString(); 
     } 

     /** 
     * The contents of the "\" diagonal containing the last played chip 
     * (coordinates have a constant difference). 
     */ 
     private String backslashDiagonal() { 
      StringBuilder sb = new StringBuilder(this.height); 
      for (int h = 0; h < this.height; h++) { 
       int w = this.lastCol - this.lastTop + h; 
       if (0 <= w && w < this.width) { 
        sb.append(this.grid[h][w]); 
       } 
      } 
      return sb.toString(); 
     } 

     private static boolean contains(String haystack, String needle) { 
      return haystack.indexOf(needle) >= 0; 
     } 

     public static void main(String[] args) { 
      try (Scanner input = new Scanner(System.in)) { 
       int height = 6, width = 8, moves = height * width; 
       ConnectFour board = new ConnectFour(width, height); 
       System.out.println("Use 0-" + (width - 1) + " to choose a column."); 
       System.out.println(board); 

       for (int player = 0; moves-- > 0; player = 1 - player) { 
        char symbol = players[player]; 
        board.chooseAndDrop(symbol, input); 
        System.out.println(board); 
        if (board.isWinningPlay()) { 
         System.out.println("Player " + symbol + " wins!"); 
         return; 
        } 
       } 
       System.out.println("Game over, no winner."); 
      } 
     } 
    } 
+3

무엇이 문제입니까? 디버거에서 이것을 실행 했습니까? 그 결과는 무엇입니까? 작동 했나요? 그렇지 않은 경우 행동이 귀하의 기대치에서 벗어나는 곳을 파악할 수 있습니까? –

답변

2

그 어려운 비트가 무엇을 말할 수는 자신의 코드에서 원하는 것이지만 플레이어가 무엇인지 추적하는 가장 간단한 방법은 회전 수를 추적하고 모듈러스 함수로 짝수 또는 홀수인지 확인하는 것입니다

이것은 간단한 수학으로 차례가 무엇인지 알 수있는 방법을 보여주기위한 간단한 코드입니다. 당신은 자신의 필요에 맞게 적응해야 할 것입니다. 턴 번호에 2를 나눈 짝수 턴에만 "플레이어 2"의 턴이 남음을 볼 수 있습니다. 모든 이동 후에 턴을 증가시키는 것을 잊지 마십시오.

"좋은"대답은 없습니다. 당신은 코드를 작성한 사람이고, 누구의 순서인지 결정할 수 있습니다. 코드를 추적하면됩니다.

int turn = 1; 

for () { 
    if (turn % 2 == 0) { 
     System.out.println("Player 2"); 
    } else { 
     System.out.println("Player 1"); 
    } 
    turn++; 
} 
+0

안녕하세요, 귀하의 회신에 감사드립니다. 누구 차례인지 확인하려고 노력 중입니다. 플레이어 1이면 플레이어 1이 움직입니다. 플레이어 2라면 플레이어 2가 움직입니다. –

+0

당신은 그것이 무엇인지를 추적하고 있습니다. "예"숫자 대신 "이동"을 사용하기 위해 나의 예를 외삽 할 수 있습니다. "1로 이동"이 항상 1 번 플레이어에게 속한 경우 이동을 알면 누가 재생 중인지 항상 알아야합니다. – mstorkson

관련 문제