Skip to content

Instantly share code, notes, and snippets.

@Sup3rc4l1fr4g1l1571c3xp14l1d0c10u5
Last active November 27, 2016 06:59
Show Gist options
  • Save Sup3rc4l1fr4g1l1571c3xp14l1d0c10u5/295a4688346d1fddff83a6be60fffc08 to your computer and use it in GitHub Desktop.
Save Sup3rc4l1fr4g1l1571c3xp14l1d0c10u5/295a4688346d1fddff83a6be60fffc08 to your computer and use it in GitHub Desktop.
IRPC2016で使用した薄いフレームワークより状態遷移を少しだけ手軽にする仕掛け。
#
# ほんの少しですが、手軽に状態遷移機械を作ることができます。
#
require 'dxruby'
class GameBase
# 状態遷移を sceneで指定されたシンボルで示されるメソッドから開始する。
# その際に、paramsで指定された引数が渡される。
def run(scene, *params)
# メソッドから出る際に、次に遷移したい状態と遷移時に渡したいパラメータがあるなら、
# return <遷移したいメソッド名のシンボル>, <引き数>...
# としてreturnすれば、そのメソッドが起動される。
# 存在しないメソッド名やnullを渡すと遷移を終了する。
while methods.include?(scene) do
(scene, params) = send(scene, *params)
end
end
# シーン定義を支援するメソッド
def scene(&block)
Window.loop(true) do
if Input.requested_close?
exit
end
# block内部での break 以外で脱出されると不味いので #tap 経由で呼び出す
block.tap &block
end
end
end
if __FILE__ == $0
# 以下が利用例です。
# ほんの少しですが、手軽に状態遷移機械を作れます。
class Game < GameBase
def initialize()
Window.width = 640
Window.height = 480
@font = Font.new(30, 'MS Pゴシック', { :weight=>false, :italic => false })
end
def title()
# 直接シーン中から脱出することもできます。
scene do
Window.draw_font( 20, 200, "右クリックか左クリックしてね" ,@font, {:color=> [255,0,0] })
if Input.mouse_push?(M_LBUTTON)
return :detect_click, "左クリック"
end
if Input.mouse_push?(M_RBUTTON)
return :detect_click, "右クリック"
end
end
end
def detect_click(message)
# 一旦シーンのみから脱出し、結果によって遷移したり別のシーンを起動したりもできます。
ret = scene do
Window.draw_font( 20, 200, "#{message}だね" ,@font, {:color=> [255,0,0] })
Window.draw_font( 20, 240, "もう1回やるなら左クリックしてね。\n右クリックはダメだよ。" ,@font, {:color=> [255,0,0] })
if Input.mouse_push?(M_LBUTTON)
break :goto_title
end
if Input.mouse_push?(M_RBUTTON)
break :forbidden
end
end
case ret
when :forbidden then
scene do
Window.draw_font( 20, 200, "だめだって言ったよね" ,@font, {:color=> [255,0,0] })
end
when :goto_title then
return :title
end
end
end
Game.new().run(:title)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment