22 — Terminal menu — a small TUI
A menu shows what can be done, lets you choose one, does it, and comes back to the menu. Because it clears the screen and draws it again, one window seems to stay alive. The clearing, the box and the rule from 14 — Screen all appear here. No quotes, no brackets, no equals sign.
Steps
Draw just the menu screen first:
run it →clear the screen say in a box A small menu show greet show dice show quit draw a lineThe screen goes clean, the title sits in a box, the three things you can do appear, and a rule closes them off.
Let them choose, and branch:
run it →ask choice What now? if choice equals greet show Hello there! else if choice equals quit show Goodbye else show There is no such thing endWords are easier answers than numbers. What someone types is always text, so an answer of
1is the letter1and never equals the number 1.To come back to the menu, wrap the whole thing in
repeat forever. The only way out isstop, so it belongs in thequitbranch alone:
run it →repeat forever clear the screen say in a box A small menu show quit draw a line ask choice What now? if choice equals quit show Goodbye stop end endPause so the answer can be read. Without it the screen is wiped before anyone sees what just appeared:
run it →show Hello there! wait 1 secondThe whole thing is
examples/terminal-menu.nme, and the Korean twin isexamples/terminal-menu.ko.nme.
run it →repeat forever clear the screen say in a box A small menu show greet show dice show quit draw a line ask choice What now? if choice equals greet show Hello there! wait 1 second else if choice equals dice set roll to random number from 1 to 6 show roll wait 1 second else if choice equals quit show Goodbye stop else show There is no such thing wait 1 second end end
Try it yourself
Add one more thing it can do. An answer of time could show how many seconds
the program has been running, using the stopwatch from 15 — Time.
What you learned
- A menu is
repeat foreverplus a chain of conditions. Nothing more. - Clearing the screen at the top of the loop makes one window seem to live on.
- Words are better answers than numbers: what is typed is always text.
wait 1 secondbefore the screen is wiped is what makes it readable.stopis the only way out.