-
Notifications
You must be signed in to change notification settings - Fork 0
/
battleship.py
205 lines (183 loc) · 6.38 KB
/
battleship.py
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import random
class BattleShip:
def __init__(self, n):
self.boardSize = n
self.board = [[0 for i in range(n)] for j in range(n)]
self.probMap = [[0 for i in range(n)] for j in range(n)]
self.ships = {
"Destroyer": {"size": 2, "rep": "D"},
"Cruiser": {"size": 3, "rep": "C"},
"Submarine": {"size": 3, "rep": "S"},
"Battleship": {"size": 4, "rep": "B"},
"Aircraft Carrier": {"size": 5, "rep": "A"}
}
self.shipState = {
"D": 2,
"C": 3,
"S": 3,
"B": 4,
"A": 5
}
self.shipRep = {
"D": "Destroyer",
"C": "Cruiser",
"S": "Submarine",
"B": "Battleship",
"A": "Aircraft Carrier"
}
self.shipCount = 5
self.directions = ["d", "r"]
self.firstHitMade = False
def recalculateHitProbabilities(self):
self.probMap = [[0 for i in range(self.boardSize)] for j in range(self.boardSize)]
for i in range(self.boardSize):
for j in range(self.boardSize):
self.generateProbabilityValues(i, j)
for i in range(self.boardSize):
for j in range(self.boardSize):
if self.board[i][j] == "*":
self.updateHitProbabilty(i, j)
# self.displayProbMap()
def getNeighbors(self, x, y):
adj = [[1,0],[0,1],[-1,0],[0,-1]]
neighbors = []
for i,j in adj:
if self.isValidCoordinate(x+i, y+j) and self.board[x+i][y+j] not in {".","*"}:
neighbors.append([x+i, y+j])
return neighbors
def updateHitProbabilty(self, x, y):
for i,j in self.getNeighbors(x,y):
self.probMap[i][j]*=2
def canShipExist(self, shipSize, x, y, direction):
if direction == "r":
if y+shipSize <= self.boardSize:
if "." not in [self.board[x][i] for i in range(y, y+shipSize)]:
return True
return False
else:
if x+shipSize <= self.boardSize:
if "." not in [self.board[i][y] for i in range(x, x+shipSize)]:
return True
return False
def generateProbabilityValues(self, x, y):
for ship, values in self.ships.items():
# if ship already not destroyed
if self.shipState[values['rep']]:
# if ship placed downward
if self.canShipExist(values['size'], x, y, "r"):
for i in range(y, y+values['size']):
self.probMap[x][i]+=1
# if ship placed towards right
if self.canShipExist(values['size'], x, y, "d"):
for i in range(x, x+values['size']):
self.probMap[i][y]+=1
def getBestLocation(self):
location = [0,0]
maxProb = 0
for i in range(self.boardSize):
for j in range(self.boardSize):
if self.board[i][j] not in {".","*"} and self.probMap[i][j] > maxProb:
maxProb = self.probMap[i][j]
location = [i,j]
return location
def isValidCoordinate(self, x, y):
return 0 <= x < self.boardSize and 0 <= y < self.boardSize
# check if valid placement
def validPlacement(self, ship, x, y, direction):
shipSize = self.ships[ship]["size"]
if self.isValidCoordinate(x,y):
if direction == "d" and 0 <= x+shipSize <= self.boardSize:
if not any([self.board[i][y] for i in range(x, x+shipSize)]):
return True
elif direction == "r" and 0 <= y+shipSize <= self.boardSize:
if not any([self.board[x][i] for i in range(y, y+shipSize)]):
return True
return False
def place_ship(self, ship, x, y, direction):
shipSize = self.ships[ship]["size"]
shipRep = self.ships[ship]["rep"]
if direction == "d":
for i in range(x, x+shipSize):
self.board[i][y] = shipRep
else:
for i in range(y, y+shipSize):
self.board[x][i] = shipRep
def placeAllShipsHuman(self):
for ship, values in self.ships.items():
shipSize = values['size']
valid = False
while not valid:
print("Enter the co-ordinates in the format x,y,direction ('d' for down and 'r' for right) eg. (1,4,d)")
try:
x,y,direction = input("Enter co-ordinates and direction where you want to place the {} ({}): ".format(ship,shipSize)).split(",")
x = int(x)
y = int(y)
except:
print("Please enter input in correct format")
valid = False
else:
valid = self.validPlacement(ship, x, y, direction)
if valid:
self.place_ship(ship, x, y, direction)
else:
print("Location already occupied. Please try again.")
self.displayBoard()
def placeAllShipsComputer(self):
for ship, shipSize in self.ships.items():
valid = False
while not valid:
x = random.randint(0,self.boardSize-1)
y = random.randint(0,self.boardSize-1)
direction = self.directions[random.randint(0,1)]
valid = self.validPlacement(ship, x, y, direction)
if valid:
print("Placing {} at ({},{}) in direction {}".format(ship, x, y, direction))
self.place_ship(ship, x, y, direction)
self.displayBoard()
def hitTarget(self,x,y):
if self.isValidCoordinate(x,y):
if self.board[x][y] in self.shipRep:
print("It was a Hit at ({},{})!".format(x,y))
rep = self.board[x][y]
self.shipState[rep]-=1
if self.shipState[rep] == 0:
print("{} destroyed!".format(self.shipRep[rep]))
self.shipCount-=1
self.board[x][y] = "*"
if not self.firstHitMade:
self.firstHitMade = True
return True
elif self.board[x][y] == 0:
print("It was a Miss at ({},{})!".format(x,y))
self.board[x][y] = "."
return True
print("Please try again.")
return False
def displayBoard(self):
print(" ", end="")
for i in range(self.boardSize):
print(" {} ".format(i), end="")
print()
print(" ", end="")
print('-' * (self.boardSize*4+1))
for i, row in enumerate(self.board):
print("{} |".format(i), end=" ")
print(*row, sep=" | ", end="")
print(" |")
print(" ", end="")
print('-' * (self.boardSize*4+1))
def displayProbMap(self):
print(" ", end="")
for i in range(self.boardSize):
print(" {} ".format(i), end="")
print()
print(" ", end="")
print('-' * (self.boardSize*4+1))
for i, row in enumerate(self.probMap):
print("{} |".format(i), end=" ")
print(*row, sep=" | ", end="")
print(" |")
print(" ", end="")
print('-' * (self.boardSize*4+1))
# b = BattleShip(10)
# b.displayBoard()