Battleship

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • telgroc
    New Member
    • Oct 2008
    • 3

    Battleship

    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.'
  • Fabez
    New Member
    • Oct 2008
    • 29

    #2
    If it scores a hit then it should look in the eight squares around it for another hit, if not then it should pick a random place. If the hit is near the edge omit squares as needed.

    Comment

    • YarrOfDoom
      Recognized Expert Top Contributor
      • Aug 2007
      • 1243

      #3
      Don't you mean 4 squares? If I remember it right, ships can't be set up diagonally. Just a detail, but it makes it more efficient.

      Comment

      • Fabez
        New Member
        • Oct 2008
        • 29

        #4
        Thanks for pointing that out, you are correct, it should be four squares instead of eight.

        Comment

        Working...