-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattleship.py
executable file
·68 lines (63 loc) · 1.63 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
#!/usr/bin/env python3
##This is a battleship game where you gotta sink that battleship!
from random import randint
board_height = 6
board_width = 6
board = []
##Creates a list of list to create a 2-D game board "gb"
def create_board():
gb = []
if gb == []:
for i in range(board_height):
row = []
for i in range(board_width):
row.append('O')
gb.append(row)
return gb
else:
board = []
for i in range(board_height):
row = []
for i in range(board_width):
row.append('O')
board.append(row)
return gb
##This will display the entire board with row and column numbers
def print_board():
##Print top row with only columns numbers
print(' ', end='')
row = 0
for i in range(board_width):
print(str(i), end=' ')
print('')
##Print rows with row number
for i in board:
print(str(row)+' '.join(i))
row += 1
##Spawn single boat on board
def spawn_boat():
x = randint(0,board_width-1)
y = randint(0,board_height-1)
##If the boat in not in the 'O'cean try again
while board[x][y] != 'O':
x = randint(0,board_width)
y = randint(0,board_height)
else:
board[x][y] = 'B'
##Shoot the ocean
def offer_shoot():
x = int(input('X: '))
y = int(input('Y: '))
cell = board[x][y]
if cell == 'B':
print('Hit!')
board[x][y] = 'X'
else:
print('Miss!')
board[x][y] = 'X'
board = create_board()
print('Board Hight: '+str(len(board))+' Board Width: '+str(len(board[0])))
spawn_boat()
print_board()
offer_shoot()
print_board()