Created
January 11, 2022 08:52
-
-
Save zmalltalker/65c23e71d5c5deef919aa53634250aea to your computer and use it in GitHub Desktop.
Wordle CLI clone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In order to play the server version, use
telnet
ornc
to connect to your game server: