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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

A Text user <strong>in</strong>terface 321<br />

package Class_Board is<br />

type Board is private;<br />

type Game_State is ( W<strong>in</strong>, Playable, Draw );<br />

procedure Add( The:<strong>in</strong> out Board; Pos:<strong>in</strong> Integer;<br />

Piece:<strong>in</strong> Character );<br />

function Valid( The:<strong>in</strong> Board; Pos:<strong>in</strong> Integer ) return Boolean;<br />

function State( The:<strong>in</strong> Board ) return Game_State;<br />

function Cell( The:<strong>in</strong> Board; Pos:<strong>in</strong> Integer ) return Character;<br />

procedure Reset( The:<strong>in</strong> out Board );<br />

private<br />

subtype Board_Index is Integer range 1 .. 9;<br />

type Board_Array is array( Board_Index ) of Character;<br />

type Board is record<br />

Sqrs : Board_Array := ( others => ' '); --Initialize<br />

Moves : Natural := 0;<br />

end record;<br />

end Class_Board;<br />

Note:<br />

It would have been elegant to re-use the previous noughts and crosses class for Board but the<br />

functionality is too dissimilar to make this a practical proposition. Code re-use is not always possible!<br />

In the implementation of the class the function Valid returns True if the suggested noughts and crosses<br />

move is valid.<br />

package body Class_Board is<br />

function Valid(The:<strong>in</strong> Board; Pos:<strong>in</strong> Integer) return Boolean is<br />

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

return Pos <strong>in</strong> Board_Array'Range and then<br />

The.Sqrs( Pos ) = ' ';<br />

end Valid;<br />

The procedure Add is responsible for add<strong>in</strong>g a new piece onto the board..<br />

procedure Add( The:<strong>in</strong> out Board; Pos:<strong>in</strong> Integer;<br />

Piece:<strong>in</strong> Character ) is<br />

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

The.Sqrs( Pos ) := Piece;<br />

end Add;<br />

The function State returns the enumeration W<strong>in</strong>, Draw or Playable depend<strong>in</strong>g on the current state of the<br />

game. The constant array cells holds all possible w<strong>in</strong> l<strong>in</strong>es and the ma<strong>in</strong> body of the code uses the values held<br />

<strong>in</strong> this array to determ<strong>in</strong>e the current state of the game.<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!