-
-
Save eiel/4748226 to your computer and use it in GitHub Desktop.
https://gist.github.com/Shinpeim/4745446 へ変化するコードなのだけど、リファクタリング的にみると飛躍があってその中間をかくとどうなるか。 というのを考えてみる。パターン2。 いきなりStateパターンへの方向転換を試みる。コピペして修正。という流れになる。 これもStateパターンと名前がついてる方向があるので迷わず済むのかなー。リファクタリングのステップを検討するのはなかなか面白い。
This file contains hidden or 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 | |
class Normal | |
# move の内容をもってきて、いらない caseを削除 | |
# return を追加 | |
# x_speed, y_speed を展開すれば 03のコードに向う | |
def move(direction, position) | |
x_speed = 10 | |
y_speed = 10 | |
case direction | |
when :up | |
position[:y] -= y_speed | |
when :down | |
position[:y] += y_speed | |
when :left | |
position[:x] -= x_speed | |
when :right | |
position[:x] += x_speed | |
end | |
return position | |
end | |
end | |
Class Fast | |
def move(direction, position) | |
x_speed = 20 | |
y_speed = 20 | |
case direction | |
when :up | |
position[:y] -= y_speed | |
when :down | |
position[:y] += y_speed | |
when :left | |
position[:x] -= x_speed | |
when :right | |
position[:x] += x_speed | |
end | |
return position | |
end | |
end | |
Class Kani | |
def move(direction, position) | |
x_speed = 20 | |
y_speed = 20 | |
case direction | |
when :up | |
position[:y] -= y_speed | |
when :down | |
position[:y] += y_speed | |
when :left | |
position[:x] -= x_speed | |
when :right | |
position[:x] += x_speed | |
end | |
return position | |
end | |
end | |
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 | |
@position = MovingMode::Normal.new | |
.move(direction, @position) | |
when MOVING_MODE::FAST | |
@position = MovingMode::Fast.new | |
.move(direction, @position) | |
when MOVING_MODE::KANI | |
@position = MovingMode::KANI.new | |
.move(direction, @position) | |
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
コメントをdescritionにかくと改行が飛んでよみにくいな…。