readlineを使用してコマンドラインから実行できるタイピングゲームを作りました。
まずはベースとなるソースコードです。
任意のファイル名で保存し、実行するとタイピングゲームが始まります。
# -*- coding: utf-8 -*-
# タイピング
require "readline"
qa = [
"take a risk.",
"easier said than done.",
"more haste, less speed.",
"there is always something better.",
"good morning.",
]
score = 0
puts "問題は#{ qa.length }問です。"
qa.shuffle!
start_time = Time.now
qa.each_with_index do |text, i|
puts "第#{i+1}問"
puts text
loop do
t = Readline.readline('入力: ')
if text == t
puts "正解"
score += 10
break
else
puts "入力ミス!!"
score -= 10
end
end
end
end_time = Time.now
time = end_time - start_time
puts "時間: #{time} sec"
puts "得点は#{score}点でした"
puts "returnまたはenterキーで終了します。"
gets
上記のコードをベースに、時間を得点に換算したり、裏技的なボーナスポイントを付けたり、表示を調整したものが以下のコードになります。
# -*- coding: utf-8 -*-
# タイピング
require "readline"
#初期設定
qa = [
"take a risk.",
"easier said than done.",
"more haste, less speed.",
"there is always something better.",
"good morning.",
]
max_score = 50 * qa.join.size
score = 0
point = 10
bonus_hints = ["Rubyを楽しみなさい", "Rubyってカッコいい"]
bonus_words = ["ruby is cool", "enjoy ruby"]
ng_word = []
#ゲームスタート
puts "----------------------------------------------------------"
puts "問題は#{ qa.length }問です。"
puts "ボーナスヒント「#{bonus_hints[rand(bonus_hints.length)]}」(英語で書くと…)"
puts "----------------------------------------------------------\n\n"
#入力モードチェック
loop do
puts '入力モードが半角英数字であることを確認し、スペース入力後、Enterを押してください。'
t = Readline.readline('入力')
if t == " "
puts "スタート\n\n"
break
else
puts "入力モードを確認してください。"
end
end
#入力スタート
qa.shuffle!
start_time = Time.now
qa.each_with_index do |text, i|
puts "第#{i+1}問"
loop do
puts "入力:「#{text}」"
t = Readline.readline('> ')
if text == t
puts "正解"
score += point
break
elsif bonus_words.include? t
puts "偉い! ボーナス#{point*5}点!!"
score += point*2
ng_word = bonus_words.delete t
elsif ng_word.include? t
puts "あまいわ! マイナス#{point*5}点!!!"
score -= point*2
else
puts "入力ミス!!"
score -= point
end
end
puts "\n"
end
end_time = Time.now
time = end_time - start_time
time = time.ceil
score += max_score / time
#結果発表
puts "得点は#{score}点でした"
puts "returnまたはenterキーで終了します。"
gets
あと、今の問題は英語の文章にしてるけど、rubyの文法とかにしても面白いかも。
String.new("hoge")
ary = [1, 2, 3, 4]
puts "hoge"
(1..9).to_a.each { |ary| puts ary }
などなど、やってみれば遊びながらメドッドを覚えたり、入力スピードがアップできないかな。。。