Question: How do I get my numbers inside the lines like the photo? My grid needs to look exactly like the photo. This is how your
How do I get my numbers inside the lines like the photo? My grid needs to look exactly like the photo. This is how your program should behave after it starts.
import random
# Constants for the grid
gridsize
numofships
# Function to draw the board with grid lines
def drawboardboard:
# Print column headers
printjoinstri for i in rangegridsize
print gridsize # Top border
for idx, row in enumerateboard:
# Print each row with borders
rowline joinrow # Join each cell with
printfidxrowline # Add row header and side borders
print gridsize # Row separator
# Function to set up the board with ships placed randomly
def setupboard:
board for in rangegridsize for in rangegridsize
shipsplaced
while shipsplaced numofships:
row random.randint gridsize
col random.randint gridsize
if boardrowcol:
boardrowcolS
shipsplaced
return board
# Function to check if a hit or miss occurred
def checkhitormissboard guessrow, guesscol:
if boardguessrowguesscolS:
boardguessrowguesscolX # Mark hit with X
return True
elif boardguessrowguesscol:
boardguessrowguesscolO # Mark miss with O
return False
else:
return None # Already guessed position
# Function to check if all ships have been hit
def isgameoverboard:
for row in board:
if S in row:
return False
return True
# Main game function
def main:
# Set up player's and computer's boards
playerboard setupboard
computerboard setupboard
while True:
drawboardplayerboard # Display the player's board
# Get the user's guess
try:
guessrow intinputGuess Row :
guesscol intinputGuess Column :
if guessrow or guessrow gridsize or guesscol or guesscol gridsize:
printOops That's out of bounds. Try again."
continue
# Check if it's a hit or miss on the computer's board
hit checkhitormisscomputerboard, guessrow, guesscol
if hit is True:
printHit
elif hit is False:
printMiss
else:
printYou already guessed that!"
# Check if the game is over
if isgameovercomputerboard:
printCongratulations You've sunk all the battleships!"
break
except ValueError:
printPlease enter valid numbers."
except IndexError:
printOops That's out of bounds. Try again."
# Run the game
if namemain:
main
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
