What does this section of code do?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
don ARM
am 17 Apr. 2017
Beantwortet: Alice
am 4 Okt. 2024
I am creating a Battleship style game for a class project and I found this piece of code found below and my game only works with it in the code. I would like to have a better understanding of what the variables mean, they are not used in the code prior to this(other than "board"). Thank you for any help given.
i = 1+size*rand;
j = 1+size*rand;
loop = 1;
while (loop)
temp = rand * 3;
dx = 0;
if (temp > 2)
dx = 1;
elseif (temp < 1)
dx = -1;
end
temp = rand * 3;
dy = 0;
if (temp > 2)
dy = 1;
elseif (temp < 1)
dy = -1;
end
i0 = dx * 4 + i;
j0 = dy * 4 + j;
if (i0 > 0 && i0 <= size && j0 > 0 && j0 <= size)
loop = 0;
end
if (dx == 0 && dy == 0)
loop = 1;
end
end
for I = 0:3
Board(int32(i + I * dx),int32(j + I * dy))=1;
end
1 Kommentar
John D'Errico
am 17 Apr. 2017
Bearbeitet: John D'Errico
am 17 Apr. 2017
An arbitrary, uncommented block of code has no meaning at all, when taken out of context. Even knowing that it is part of code for a game is not relevant. And of course, removing any such arbitrary block of code will of course cause working code to fail, else it is hardly likely that code would have been included in the first place.
Akzeptierte Antwort
James Tursa
am 17 Apr. 2017
It looks like:
i & j are generated as a random point on the board.
dx and dy are generated as a random direction (they are either -1, 0, or 1)
dx and dy are then checked to see that, when 4 is added to i and j in the dx and dy directions, the result is still on the board. If everything is still on the board, then the while loop exits. Otherwise, new random dx and dy directions are generated for testing. Also, at least one of dx or dy must be non-zero for the while loop to exit.
Then the board i and j position as well as three additional positions in the direction of dx and dy are assigned a value of 1.
0 Kommentare
Weitere Antworten (1)
Alice
am 4 Okt. 2024
function [mArea] = midArr(f,a,b,n)
c = (b-a)/n;
mArea = 0;
for i = 1:n
mArea = mArea+(f(a+(i-0.5)*c)*c);
end
end
0 Kommentare
Siehe auch
Kategorien
Mehr zu Strategy & Logic finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!