Skip to content

Instantly share code, notes, and snippets.

@zmalltalker
Created January 11, 2022 08:52
Show Gist options
  • Save zmalltalker/65c23e71d5c5deef919aa53634250aea to your computer and use it in GitHub Desktop.
Save zmalltalker/65c23e71d5c5deef919aa53634250aea to your computer and use it in GitHub Desktop.
Wordle CLI clone
def guess(guessed, correct)
guessed_chars = guessed.split(//)
correct_chars = correct.split(//)
used_chars = correct_chars.dup
result = guessed_chars.map.with_index do |c, idx|
if correct_chars[idx] == c
used_chars.delete(c)
:correct
elsif used_chars.include?(c)
used_chars.delete(c)
:wrong_placement
else
:wrong
end
end
end
def cli_print_result(guessed, correct)
guesses = guess(guessed, correct)
result = guessed.split(//).map.with_index do |c, idx|
str = case guesses[idx]
when :correct
"\e[42m#{c.upcase}\e[0m"
when :wrong_placement
"\e[43m#{c.upcase}\e[0m"
when :wrong
"\e[m#{c.upcase}\e[0m"
end
str
end
result.join("")
end
def print_result(result)
m = {correct: "🟩", wrong_placement: "🟨", wrong: "🟥"}
result.map{|c|m[c]}.join("")
end
def play(correct_word, io)
io.puts "Enter your guess (#{correct_word.size} characters)"
correct_answer = false
tries = []
until correct_answer do
given = io.gets.chomp
tries << given
result = guess(given, correct_word)
io.puts cli_print_result(given, correct_word)
if result.all?{|c|c == :correct}
correct_answer = true
end
end
tries.each do |t|
io.puts print_result(guess(t, correct_word))
end
end
def words_of_length(l)
words = File.read("./1000-most-common-words.txt").split("\n")
words.select{|w|w.length == l}
end
def play_game(io)
io.puts "Let's play Wordle. How many characters should I use for the word?"
length = io.gets.chomp.to_i
dictionary = words_of_length(length)
idx = Random.rand(dictionary.size)
word = dictionary[idx]
begin
play(word, io)
rescue Interrupt
io.puts "You gave up. The correct word was #{word.upcase}"
end
end
# Play over a socket
require "socket"
PORT = 3000
server = TCPServer.open(PORT)
loop do
puts "Server running on port #{PORT}"
client_connection = server.accept
Thread.start(client_connection) do |connection|
play_game(connection)
connection.close
end
end
# Uncomment for local game
#play_game(IO.new(STDOUT.fileno))
@zmalltalker
Copy link
Author

Wordle must be one of the most fun programming exercises I have seen for a while.

This version lets you select how long the word should be, suggests a word from a dictionary of common worlds and then lets you play in the CLI.

Can be run as a server, or just alone in your terminal.

No dependencies, just this single script.

@zmalltalker
Copy link
Author

In order to play the server version, use telnet or nc to connect to your game server:

nc localhost 3000

@zmalltalker
Copy link
Author

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