Unit Game of BattleshipGames

by Josh Blake: L6 Age ~17

unit Game;
//Object that controls the game
{
    Copyright (c) 2014 Josh Blake

    Licensed under the Apache License, Version 2.0 (the "License"); you may not
    use this file except in compliance with the License, as described at
    http://www.apache.org/licenses/ and http://www.pp4s.co.uk/licenses/
}
interface
uses
  Crt,
  Settings,
  Grid,
  SysUtils;

type
  TGame = class(TObject)  //Keeps track and manages a game (a single grid)
  private
    GridSize : Integer;
    ShipsLeft : Integer;
  public
    Grid: TGrid;
    GuessCount: Integer;  //Keeps track of number of guesses taken (simple score)
    Hidden: Boolean;      //Should we display the ship positions to user?
    LastGuess: TCoord;
    LastGuessResult: TGuessResult;
    constructor Create(const SizeOfGrid : Integer; const IsHidden: Boolean);
    function ProcessGuess(const Guess : TCoord) : TGuessResult;
    procedure AddShip;    //Signal that a ship has been added
    function CheckGuessValid(const Guess: TCoord): Boolean;
  end;
  
implementation
constructor TGame.Create(const SizeOfGrid : Integer; const IsHidden: Boolean);
var
  I, J : Integer;
begin
  GuessCount := 0;
  ShipsLeft := 0;
  GridSize := SizeOfGrid;
  SetLength(Grid, GridSize);
  //set all squares to unguessed and empty
  for I := 0 to SizeOfGrid - 1 do begin
    SetLength(Grid[I], GridSize);
    for J := 0 to SizeOfGrid do begin
      Grid[I][J].Guessed := False;
      Grid[I][J].Content := TShip.Create(0);
    end;
  end;

  Hidden := IsHidden;
  LastGuessResult := None;
end;

procedure TGame.AddShip;
begin
  Inc(ShipsLeft);
end;

function TGame.ProcessGuess(const Guess : TCoord) : TGuessResult;
{Takes a guess and grid then changes the grid to reflect the guess.}
begin
  Log(IntToStr(Guess.X) + ',' + IntToStr(Guess.Y));
  if not CheckGuessValid(Guess) then begin
    Result := Invalid;
    Log('Invalid');
  end else begin
    Inc(GuessCount);
    Grid[Guess.X][Guess.Y].Guessed := True;
    Result := Grid[Guess.X][Guess.Y].Content.Attack;
    if Result = Sunk then begin
      Dec(ShipsLeft);
      if ShipsLeft = 0 then begin
        Result := Won;
        Log('Won');
      end
      else Log('Ship sunk');
    end
    else if Result = Hit then Log('Hit')
    else if Result = Miss then Log('Miss');
  end;
  LastGuess := Guess;
  LastGuessResult := Result;
end;

function TGame.CheckGuessValid(const Guess: TCoord): Boolean;
begin
  //Check within grid
  if (Guess.Y > Length(Grid)) or (Guess.Y < 0) then Result := False
  else if (Guess.X > Length(Grid)) or (Guess.X < 0) then Result := False
  //Check not already guessed
  else if Grid[Guess.X][Guess.Y].Guessed then Result := False
  
  else Result := True;
end;

end.
Programming - a skill for life!

by Josh Blake: L6 Age ~17