-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFight.java
More file actions
84 lines (68 loc) · 2.22 KB
/
Fight.java
File metadata and controls
84 lines (68 loc) · 2.22 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
import java.util.Random;
/**
* Class to represent a fight between two characters.
*
* @author Thomas Vakili
* @version 2013.12.15
*/
public class Fight {
private static final int N_COMBATANTS = 2;
private Character[] combatant;
private Character winner;
private Random rand;
public Fight(Character combatant1, Character combatant2) {
combatant = new Character[]{combatant1, combatant2};
rand = new Random();
}
/**
* Main loop of the fight.
*/
public void start() {
int round;
for (round = 1; winner == null; round++) {
printRoundInfo(round);
// Randomly select who gets to start
int firstIndex = rand.nextInt(N_COMBATANTS);
Character first = combatant[firstIndex];
Character second = combatant[firstIndex == 0 ? 1 : 0];
round(first, second);
}
winner.battleOver();
Character loser = (winner == combatant[0] ?
combatant[1] : combatant[0]);
loser.die();
}
/**
* Run a round.
*/
private void round(Character first, Character second) {
Action firstAction = first.getAction(second);
executeAction(first, firstAction);
if (winner == null) {
Action secondAction = second.getAction(first);
executeAction(second, secondAction);
}
}
/**
* Execute the action chosen by the character.
*/
private void executeAction(Character combatant, Action action) {
Result result = action.execute();
System.out.println(result);
if (result.fightOver()) {
this.winner = result.getWinner();
}
}
/**
* Prints the round number and the combatants HPs
*/
private void printRoundInfo(int round) {
System.out.println("\n=============");
System.out.println("ROUND " + round);
System.out.println(combatant[0].getName() + ": "
+ combatant[0].getHP() + "HP");
System.out.println(combatant[1].getName() + ": "
+ combatant[1].getHP() + "HP");
System.out.println("=============");
}
}