By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,594 Members | 1,570 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,594 IT Pros & Developers. It's quick & easy.

Battleship

telgroc
P: 3
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,
Expand|Select|Wrap|Line Numbers
  1. import random
  2. battleBoard=\
  3.               [['a','a','a','a','a','a','a','a','a','a'],\
  4.                ['a','a','a','a','a','a','a','a','a','a'],\
  5.                ['a','B','a','a','a','a','a','a','a','a'],\
  6.                ['a','B','a','a','B','B','B','B','B','a'],\
  7.                ['a','B','a','a','a','a','a','a','a','a'],\
  8.                ['a','a','a','B','a','a','a','a','a','a'],\
  9.                ['a','a','a','B','a','a','a','a','a','a'],\
  10.                ['a','a','a','B','a','a','a','a','a','a'],\
  11.                ['a','a','a','a','a','a','a','a','a','B'],\
  12.                ['a','B','B','B','B','a','a','a','a','B']]
  13. count=0
  14. hitCount=0
  15. priorMove=[]
  16. while hitCount<17:
  17.     n=random.randint(0,9)
  18.     j=random.randint(0,9)
  19.     b=[n,j]
  20.     dupCount=0
  21.     for a in range(len(priorMove)):
  22.         if b==priorMove[a]:
  23.             dupCount=dupCount+1
  24.         elif b!=priorMove[a]:
  25.             dupCount=dupCount
  26.     if dupCount==0:
  27.         if battleBoard[n][j]=='B':
  28.             priorMove.append(b)
  29.             hitCount=hitCount+1
  30.             count=count+1
  31.         elif battleBoard[n][j]=='a':
  32.             priorMove.append(b)
  33.             count=count+1
  34. print 'The  program took',count,'turns to sink all 5 ships.'
  35.  
Nov 6 '08 #1
Share this Question
Share on Google+
3 Replies


P: 29
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.
Nov 7 '08 #2

YarrOfDoom
Expert 100+
P: 1,247
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.
Nov 8 '08 #3

P: 29
Thanks for pointing that out, you are correct, it should be four squares instead of eight.
Nov 24 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.