Skip to content

Instantly share code, notes, and snippets.

@aisamanra
Created March 10, 2022 03:56
Show Gist options
  • Save aisamanra/2dea5f9e324fa2d66029bf821064646a to your computer and use it in GitHub Desktop.
Save aisamanra/2dea5f9e324fa2d66029bf821064646a to your computer and use it in GitHub Desktop.
A terminal-based Wordle clone for four-letter Toki Pona words
require 'csv'
require 'set'
module Tokile
YELLOW = "\x1b[33m"
GREEN = "\x1b[32m"
CLEAR = "\x1b[39m"
UP = "\033[F"
TOKI_LETTERS = Set.new(%w{a e i o u m n p t k s w l j})
# all the four-letter words from pu
WORDS = [
'anpa',
'ante',
'awen',
'esun',
'insa',
'jaki',
'jelo',
'kala',
'kama',
'kasi',
'kili',
'kule',
'kute',
'lape',
'laso',
'lawa',
'lete',
'lili',
'lipu',
'loje',
'luka',
'lupa',
'mama',
'mani',
'meli',
'mije',
'moku',
'moli',
'musi',
'mute',
'nasa',
'nena',
'nimi',
'noka',
'olin',
'open',
'pali',
'pana',
'pini',
'pipi',
'poka',
'poki',
'pona',
'sama',
'seli',
'selo',
'seme',
'sewi',
'sike',
'sina',
'sona',
'suli',
'suno',
'supa',
'suwi',
'taso',
'tawa',
'telo',
'toki',
'tomo',
'unpa',
'walo',
'waso',
'wawa',
'weka',
'wile',
]
def self.print_state(state, last_guess)
str = [UP]
state.zip(last_guess.chars).each do |s, guess|
if guess == s[:char]
str << GREEN
elsif state.map {|s| s[:char]}.include?(guess)
str << YELLOW
end
str << guess
str << CLEAR
str << " "
end
puts " #{str.join}"
end
def self.guess
loop do
begin
print("> ")
ln = gets
if ln.nil?
puts UP
next
end
ln = ln.strip
rs = ln.strip.gsub(/ +/, '')
if rs.size != 4
puts("#{UP}\x1b[31m #{ln} (not 4 letters)\x1b[39m")
elsif rs.chars.any? {|c| !TOKI_LETTERS.include?(c)}
err = ln.chars.map {|c| TOKI_LETTERS.include?(c) ? c : "\x1b[31m#{c}\x1b[39m"}.join
puts("#{UP} #{err} \x1b[31m(non Toki Pona letters)\x1b[39m")
else
return rs
end
rescue Interrupt
exit
end
end
end
def self.main
word = WORDS.sample
state = word.chars.map {|c| {:char => c, :known => false}}
(0..3).each do |_|
this_guess = guess
print_state(state, this_guess)
exit if word == this_guess
end
puts word.chars.join(" ")
end
end
Tokile.main if $PROGRAM_NAME == __FILE__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment