Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Refactoring Player class.

  • Loading branch information...
commit 77f2e47b00f17ac72fb6709e9a37b79538bf8b21 1 parent 90643fb
@mauricioszabo authored
Showing with 45 additions and 36 deletions.
  1. +45 −36 lib/player.rb
View
81 lib/player.rb
@@ -8,6 +8,15 @@ class Player
COLLISION_SIZE = 26
COLLISION_COMPENSATION = COLLISION_SIZE/2
+ UPPER = 1
+ UPPER_RIGHT = 2
+ RIGHT = 3
+ LOWER_RIGHT = 4
+ LOWER = 5
+ LOWER_LEFT = 6
+ LEFT = 7
+ UPPER_LEFT = 8
+
attr_reader :x, :y
def initialize(file, x=0, y=0)
@@ -26,6 +35,42 @@ def update
update_steps
end
+ def update_steps
+ distance_x = @destination_x.to_i - @x
+ distance_y = @destination_y.to_i - @y
+ total_distance = (distance_x.abs + distance_y.abs).to_f
+ return if total_distance <= STEP_SIZE
+
+ new_animation = direction_to(@destination_x, @destination_y)
+ if new_animation == @current_animation
+ multiplier_x = distance_x / total_distance
+ multiplier_y = distance_y / total_distance
+ @x += STEP_SIZE * multiplier_x
+ @y += STEP_SIZE * multiplier_y
+ else
+ @turn_time += 1
+ @turn_time = 0 if @turn_time == TURN_DELAY
+ return if @turn_time != 0
+ @current_animation = turn_to(new_animation)
+ end
+ end
+ private :update_steps
+
+ def turn_to(direction)
+ if direction > @current_animation
+ value = +1
+ distance = direction - @current_animation
+ else
+ value = -1
+ distance = @current_animation - direction
+ end
+ if distance < 5
+ @current_animation + value
+ else
+ (@current_animation - value) % 8
+ end
+ end
+
def direction_to(x, y)
x_distance = x - @x
y_distance = y - @y
@@ -65,42 +110,6 @@ def diagonal(x, y)
end
private :diagonal
- def update_steps
- distance_x = @destination_x.to_i - @x
- distance_y = @destination_y.to_i - @y
- total_distance = (distance_x.abs + distance_y.abs).to_f
- return if total_distance <= STEP_SIZE
-
- new_animation = direction_to(@destination_x, @destination_y)
- if new_animation == @current_animation
- multiplier_x = distance_x / total_distance
- multiplier_y = distance_y / total_distance
- @x += STEP_SIZE * multiplier_x
- @y += STEP_SIZE * multiplier_y
- else
- @turn_time += 1
- @turn_time = 0 if @turn_time == TURN_DELAY
- return if @turn_time != 0
- @current_animation = turn_to(new_animation)
- end
- end
- private :update_steps
-
- def turn_to(direction)
- if direction > @current_animation
- value = +1
- distance = direction - @current_animation
- else
- value = -1
- distance = @current_animation - direction
- end
- if distance < 5
- @current_animation + value
- else
- (@current_animation - value) % 8
- end
- end
-
def draw_on(screen)
screen.draw(@animations[@current_animation], @x - COMPENSATION, @y - COMPENSATION)
end
Please sign in to comment.
Something went wrong with that request. Please try again.