-
-
Save eiel/4748209 to your computer and use it in GitHub Desktop.
https://gist.github.com/Shinpeim/4745446 へ変化するコードなのだけど、リファクタリング的にみると飛躍があってその中間をかくとどうなるか。
というのを考えてみる。パターン1。 なかなか興味深くて、こういうプログラムをかける人はレアな気がする。
故にStateパターンと名前がついてる方向があるので迷わず済むのかなとか思った。 蛇足だけど、 @moving_mode には Rubyなら普通は シンボルを突っ込む気がする。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
class Player | |
attr_reader :position | |
# Cで言うenum的なやつ | |
module MOVING_MODE | |
NORMAL = 1 | |
FAST = 2 | |
KANI = 3 #蟹モードが増えた | |
end | |
def initialize(position) | |
@position = position | |
@moving_mode = MOVING_MODE::NORMAL | |
end | |
def to_fast_mode | |
@moving_mode = MOVING_MODE::FAST | |
end | |
def to_kani_mode | |
@moving_mode = MOVING_MODE::KANI | |
end | |
def move(direction) | |
case @moving_mode | |
when MOVING_MODE::NORMAL | |
case direction | |
when :up | |
@position[:y] -= 10 | |
when :down | |
@position[:y] += 10 | |
when :left | |
@position[:x] -= 10 | |
when :right | |
@position[:x] += 10 | |
end | |
when MOVING_MODE::FAST | |
case direction | |
when :up | |
@position[:y] -= 20 | |
when :down | |
@position[:y] += 20 | |
when :left | |
@position[:x] -= 20 | |
when :right | |
@position[:x] += 20 | |
end | |
when MOVING_MODE::KANI | |
case direction | |
when :up | |
@position[:y] -= 40 | |
when :down | |
@position[:y] += 40 | |
when :left | |
@position[:x] -= 5 | |
when :right | |
@position[:x] += 5 | |
end | |
end | |
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