projet-court-programmation-.../allumettes/Arbitre.java

126 lines
3.5 KiB
Java
Raw Permalink Normal View History

2023-06-20 19:05:21 +00:00
package allumettes;
public class Arbitre {
// Attributs
/** Joueurs de la partie */
private Joueur j1;
private Joueur j2;
/** Joueur jouant actuellement */
private Joueur courant;
/** Détermine si l'arbitre vérifie la triche */
private Boolean confiant = false;
// Constructeurs
/**
* Construire un arbitre à partir de deux joueurs.
*
* @param j1 Joueur n°1
* @param j2 Joueur n°2
*/
public Arbitre(Joueur j1, Joueur j2) throws ConfigurationException {
if (j1 == null) {
throw new ConfigurationException("j1 n'existe pas");
} else if (j2 == null) {
throw new ConfigurationException("j2 n'existe pas");
} else {
this.j1 = j1;
this.j2 = j2;
this.courant = j1;
}
}
// GETS
/**
* Déterminer quel joueur ne joue pas actuellement.
*/
private Joueur getAutre() {
if (this.courant == j1) {
return this.j2;
} else {
return this.j1;
}
}
// SETs
public void setConfiant(Boolean confiant) {
this.confiant = confiant;
}
/**
* Permet de changer le joueur courant de la partie
*/
private void swapCourant() {
if (this.courant == this.j1) {
this.courant = this.j2;
} else {
this.courant = this.j1;
}
}
// Méthodes
/**
* Arbitrer un jeu d'allumettes.
*
* @param game Jeu que l'on arbitre
*/
public void arbitrer(Jeu game) {
while (true) {
int nbPrise;
System.out.format("Nombre d'allumettes restantes : %d\n", game.getNombreAllumettes());
try {
// le joueur choisit sont coup
if (this.confiant) {
nbPrise = this.courant.getPrise(game);
} else {
nbPrise = this.courant.getPrise(new PartieSafe(game));
}
// l'arbitre énonce le coup
if (nbPrise == 1 || nbPrise == 0 || nbPrise == -1) {
System.out.format("%s prend %d allumette.\n", this.courant.getNom(), nbPrise);
} else {
System.out.format("%s prend %d allumettes.\n", this.courant.getNom(), nbPrise);
}
// l'arbitre vérifie la validité du coup
if (nbPrise > game.getNombreAllumettes()) {
throw new CoupInvalideException(nbPrise, String.format("> %d", game.getNombreAllumettes()));
} else if (nbPrise > Jeu.PRISE_MAX) {
throw new CoupInvalideException(nbPrise, String.format("> %d", Jeu.PRISE_MAX));
} else {
game.retirer(nbPrise);
}
// l'arbitre passe la main
this.swapCourant();
System.out.println();
break;
} catch (OperationInterditeException e) {
System.out.format("Abandon de la partie car %s triche !\n", this.courant.getNom());
throw e;
} catch (CoupInvalideException e) {
System.out.format("Impossible ! %s\n\n", e.getMessage());
}
}
}
/**
* Déterminer le vainqueur en fin de partie.
*/
public void afficherGagnant() {
System.out.format("%s perd !\n", this.getAutre().getNom());
System.out.format("%s gagne !\n", this.courant.getNom());
}
}