Question: import random - - - - - - - BATTLESHIPS - - - - - - - Pre - reqs: Loops, Strings,
import random
BATTLESHIPS
Prereqs: Loops, Strings, Arrays, D Arrays, Global Variables, Methods
How it will work:
A x grid will have ships randomly placed about
You can choose a row and column to indicate where to shoot
For every shot that hits or misses it will show up in the grid
If all ships are shot, game over
Legend:
water
S ship position
O water that was shot with bullet, a miss because it hit no ship
X ship sunk!
# Global variable for grid size
gridsize
# Global variable for grid
grid gridsize for i in rangegridsize
# Global variable for number of ships to place
numofships
def drawBoardmyBoard:
# implement draw board here
for i in rangegridsize:
for j in rangegridsize:
print thearrayij end
print
return
def setupBoardmyBoard:
for i in rangegridsize:
for j in rangegridsize:
gridij
# implement setup board here
# initialize all gridij
# now place the ships
# you can get a random row by using
# remember to call myBoardrandomRowrandomColS for every ship
for ship in rangegridsize:
randomRow random.randint gridsize
randomCol random.randint gridsize
while myBoardguessrowguesscolS:
randomRow random.randint gridsize
randomCol random.randint gridsize
myBoardshiprowshipcolS
def hitOrMissmyBoard row, col:
if myBoardrowcol:
myBoardrowcolO
printMiss
elif myBoardrowcolS:
myBoardrowcolX
printHit and Sunk!"
elif myBoardrowcolX:
printAlready Hit!"
else:
myBoardrowcolO
printMiss
# implement the hit or miss functionality here
return
def isGameOvermyBoard:
count
for row in myBoard:
for column in row:
if column S:
count
if count :
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 mainmyBoard:
printWelcome to Battleship"
setupBoardmyBoard
drawBoardmyBoard
guessrow evalinputEnter a row
guesscol evalinputEnter a column
hitormissmyBoard guessrow, guesscol
if isGameOvermyBoard:
printGame 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!
maingrid
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
