1require 'osx/cocoa' 2 3class AppCtrl < OSX::NSObject 4 5 ib_outlets :playingView, :startBtn 6 7 def awakeFromNib 8 paddle_init 9 ball_init(@paddle) 10 end 11 12 def start 13 if @thread == nil then 14 @movings.each {|m| m.died = false } 15 @startBtn.setTitle "Stop" 16 @thread = Thread.start do 17 loop do 18 sleep 0.02 19 ary = @movings.select {|m| ! m.died } 20 if ary.size > 0 then 21 ary.each {|m| m.next } 22 else 23 break 24 end 25 redraw 26 end 27 @thread = nil 28 reset 29 end 30 end 31 end 32 33 def reset 34 stop 35 @playingView.balls.replace [] 36 ball_init(@paddle) 37 end 38 39 def stop 40 @thread.kill if @thread 41 @thread = nil 42 @startBtn.setTitle "Start" 43 end 44 45 def redraw 46 @playingView.setNeedsDisplay(true) 47 end 48 49 def mouseDragged(evt) 50 point = @playingView.convertPoint_fromView(evt.locationInWindow, nil) 51 @paddle.hpos = point.x 52 redraw 53 end 54 55 def startBtnClicked(sender) 56 if @thread then 57 stop 58 else 59 start 60 end 61 end 62 ib_action :startBtnClicked 63 64 def resetBtnClicked(sender) 65 stop 66 reset 67 redraw 68 end 69 ib_action :resetBtnClicked 70 71 def windowShouldClose(sender) 72 OSX::NSApp.stop(self) 73 true 74 end 75 ib_action :windowShouldClose 76 77 def ball_init(paddle) 78 @movings = Array.new 79 [ 80 [ rand(200), rand(200), 5.0, angle_new, OSX::NSColor.redColor ], 81 [ rand(200), rand(200), 4.0, 180 - angle_new, OSX::NSColor.blueColor ] 82 ].each do |h,v,s,a,c| 83 ball = Ball.new(c) 84 ball.hpos = h 85 ball.vpos = v 86 moving = BallMoving.new(ball, paddle) 87 moving.speed = s 88 moving.angle = a 89 moving.area = @playingView 90 @playingView.balls.push(ball) 91 @movings.push(moving) 92 end 93 end 94 95 def paddle_init 96 @paddle = Paddle.new 97 @paddle.hpos = 50 98 @paddle.vpos = 15 99 @playingView.paddle = @paddle 100 end 101 102 def angle_new 103 20 + rand(60) 104 end 105 106end 107