unit TugOfWar;

interface

uses
  Classes, SysUtils, Game, Graphics, Scene;

type

  { TSceneMain }

  TSceneMain = class(TScene)
    Game: TGame;
    procedure Draw; override;
  end;

  { TTugOfWar }

  TTugOfWar = class(TGame)
    Position: Integer;
    Min: Integer;
    Max: Integer;
    Winner: string;
    procedure Run; override;
    procedure KeyUp(var Key: Word; Shift: TShiftState); override;
    constructor Create;
    destructor Destroy; override;
  end;


implementation

resourcestring
  STugOfWar = 'Tug of War';
  SWinnerIs = 'The winner is';
  SLeft = 'Left';
  SRight = 'Right';

{ TSceneMain }

procedure TSceneMain.Draw;
var
  Shift: Integer;
  Center: Integer;
  Text: string;
  RopeWidth: Integer;
begin
  Clear;
  with Canvas do begin
    Center := Width div 2;
    RopeWidth := Width div 3;
    Shift := TTugOfWar(Game).Position * 20;
    MoveTo(Center + Shift - RopeWidth div 2, 100);
    LineTo(Center + Shift + RopeWidth div 2, 100);

    MoveTo(Center + Shift, 100);
    LineTo(Center + Shift, 110);

    Text := '^';
    TextOut(Center - TextWidth(Text) div 2, 110, Text);
    Text := 'R';
    TextOut(Center + Shift + RopeWidth div 2 + 20 - TextHeight(Text) div 2, 100 - TextHeight(Text) div 2, Text);
    Text := 'L';
    TextOut(Center + Shift - RopeWidth div 2 -20 - TextHeight(Text) div 2, 100 - TextHeight(Text) div 2, Text);

    if TTugOfWar(Game).Winner <> '' then begin
      TextOut(100, 200, SWinnerIs + ' ' + TTugOfWar(Game).Winner);
    end;
  end;
end;

{ TTugOfWar }

procedure TTugOfWar.Run;
begin
  Position := 0;
  Max := 10;
  Min := -10;
  Winner := '';
  inherited;
end;

procedure TTugOfWar.KeyUp(var Key: Word; Shift: TShiftState);
begin
  if not (State = gsRunning) then Exit;
  case Key of
    KeyCodeRight: begin
      if Position < Max then Inc(Position) else begin
        Winner := SRight;
        State := gsStopped;
      end;
      Scene.Redraw;
    end;
    KeyCodeLeft: begin
      if Position > Min then Dec(Position) else begin
        Winner := SLeft;
        State := gsStopped;
      end;
      Scene.Redraw;
    end;
  end;
end;

constructor TTugOfWar.Create;
begin
  Name := STugOfWar;
  Scene := TSceneMain.Create;
  TSceneMain(Scene).Game := Self;
end;

destructor TTugOfWar.Destroy;
begin
  inherited;
end;

end.

