-
Notifications
You must be signed in to change notification settings - Fork 0
/
navalbattle.py
224 lines (201 loc) · 5.68 KB
/
navalbattle.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
"""
This module creates a naval game to be played by a single player in the command
line / console similar to the game Battleship.
Author: Matthew Festa
"""
import random
"""
-------NAVAL BATTLE-------
How it will work:
1. A 10x10 grid will have 5 ships randomly placed about
2. You can choose a row and column to indicate where to shoot
3. For every shot that hits or misses it will show up in the grid
4. If all ships are shot, game over
Legend:
1. "." = water
2. "S" = ship position
3. "O" = a miss
4. "X" = a hit
"""
# Global variable for grid size
grid_size = 10
# Global variable for grid
user_grid = [[''] * grid_size for i in range(grid_size)]
computer_grid = [[''] * grid_size for i in range(grid_size)]
# Global variable for number of ships to place
num_of_ships = 5
def draw_board(my_board):
"""
This function prints the game board that has already been set up.
:param my_board:
:return: Void
"""
print("+---" * 11 + "+")
print("| | ", end="")
for col in range(len(my_board)):
print(str(col), end=" | ")
print()
for row in range(len(my_board)):
print("+---" * 11 + "+")
print("| " + str(row) + " |", end="")
for col in range(len(my_board)):
print(my_board[row][col] + '|', end="")
print()
print("+---" * 11 + "+")
def setup_board(my_board):
"""
This function sets up the 2D board and fills each of the matrices with
'.' if empty space and 'S' if there is a ship.
:param my_board:
:return: my_board 2D list object
"""
# Initialize all grid[row][col] = '.'
for row in range(grid_size):
for col in range(grid_size):
my_board[row][col] = ' . '
# Place the ships
for i in range(num_of_ships):
randomRow = random.randint(0, grid_size - 1)
randomCol = random.randint(0, grid_size - 1)
my_board[randomRow][randomCol] = ' S '
return my_board
def hit_or_miss(my_board, row, col):
"""
The hit or miss takes the values inputted by the user as parameters for
the location of the ship and checks if it is a hit or miss.
:param my_board:
:param row:
:param col:
:return: check - HIT if is ship, MISS if is empty
"""
space = my_board[row][col]
if space == ' S ' or space == ' X ':
my_board[row][col] = ' X '
check = 'HIT'
draw_board(my_board)
return check
else:
my_board[row][col] = ' O '
check = 'MISSED'
draw_board(my_board)
return check
def hit_or_miss_computer(my_board, row, col):
"""
The hit or miss takes the values inputted by the computer as parameters for
the location of the ship and checks if it is a hit or miss.
:param my_board:
:param row:
:param col:
:return: check - HIT if is ship, MISS if is empty
"""
space = my_board[row][col]
if space == ' S ' or space == ' X ':
my_board[row][col] = ' X '
check = 'HIT'
return check
else:
my_board[row][col] = ' O '
check = 'MISSED'
return check
def is_game_over(my_board):
"""
This function returns a boolean value to check if the prerequisites of
ending the game are met.
:param my_board:
:return: True if all ships are sunk, False if ships remain
"""
for row in range(grid_size):
for column in range(grid_size):
if my_board[row][column] == ' S ':
return False
return True
def main(user_board, computer_board):
"""
This function defines how the code in the main function will execute.
:param user_board, computer_board:
:return:
"""
round = 1
user_name = input('Enter Name: \n')
try:
user_name = str(user_name)
except:
print('Invalid name')
print(f'Hello {user_name}! Welcome to the game!')
print(f'**** Drawing Boards ~ Round {round} ****')
setup_board(user_board)
setup_board(computer_board)
print(f'{user_name}\'s board:')
draw_board(user_board)
print('Legend:')
print('1. . = water \n'
'2. S = ship position \n'
'3. O = a miss \n'
'4. X = a hit')
while not is_game_over(user_board):
row = input('Enter a row (X): \n')
try:
row = int(row)
if int(row) < 0 or int(row) >= 10:
raise ValueError('Invalid row')
except ValueError as e:
print(e)
continue
col = input('Enter a column (Y): \n')
try:
col = int(col)
if int(col) < 0 or int(col) >= 10:
raise ValueError('Invalid column')
except ValueError as e:
print(e)
continue
else:
# Computer's random row and column
comp_row = random.randint(0, grid_size - 1)
comp_col = random.randint(0, grid_size - 1)
# Check each board for hit or miss
check_user = hit_or_miss_computer(computer_board, row, col)
check_computer = hit_or_miss(user_board, comp_row,
comp_col)
# Print out
print(f'Your torpedo {check_user} one of the computer\'s ships!')
print(f'The computer\'s torpedo {check_computer} one'
f' of {user_name}\'s ships')
# Check if game is over
is_game_over(user_board)
is_game_over(computer_board)
# If over, print out Game over
if is_game_over(user_board):
print('Game over! Computer wins!')
print(f'{user_name}\'s final board:')
draw_board(user_board)
print('Computer\'s final board:')
draw_board(computer_board)
break
elif is_game_over(computer_board):
print(f'Game over! {user_name} wins!')
print(f'{user_name}\'s final board:')
draw_board(user_board)
print('Computer\'s final board:')
draw_board(computer_board)
break
else:
round += 1
print(f'Round: {round}')
# Ask if you want to play again
yes_no = input('Do you want to play again Y / N ?')
try:
yes_no = yes_no.upper()
except:
print('Something went wrong')
else:
if yes_no == 'Y':
main(user_board, computer_board)
elif yes_no == 'N':
print(f"Thank you for playing, {user_name}")
print("Play again soon!")
quit()
else:
print('Something went wrong.')
if __name__ == '__main__':
main(user_grid, computer_grid)