18.10.2014 Views

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Case study: Design of a game 141<br />

The function F<strong>in</strong>d_Turned f<strong>in</strong>ds the number of the opponent’s counters that would be turned for a<br />

particular move. The strategy for F<strong>in</strong>d_Turned is to sum the number of opponent's counters which will be<br />

flipped <strong>in</strong> each compass direction. For any position on the board there are potentially eight directions to check.<br />

The directions are illustrated <strong>in</strong> Figure 9.5.<br />

7<br />

8<br />

1<br />

6<br />

2<br />

Figure 9.5 Compass direction to check when a new counter is added to the board.<br />

function F<strong>in</strong>d_Turned( The:<strong>in</strong> Board; X,Y: <strong>in</strong> Board_Index )<br />

return Natural is<br />

Sum : Natural := 0; --Total stones turned<br />

beg<strong>in</strong><br />

if Holds( The.Sqrs( X, Y ) ) = Empty then<br />

for Dir <strong>in</strong> 1 .. 8 loop --The 8 possible directions<br />

Sum := Sum + No_Turned( The, X, Y, Dir );<br />

end loop;<br />

end if;<br />

return Sum; --return total<br />

end F<strong>in</strong>d_Turned;<br />

5<br />

4<br />

3<br />

The recursive function No_Turned counts the number of the opponent’s pieces that would be captured. This<br />

may of course be zero.<br />

function No_Turned(The:<strong>in</strong> Board; O_X,O_Y:<strong>in</strong> Board_Index;<br />

Dir:<strong>in</strong> Natural;<br />

N:<strong>in</strong> Natural := 0 ) return Natural is<br />

Ok : Boolean;<br />

--Result from next<br />

Nxt: Cell_Holds;<br />

--Next <strong>in</strong> l<strong>in</strong>e is<br />

Col: Counter_Colour;<br />

--Counter colour<br />

X : Board_Index := O_X; --Local copy<br />

Y : Board_Index := O_Y; --Local copy<br />

beg<strong>in</strong><br />

Next( The, X,Y, Dir, Ok ); --Next cell<br />

if Ok then<br />

--On the board<br />

Nxt := Holds( The.Sqrs(X,Y) ); --Contents are<br />

if Nxt = Empty then --End of l<strong>in</strong>e<br />

return 0;<br />

else<br />

Col := To_Colour( Nxt ); --Colour<br />

if Col = The.Opponent then --Opponents counter<br />

return No_Turned(The, X,Y, Dir, N+1); --Try next cell<br />

elsif Col = The.Player then --End of counters<br />

return N;<br />

end if;<br />

end if;<br />

else<br />

return 0;<br />

end if;<br />

end No_Turned;<br />

--Counters turned<br />

--No l<strong>in</strong>e<br />

© M A Smith - May not be reproduced without permission

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!