Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Battleship Game - Placing random ships
Index -> Programming, Turing -> Turing Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Sur_real




PostPosted: Tue May 13, 2008 4:52 pm   Post subject: Battleship Game - Placing random ships

I need help on how to place 2 random ships on a 5 by 5 grid for my battleship game using arrays and is inside a procedure.

I already read the other theads regarding battleship games so there's no use linking me to them...

Thanks


(Nothing too hard please, i'm really noobie...)
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: Tue May 13, 2008 5:07 pm   Post subject: RE:Battleship Game - Placing random ships

A really simple (to understand) approach would be to pick a random spot on the grid
code:

row := Rand.Int(0,4)
column := Rand.Int(0,4)

+ the orientation of the ship (up/down, left/right)
code:

orientation =: Rand.Int(0,1)

And then check if all the spots are available (that is, there are no overlapping ships and the array is not out of bound -- you need to be careful about the latter)
Turing:

for i: row .. row + length_of_ship
   if array[i][column] then
      % hey, there's something here already
   end if
end for


a more sophisticated way is to realize that not all starting locations are valid for certain ship sizes and orientations, so narrowing down the range of choices will optimize the performance and will (hopefully) avoid out-of-bounds errors.
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Sur_real




PostPosted: Tue May 13, 2008 5:23 pm   Post subject: RE:Battleship Game - Placing random ships

Thanks Tony
but what do you mean by the brackets...
code:
if array[i][column] then
Tony




PostPosted: Tue May 13, 2008 5:34 pm   Post subject: RE:Battleship Game - Placing random ships

I meant the cell at row/column position in the grid/2d-array
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Sur_real




PostPosted: Tue May 13, 2008 5:46 pm   Post subject: RE:Battleship Game - Placing random ships

Oooo
ok
Display posts from previous:   
   Index -> Programming, Turing -> Turing Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 5 Posts ]
Jump to:   


Style:  
Search: