2015-11-04 2 views
1

Im пытается создать улучшенную игру свиньи, где пользователь может катить пользователя, введенное количество кубиков. если все брошенные кубики были одним, тогда вы теряете свои банковские баллы, если из них один, вы не получаете очков, а ваш банк в безопасности. в противном случае вы получаете банковские баллы, которые вы прокатили. Я пытаюсь пройти через очередь, чтобы каждый игрок мог по очереди, но он просто зацикляет одного и того же человека в очереди, спрашивая, сколько костей игрок хочет катить, а затем получает результат и заканчивается. Что я здесь делаю неправильно?Очередь не зацикливается и заканчивается раньше?

Также здесь токовый выход консоли:

enter image description here

import java.util.Scanner; 
import java.util.stream.IntStream; 
import javax.lang.model.element.Element; 
import java.util.LinkedList; 
import java.util.Queue; 
import java.util.Random; 

public class EnhancedGameOfPig { 
    static int count; 

    static int roll() { 
     return (int) (6.0 * Math.random()) + 1; 
    } 

    public static void play() { 

     Scanner sc = new Scanner(System.in); 
     Queue<Player> myQueue = new LinkedList<Player>(); 
     System.out.println("How many players are there? (2-10 Max)"); 
     int numOfPlayers = sc.nextInt(); 
     sc.nextLine(); 
     for (int i =0; i < numOfPlayers; i++) { // creates specified number of 
                // players and adds 
                // them to a queue 
      System.out.println("What is your name player " + (i+1) + "?"); 
      String playerName = sc.nextLine(); 
      Player player = new Player(playerName, 0); 
      myQueue.add(player); 
     } 

     System.out.println("How many points would you like to play to, to win?"); // sets 
                        // the 
                        // number 
                        // of 
                        // points 
                        // required 
                        // to 
                        // win 
                        // the 
                        // game 
     int maxPoints = sc.nextInt(); 
     sc.nextLine(); 

     for (Player e : myQueue) { 
      System.out.println("How many dice would you like to roll " + myQueue.peek().getPlayerName() + " ?"); 
      int numofDice = sc.nextInt(); 
      sc.nextLine(); 
      int[] diceArray = new int[numofDice]; // creates an array to hold 
                // values of each dice roll 
      for (int i = 0; i <= numofDice-1; i++) { 
       diceArray[i] = roll(); // rolls dice and adds dice roll values 
             // to array 
       if (diceArray[i] == 1) { 
        count++; 
       } 
      } 
      int first = diceArray[0]; // looks at first value of array 
      for (int element : diceArray) { 
       if (element == first && first == 1) { // checks to see if all 
                 // rolls were 1's 
        System.out.println("All of the dice you rolled were ones! You loose all your banked points!"); 
        myQueue.peek().setBankedPoints(0); 
        break; 
       } 

      } 
      if (count == 1) { 
       System.out.println("You rolled a one, so you don't get any points. Sorry!"); 
      } else { 
       int sum = IntStream.of(diceArray).sum(); 
       System.out.println(sum + " points have been added to your bank!"); 
       myQueue.peek().bankedPoints += sum; 
      } 
     } 
    } 
} 
+1

В вашем for-each цикле 'for (Player e: myQueue)' change 'myQueue.peek(). GetPlayerName()' to 'e.getPlayerName()', ваш цикл for корректно перебирает через 'myQueue' один раз до того, как ваш 'main' метод будет завершен – phflack

ответ

3

Ваш контроль цикл перебирает каждый игрок в очереди.

for (Player e : myQueue) { 

Но на протяжении всего тела цикла вашего относятся только к первому игроку в очереди, с myQueue.peek(). Например:

System.out.println("How many dice would you like to roll " 
    + myQueue.peek().getPlayerName() + " ?"); 

peek() метод возвращает первый игрок в очереди, но вы пытаетесь повлиять на игрока e. Вы можете решить эту проблему, используя e вместо myQueue.peek(), по всему телу.

+0

, что было бы более подходящим вызовом метода. im new to quees sorry heh –

+0

Если вы хотите обратиться к игроку 'e', вам не нужен вызов метода. У вас уже есть ссылка на этого игрока - это 'e'. –

+0

так e.peek() или myQueue.e? –

Смежные вопросы