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

131 lines
3.1 KiB
Java
Raw Permalink Normal View History

2023-06-20 19:05:21 +00:00
package allumettes;
/**
* Lance une partie du jeu des allumettes en fonction des arguments fournis sur
* la ligne de commande.
*
* @author Xavier Crégut
* @version $Revision: 1.5$
*/
public class Jouer {
/**
* Lancer une partie. En argument sont donnés les deux joueurs sous la forme
* nom@stratégie.
*
* @param args la description des deux joueurs
*/
public static void main(String[] args) {
Joueur j1 = null;
Joueur j2 = null;
Arbitre arbitre = null;
Jeu game = null;
try {
verifierNombreArguments(args);
if (args.length > 2) {
j1 = parsePlayer(args[1]);
j2 = parsePlayer(args[2]);
} else {
j1 = parsePlayer(args[0]);
j2 = parsePlayer(args[1]);
}
arbitre = new Arbitre(j1, j2);
arbitre.setConfiant(args[0].equals("-confiant"));
game = new Partie();
} catch (ConfigurationException e) {
System.out.println("\nErreur : " + e.getMessage());
afficherUsage();
System.exit(1);
}
try {
while (game.getNombreAllumettes() > 0) {
arbitre.arbitrer(game);
}
arbitre.afficherGagnant();
} finally {
System.exit(0);
}
}
/**
* Créer un joueur à partir d'une chaine de caractères.
*
* @param arg chaine de caractère permettant de créer le joueur
* @throws ConfigurationException si le joueur ne peut pas être créé
*/
private static Joueur parsePlayer(String arg) throws ConfigurationException {
String[] pre = arg.split("@");
if (pre.length != 2) {
throw new ConfigurationException("Configuration d'un joueur invalide");
}
String nom = pre[0];
Strategie strat;
switch (pre[1].toLowerCase()) {
case "naif":
strat = new Naif();
break;
case "rapide":
strat = new Rapide();
break;
case "expert":
strat = new Expert();
break;
case "humain":
strat = new Humain();
break;
case "lente":
strat = new Lente();
break;
case "tricheur":
strat = new Tricheur();
break;
default:
throw new ConfigurationException(String.format("Stratégie de %s invalide", nom));
}
return new Joueur(nom, strat);
}
/**
* Vérifier si le nombre d'arguments fournis dans la ligne de commande est
* cohérent.
*
* @param args arguments de la ligne de commande
* @throws ConfigurationException si les argument ne sont pas correctes
*/
private static void verifierNombreArguments(String[] args) throws ConfigurationException {
final int nbJoueurs = 2;
if (args.length < nbJoueurs) {
throw new ConfigurationException("Trop peu d'arguments : " + args.length);
}
if (args.length > nbJoueurs + 1) {
throw new ConfigurationException("Trop d'arguments : " + args.length);
}
}
/**
* Afficher des indications sur la manière d'exécuter cette classe.
*/
public static void afficherUsage() {
System.out.println("\n"
+ "Usage :"
+ "\n\t" + "java allumettes.Jouer joueur1 joueur2"
+ "\n\t\t" + "joueur est de la forme nom@stratégie"
+ "\n\t\t" + "strategie = naif | rapide | expert | humain | tricheur | lente"
+ "\n\n\t" + "Exemple :"
+ "\n\t\t" + "java allumettes.Jouer Xavier@humain Ordinateur@naif"
+ "\n");
}
}