Newer
Older
Ruby / happyou.rb
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

require "csv"
require "rmagick"
require "curses"
include Curses

init_screen

def output(word,x,y)
  setpos(x,y)
  addstr(word)
  refresh
end

quiz_key_ary = []
quiz_key_value = []
quiz_choice = []
quiz_choice_all = []
quiz_explanation = []
quiz_picture = []
quiz_csv = CSV.read("quiz.csv",:headers => true)  #CSVファイル読み込み
quiz_csv.each{|row|
  quiz_key_ary << row["クイズ"]
  quiz_key_value << row["答え"].to_i
  quiz_choice << "1.#{row["選択肢 1"]}"
  quiz_choice << "2.#{row["選択肢 2"]}"
  quiz_choice << "3.#{row["選択肢 3"]}"
  quiz_choice_all << quiz_choice
  quiz_choice = []
  quiz_explanation << row["解説"]
  quiz_picture << row["写真"]
}
ary = [quiz_key_ary,quiz_key_value].transpose
quiz_hash = Hash[*ary.flatten]

output("クイズ",0,0)
sleep(3)
clear
refresh
correct = 0
quiz_hash.length. times do
  order = rand(quiz_hash.length)
  srand()
  output(quiz_hash.keys[order],0,0)
  x = 1
  y = 4
  for i in quiz_choice_all[order]
    output(i,x,y)
    x += 2
  end
  begin
    curs_set(0)
    noecho
    stdscr.keypad(true)
    choice = 1
    a = 1
    b = 1
    refresh
    while true
      setpos(b,a)
      addstr(">>")
      refresh
      c = getch
      setpos(b,a)
      addstr("  ")
      refresh
      case c
      when Curses::KEY_UP
        if choice > 1
          b -= 2
          choice -= 1
        end
      when Curses::KEY_DOWN
        if choice < 3
          b += 2
          choice += 1
        end
      when Curses::KEY_LEFT
        sleep(3)
        right_answer = quiz_hash.values[order]
        if choice.to_i == right_answer
          output("正解",9,0)
          correct += 1
        else
          output("不正解",9,0)
        end
        sleep(1)
        output("解説\n",10,0)
        sleep(3)
        output(quiz_explanation[order].to_s,11,0)
        picture = Magick::ImageList.new(quiz_picture[order])
        new_picture = picture.resize(0.25)
        new_picture.write("new_picture.png")
        picture = spawn "display -geometry +0+0 new_picture.png"
        sleep(5)
        Process.kill(:INT,picture)
        clear
        refresh
        quiz_hash.delete(quiz_hash.keys[order])
        quiz_explanation.delete_at(order)
        quiz_choice_all.delete_at(order)
        quiz_picture.delete_at(order)
        break
      end
    end
  ensure
    close_screen
  end
end
printf("正答数:%d/12\n",correct)
printf("正答率:%dパーセント",correct * 100 / 12)