Question: import random - - - - - - - BATTLESHIPS - - - - - - - Pre - reqs: Loops, Strings,

import random
"""
-------BATTLESHIPS-------
Pre-reqs: Loops, Strings, Arrays, 2D Arrays, Global Variables, Methods
How it will work:
1. A 10x10 grid will have 5 ships randomly placed about
2. You can choose a row and column to indicate where to shoot
3. For every shot that hits or misses it will show up in the grid
4. If all ships are shot, game over
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
grid =[['']* grid_size for i in range(grid_size)]
# Global variable for number of ships to place
num_of_ships =5
def drawBoard(myBoard):
# implement draw board here
for i in range(grid_size):
for j in range(grid_size):
print('['+ thearray[i][j]+']', end="")
print()
return
def setupBoard(myBoard):
for i in range(grid_size):
for j in range(grid_size):
grid[i][j]='.'
# implement setup board here
# initialize all grid[i][j]='.'
# now place the ships
# you can get a random row by using
# remember to call myBoard[randomRow][randomCol]='S' for every ship
for ship in range(grid_size):
randomRow = random.randint(0, grid_size -1)
randomCol = random.randint(0, grid_size -1)
while myBoard[guess_row][guess_col]=='S':
randomRow = random.randint(0, grid_size -1)
randomCol = random.randint(0, grid_size -1)
myBoard[ship_row][ship_col]='S'
def hitOrMiss(myBoard, row, col):
if myBoard[row][col]=='.':
myBoard[row][col]='O'
print("Miss!")
elif myBoard[row][col]=='S':
myBoard[row][col]='X'
print("Hit and Sunk!")
elif myBoard[row][col]=='X':
print("Already Hit!")
else:
myBoard[row][col]='O'
print("Miss")
# implement the hit or miss functionality here
return
def isGameOver(myBoard):
count =0
for row in myBoard:
for column in row:
if column =="S":
count +=1
if count ==5:
return True
else:
return False
# check if there are ships remaining on the grid.
# if there are ships remaining, return false else return true
def main(myBoard):
print("Welcome to Battleship")
setupBoard(myBoard)
drawBoard(myBoard)
guess_row = eval(input("Enter a row "))
guess_col = eval(input("Enter a column "))
hit_or_miss(myBoard, guess_row, guess_col)
if isGameOver(myBoard):
print("Game Over")
# here do everything like
# set up the board
# till the game is over
# draw the board
# ask for a row and column and check it is a hit or a miss
# when the game is over, print that message!
# do not forget to call main!
main(grid)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!