I am making the game battleships in Python and have gotten stuck on a piece of code. I have made a 10x10 grid board where the player/computer will place 5 ships with different sizes. The ships are stored in a dictionary.
I have #hastagged the spot where I am stuck. When the player tries to place a ship that a spot which is not available, it prints "invalid choice" and the player should be able to place it again. But the loop continues and therefore skips placing that ship. I've tried calling the function "player_place_ships" but then it starts all over and places duplicates of the ships that are already placed.
I was thinking of creating a count in the for loop and starting the loop again from where it left off before the "invalid choice" but unsure if it's doable to start a for loop from dict.items at a specific spot?
Hoping there is a kind soul out there with some advice, I'm rather new at python so might be using bad/unorthodox codes here.
Here is the code:
#Dictionary for ships
ships = {'A': 5, 'B': 4, 'C': 3, 'S': 3, 'D': 2}
#Create player board
player_board = []
for player_row in range(10):
player_board.append([])
for player_col in range(10):
player_board[player_row].append('.')
#Print player board
def print_player_board(player_board):
for player_row in player_board:
print(" ".join(player_row))
def player_place_ships(player_board, ships):
for i, j in ships.items():
ori = input('Enter orientation, v or h: ')
x = int(input('Enter row: '))
y = int(input('Enter col: '))
place = x,y
placement = player_board[x][y]
if ori == 'v' and placement == '.':
for k in range(j):
player_board[x][y] = i
player_board[x+k][y] = i
elif ori == 'h' and placement == '.':
player_board[x][y] = i
player_board[x][y+k] = i
elif ori != 'v' or 'h' and placement != '.':
print('Invalid choice, please try again.') #This is where I'm stuck
player_place_ships(player_board, ships)
print_player_board(player_board)