guillemc23
Technical User
Hi, I'm from Spain, so please, don't be too bad with my english
I'm just having a little trouble trying to finish some kind of Battleship code, I'm stuck with boats 3 and 4 units long, and I haven't found any other place to ask for some help/advice.
The code I posted here works perfectly fine for boats 1 or 2 units long. The *.dat file is a matrix made of O's where you can place your ships in, by placing an * on that position. The code opens that file as a Matrix and sees if your shoot hit an * or not. I just want to know what to do when ships are bigger.
I know it's such a stupid program, but i just can't see how to do it...
Thanks a lot for your attention.
I'm just having a little trouble trying to finish some kind of Battleship code, I'm stuck with boats 3 and 4 units long, and I haven't found any other place to ask for some help/advice.
The code I posted here works perfectly fine for boats 1 or 2 units long. The *.dat file is a matrix made of O's where you can place your ships in, by placing an * on that position. The code opens that file as a Matrix and sees if your shoot hit an * or not. I just want to know what to do when ships are bigger.
I know it's such a stupid program, but i just can't see how to do it...
Thanks a lot for your attention.
Code:
program battleship
implicit none
integer :: i, j, k ,l
character :: A(10,10), V(3,3)
do
j=0
open (unit = 10, file = 'tablero.dat', status= 'unknown')
read(10,fmt='(7x,10i4)')(i, i=1,10)
read (10,*)
do i = 1,10
read(10,fmt='(i2,5x,10a4)') j,A(i,:) ! Open tablero.dat file
enddo
do
if (any(A=='*')) then ! If there's a boat not sunk, keep going
write (*,*) ''
write (*,*) ' Where do you want to shoot? '
read(*,*) k,l
if (A(k,l)=='*') then ! If there's a boat in (k,l), see if it's sunk or not
A(k,l)='T'
V=A(k-1:k+1,l-1:l+1)
if (any(V=='*')) then
write (*,*) k,',',l
write (*,*) 'Tocado'
write (*,*) ''
else
write (*,*) k,',',l
write (*,*) ' Sunk'
write (*,*) ''
end if
write (*,fmt='(10a4)') A
else ! If there's no boat, check if there's one close
V=A(k-1:k+1,l-1:l+1)
if (any(V=='*')) then
write (*,*) k,',',l
write (*,*) 'Almost'
write (*,*) ''
A(k,l)='A'
write (*,fmt='(10a4)') A
else ! If no boats close, shot missed
write (*,*) k,',',l
write (*,*) ' Water '
write (*,*) ''
A(k,l)='W'
write (*,fmt='(10a4)') A ! This shows the whole matrix each time you shoot
end if
end if
else
exit
end if
end do
write (*,*) ' '
write (*,*) ' Congrats, you won the game! '
write (*,*) ' '
write (*,*) ' Press enter to play again'
read (*,*)
end do
end program