Created
January 11, 2014 03:36
-
-
Save tamalw/8366666 to your computer and use it in GitHub Desktop.
LEGO!
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
class Monster | |
def initialize(options) | |
@name = options[:name] | |
@lifepoints = options[:lifepoints] | |
@drop_mechanic = options[:drop_mechanic] | |
@hit_log = [] | |
@output_buffer = [] | |
end | |
def get_hit(player, hit) | |
@lifepoints -= hit | |
@hit_log << [player, hit] | |
die if @lifepoints <= 0 | |
@output_buffer << "#{player.name} hits #{hit}." | |
game_log | |
end | |
private | |
def die | |
@output_buffer << "#{winning_player.name} gets the drop." | |
end | |
def winning_player | |
@drop_mechanic.winning_player(@hit_log) | |
end | |
def game_log | |
result = @output_buffer.reverse.join(' ') | |
@output_buffer = [] | |
result | |
end | |
end | |
class Player | |
attr_reader :name | |
def initialize(options) | |
@name = options[:name] | |
@strength = options[:strength] | |
end | |
def attack(monster) | |
monster.get_hit(self, @strength) | |
end | |
end | |
class TagFirst | |
def self.winning_player(hits) | |
hits[0][0] | |
end | |
end | |
class MostDamage | |
def self.winning_player(hits) | |
players = hits.group_by { |h| h[0] }.map { |k,v| [k, v.inject(0) { |m,o| m += o[1] }] }.sort { |a,b| b[1] <=> a[1] } | |
most_damage = players[0][1] | |
potential_winners = players.select { |p| p[1] == most_damage }.map { |p| p[0] } | |
return potential_winners.first if potential_winners.size == 1 | |
potential_winners.map { |p| [p, hits.find_index { |h| h[0] == p }] }.sort { |a,b| a[1] <=> b[1] }.first[0] | |
end | |
end | |
weakie = Player.new(name: "Weakie", strength: 100) | |
strong = Player.new(name: "Strongie", strength: 200) | |
baddie = Monster.new(name: "Baddie", lifepoints: 1000, drop_mechanic: TagFirst) | |
weakie.attack baddie # => "Weakie hits 100." | |
strong.attack baddie # => "Strongie hits 200." | |
weakie.attack baddie # => "Weakie hits 100." | |
strong.attack baddie # => "Strongie hits 200." | |
weakie.attack baddie # => "Weakie hits 100." | |
strong.attack baddie # => "Strongie hits 200." | |
weakie.attack baddie # => "Weakie hits 100. Weakie gets the drop." | |
baddie = Monster.new(name: "Baddie", lifepoints: 1000, drop_mechanic: MostDamage) | |
weakie.attack baddie # => "Weakie hits 100." | |
strong.attack baddie # => "Strongie hits 200." | |
weakie.attack baddie # => "Weakie hits 100." | |
strong.attack baddie # => "Strongie hits 200." | |
weakie.attack baddie # => "Weakie hits 100." | |
strong.attack baddie # => "Strongie hits 200." | |
weakie.attack baddie # => "Weakie hits 100. Strongie gets the drop." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment