Tableau Java-Player de la classe


Ce que je dois faire, c'est pouvoir appeler le tableau de joueurs dans ma classe view, imprimer dont c'est le tour et leur score. Lorsque leur tour est terminé, passez au joueur suivant et imprimez le score des joueurs. Quand il revient au tour du joueur 1, il ramène leur score total et ajoute à cela.

Le but final: Player et Die class sont un tableau. Mes méthodes de dé et de notation sont plutôt bonnes. C'est le jeu de la cupidité/farkle. 1 joueur lance 6 dé, et obtient un score basé sur de ceux-ci. Le dé inutilisé/unscored est ensuite roulé. À la fin du tour des joueurs, nous devons imprimer leur score de tour et leur score total. Passez au joueur suivant et recommencez. Quand un certain joueur atteint un certain score, le jeu est terminé et cette personne est le gagnant.

Maintenant je n'ai qu'une instruction if qui parcourt 4 joueurs. Ce n'est pas l'objectif. J'ai besoin d'obtenir la classe player dans un tableau, et d'utiliser cette classe pour parcourir les joueurs, et éventuellement l'utiliser pour rapportez leur score de jeu.

public class Player {

/** player id */
private int id;

/** player name */
private String name;

/** player's score in the game */
private int gameScore;  

/**
 * Constructs a new Player with the specified id.
 * 
 * @param id player's id
 */
public Player(int id) {
    this.id = id;
}

/**
 * Returns the id of player.
 * 
 * @return player's id
 */
public int getId() {
    return id;
}

/**
 * Returns the name of player.
 * 
 * @return player's name
 */
public String getName() {
    return name;
}

/**
 * Sets the name of player using the given parameter value.
 * 
 * @param name value used to set the name of player
 */
public void setName(String name) {
    this.name = name;
}

/**
 * Returns the player's score in the game.
 * 
 * @return player's score in the game
 */
public int getGameScore() {
    return gameScore;
}

/**
 * Sets the game score of a player.
 * 
 * @param score value used to set the game score of player
 */
public void setGameScore(int score) {
    this.gameScore = score;
}

/**
 * Returns a String representing a player.
 * 
 * @return string form of this player
 */
public String toString() {
    return id + "";
}

}

public class Die {

/** maximum face value */
private static final int MAX = 6;

/** current value showing on the die */
private int faceValue;

/**
 * Constructs a Die instance with a face value of 1.
 */
public Die() {
    faceValue = 1;
}

/**
 * Computes a new face value for this die and returns the result.
 * 
 * @return face value of die
 */
public int roll() {
    faceValue = (int) (Math.random() * MAX) + 1;
    return faceValue;
}

/**
 * Sets the face value of the die.
 * 
 * @param value an int indicating the face value of the die
 */
public void setFaceValue(int value) {
    if (value > 0 && value <= MAX) {
        faceValue = value;
    }
}

/**
 * Returns the face value of the die.
 * 
 * @return the face value
 */
public int getFaceValue() {
    return faceValue;
}

}

import java.util.*;

import model.Die;
import model.Player;
import model.GreedGame;

