How can i create longer randomly placed ships in the battleship game?

i wrote this code already and the game works but i want to make the ships longer

from random import randint

board =
guess_count = 1
guess_limit = 4
hit_count = 0

for x in range(0, 5):
board.append([“O”] * 5)

def print_board(board):
for row in board:
print " ".join(row)

print_board(board)

def random_row(board):
return randint(0, len(board) - 1)

def random_col(board):
return randint(0, len(board[0]) - 1)

checks if the ships ontpo of each other

ship_row = random_row(board)
ship_col = random_col(board)

ship_row2 = random_row(board)
ship_col2 = random_col(board)

while ship_row == ship_row2 and ship_col == ship_col2:
ship_row2 = random_row(board)
ship_col2 = random_col(board)

print ship_row,ship_col
print ship_row2,ship_col2

while guess_count <= guess_limit:
print “your " + str(guess_count) + " turn”
if guess_count == guess_limit:
print “last chance!”

guess_row = int(input("guess row: "))
guess_col = int(input("guess col: "))

#if you miss
if not (guess_row == ship_row and guess_col == ship_col)
and not (guess_row == ship_row2 and guess_col == ship_col2):
guess_count +=1
# fi inside range
if 5> guess_row >0 and 5> guess_col >0:
board[guess_row][guess_col] = “X”
print_board(board)
print “haha… you missed!”
# if outside range
else:
print “now thats a talent!”
print “YOU MISSED THE OCEAN!!”

#if you win

elif guess_row == ship_row and guess_col == ship_col or guess_row == ship_row2 and guess_col == ship_col2:
guess_count += 1
hit_count += 1
board[guess_row][guess_col] = “X”
print_board(board)
if hit_count == 1:
print “you sank my battleship.”
print “gossh thats a good guess.”
elif hit_count == 2:
print “you sank my battleships”
print “WWOOWW amazing! you won!”
break

print “GAME OVER”

2 Likes

This is from a long time ago, and only deals with two ships of the same size, but it’s a scaffold upon which to build the logic. Don’t worry if you cannot understand it. Try playing it and see how it plays.

Multiple Ships Troubleshooting

This example does have multiple ships with various lengths. It too is a little bit complicated, but works as expected. It’s not a game yet, just a set up.

19. Track hits across different ships without using classes?

1 Like