I'm trying to write the code for the game Battleship, in order to count how many turns it will take to sink all 5 ships. I've written it without strategy (it just generates random numbers until 17 hits have occurred. However, I can't figure out how to add strategy, so when a hit is scored, the program will adjust to try and specify the spots around the hit and when it finds which direction the rest of the ship lies, it finishes off the ship. Any suggestions? Code is posted below,
Code:
import random battleBoard=\ [['a','a','a','a','a','a','a','a','a','a'],\ ['a','a','a','a','a','a','a','a','a','a'],\ ['a','B','a','a','a','a','a','a','a','a'],\ ['a','B','a','a','B','B','B','B','B','a'],\ ['a','B','a','a','a','a','a','a','a','a'],\ ['a','a','a','B','a','a','a','a','a','a'],\ ['a','a','a','B','a','a','a','a','a','a'],\ ['a','a','a','B','a','a','a','a','a','a'],\ ['a','a','a','a','a','a','a','a','a','B'],\ ['a','B','B','B','B','a','a','a','a','B']] count=0 hitCount=0 priorMove=[] while hitCount<17: n=random.randint(0,9) j=random.randint(0,9) b=[n,j] dupCount=0 for a in range(len(priorMove)): if b==priorMove[a]: dupCount=dupCount+1 elif b!=priorMove[a]: dupCount=dupCount if dupCount==0: if battleBoard[n][j]=='B': priorMove.append(b) hitCount=hitCount+1 count=count+1 elif battleBoard[n][j]=='a': priorMove.append(b) count=count+1 print 'The program took',count,'turns to sink all 5 ships.'
Comment