bordle/src/game.cr

81 lines
2.1 KiB
Crystal
Raw Normal View History

2022-08-21 13:43:39 +02:00
require "colorize"
require "./types"
require "./dictionary"
require "./target_word"
2025-06-14 15:49:42 +02:00
class Bordle
2022-08-21 13:43:39 +02:00
class Game
def initialize
@length = 5_u8
@dict = Dictionary.new(@length)
@target = TargetWord.new(@dict.choose_word)
end
def display(diff : Array(LetterScore), try)
printf("#{try}. ")
diff.each do |ls|
colors = case ls[1]
2025-06-14 15:49:42 +02:00
when Score::NotOk then {:white, :black}
2022-08-21 13:43:39 +02:00
when Score::WrongPlace then {:white, :yellow}
when Score::RightPlace then {:white, :green}
2025-06-14 15:49:42 +02:00
else {:white, :black}
2022-08-21 13:43:39 +02:00
end
str = ("%s" % ls[0]).colorize.fore(colors[0]).back(colors[1])
printf("%s", str)
end
puts ""
end
def input_word(try)
word = ""
loop do
printf "#{try}. "
word = gets()
word = "" if word.nil?
word.tr(TR_DIACRITICS, TR_ASCII).downcase
2025-06-14 15:49:42 +02:00
error = [] of String
error << "language" if !@dict.includes? word
error << "length" if word.size != @length
2022-08-21 13:43:39 +02:00
break if word.size == @length && @dict.includes? word
printf("\x1B[A\x1B[2K")
2025-06-14 15:49:42 +02:00
puts "-- #{word} : invalid #{error.join(" and ")} --"
2022-08-21 13:43:39 +02:00
end
word
end
def run
2025-06-14 15:49:42 +02:00
puts "-- BORDLE (#{@target.inspect}) --".colorize.fore(:blue)
puts <<-MARK
1. You win when you find the secret word.
2. You have 5 attempts; you lose if you use them all.
3. The secret word is in #{@dict.language} and 5 characters long.
4. Language and length mistakes are not counted as attemps.
5. Diacritics (accents, etc.) are removed.
6. Use CTRL-C to exit.
MARK
puts ""
puts " ....."
2022-08-21 13:43:39 +02:00
try = 0
2025-06-14 15:49:42 +02:00
while true
2022-08-21 13:43:39 +02:00
try += 1
word = input_word(try)
printf("\x1B[A\x1B[2K")
diff = @target.diff(word)
display(diff, try)
if @target.equals?(word)
puts "-- GAGNÉ ! --".colorize.fore(:green)
return
end
2025-06-14 15:49:42 +02:00
if try >= 5
2022-08-21 13:43:39 +02:00
puts "-- PERDU ! --".colorize.fore(:red)
return
end
end
end
end
end