-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayer.java
More file actions
113 lines (96 loc) · 3.16 KB
/
Copy pathPlayer.java
File metadata and controls
113 lines (96 loc) · 3.16 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
/*
* Player.java - blueprint class for objects that represent a single
* human player in the game of Battleship.
*
* Computer Science 111, Boston University
*/
import java.util.*;
public class Player {
private String name;
private Ship[] fleet;
private int numShips;
/*
* constructor for a Player with the specified name
*/
public Player(String name) {
if (name == null || name.equals("")) {
throw new IllegalArgumentException("name must have at least one character");
}
this.name = name;
this.fleet = new Ship[BattleshipGame.SHIPS_PER_PLAYER];
this.numShips = 0;
}
/*
* getName - returns the name of the player
*/
public String getName() {
return this.name;
}
/*
* addShip - add the specified ship to the player's collection of ships
*/
public void addShip(Ship s) {
if (s == null) {
throw new IllegalArgumentException("parameter must be non-null");
}
if (this.numShips == this.fleet.length) {
throw new IllegalArgumentException("no more room");
}
this.fleet[this.numShips] = s;
this.numShips++;
}
/*
* removeShip - removes the specified ship from the player's collection of ships
*/
public void removeShip(Ship s) {
if (s == null) {
throw new IllegalArgumentException("parameter must be non-null");
}
for(int i = 0; i < this.numShips; i++) {
if(s.getType().equals(fleet[i].getType())) {
this.fleet[i] = this.fleet[this.numShips - 1];
this.fleet[this.numShips - 1] = null;
this.numShips--;
return;
}
}
}
/*
* printShips - prints whatever ships remain in the player's collection
*/
public void printShips() {
for(int i = 0; i < this.numShips; i++) {
System.out.println(fleet[i]);
}
}
/*
* hasLost - has this player lost the game?
* Returns true if this is the case, and false otherwise.
*/
public boolean hasLost() {
return (numShips == 0);
}
/*
* nextGuess - returns a Guess object representing the player's
* next guess for the location of a ship on the board specified
* by the parameter otherBoard.
*/
public Guess nextGuess(Scanner console, Board otherBoard) {
int row;
int col;
// Keep randomly selecting coordinates until we get
// a position that has not already been tried.
do {
row = Board.RAND.nextInt(otherBoard.getDimension());
col = Board.RAND.nextInt(otherBoard.getDimension());
} while (otherBoard.hasBeenTried(row, col));
Guess guess = new Guess(row, col);
return guess;
}
/*
* toString - returns a string representation of the player
*/
public String toString() {
return this.name;
}
}