I'm new to coding, and have developed a Battleship game. One bug I am noticing in the game is that when it ends, the final "S" (ship) does not change to an "X" before announcing the game is over. I'm not exactly sure what is causing this to happen, but am hoping it's an easy fix! I tried putting |X| == 5 in my main function under isGameOver, but it seems as though I can only have X == 5 or total_number_of_ships == 5, so I'm kind of stuck on where to go from here.
Here is my code:
import random
# Legend:
# 1. "." = water
# 2. "S" = ship position
# 3. "O" = water that was shot with bullet, a miss because it hit no ship
# 4. "X" = ship sunk!
#global variable for grid size
grid_size = 10
#global variable for grid
myBoard = [['|.|']*grid_size for i in range(grid_size)]
# display the grid (2d array)
total_number_of_ships = 0
#formatting
s = "| |"
def main():
keep_playing = True
while keep_playing:
drawBoard(myBoard)
# user_guess(myBoard)
guess = user_guess(myBoard)
row = guess[0]
col = guess[1]
hitOrMiss(myBoard, row, col)
isGameOver(myBoard)
if total_number_of_ships == 5:
return False
def drawBoard(myBoard):
# Print header
# print(end=" ")
for i in range(grid_size):
print(" ", i, end=" ") #how to space end=" "
print()
# Print rows
for i in range(grid_size):
print(i, end=" ")
for j in range(grid_size):
print(myBoard[i][j], end=" ") # change grid to myBoard
print()
# Place ships
for _ in range(5):
while True: # continuously loop...
randomRow = random.randrange(grid_size)
randomCol = random.randrange(grid_size)
# ...until an open space is selected
if myBoard[randomRow][randomCol] == '|.|':
break
myBoard[randomRow][randomCol] = '|S|'
def user_guess(myBoard):
row = int(input('Please enter a row: '))
while row not in (0,1,2,3,4,5,6,7,8,9):
print('Not an appropriate choice, please select a valid row')
row = int(input('Please enter a row: '))
col = int(input('Please enter a column: '))
while col not in (0,1,2,3,4,5,6,7,8,9):
print('Not an appropriate choice, please select a valid row')
col = int(input('Please enter a column: '))
return (row, col)
def hitOrMiss(myBoard, row, col):
global total_number_of_ships
if myBoard[row][col] == '|.|':
print('Miss!')
myBoard[row][col] = '|0|'
return "Miss"
elif myBoard[row][col] == '|S|':
print('Hit! Ship is sunk!')
myBoard[row][col] = '|X|'
total_number_of_ships += 1
return "Hit! Ship is sunk!"
elif myBoard[row][col] == '|0|':
print('You already guessed this spot!')
return 'You already guessed this spot!'
elif myBoard[row][col] == '|X|':
print('Ship is already sunk!')
return 'Ship is already sunk!'
def isGameOver(myBoard):
global total_number_of_ships
if total_number_of_ships < 5:
print ('There are still ships remaining. Try again.')
else:
total_number_of_ships == 5
print ('Game over. Congratulations. You have won!')
return False
# Call main function
if __name__ == '__main__':
main()
Thank you for your help!