Created
October 10, 2023 03:18
-
-
Save rebekah/67e73da0f8f3087fc34b2c9766f89c51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Scanner; | |
import java.util.Random; | |
public class HangMan { | |
final String[] words = { | |
"abandon", | |
"cabaret", | |
"eagerly", | |
"habitat", | |
"iceberg", | |
"labeled", | |
"rabbits", | |
"sabbath", | |
"ugliest", | |
"vacancy", | |
"vaccine", | |
"eager", | |
"faces", | |
"habit", | |
"labor", | |
"rabbi", | |
"wacky", | |
"yacht", | |
"babies", | |
"eagles" | |
}; | |
String[] randomWordArray; | |
String randomWord; | |
final String[] hangmanBodyParts = {" O \n", "/", "|", "\\\n", "/ ", "\\"}; | |
HangMan(){ | |
setWord(); | |
} | |
void setWord() { | |
int randomWordsIndex = new Random().nextInt(words.length); | |
randomWord = words[randomWordsIndex]; | |
randomWordArray = randomWord.split(""); | |
} | |
void showHangMan(int incorrectGuesses) { | |
for(int i = 0; i < incorrectGuesses; i++){ | |
System.out.print(hangmanBodyParts[i]); | |
} | |
System.out.println(""); | |
} | |
String underscoresToString(String[] underscores) { | |
return "\"" + String.join("", underscores) + "\""; | |
} | |
void playGame() { | |
String[] underscores = new String[randomWord.length()]; | |
Arrays.fill(underscores, "_"); | |
Scanner sc = new Scanner(System.in); | |
System.out.println(String.format( | |
"This is a game of HangMan. Please choose a letter for the hidden word: %s", | |
underscoresToString(underscores) | |
)); | |
int incorrectGuesses = 0; | |
while(sc.hasNext()){ | |
String guess = sc.next(); | |
boolean hasLetter = randomWord.indexOf(guess) != -1; | |
if(hasLetter) { | |
boolean winner = true; | |
for(int i = 0; i < underscores.length; i++) { | |
if (randomWordArray[i].equals(guess)) { | |
underscores[i] = guess; | |
} else if (underscores[i] == "_") { | |
winner = false; | |
} | |
} | |
if (winner) { | |
System.out.println( | |
"You won! Congratulations!!! The word is: " + underscoresToString(underscores) | |
); | |
break; | |
} else { | |
System.out.println(String.format( | |
"That guess was correct!\nHere is the word with your current correct guesses: %s.\nPlease enter your next guess.", | |
underscoresToString(underscores) | |
)); | |
} | |
} else { | |
incorrectGuesses++; | |
showHangMan(incorrectGuesses); | |
if(incorrectGuesses == hangmanBodyParts.length) { | |
System.out.println("Game Over. Thanks for playing!"); | |
break; | |
} else { | |
System.out.println("Please guess again."); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment