Skip to content

Instantly share code, notes, and snippets.

@Shinpeim
Last active December 12, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shinpeim/4745446 to your computer and use it in GitHub Desktop.
Save Shinpeim/4745446 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
class Player
# それぞれのモードをクラスに切り分けて、
# それぞれの振る舞いを定義してあげる
module MovingMode
class Normal
def move(direction, position)
case direction
when :up
position[:y] -= 10
when :down
position[:y] += 10
when :left
position[:x] -= 10
when :right
position[:x] += 10
end
return position
end
end
class Fast
def move(direction, position)
case direction
when :up
position[:y] -= 20
when :down
position[:y] += 20
when :left
position[:x] -= 20
when :right
position[:x] += 20
end
return position
end
end
class Kani
def move(direction, position)
case direction
when :up
position[:y] -= 5
when :down
position[:y] += 5
when :left
position[:x] -= 40
when :right
position[:x] += 40
end
return position
end
end
end
attr_reader :position
def initialize(position)
@position = position
# 状態変数じゃなくて、さっき振る舞いを定義したオブジェクトを持たせる
@moving_mode = MovingMode::Normal.new
end
def to_fast_mode
# ここも
@moving_mode = MovingMode::Fast.new
end
def to_kani_mode
# ここも
@moving_mode = MovingMode::Kani.new
end
def move(direction)
# 自分で動くんじゃなくて、持ってるオブジェクトにかわりに仕事させる
@position = @moving_mode.move(direction, @position)
end
end
player = Player.new(:x => 100, :y => 100)
player.move(:up)
p player.position # => {:x => 100, :y => 90}
player.to_fast_mode #ここで倍速モードに
player.move(:down)
p player.position # => {:x => 100, :y => 110}
player.to_kani_mode
player.move(:up)
player.move(:left)
p player.position # => {:x => 60, :y => 105}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment