クラスを使う 2, 包含判定をする

-- 包含判定をする。
-- 参考: http://compasstech.com.au/TNS_Authoring/Scripting/script_tut11.html

require "color"

Square = class() -- Square クラスを作る。
function Square:init(x, y, width, height)
   self.x           = x
   self.y           = y
   self.width       = width
   self.height      = height
   self.color       = color.dodgerblue
   self.colorBorder = color.navy
   self.selected    = false
end
function Square:contains(x, y) -- Square クラスの包含判定メソッドを定義する。
   return self.x <= x and x <= self.x + self.width and self.y <= y and y <= self.y + self.height
end
function Square:paint(gc)     -- Square クラスの描画メソッドを定義する。
   gc:setColorRGB(self.color)
   gc:fillRect(self.x, self.y, self.width, self.height)
   if self.selected then      -- selected プロパティが true ならさらに枠を描く。
      cursor.set("hand closed")
      gc:setColorRGB(self.colorBorder)
      gc:drawRect(self.x, self.y, self.width, self.height)
      gc:drawString("selected", 10, 20)
   else
      gc:drawString("not selected", 10, 20)
      cursor.set("default")
   end
end

Sq = Square(100, 50, 120, 120)
function on.mouseDown(x,y) -- クリックした座標の包含判定をする。
   if Sq:contains(x, y) then
      Sq.selected = true 
   end
   platform.window:invalidate()
end
function on.mouseUp()
   Sq.selected = false
   platform.window:invalidate()
end
function on.paint(gc)
   Sq:paint(gc)
end