public class GreedCLI {

private int whoInt;
private int farkleScore;
private Player playerClass;
private GreedGame farkle;
private Scanner scan = new Scanner(System.in);
private final int max = 4;
private final int min = 2;
private final int minStarter = 1;
private final int minScore = 1000;
private final int maxScore = 10000;
int toWin, totalPlayers, player;
public GreedCLI() {
    startUp();
    gameOn();
}

public void startUp() {
    System.out.println("Welcome to Farkle! \n \n");

    totalPlayers = getPlayerTotal("Please enter total number of player (2-4): ");
    toWin = getScoreTotal("Please enter total points needed to win: ");
    player = getStartPlayer();

    System.out.println("\nGood Luck!\n");
    farkle = new GreedGame(totalPlayers, player, toWin);
}

private int getStartPlayer() {
    int who;
    while (true) {
        try {
            System.out.print("Which player will start the game(1-"
                    + totalPlayers + ")?: ");
            who = Integer.parseInt(scan.nextLine());

            if (who < minStarter || who > totalPlayers) {
                System.out.println("Error - values outside parameter.");
            } else {
                break;
            }
        } catch (InputMismatchException ex) {
            scan.next();
            System.out.println("Error - input must be an integer value.");
        }
    }
    return who;
}

private int getPlayerTotal(String enter) {
    int playerTotal;
    while (true) {
        try {
            System.out.print(enter + "");
            playerTotal = Integer.parseInt(scan.nextLine());
            if (playerTotal < min || playerTotal > max) {
                System.out.println("Error - values outside parameter.");
            } else {
                break;
            }
        } catch (InputMismatchException ex) {
            scan.next();
            System.out.println("Error - input must be an integer value.");
        }
    }
    return playerTotal;
}

private int getScoreTotal(String enter) {
    int scoreTotal;
    while (true) {
        try {
            System.out.print(enter + "");
            scoreTotal = Integer.parseInt(scan.nextLine());
            if (scoreTotal < minScore || scoreTotal > maxScore) {
                System.out.println("Error - values outside parameter.");
            } else {
                break;
            }
        } catch (InputMismatchException ex) {
            scan.next();
            System.out.println("Error - input must be an integer value.");
        }
    }
    return scoreTotal;
}

//  public int scoreTotal() {
//      int playerScore = playerClass.getGameScore() + farkleScore;
//      return playerScore;
//  }

private void gameOn() {
    boolean over = false;
    boolean endTurn = false;
    String answer;
    char answerChar = 'Y';

    String roll;

    System.out.println("Player " + farkle.getPlayers() + "'s turn!");

    while (!over) {

        while (!endTurn) {
            roll = farkle.toString();
            farkleScore = farkle.score();
            System.out.println("Player " + farkle.getPlayers() + " rolls "
                    + roll + " worth " + farkleScore);

            if (farkleScore < 1) {
                System.out
                        .println("Sorry, you rolled a 0. Moving on to the next Player!");
                endTurn = true;
            }
            if (farkle.availableDie() < 1) {
                System.out
                        .println("Sorry, you are out of dice. Moving on to the next Player!");
                endTurn = true;
            }
            if (farkle.availableDie() > 1 && farkleScore > 1) {
                System.out
                        .print("Would you like to keep rolling? You have "
                                + farkle.availableDie()
                                + " die remaining (Y or N): ");
                answer = scan.nextLine().trim().toUpperCase();
                answerChar = answer.charAt(0);
                if (answerChar == 'N') {
                    endTurn = true;
                }
            }

        }
        while (endTurn) {
            System.out.println("\nNow it is the next player's turn.");
            farkle.passDie();
            farkle.nextPlayer();
            endTurn = false;
        }
    }
}

public static void main(String[] args) {
    new GreedCLI();
}

}

package model;

import java.util.*;

