Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in

Sequence

Hangman

Core exercise

The secret word is hard-coded (for example “JAVA”). The player suggests letters; the right ones are revealed at all their positions. Six mistakes are allowed.

Goals: Arrays and strings, loops, membership tests, partial display of the word.

Features

  • etat(char[] mot, boolean[] decouvert) returns the word with _ in place of the letters not yet found.
  • devoiler(char[] mot, boolean[] decouvert, char lettre) uncovers all the occurrences and returns how many there are.
  • gagne(boolean[] decouvert) returns true when everything is uncovered.

Steps

  1. Represent the state: a char[] for the word, a boolean[] for the letters found.
  2. etat(...) then afficherEtat(...), which prints it.
  3. proposerLettre(Scanner sc) → read a letter, checking that there is only one.
  4. Update the state; otherwise increment the mistake counter.
  5. Victory: all letters uncovered (the check looks for the word “Gagne”, French for “won”, in the final message). Defeat: mistakes ≥ 6.

Criteria: Handling repeated letters, readable display, correct end of game.

A workshop goes here: you write and run code in it. It requires JavaScript.

Starting code

Pendu.java

import java.util.Scanner;

public class Pendu {

    public static String etat(char[] mot, boolean[] decouvert) {
        // TODO : les lettres trouvees, un _ pour les autres
        return "";
    }

    public static int devoiler(char[] mot, boolean[] decouvert, char lettre) {
        // TODO : decouvrir TOUTES les occurrences, renvoyer combien
        return 0;
    }

    public static boolean gagne(boolean[] decouvert) {
        // TODO : vrai si tout est decouvert
        return false;
    }

    public static void jouer(Scanner sc, String motSecret) {
        char[] mot = motSecret.toCharArray();
        boolean[] decouvert = new boolean[mot.length];
        // TODO : boucle de jeu, 6 erreurs autorisees
    }
}

Exercices.java

import java.util.Scanner;

public class Exercices {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Pendu.jouer(sc, "java");
        sc.close();
    }
}

The core exercise is validated in the workshop, which requires JavaScript.

Hint 1

The repeated-letter trap: in “JAVA”, suggesting A must reveal both As. So go through the whole array at each suggestion, without stopping at the first one found.

Extensions

  • A list of words and a random draw.
  • Prevent suggesting a letter that has already been tried (with a Set<Character>).