-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBattleships.py
73 lines (64 loc) · 2.27 KB
/
Battleships.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
#Random module for randomly accepting the values
# 'X' indicates the ships hit
# '-' indicates the hits missed
from random import randint
Hidden_Pattern = [[' ']*8 for x in range(8)]
Guess_Pattern = [[' ']*8 for x in range(8)]
let_to_num = {'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7}
def print_board(board):
print(' A B C D E F G H')
print(' ***************')
row_num = 1
for row in board:
print("%d¦%s¦" % (row_num, "¦".join(row)))
row_num+=1
def get_ship_location():
# enter the row number between 1 to 8
row = input("Please enter a ship row 1-8: ").upper()
while row not in '01234567':
print("Please enter a valid row ")
row = input("Please enter a ship row 1-8: ")
#enter the ship column from A to H
column = input("Please enter a ship column A-H: ").upper()
while column not in 'ABCDEFGH':
print("Please enter a valid column")
column = input("Please enter a ship column A-H: ")
return int(row)-1,let_to_num[column]
#function that creates the ships
def create_ships(board):
for ship in range(6):
ship_r, ship_cl=randint(0,7), randint(0,7)
while board[ship_r][ship_cl] == 'X':
ship_r, ship_cl = randint(0,7), randint(0,7)
board[ship_r][ship_cl] = 'X'
def count_hit_ships(board):
count = 0
for row in board:
for column in row:
if column == 'X':
count+=1
return count
create_ships(Hidden_Pattern)
#print_board(Hidden_Pattern)
turns = 10
while turns > 0:
print("Welcome to Battleship")
print_board(Guess_Pattern)
row,column = get_ship_location()
if Guess_Pattern[row][column] == '-':
print("You already guessed that!")
elif Hidden_Pattern[row][column] == 'X':
print("Congratulations you have hit the battleship!")
Guess_Pattern[row][column] = 'X'
turns-=1
else:
print("Sorry you missed")
Guess_Pattern[row][column] = '-'
turns-=1
if count_hit_ships(Guess_Pattern) == 5:
print("Congratulations you have sunk all the battleships!")
break
print("You have " + str(turns) + " turns remaining")
if turns == 0:
print("Game Over!")
break