-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBattleshipsGame.java
107 lines (88 loc) · 2.03 KB
/
BattleshipsGame.java
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
/*
Written by: Maeve Carr
Date:
Desc:
Filename:
*/
/////NO COMMENTS - FIGURE IT OUT
import java.util.*;
public class BattleshipsGame
{
private BattleshipCell[][] grid;
private int lives;
private int hits;
private int noOfShips;
public BattleshipsGame() {
grid = new BattleshipCell[4][4];
initGrid();
lives = 7;
setNoOfShips(6);
}
public BattleshipsGame(int livesIn, int shipsIn) {
grid = new BattleshipCell[4][4];
initGrid();
lives = livesIn;
setNoOfShips(shipsIn);
}
public void initGrid() {
for(int r = 0; r < 4; r++)
for(int c = 0; c < 4; c++)
grid[r][c] = new BattleshipCell();
}
//this is only for testing
public void showGrid() {
for(int r = 0; r < 4; r++)
{
for(int c = 0; c < 4; c++)
System.out.print(grid[r][c] +" ");
System.out.println();
}
}
public void setNoOfShips(int noOfShips) {
Random noGen = new Random();
int count = 0;
do
{
int r = noGen.nextInt(4);
int c = noGen.nextInt(4);
if(!checkIfShip(r, c))
{
grid[r][c].setToShip();
count++;
}
}while(count < noOfShips);
}
public boolean checkIfShip(int r, int c)
{
return grid[r][c].isShip();
}
public int getLives()
{
return lives;
}
public int getHits()
{
return hits;
}
public String shoot(int r, int c)
{
String s;
if(grid[r][c].isHit())
s = "Already chosen";
else
{
if(grid[r][c].isShip())
{
s = "HIT!";//Changed 'ship sunk' because they're spaceships
hits++;
}
else
{
s = "Miss!";
lives--;
}
grid[r][c].setToHit();
}
return s;
}
}//end class