Skip to content

Instantly share code, notes, and snippets.

@0racle
Created January 15, 2022 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0racle/77fb3e50b6b9b8666ba4082188bb81d8 to your computer and use it in GitHub Desktop.
Save 0racle/77fb3e50b6b9b8666ba4082188bb81d8 to your computer and use it in GitHub Desktop.
Terminal based Wordle-ish game
#!/usr/bin/env raku
use Term::ReadKey;
use Terminal::ANSIColor;
use Terminal::Print < T >;
unit sub MAIN(:$chars = 5, :$tries = 6);
my @wordlist = '/usr/share/dict/SOWPODS'.IO.words;
my $words = @wordlist.grep(*.chars == $chars).Set;
T.initialize-screen;
my ($h, $w) = (T.rows, T.columns);
my $X = ($w div 2);
my $Y = ($h div 2) - ($tries div 2) - 2;
my ($x, $y);
my $unused = Set('A' .. 'Z');
my &draw-remaining = {
T.print-string: $X - 13, $Y + $tries + 2, ('A' .. 'Z').batch(13).map({
.map(-> $l { colored($l, $unused{$l} ?? 'white' !! 'magenta') })
}).join("\n")
}
my &draw-blanks = {
my $col = 'white';
for 0 ..^ $tries -> $i {
T.print-string:
$x, $y + $i, colored(~('_' xx $chars), $col);
$col = 'magenta';
}
}
my @word;
my @guess;
my $turn = 0;
my &start-game = {
($x, $y) = ($X - ($chars × 2) div 2, $Y);
@word = $words.keys.pick.comb;
draw-remaining();
draw-blanks();
}
start-game();
react {
whenever key-pressed(:!echo) -> $k {
given $k {
when $turn == $tries {
T.print-string: $x, $Y + $tries, ' ' x ($chars × 2);
@word = $words.keys.pick.comb;
$unused = Set('A' .. 'Z');
start-game();
$turn = 0;
}
when /<:L>/ && @guess.elems < $chars {
@guess.push: $k.uc;
T.print-string: $x, $y, $k.uc;
$x += 2;
}
when .ord == 127 && @guess.elems > 0 {
$x -= 2;
T.print-string: $x, $y, '_';
@guess.pop if @guess;
}
when .ord == 10 && @guess.elems == $chars {
if $words{@guess.join}:!exists {
for (< red white > xx 2).flat -> $col {
T.print-string:
$X - ($chars × 2) div 2, $y, colored(~@guess, $col);
sleep 0.05;
}
}
else {
my $ok = 0;
$x = $X - ($chars × 2) div 2;
T.print-string: $x, $y, ~(@guess Z @word).map: -> ($a, $b) {
my $col = do {
when $a eq $b { $ok++; 'black on_green' }
when $a ∈ @word { 'black on_yellow' }
default { 'white' }
}
colored($a, $col);
}
$unused ∖= @guess;
draw-remaining();
@guess = ();
$turn++;
$y++;
if $ok == $chars {
$turn = $tries;
T.print-string:
$x, $Y + $tries, colored(~('*' xx $chars), 'green');
}
elsif $turn == $tries {
T.print-string:
$x, $Y + $tries, colored(~@word, 'red');
}
else {
T.print-string: $x, $y, ~('_' xx $chars);
}
}
}
}
}
}
T.shutdown-screen
@0racle
Copy link
Author

0racle commented Jan 22, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment