Java >> Tutoriel Java >  >> Java

Créer un jeu de pendu en Java à l'aide de code simple

Qu'est-ce que le jeu du pendu ?

Hangman est un jeu classique de devinettes de lettres dans lequel vous devez deviner le mot représenté par une série de tirets. Le joueur a un nombre limité de suppositions pour identifier le mot. Le jeu peut être personnalisé facilement en modifiant la valeur des variables.

Programme Java Hangman utilisant Array

//Java program for Hangman game with array

//Importing the java package
import java.util.Scanner;
import java.util.Random;
import java.util.LinkedList;
import java.net.*;
import java.io.*;

//Main class of the program
public class Main{
    //Printing the user's guessed character
    public static void printArray(char[] array){
        for(int i =0; i < array.length; i++){
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

    public static boolean isTheWordGuessed(char[] array){
        for(int i =0; i < array.length; i++){
            if(array[i] == '_') {return false;}
        }
        return true;
    }

    //Main Class of the program
    public static void main(String[] args){
        //Creating the object of scanner class
        Scanner scanner = new Scanner(System.in);
        //Creating the object of random class
        Random random = new Random();
        //Array of available strings
        String[] guesses = {"stechies","tutorial","programming","google","facebook","sap"};

        boolean weArePlaying = true;
        //Checking with user that Are we still in the play
        while(weArePlaying){
            System.out.println("Welcome to my game of Hangman");
            char[] randomWordToGuess = guesses[random.nextInt(guesses.length)].toCharArray();

            int amountofGuesses = randomWordToGuess.length;
            char[] playerGuess = new char[amountofGuesses];

            for(int i = 0; i < playerGuess.length; i++){
                playerGuess[i] = '_';
            }

            boolean wordIsGuessed = false;
            int tries = 0;
            //Loop will till the number of guesses will not
            // equals to the available amount of guesses
            while( !wordIsGuessed && tries != amountofGuesses ){
                System.out.print("Current guesses : ");
                printArray(playerGuess);
                //Giving information to the user how many guesses are available
                System.out.printf("You have %d tries left.n", amountofGuesses - tries);
                //Telling user what to enter
                System.out.println("Enter a single character : ");
                char input = scanner.nextLine().charAt(0);
                //Increasing the tries counter
                tries++;

                if(input == '-'){
                    weArePlaying = false;
                    wordIsGuessed = true;
                }else{

                    for(int i = 0; i < randomWordToGuess.length; i++){
                        if(randomWordToGuess[i] == input) {
                            playerGuess[i] = input;
                        }
                    }

                    if(isTheWordGuessed(playerGuess)){
                        wordIsGuessed = true;
System.out.println("nn**************************nCongratulations you won!n**************************");
                    }

                }
            }
            //If loop if user out of moves
            if(!wordIsGuessed) System.out.println("You ran out of guesses :/");
            //Asking user if user wants to continue the game
            System.out.print("nDo you want to play another game? (y/n) : ");
            String anotherGame = scanner.nextLine();
            if(anotherGame.equals("n")) weArePlaying = false;
        }
        System.out.println("Game Over");
    }
} 

Sortie

Welcome to my game of Hangman
Current guesses : _ _ _ _ _ _ _ _
You have 8 tries left.
Enter a single character :
b
Current guesses : _ _ _ _ b _ _ _
You have 7 tries left.
Enter a single character :
o
Current guesses : _ _ _ _ b o o _
You have 6 tries left.
Enter a single character :
f
Current guesses : f _ _ _ b o o _
You have 5 tries left.
Enter a single character :
a
Current guesses : f a _ _ b o o _
You have 4 tries left.
Enter a single character :
k
Current guesses : f a _ _ b o o k
You have 3 tries left.
Enter a single character :
c
Current guesses : f a c _ b o o k
You have 2 tries left.
Enter a single character :
e


**************************
Congratulations you won!
**************************

Do you want to play another game? (y/n) : n
Game Over 

Programme Java Hangman sans tableau

//Java program for Hanman Game {Without Array}

//Importing the Scanner Class of util package for Input
import java.util.Scanner;
    //Main Class of the program
    public class Main {
        //Global Variable Start
        private static Scanner scanner = new Scanner(System.in);
        private static String word;
        private static String hiddenWord;
        private static boolean winner = false;
        //Global Variable Ends

        //Main Function of the program
        public static void main(String[] args) {

            System.out.print("Enter a word to guess: ");
            //Taking  secret word as input from user
            word = scanner.nextLine();
            //Converting word into `Question (?)` Mark
            hiddenWord = wordToQuestionMarks(word);
            System.out.println("Hangman Word is Set\n\n");

            int amountofGuesses = word.length();
            int tries = 0;
            //Loop will run till you are winner / you are out of moves
            while (!winner && tries != amountofGuesses) {
                guessLetter();
                tries++;
            }

            if(!winner)
            {
                System.out.println("Oh! You ran out of guesses");
            }else{
                System.out.println("Congrats! You won");
            }
        }

        //Function to convert string
        private static String wordToQuestionMarks(String word) {
            return word.replaceAll(".", "?");
        }

        //Taking guess character input from user
        private static void guessLetter() {
            System.out.println("Hidden Word: " + hiddenWord);

            System.out.print("Guess a letter: ");
            String letterChoice = scanner.nextLine();

            int found = 0;

            if (hasLetter(letterChoice)) {
                found = updateGameState(letterChoice);
            }

            System.out.println("You found " + found + " " + letterChoice + "\n");
            gameOver();
        }

        //Updating the game states
        private static int updateGameState(String letter) {
            int found = 0;

            for(int i=0; i< word.length(); i++) {
                if (word.charAt(i) == letter.charAt(0)) {
                    String prev = hiddenWord.substring(0,i).concat(letter);
                    hiddenWord = prev.concat(hiddenWord.substring(i+1));
                    found++;
                }
            }

            return found;
        }

        private static void gameOver() {
            if (!hiddenWord.contains("?")) {
                winner = true;
            }
        }

        private static boolean hasLetter(String letter) {
            if (word.contains(letter)) {
                return true;
            }
            else {
                return false;
            }
        }

    } 

Sortie

Enter a word to guess: stechies
Hangman Word is Set

Hidden Word: ????????
Guess a letter: s
You found 2 s

Hidden Word: s??????s
Guess a letter: t
You found 1 t

Hidden Word: st?????s
Guess a letter: h
You found 1 h

Hidden Word: st??h??s
Guess a letter: e
You found 2 e

Hidden Word: ste?h?es
Guess a letter: i
You found 1 i

Hidden Word: ste?hies
Guess a letter: c
You found 1 c

Congrats! You won


Balise Java