-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
127 lines (103 loc) · 3.47 KB
/
Copy pathMain.java
File metadata and controls
127 lines (103 loc) · 3.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
String filePath = "words.txt";
ArrayList<String> carNames = new ArrayList<>();
try(BufferedReader reader = new BufferedReader(new FileReader(filePath))){
String line;
while((line = reader.readLine()) != null){
carNames.add(line.trim());
}
}
catch(FileNotFoundException e){
System.out.println("Could not find file");
}
catch(IOException e){
System.out.println("Something went wrong");
}
Random random = new Random();
Scanner scanner = new Scanner(System.in);
String carName = carNames.get(random.nextInt(carNames.size()));
String word = carName;
ArrayList<Character> wordState = new ArrayList<>();
int wrongGuesses = 0;
for(int i = 0; i < word.length(); i++){
wordState.add('_');
}
System.out.println("-----------------------");
System.out.println("Welcome to HangMan Game");
System.out.println("-----------------------");
while(wrongGuesses < 6){
System.out.print(getHangmanArt(wrongGuesses));
System.out.print("Word: ");
for(char c: wordState){
System.out.print(c + " ");
}
System.out.println();
System.out.print("Guess a letter: ");
char guess = scanner.next().toLowerCase().charAt(0);
if(word.indexOf(guess) >= 0){
System.out.println("Correct Guess!");
for(int i = 0; i < word.length(); i++){
if(word.charAt(i) == guess){
wordState.set(i, guess);
}
}
if(!wordState.contains('_')){
System.out.println(getHangmanArt(wrongGuesses));
System.out.println("YOU WON!");
System.out.println("The word was: " + word);
break;
}
}
else{
wrongGuesses++;
System.out.println("Wrong guess!");
}
}
if(wrongGuesses >= 6){
System.out.print(getHangmanArt(wrongGuesses));
System.out.println("GAME OVER!");
System.out.println("The word was: " + word);
}
scanner.close();
}
static String getHangmanArt(int wrongGuesses){
return switch(wrongGuesses){
case 0 -> """
""";
case 1 -> """
O
""";
case 2 -> """
O
|
""";
case 3 -> """
O
/|
""";
case 4 -> """
O
/|\\
""";
case 5 -> """
O
/|\\
/
""";
case 6 -> """
O
/|\\
/ \\
""";
default -> "";
};
}
}