Pascal · projectCable run: a moving game in Free Pascal
Cable run is an action game for the SSH window. You steer a network cable with the arrow keys. Each data packet it picks up makes it one cell longer, adds 10 points and makes it faster, until the cable hits the frame or itself.
╔═ Cable run ════════════════════════════════════════════════╗ ┌─ Run ───────┐ ║ ║ │ │ ║ ║ │Score 0 │ ║ ║ │Length 4 │ ║ ║ │Speed 6/s│ ║ [] ║ └─────────────┘ ║ ║ ║ ║ [] a packet ║ ║ ║ ████████ ║ ↑ ↓ ← → steer ║ ║ n new run ║ ║ q quit ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ╚════════════════════════════════════════════════════════════╝
╔═ Cable run ════════════════════════════════════════════════╗ ┌─ Run ───────┐ ║ ║ │ │ ║ ║ │Score 20 │ ║ ║ │Length 6 │ ║ ║ │Speed 7/s│ ║ ║ └─────────────┘ ║ ████████████ ║ ║ ║ [] a packet ║ ║ ║ ║ ↑ ↓ ← → steer ║ ║ n new run ║ ║ q quit ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ [] ║ ╚════════════════════════════════════════════════════════════╝
╔═ Cable run ════════════════════════════════════════════════╗ ┌─ Run ───────┐ ║ ██ ║ │ │ ║ ██ ║ │Score 20 │ ║ ██ ║ │Length 6 │ ║ ██ ║ │Speed 7/s│ ║ ██ ║ └─────────────┘ ║ ██ ║ ║ ║ [] a packet ║ ║ ║ The cable is cut. Score 20. ║ ↑ ↓ ← → steer ║ n new run q quit ║ n new run ║ ║ q quit ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ [] ║ ╚════════════════════════════════════════════════════════════╝
Download it on the NAS
curl -fsSLO https://kb.nasutils.net/projects/pascal/game.pasgame.pas Download game.pas
{ 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.
What you learn
- A game loop without blocking:
KeyPressedchecks for a key,Delay(10)waits 10 ms, and the cable moves when the time of one step is up. - The record
TCellkeeps the column and the line of one cell; the cable is an array of them, head first. - A grid
used[x, y]of booleans answers "is the cable here?" in one look, without a walk along the cable. - Only the cells that change get drawn: the new head, the old head as body and the cell the tail leaves.
RandSeed := StrToInt(...)makesRandomgive the same packets for the sameSEED.
How it works
NewRun clears the grid, lays a cable of 4 cells in the middle line, draws the frame, the panel with the score and the key help, and puts down the first packet. One cell of the field is two characters wide, so a cell looks square.
Each step Step works out the new head. Outside the frame the run ends. On the packet the cable grows: the tail stays where it is, the score rises by 10 and the time of a step drops by 8 ms, down to 60 ms. Elsewhere the tail cell gets free and is cleared. If the new head lands on a cell of the cable, the run ends too. Otherwise every cell moves one place back in the array and the head goes in front.
NextKey decides when the next step comes. In play it waits up to one step of time for a key. With STEP=1 it waits for a key and every key is one step, so a test, or a reader learning the rules, sees the same moves every time.
Notes to the lines
- 9The field has 30 x 18 cells; it starts at column 3, line 4 of the screen.
- 14The cable can grow to fill the field, so the array has one cell per cell of the field.
- 27–28
Paintturns a cell into a screen position: two columns per cell. - 38A new packet never lands on the cable: the loop draws again until the cell is free.
- 47The cable starts with its head at cell 8 and its tail at cell 5 of the middle line, moving right.
- 65A head outside the field means the cable hit the frame.
- 68A packet: longer, 10 points, and 8 ms less per step while the step is above 60 ms.
- 72Without a packet the tail leaves its cell before the check on line 74, so the head may take that cell.
- 75–78The body moves one place back, the old head turns plain amber and the new head bright amber.
- 87–90A turn is allowed only across the way the cable runs, so it never turns back into itself.
- 99–100The wait for a key in steps of 10 ms; a key ends the wait at once.
- 110With
SEEDthe packets come in the same order; without it,Randomizetakes the clock. - 120–122The message of a cut cable goes over the middle of the field.
Run it
fpc game.pas && ./gameThe arrow keys steer, n starts a new run and q quits. STEP=1 ./game moves the cable one step per key; space steps without a turn.
Try it yourself
Make the cable faster from the start: set wait := 100 on line 46. Give 20 points for a packet once the cable is longer than 10 cells.
More projects in Pascal
- A menu bar with drop-down boxes in Free PascalA Free Pascal program draws a desktop with a menu bar, drop-down boxes and dialog boxes with shadows, and fills the dialogs with the NAS's memory, load, processor, volumes and RAID groups. You learn to draw boxes with escape codes, read keys with crt and run commands with POpen.
- A greeting screen with large letters in Free PascalA Free Pascal program prints the word NAS in large block letters, greets you by the hour and lists the model, kernel, uptime, load and memory in a framed table. You learn records and dynamic arrays, reading the date with dateutils and drawing a table with box characters.
- A NAS summary in two columns in Free PascalA Free Pascal program reads the CPU, temperatures, load, memory, data volumes and network ports into records and prints them as framed panels in two columns. You learn records, dynamic arrays of records, var parameters and a layout built from lists of lines.
- Cable run: a moving game in Free PascalA Free Pascal game where you steer a network cable round a frame with the arrow keys; it grows with every data packet it picks up, and the wall or its own body ends the run. You learn a game loop with KeyPressed and Delay, records for coordinates and drawing only the cells that change.
- A temperature chart of the NAS in Free PascalA Free Pascal program asks QNAP's getsysinfo for the system, CPU and disk temperatures and draws them as a vertical bar chart with a scale, coloured green, amber or red by level. You learn to build a chart line by line from the top and to treat an empty disk bay as a value of its own.
- A log viewer with colours and search in Free PascalA Free Pascal program shows a log file a screen at a time, colours warnings amber and errors red, scrolls with the arrow and page keys and jumps to the next error with /. You learn to load a file into a TStringList, keep a window of lines on the screen and search with UpperCase and Pos.