Ruby Warrior是一个用Ruby代码控制一个小人打怪升级刷装备的小游戏,可以帮助小伙伴们了解Ruby
[url=https://www.bloc.io/ruby-warrior#/]传送门[/url]
最近正好有同事想了解一下Ruby,就推荐给他们这个小游戏,同时把我的答案也分享一下,大家可以交流一下更漂亮的写法。
[url=https://www.bloc.io/ruby-warrior#/]传送门[/url]
最近正好有同事想了解一下Ruby,就推荐给他们这个小游戏,同时把我的答案也分享一下,大家可以交流一下更漂亮的写法。
# level 1
class Player
def play_turn(warrior)
warrior.walk!
end
end
# level 2
class Player
def play_turn(warrior)
warrior.feel.empty? ? warrior.walk! : warrior.attack!
end
end
# level 3
class Player
def play_turn(warrior)
if warrior.feel.empty?
warrior.health < 10 ? warrior.rest! : warrior.walk!
else
warrior.attack!
end
end
end
# level 4
class Player
def play_turn(warrior)
@health ||= warrior.health
if warrior.feel.empty?
warrior.health < 15 && @health <= warrior.health ? warrior.rest! : warrior.walk!
else
warrior.attack!
end
@health = warrior.health
end
end
# level 5
class Player
def play_turn(warrior)
@health ||= warrior.health
if warrior.feel.empty?
warrior.health < 15 && @health <= warrior.health ? warrior.rest! : warrior.walk!
else
warrior.feel.enemy? ? warrior.attack! : warrior.rescue!
end
@health = warrior.health
end
end
# level 6
class Player
def play_turn(warrior)
@backward = true if @backward.nil?
if @backward
if warrior.feel(:backward).captive?
@backward = false
return warrior.rescue! :backward
else
return warrior.walk! :backward
end
end
@health ||= warrior.health
if warrior.feel.empty?
if warrior.health < 20 && @health <= warrior.health
warrior.rest!
else
direction = warrior.health < 10 ? :backward : :forward
warrior.walk! direction
end
else
warrior.feel.enemy? ? warrior.attack! : warrior.rescue!
end
@health = warrior.health
end
end
# level 7
class Player
def play_turn(warrior)
@health ||= warrior.health
if warrior.feel.empty?
if warrior.health < 20 && @health <= warrior.health
warrior.rest!
else
direction = warrior.health < 10 ? :backward : :forward
warrior.walk! direction
end
else
if warrior.feel.enemy?
warrior.attack!
elsif warrior.feel.wall?
warrior.pivot!
else
warrior.rescue!
end
end
@health = warrior.health
end
end
# level 8
class Player
def play_turn(warrior)
warrior.look.each do |space|
break if space.captive?
return warrior.shoot! if space.enemy?
end
warrior.feel.captive? ? warrior.rescue! : warrior.walk!
end
end
# level 9
class Player
def initialize
@first_turn, @archer_dead, @melee = true, false, false
end
def archer_dead?; @archer_dead; end
def play_turn(warrior)
# Kill archer with hardcode
if @first_turn
@first_turn = false
return warrior.pivot!
end
if !archer_dead?
if warrior.feel.enemy?
@melee = true
return warrior.attack!
else # feel.empty?
if @melee
@archer_dead = true
return warrior.pivot!
else
return warrior.walk!
end
end
end
warrior.look.each do |space|
break if space.captive?
return warrior.shoot! if space.enemy?
end
if warrior.feel.captive?
warrior.rescue!
elsif warrior.feel.wall?
warrior.pivot!
else
warrior.walk!
end
end
end