-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattleship_optional.py
executable file
·322 lines (261 loc) · 9.69 KB
/
battleship_optional.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
'''
Battleship: a one-player Python implementation of the classic board game.
Author: sql.sith
'''
from random import randint
# from reportlab.lib.validators import isInt
import re
import sys
import os
g_intRegex = re.compile(r"^\s*[-+]?\d+(\.0*)?\s*$")
def isInt(candidate):
"""Determine if candidate can be represented as an int"""
return g_intRegex.match(str(candidate).strip()) is not None
def get_int_from_user(prompt, min, max):
done = False
while not done:
the_string = input(prompt)
if isInt(the_string):
the_int = int(the_string)
if the_int >= min and the_int <= max:
done = True
else:
print(f'Error - the integer must be between {min} and {max}!')
else:
print(('{} is not an integer. Please try again.'.format(the_string)))
return(the_int)
def print_board(board):
print(" 1 2 3 4 5 6 7 8 9 10")
print(" --- --- --- --- --- --- --- --- --- ---")
for row in range(len(board)):
sys.stdout.write(chr(ord("A") + row) + " | " + " "
.join(board[row]) + " ")
if row in (0, 2, 9):
sys.stdout.write("=".center(30, "="))
elif row == 1:
sys.stdout.write("==" + "Turn # {0}"
.format(_turns).center(26) + "==")
elif row in (3, 8):
sys.stdout.write("==" + " ".center(26) + "==")
elif row == 4:
sys.stdout.write("==" + "Hits: {0}"
.format(_hits).center(26) + "==")
elif row == 5:
sys.stdout.write("==" + "Misses: {0} / {1}"
.format(_misses, _misses_allowed)
.center(26) + "==")
elif row == 6:
sys.stdout.write("==" + "Mistakes: {0}"
.format(_mistakes).center(26) + "==")
elif row == 7:
sys.stdout.write("==" + "Sunk: {0} / {1}"
.format(_ships_sunk, _ships_count)
.center(26) + "==")
sys.stdout.write("\n")
def mark_ships_positions(board, ships, case=None):
'''
Marks the position of each ship in board, but only if it has not
already been marked (by being sunk).
'''
for ship in ships:
mark_ship_position(ship, case)
def mark_ship_position(ship, case=None):
'''
Marks the position of one ship, but only if it has not already
been marked (by being sunk).
'''
for position in ship["Positions"]:
row = position[0]
col = position[1]
if _board[row][col] in (_board_initial_char, _board_hit_char):
marker = ship["Abbreviation"]
if case.lower() == "lower":
marker = marker.lower()
elif case.lower() == "upper":
marker = marker.upper()
_board[row][col] = marker
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
def place_ship(board, ship):
ship_placed = False
max_row_if_vertical = len(board) - ship["Length"]
max_row_if_horizontal = len(board) - 1
max_col_if_vertical = len(board[0]) - 1
max_col_if_horizontal = len(board[0]) - ship["Length"]
occupied_positions = []
for s in _ships:
occupied_positions += s["Positions"]
while not ship_placed:
collision = False
if randint(0, 1) == 0:
horizontal = True
else:
horizontal = False
if horizontal:
fixed_coordinate = randint(0, max_row_if_horizontal)
variable_coordinate_start = randint(0, max_col_if_horizontal)
else:
fixed_coordinate = randint(0, max_col_if_vertical)
variable_coordinate_start = randint(0, max_row_if_vertical)
ship["Positions"] = []
for x in range(ship["Length"]):
variable_coordinate = variable_coordinate_start + x
if horizontal:
coords = (fixed_coordinate, variable_coordinate)
else:
coords = (variable_coordinate, fixed_coordinate)
if coords in occupied_positions:
collision = True
break
else:
ship["Positions"] += [coords]
if not collision:
ship_placed = True
if _debug:
print(ship)
print(max_row_if_vertical)
print(max_col_if_horizontal)
print(ship["Positions"])
def trim_leading_noise(the_string):
trim_string = the_string
if ' ' in the_string:
space_index = the_string.index(' ')
if the_string[:space_index].lower() in noise_words:
trim_string = the_string[(space_index + 1):]
return(trim_string)
def best_effort_abbreviation(the_string):
best_effort = trim_leading_noise(the_string)[0]
if best_effort == _board_initial_char:
best_effort = "!"
return(best_effort)
def hit(row, col):
for ship in _ships:
if (row, col) in ship["Positions"]:
return(ship)
# return None for a miss:
return(None)
def sunk(ship):
all_hit = True
for position in ship["Positions"]:
if _board[position[0]][position[1]] not in(
ship["Abbreviation"].upper(), _board_hit_char):
all_hit = False
break
return(all_hit)
def clear_console():
if 'TERM' in os.environ:
os.system('cls' if os.name=='nt' else 'clear')
else:
print(("\n" * 50))
# main:
_debug = False
_board_initial_char = "*"
_board_missed_char = "X"
_board_hit_char = "H"
_noise_words = ['the', 'a', 'an', 'this', 'these', 'those', 'some']
_ships_sunk = 0
_misses = 0
_hits = 0
_mistakes = 0
_turns = 0
_guess_prompt = "Your guess? "
_guess_regex = "^([a-jA-J])-?(10|[1-9])$"
_rows = 10
_cols = 10
_board = []
for x in range(_rows):
_board.append([_board_initial_char] * _cols)
_ships = [ { "Name" : "Aircraft Carrier", "Length" : 5,
"Abbreviation" : "a", "Positions" : []},
{ "Name" : "Battleship", "Length" : 4,
"Abbreviation" : "b", "Positions" : []},
{ "Name" : "Cruiser", "Length" : 3,
"Abbreviation" : "c", "Positions" : []},
{ "Name" : "Destroyer", "Length" : 2,
"Abbreviation" : "d", "Positions" : []},
{ "Name" : "Submarine", "Length" : 3,
"Abbreviation" : "s", "Positions" : []}
]
_ships_count = len(_ships)
for ship in _ships:
place_ship(_board, ship)
if _debug:
for ship in _ships:
print(ship)
mark_ships_positions(_board, _ships, "lower")
if not _debug:
clear_console()
print("Let's play Battleship!\n")
print("")
_misses_allowed = get_int_from_user("How many misses allowed? ", 10, 50)
clear_console()
print("") # so this screen has the same "top buffer" as other screens
while _misses < _misses_allowed and _ships_sunk < _ships_count:
_turns += 1
print("")
print_board(_board)
print("")
print(("Turn {0}".format(_turns)))
print("")
# get user's guess:
_guess_match = None
while _guess_match is None:
_guess_input = input(_guess_prompt)
_guess_match = re.match(_guess_regex, _guess_input)
if _guess_match is None:
print("Please enter your guess in the format A-1 or A1.")
print("")
# maps A -> 0, B -> 1, etc:
_guess_row = ord(_guess_match.group(1).upper()) - ord("A")
# should never fail, per validation:
_guess_col = int(_guess_match.group(2)) - 1
if not _debug:
clear_console()
if _debug:
print(("You guessed {0:s}, which maps to row {1:d} and column {2:d}."
.format(_guess_input, _guess_row, _guess_col)))
# first case should not happen per validation,
# but leaving it in just in case:
if ((_guess_row < 0 or _guess_row > _rows - 1) or
(_guess_col < 0 or _guess_col > _cols - 1)):
print("Oops, that's not even in the ocean.")
_mistakes += 1
elif _board[_guess_row][_guess_col] not in(
_board_initial_char,
_board_hit_char,
_board[_guess_row][_guess_col].lower()):
print("You guessed that one already.")
_mistakes += 1
else:
_ship_hit = hit(_guess_row, _guess_col)
if _ship_hit is None:
print("You missed!")
_board[_guess_row][_guess_col] = "X"
_misses += 1
else:
if _debug:
board[_guess_row][_guess_col] = (
_ship_hit["Abbreviation"].upper())
else:
_board[_guess_row][_guess_col] = _board_hit_char
if sunk(_ship_hit):
print(("You sunk my {}!".format(_ship_hit["Name"])))
mark_ship_position(_ship_hit, "upper")
_ships_sunk += 1
else:
#print("Hit - {}.".format(_ship_name))
print("Hit!")
_hits += 1
if _misses == _misses_allowed or _ships_sunk == _ships_count:
print("")
print("Game Over")
if _ships_sunk == _ships_count:
print("Congratulations - you won!!!")
else:
print("You poor sap - lost again, did you?")
print("")
mark_ships_positions(_board, _ships, "lower")
print_board(_board)
print("")