Rubyの宿題教えてください。2限目

このエントリーをはてなブックマークに追加
309デフォルトの名無しさん
require 'tk'
class Drill100
 PACKOPT = {:side=>:left,:fill=>:both,:expand=>true}
 PACKOPTF = {:side=>:top,:fill=>:both,:expand=>true}
 CELLOPT = {:width=>3}
 def initialize(root)
  @root = root
  @root.title = '100マス計算'
  @size,@min,@max = ( $test ? [2,0,9] : [10,11,99] )
  @column,@row,@cells = [],[],[]
  f = TkFrame.new(@root).pack(PACKOPTF)
  @reset = TkButton.new(f,:text=>'切替',:command=>proc{init}).pack(:side=>:left)
  @start = TkButton.new(f,:text=>'開始',:command=>proc{start}).pack(:side=>:left)
  f = TkFrame.new(@root).pack(PACKOPTF)
  @op = TkLabel.new(f,CELLOPT).pack(PACKOPT)
  @size.times {|i| @column << TkLabel.new(f,CELLOPT).pack(PACKOPT) }
  @size.times do |i|
   f = TkFrame.new(@root).pack(PACKOPTF)
   @row << TkLabel.new(f,CELLOPT).pack(PACKOPT)
   @cells << []
   @size.times {|j| @cells[i] << TkEntry.new(f,CELLOPT).pack(PACKOPT) }
  end
 end
 def init
  @reset.state = :normal
  @start.configure(:text=>'開始',:command=>proc{start})
  @op.text = {'+'=>'-','-'=>'*','*'=>'+'}[@op.text] || '+'
  [@column,@row].each {|labels| labels.each {|l| l.text = random(@min,@max).to_s }}
  @cells.each {|line| line.each {|cell| cell.state = :disabled }}
 end
# つづく
310デフォルトの名無しさん:2009/01/05(月) 10:20:05
# つづき
 def start
  @reset.state = :disabled
  @start.configure(:text=>'確認',:command=>proc{check})
  @cells.each {|line| line.each {|cell| cell.state = :normal ; cell.value = '' }}
  @cells[0][0].focus
  @starttime = Time.now
 end
 def check
  @endtime = Time.now
  @cells.each_with_index do |line,r|
   line.each_with_index do |cell,c|
    y,x = @row[r].text.to_i,@column[c].text.to_i
    case @op.text
    when '+' then answer = y + x
    when '-' then answer = y - x
    when '*' then answer = y * x
    end
    ( cell.focus ; Tk.bell ; return ) if answer != cell.value.to_i
   end
  end
  time = @endtime - @starttime
  TkDialog.new(@root,:buttons=>[:OK],:message=>"#{time.to_i}秒かかりました")
  init
 end
 def random(min,max) ; rand(max - min + 1) + min ; end
 def run ; init ; Tk.mainloop ; end
end
# $test = true
Drill100.new(Tk.root).run
311デフォルトの名無しさん:2009/01/05(月) 10:52:54
# 修正
# >>309 initialize の中ほど
  @reset = TkButton.new(f,:text=>'切替',:command=>proc{init}).pack(PACKOPT)
  @start = TkButton.new(f,:text=>'開始',:command=>proc{start}).pack(PACKOPT)
# >>310
 def check
  time = Time.now - @starttime
  op = {'+'=>proc{|y,x| y+x},'-'=>proc{|y,x| y-x},'*'=>proc{|y,x| y*x}}[@op.text]
  @cells.each_with_index do |line,r|
   line.each_with_index do |cell,c|
    answer = op.call(@row[r].text.to_i,@column[c].text.to_i)
    ( cell.focus ; Tk.bell ; return ) if answer != cell.value.to_i
   end
  end
  TkDialog.new(@root,:title=>'全問正解',:buttons=>[:OK],:message=>"#{time.to_i}秒かかりました")
  init
 end
312デフォルトの名無しさん:2009/01/05(月) 11:12:45
もしかして減算は上の値から左の値を引くのかな
だったらcheckメソッド内の '-'=>proc{|y,x| y-x} を {|y,x| x-y} に修正