-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhangmanGame.java
More file actions
119 lines (113 loc) · 3.83 KB
/
hangmanGame.java
File metadata and controls
119 lines (113 loc) · 3.83 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
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class hangmanGame {
public static void main(String[]args)
{
ArrayList<String> words=new ArrayList<>();
String filepath="hangmanwords";
try(BufferedReader file=new BufferedReader(new FileReader(filepath))){
String line;
while((line=file.readLine())!=null)
{
words.add(line);
}
} catch (FileNotFoundException e) {
System.out.println("could not locate file location");
} catch (IOException e) {
System.out.println("Something went wrong");
} catch(IllegalArgumentException e)
{
System.out.print("Something went wrong");
}
Random rd=new Random();
String word=words.get(rd.nextInt(words.size()));
System.out.println(word);
int wrongguess=0;
//hangman game of guessing correct letters of word
Scanner sc = new Scanner(System.in);
ArrayList<Character> state= new ArrayList<>();
for(int i=0;i<word.length();i++)
{
state.add('_');
}
System.out.println("**********************************");
System.out.println("Welcome to java hangman game");
System.out.println("**********************************");
while(wrongguess<6)
{
System.out.println(hangman(wrongguess));
System.out.print("Word: ");
for(char c:state)
{
System.out.print(c+" ");
}
System.out.println();
System.out.print("Choose a letter : ");
char guess=sc.next().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) {
state.set(i, guess);
}
}
if(!state.contains('_')){
System.out.println(hangman(wrongguess));
System.out.println("You win!");
System.out.print("The word was "+word);
break;
}
}else{
wrongguess++;
System.out.println("Wrong guess");
}
}
if(wrongguess>=6)
{
System.out.println(hangman(wrongguess));
System.out.println("Game over!");
System.out.print("The word was "+word);
}
}
static String hangman(int wrongguess)
{
return switch(wrongguess)
{
case 0 -> """
0
""";
case 1 -> """
0
|
""";
case 2 -> """
0
/ |
""";
case 3 -> """
0
/ | \\
""";
case 4 -> """
0
/ | \\
/
""";
case 5 -> """
0
/ | \\
/ \\
""";
default ->"""
0
/ | \\
/ \\
""";
};
}
}