public class GreedGame {

/** int for total die remaining */
private int remainingDie = 6;

/** counts number of times number appears */
private int[] numFreq;

/** array for players */
private int players = 1;

/** call player class */
private Player playerFromClass;

/** array for die */
private int[] die;


private Player[] who;
private int whoInt;

/** total players */
private int totalPlayers;

/** starting player */
private int currentPlayer;

/** total number of points needed */
private int winningPoints;

/** calls player method to get turn */
private Player turn;

/** score for the turn */
private int turnScore = 0;

/** score for the turn */
private int totalScore;

/** string for the roll result for the toString */
private String rollResult;

/** calls class to roll the die */
Die dieRoll = new Die();


/*****************************************************************
 * Default constructor, sets the values of the instance variables
 * 
 * @param players
 *            and winning points pulled from CLI
 *****************************************************************/

public GreedGame(int totalPlayers, int firstPlayer, int winningPoints) {
    super();
    this.totalPlayers = totalPlayers;
    this.currentPlayer = firstPlayer;
    this.winningPoints = winningPoints;
}

public Player playerClass() {
    return playerFromClass;
}

public int getPlayers() {
    return players;
}

/*  private Player[] getStartPlayerClass() {
    for(int i = 0; i < totalPlayers; i++){
        i = this.currentPlayer++;
    }
    return who;
}*/

public void nextPlayer(){
    if(players < 1){
        players = 1;
    }
    else if(players < 4){
        players++;
    }
    else{
        players = 1;
    }
}

/*private int getStartPlayerInt(){
    whoInt = who.getId();
    return whoInt;
}*/

public Player getTurn(){
    return turn;
}

public void setPlayers(int players) {
    this.players = players;
}

/*****************************************************************
 * calculates remaining die
 *****************************************************************/

public int availableDie() {
    return this.remainingDie;
}

/*****************************************************************
 * boolean to passDie
 *****************************************************************/

public void passDie() {
    this.remainingDie = 6;
}

/*****************************************************************
 * array to roll the remaining dice
 *****************************************************************/

public int[] rollDie() {
    this.die = new int[this.remainingDie];

    for (int i = 0; i < this.die.length; i++) {
        this.die[i] = dieRoll.roll();
    }

    return this.die;
}

/*****************************************************************
 * toString for the cli to call, puts roll in string.
 *****************************************************************/

public String toString() {
    rollResult = Arrays.toString(rollDie());
    return rollResult;
}

/*****************************************************************
 * score method to add up total points and can be called elsewhere
 *****************************************************************/

public int score() {
    rollCheck();
    turnScore = 0;
    return straight() + threePairs() + sixOfAKind() + fiveOfAKind()
            + fourOfAKind() + threeOfAKind() + eachFive() + eachOne();
}

/*****************************************************************
 * array to roll the remaining dice
 *****************************************************************/

public int[] rollCheck() {
    availableDie();
    this.numFreq = new int[6];
    for (int i = 0; i < 6; i++) { // set to zero
        this.numFreq[i] = 0;
    }

    for (int i = 0; i < this.remainingDie; i++) {

        if (die[i] == 1) {
            numFreq[0] += 1;
        }
        if (die[i] == 2) {
            numFreq[1] += 1;
        }
        if (die[i] == 3) {
            numFreq[2] += 1;
        }
        if (die[i] == 4) {
            numFreq[3] += 1;
        }
        if (die[i] == 5) {
            numFreq[4] += 1;
        }
        if (die[i] == 6) {
            numFreq[5] += 1;
        }
    }
    return this.numFreq;
}

/*****************************************************************
 * scoring method for rolling a single or two 1's
 *****************************************************************/
private int eachOne() {

    if (straight() == 0 && sixOfAKind() == 0 && threePairs() == 0
            && this.numFreq[0] < 3) {
        if (this.numFreq[0] == 1) {
            turnScore = 100;
            this.remainingDie--;
            return turnScore;
        }else if (this.numFreq[0] == 2) {
            turnScore = 200;
            this.remainingDie -= 2;
            return turnScore;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

/*****************************************************************
 * scoring method for rolling a single or two 5's
 *****************************************************************/

private int eachFive() {

    if (straight() == 0 && sixOfAKind() == 0 && threePairs() == 0
            && this.numFreq[4] < 3) {
        if (this.numFreq[4] == 1) {
            turnScore = 50;
            this.remainingDie--;
            return turnScore;
        }else if (this.numFreq[4] == 2) {
            turnScore = 100;
            this.remainingDie -= 2;
            return turnScore;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

/*****************************************************************
 * scoring method for rolling 3 of a kind
 *****************************************************************/
private int threeOfAKind() {

    if (sixOfAKind() == 0 && fiveOfAKind() == 0 && fourOfAKind() == 0
            && straight() == 0) {
        if (this.numFreq[0] == 3) {
            turnScore += 1000;
            this.remainingDie -= 3;
            return turnScore;
        }
        if (this.numFreq[1] == 3) {
            turnScore += 200;
            this.remainingDie -= 3;
            return turnScore;
        }
        if (this.numFreq[2] == 3) {
            turnScore += 300;
            this.remainingDie -= 3;
            return turnScore;
        }
        if (this.numFreq[3] == 3) {
            turnScore += 400;
            this.remainingDie -= 3;
            return turnScore;
        }
        if (this.numFreq[4] == 3) {
            turnScore += 500;
            this.remainingDie -= 3;
            return turnScore;
        }
        if (this.numFreq[5] == 3) {
            turnScore += 600;
            this.remainingDie -= 3;
            return turnScore;
        } else {
            return 0;
        }
    } else {
        return 0;
    }

}

/*****************************************************************
 * scoring method for rolling four of a kind
 *****************************************************************/
private int fourOfAKind() {

    if (sixOfAKind() == 0 && fiveOfAKind() == 0 && straight() == 0) {
        if (this.numFreq[0] == 4) {
            turnScore += 2000;
            this.remainingDie -= 4;
            return turnScore;
        }
        if (this.numFreq[1] == 4) {
            turnScore += 400;
            this.remainingDie -= 4;
            return turnScore;
        }
        if (this.numFreq[2] == 4) {
            turnScore += 600;
            this.remainingDie -= 4;
            return turnScore;
        }
        if (this.numFreq[3] == 4) {
            turnScore += 800;
            this.remainingDie -= 4;
            return turnScore;
        }
        if (this.numFreq[4] == 4) {
            turnScore += 1000;
            this.remainingDie -= 4;
            return turnScore;
        }
        if (this.numFreq[5] == 4) {
            turnScore += 1200;
            this.remainingDie -= 4;
            return turnScore;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

/*****************************************************************
 * scoring method for rolling 5 of a kind
 *****************************************************************/
private int fiveOfAKind() {

    if (sixOfAKind() == 0 && straight() == 0) {
        if (this.numFreq[0] == 5) {
            turnScore += 4000;
            this.remainingDie -= 5;
            return turnScore;
        }
        if (this.numFreq[1] == 5) {
            turnScore += 800;
            this.remainingDie -= 5;
            return turnScore;
        }
        if (this.numFreq[2] == 5) {
            turnScore += 1200;
            this.remainingDie -= 5;
            return turnScore;
        }
        if (this.numFreq[3] == 5) {
            turnScore += 1600;
            this.remainingDie -= 5;
            return turnScore;
        }
        if (this.numFreq[4] == 5) {
            turnScore += 2000;
            this.remainingDie -= 5;
            return turnScore;
        }
        if (this.numFreq[5] == 5) {
            turnScore += 2400;
            this.remainingDie -= 5;
            return turnScore;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

/*****************************************************************
 * scoring method for rolling 6 of a kind
 *****************************************************************/
private int sixOfAKind() {

    if (this.numFreq[0] == 6) {
        turnScore += 8000;
        this.remainingDie -= 6;
        return turnScore;
    }
    if (this.numFreq[1] == 6) {
        turnScore += 1600;
        this.remainingDie -= 6;
        return turnScore;
    }
    if (this.numFreq[2] == 6) {
        turnScore += 2400;
        this.remainingDie -= 6;
        return turnScore;
    }
    if (this.numFreq[3] == 6) {
        turnScore += 3200;
        this.remainingDie -= 6;
        return turnScore;
    }
    if (this.numFreq[4] == 6) {
        turnScore += 4000;
        this.remainingDie -= 6;
        return turnScore;
    }
    if (this.numFreq[5] == 6) {
        turnScore += 4800;
        this.remainingDie -= 6;
        return turnScore;
    } else {
        return 0;
    }
}

/*****************************************************************
 * scoring method for rolling 3 pairs
 *****************************************************************/
private int threePairs() {
    int pairs = 0;
    if (this.numFreq[0] == 2) {
        pairs++;
    }
    if (this.numFreq[1] == 2) {
        pairs++;
    }
    if (this.numFreq[2] == 2) {
        pairs++;
    }
    if (this.numFreq[3] == 2) {
        pairs++;
    }
    if (this.numFreq[4] == 2) {
        pairs++;
    }
    if (this.numFreq[5] == 2) {
        pairs++;
    }
    if (pairs == 3) {
        turnScore += 800;
        this.remainingDie -= 6;
        return turnScore;
    } else {
        return 0;
    }
}

/*****************************************************************
 * scoring method for rolling a straight
 *****************************************************************/
private int straight() {
    if (this.numFreq[0] == 1 && this.numFreq[1] == 1
            && this.numFreq[2] == 1 && this.numFreq[3] == 1
            && this.numFreq[4] == 1 && this.numFreq[5] == 1) {
        turnScore += 1200;
        this.remainingDie -= 6;
        return turnScore;
    } else {
        return 0;
    }
}

}

Author: Enormosaurus, 2013-06-12

2 answers

J'ai du mal à comprendre ce que vous essayez de faire, Alors corrigez-moi si ce n'est pas ce dont vous avez besoin, mais pour faire un tableau de type Player de taille n vous feriez quelque chose comme ce qui suit

Player[] playerArray = new Player[n];

for(int i=0; i<playerArray.length; i++)
{
    // If you need your player id to be different than i just say so in the comments
    playerArray[i] = new Player(i);
}

Et c'est à peu près tout.

Je soupçonne sournoisement que vos exigences sont un peu plus complexes que cela, mais Il est difficile de dire exactement ce que vous demandez, donc si vous avez besoin de quelque chose de différent, dites-le.

 0
Author: Sam I am, 2013-06-11 20:37:02

Donc, si je vous comprends bien, vous voulez que l'application attende jusqu'à ce qu'un joueur fasse un mouvement, puis passe au joueur suivant?

Vous devrez écrire un événement playerMoved. Lorsque cet événement se produit, vous augmentez manuellement votre index et attendez que le joueur suivant fasse un mouvement.

 0
Author: Michaël Benjamin Saerens, 2013-06-11 20:37:51