{ Cable run: steer a network cable that grows with every data packet it picks up.
  The wall or the cable itself ends the run. Build and run: fpc game.pas && ./game
  Arrows steer, q quits, n starts a new run. With STEP=1 the cable moves one step per key (space steps). }
program game;
{$mode objfpc}{$H+}
uses crt, sysutils;

const
  Cols = 30; Rows = 18; Left = 3; Top = 4;
type
  TCell = record x, y: integer; end;
var
  con: Text;
  cable: array[0..Cols * Rows] of TCell;
  used: array[1..Cols, 1..Rows] of boolean;
  packet: TCell;
  len, dx, dy, score, wait: integer;
  stepMode, over: boolean;
  c: char;

function Esc(const code: string): string; begin Result := #27'[' + code + 'm'; end;
function At(x, y: integer): string; begin Result := #27'[' + IntToStr(y) + ';' + IntToStr(x) + 'H'; end;
function Rep(const s: string; n: integer): string; var i: integer; begin Result := ''; for i := 1 to n do Result := Result + s; end;
procedure Send(const s: string); begin Write(con, s); Flush(con); end;

{ A cell of the field takes two columns on the screen, so it looks square }
procedure Paint(p: TCell; const look: string);
begin Send(At(Left + p.x * 2 - 1, Top + p.y) + look + Esc('0')); end;

procedure Status;
begin
  Send(Esc('0') + At(67, 6) + 'Score  ' + Esc('1;93') + Format('%4d', [score]) + Esc('0')
    + At(67, 7) + 'Length ' + Format('%4d', [len]) + At(67, 8) + 'Speed  ' + Format('%4d/s', [1000 div wait]));
end;

procedure NewPacket;
begin
  repeat packet.x := Random(Cols) + 1; packet.y := Random(Rows) + 1; until not used[packet.x, packet.y];
  Paint(packet, Esc('1;92') + '[]');
end;

procedure NewRun;
var i: integer;
begin
  FillChar(used, SizeOf(used), 0);
  len := 4; dx := 1; dy := 0; score := 0; wait := 150; over := false;
  for i := 0 to len - 1 do begin cable[i].x := 8 - i; cable[i].y := Rows div 2; used[8 - i, Rows div 2] := true; end;
  Send(Esc('0') + #27'[2J' + Esc('33') + At(Left - 1, Top) + '╔' + Rep('═', Cols * 2) + '╗');
  for i := 1 to Rows do Send(At(Left - 1, Top + i) + '║' + Rep(' ', Cols * 2) + '║');
  Send(At(Left - 1, Top + Rows + 1) + '╚' + Rep('═', Cols * 2) + '╝' + At(Left + 1, Top) + Esc('1;33') + ' Cable run ');
  Send(Esc('0;33') + At(66, 4) + '┌─ Run ───────┐' + At(66, 9) + '└─────────────┘');
  for i := 5 to 8 do Send(At(66, i) + '│' + Rep(' ', 13) + '│');
  Send(At(67, 11) + Esc('0') + Esc('1;92') + '[]' + Esc('0') + ' a packet' + At(67, 13) + '↑ ↓ ← → steer'
    + At(67, 14) + 'n  new run' + At(67, 15) + 'q  quit');
  for i := 0 to len - 1 do Paint(cable[i], Esc('33') + '██');
  Paint(cable[0], Esc('93') + '██');
  NewPacket; Status;
end;

{ One step: the head moves on; it grows on a packet, otherwise the tail moves after it }
procedure Step;
var head: TCell; i: integer;
begin
  head.x := cable[0].x + dx; head.y := cable[0].y + dy;
  if (head.x < 1) or (head.x > Cols) or (head.y < 1) or (head.y > Rows) then begin over := true; Exit; end;
  if (head.x = packet.x) and (head.y = packet.y) then
  begin
    Inc(len); Inc(score, 10); if wait > 60 then Dec(wait, 8);
  end
  else
  begin
    used[cable[len - 1].x, cable[len - 1].y] := false; Paint(cable[len - 1], '  ');
  end;
  if used[head.x, head.y] then begin over := true; Exit; end;
  for i := len - 1 downto 1 do cable[i] := cable[i - 1];
  Paint(cable[0], Esc('33') + '██');
  cable[0] := head; used[head.x, head.y] := true;
  Paint(head, Esc('93') + '██');
  if (head.x = packet.x) and (head.y = packet.y) then NewPacket;
  Status;
end;

{ A key turns the cable; it cannot turn straight back into itself }
procedure Steer(k: char);
begin
  case k of
    #72: if dy = 0 then begin dx := 0; dy := -1; end;
    #80: if dy = 0 then begin dx := 0; dy := 1; end;
    #75: if dx = 0 then begin dx := -1; dy := 0; end;
    #77: if dx = 0 then begin dx := 1; dy := 0; end;
  end;
end;

{ The next key: in STEP mode it waits for one, otherwise it waits at most one step of time }
function NextKey: char;
var t: integer = 0;
begin
  Result := #255;
  if not stepMode then
    while (t < wait) and not KeyPressed do begin Delay(10); Inc(t, 10); end;
  if stepMode or KeyPressed then
  begin
    Result := ReadKey;
    if Result = #0 then begin Steer(ReadKey); Result := #255; end;
  end;
end;

begin
  Assign(con, ''); Rewrite(con);
  if GetEnvironmentVariable('SEED') <> '' then RandSeed := StrToInt(GetEnvironmentVariable('SEED')) else Randomize;
  stepMode := GetEnvironmentVariable('STEP') = '1';
  Send(#27'[?25l');
  NewRun;
  repeat
    c := NextKey;
    if c = 'n' then NewRun
    else if not over and (c <> 'q') then
    begin
      Step;
      if over then
        Send(At(Left + 8, Top + Rows div 2) + Esc('1;37;41') + Format('  The cable is cut. Score %d.  ', [score])
          + At(Left + 8, Top + Rows div 2 + 1) + Esc('0;33') + '  n new run   q quit' + Esc('0'));
    end;
  until c = 'q';
  Send(Esc('0') + #27'[2J' + At(1, 1) + #27'[?25h');
end.
