Hello. This time I will make a typing game in Ruby. If you want to try it for the time being, please try it from here.
Then how to make it? I will write.
This time it was troublesome, so I only use 100 English words, but please add as you like. If you change it a little, you should be able to speak Japanese (although it seems to be troublesome to support Hepburn romanization) (Is it okay to set the Hash value to list?
Well, I think you can do it properly here. It ’s not that important.
You can do it easily with ʻio / console`. Ruby is easy to do like this, isn't it?
require 'io/console'
ch = STDIN.getch
puts ch
It is assumed that words contains a list of words written in [1].
require 'io/console'
miss = 0
all = 0
flag = false
while true
word = words.sample
puts "\e[36m#{word}\e[0m"
i = -1
wl = word.length
print "\e[2m#{word}\e[0m"
while i != (wl-1)
i += 1
key = STDIN.getch
all += 1
if key == word[i]
print "\r#{word[0..i]}\e[2m#{word[i+1..wl]}\e[0m"
elsif key == "\C-c"
flag = true
break
else
print "\r#{word[0...i]}\e[31m#{word[i]}\e[0m\e[2m#{word[i+1..wl]}\e[0m"
miss += 1
i -= 1
end
end
break if flag
puts
end
Well, it's simple to do, so you'll understand. \ r
is a carriage return and \ e [~~ m
is an ANSI escape sequence.
require 'io/console'
require 'benchmark'
miss = 0
all = 0
flag = false
result = Benchmark.realtime do
while true
word = words.sample
puts "\e[36m#{word}\e[0m"
i = -1
wl = word.length
print "\e[2m#{word}\e[0m"
while i != (wl-1)
i += 1
key = STDIN.getch
all += 1
if key == word[i]
print "\r#{word[0..i]}\e[2m#{word[i+1..wl]}\e[0m"
elsif key == "\C-c"
flag = true
break
else
print "\r#{word[0...i]}\e[31m#{word[i]}\e[0m\e[2m#{word[i+1..wl]}\e[0m"
miss += 1
i -= 1
end
end
break if flag
puts
end
end
print "\e[2K\e[1A\e[2K\r"
puts "miss: #{miss}"
printf "press: %.5f/s\n" %(all / result)
Well this is also simple. The time until C-c
is done with Benchmark.realtime
is measured, and the number of keystrokes per second is calculated based on that. \ e [~~ K
, \ e [~~ A
are also ANSI escape sequences.
ruby main.rb
Recommended Posts