Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in
Sequence
Rock-paper-scissors
Core exercise
Paper beats rock, rock beats scissors, scissors beats paper. The choices are coded as integers: 1 = rock (pierre), 2 = paper (papier), 3 = scissors (ciseaux).
Goals: Constants, switch, randomness, game loop.
Features
nomDuChoix(int choix)returns"pierre","papier"or"ciseaux".determinerVainqueur(int utilisateur, int ordinateur)returns1(user),-1(computer) or0(draw).- A game loop that plays again as long as the user wishes.
Steps
- Represent the choices by integers (1, 2, 3).
lireChoixUtilisateur(Scanner sc)→ an integer between 1 and 3, validation included.tirerChoixOrdinateur()withRandom.determinerVainqueur(u, o)→ the rule of the game, isolated.- The loop: play a round, print the result, offer to play again.
Criteria: Robust input, correct winning logic, readable code.
A workshop goes here: you write and run code in it. It requires JavaScript.
Starting code
Jeu.java
import java.util.Random;
import java.util.Scanner;
public class Jeu {
public static String nomDuChoix(int choix) {
// TODO : 1 = pierre, 2 = papier, 3 = ciseaux
return "";
}
public static int tirerChoixOrdinateur() {
// TODO : un entier entre 1 et 3
return 1;
}
public static int lireChoixUtilisateur(Scanner sc) {
// TODO : lire un entier entre 1 et 3, en redemandant si besoin
return 1;
}
public static int determinerVainqueur(int utilisateur, int ordinateur) {
// TODO : 1 = l'utilisateur gagne, -1 = l'ordinateur gagne, 0 = egalite
return 0;
}
}
Exercices.java
import java.util.Scanner;
public class Exercices {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int utilisateur = Jeu.lireChoixUtilisateur(sc);
int ordinateur = Jeu.tirerChoixOrdinateur();
System.out.println("Vous : " + Jeu.nomDuChoix(utilisateur));
System.out.println("Ordi : " + Jeu.nomDuChoix(ordinateur));
System.out.println("Resultat : " + Jeu.determinerVainqueur(utilisateur, ordinateur));
sc.close();
}
}
The core exercise is validated in the workshop, which requires JavaScript.
Hint 1
Arithmetic trick: with 1, 2, 3, the user wins exactly when (u - o + 3) % 3 == 1. If that looks obscure, write out the nine cases by hand first; the checks test them all.
Extensions
- Cumulative score (first to 3 wins).
- The “rock-paper-scissors-lizard-Spock” variant.