-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.java
More file actions
70 lines (60 loc) · 2.25 KB
/
Game.java
File metadata and controls
70 lines (60 loc) · 2.25 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
import java.util.Scanner;
public class Game {
private Guesser guesser;
private SecretKeeper secretKeeper;
private String secretCode;
private int maxAttempts;
private int attemptsLeft;
private Scanner scanner;
// class constructor
public Game (String[] args) {
this.scanner = new Scanner(System.in);
this.secretKeeper = new SecretKeeper(this, args);
this.guesser = new Guesser(scanner);
this.maxAttempts = secretKeeper.maxAttempts;
this.attemptsLeft = secretKeeper.attemptsLeft;
this.secretCode = secretKeeper.secretCode;
}
public void startGame() {
// Prompts to start game
if (maxAttempts == attemptsLeft) {
System.out.println("Will you find the secret code?");
System.out.println("---");
System.out.println("Round " + (maxAttempts - attemptsLeft));
}
// Play game; Guesser makes guess
// Game determines if guess is valid and wins, tracks Round, determins if loses
do {
String guess = guesser.makeGuess();
// System.out.println("GameLine28");
if (isValidGuess(guess)) {
String feedback = secretKeeper.provideFeedback(guess);
System.out.println(feedback);
attemptsLeft--;
if (guess.equals(secretCode)) {
System.out.println("Congrats! You did it!");
break;
}
if (attemptsLeft > 0) {
System.out.println("Round " + (maxAttempts - attemptsLeft));
}
} else {
System.out.println("Wrong Input!");
}
} while (attemptsLeft > 0);
// Womp womp womp . . . you lose
if (attemptsLeft == 0) {
System.out.println("Sorry, too many tries. The code was: " + secretCode);
}
scanner.close();
}
// Method to check if guess is four nums 0 - 8
public boolean isValidGuess(String guess) {
try {
int guessNum = Integer.valueOf(guess);
return guessNum >= 0 && guessNum <= 8888 && guess.length() == 4;
} catch (NumberFormatException e) {
return false;
}
}
}