Help with a battleship program?

1 visualización (últimos 30 días)
anibb
anibb el 18 de Abr. de 2016
Comentada: Walter Roberson el 18 de Abr. de 2016
I'm writing this code to play battleship against the computer and I've written the code to the point where I can get all the ships placed (battleship- 4 cells long, submarine- 3 cells long, cruiser- 2 cells long, and destroyer- 1 cell). But now I have to make the computer randomly guess spots on the board(9x9) and check to see if it hits one of the ships. The computer gets 29 missiles and if the computer doesn't get a hit for 7 guesses to automatically hit a ship. Please help I've been messing around with loops all day and can't get it right. Thank you.

Respuestas (2)

Walter Roberson
Walter Roberson el 18 de Abr. de 2016
I suggest you use logical indices, 1 to 81, indices into the 9 x 9 board. You can pre-calculate the guess locations by using
[gr, gc] = sub2ind([9 9], randperm(81));
then guess #K is at gr(K), gc(K) . No duplicate guesses will be possible if you do this.

Image Analyst
Image Analyst el 18 de Abr. de 2016
Use randi() once to get a linear index indicating an array location, or twice to get a row,column pair.
I believe there are some battleship games in the File Exchange.
  2 comentarios
anibb
anibb el 18 de Abr. de 2016
Yea I looked a those. There's only 2 and they're more complicated than what i'm trying to do. And they're having the user click on the board to guess. I'm just trying to check whether the computer's guess is where a ship is. And I'm having a lot of trouble figuring out how to automatically make a hit every 7 misses.
Walter Roberson
Walter Roberson el 18 de Abr. de 2016
Just keep making guesses (that have not been made before) until a hit is made, but do not count those guesses, and do not "tell" the computer where the guesses were made (that is, so that the computer would still have those squares in the list of places it was allowed to guess.)

Iniciar sesión para comentar.

Categorías

Más información sobre Marine and Underwater Vehicles en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by