#!ruby -Ks
# 元ネタはhttp://www.meigaku.ac.jp/~watayan/prog/
# このファイルはhttp://homepage2.nifty.com/zn/nnikki/files/ke.rb

require 'vr/vruby'
require 'vr/vrcontrol'
require 'vr/vrtimer'
require 'Win32API'

class KE
  NumberKE = 1000
  MoveSize = 4

  GetWindowRect = Win32API.new('user32','GetWindowRect','LP','I')

  def initialize(hWnd)
    rect = [0,0,0,0].pack('L4')
    @scleft,@sctop,@scright,@scbottom =
      0,0,VRLocalScreen.width,VRLocalScreen.height
    GetWindowRect.call hWnd, rect
    left,top,right,bottom = rect.unpack('L4')
    @ke = []
    NumberKE.times do |i|
      if i < NumberKE / 2 # left or right
        @ke.push [
          if i % (NumberKE / 2) > NumberKE / 4
            left
          else
            right
          end,
          top + rand(bottom - top)
        ]
      else
        @ke.push [
          left + rand(right - left),
          if i % (NumberKE / 2) > NumberKE / 4
            top
          else
            bottom
          end
        ]
      end
    end
  end

  GetDC = Win32API.new('user32','GetDC','L','L')
  ReleaseDC = Win32API.new('user32','ReleaseDC','LL','I')
  NULL = 0
  MoveToEx = Win32API.new('gdi32','MoveToEx','LLLL','L')
  LineTo = Win32API.new('gdi32','LineTo','LLL','L')

  def disp
    hDC = GetDC.call(NULL)
    @ke.each do |ke|
      if 0 <= ke[0] # Is this ke alive?
        MoveToEx.call(hDC, ke[0], ke[1], NULL)
        ke[0] += (rand(MoveSize * 2 + 1) - MoveSize)
        ke[1] += (rand(MoveSize * 2 + 1) - MoveSize)
        if ke[0] < @scleft or @scright  < ke[0] or
           ke[1] < @sctop  or @scbottom < ke[1]
          ke[0] = -1
        else
          LineTo.call(hDC, ke[0], ke[1])
        end
      end
    end
    ReleaseDC.call(NULL, hDC)
  end
end
class MyForm < VRForm
  include VRTimerFeasible

  def construct
    self.caption = '何もしないプログラムに毛の生えたやつ'
    @ke = KE.new(self.hWnd)

   # addControl VRButton, 'grow', '増毛', 10,10,250,50

    @fClean = true
    addHandler WMsg::WM_MOVE, 'move', MSGTYPE::ARGINTSINTSINT,nil
    acceptEvents [WMsg::WM_MOVE]

    addTimer 100, 't1'
  end

  def grow_clicked
    @ke.disp
  end

  def t1_timer
    @ke.disp
  end

  def self_move(*arg)
    unless @fClean
      deleteTimer 't1'
      messageBox '毛がちぎれたので終了します。'
      self.close
    else
      @fClean = false
    end
  end
end
VRLocalScreen.start(MyForm)

