Created
April 2, 2009 02:34
-
-
Save sandro/88993 to your computer and use it in GitHub Desktop.
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
proxybot | |
Wanted to capture the code flying around in my head and | |
thought a bot would be the best way to describe it. | |
A bot has a set of actions it knows how to perform. It | |
also needs to be able to perform any of its actions | |
when an event occurs. This gist attempts to solve this | |
problem through a type of proxy thing. | |
Actually, is this even a proxy? I don't even know anymore! | |
Example: | |
A bot can move around | |
b = Bot.new | |
b.move_up | |
b.move_right | |
A bot can evade and attack | |
b = Bot.new | |
b.attack | |
b.evade | |
Most importantly, the bot reuses its api when reacting to events | |
b = Bot.new | |
b.when :attacked do |tactic| | |
tactic.evade | |
tactic.move_right | |
tactic.move_down | |
end | |
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 Bot | |
def initialize | |
@tactics = {} | |
end | |
def attack | |
puts :attack | |
end | |
def evade | |
puts :evade | |
end | |
def move(where, num) | |
puts "moving #{where} by #{num}" | |
end | |
def move_down(num = 1) | |
move :down, num | |
end | |
def move_left(num = 1) | |
move :left, num | |
end | |
def move_right(num = 1) | |
move :right, num | |
end | |
def move_up(num = 1) | |
move :up, num | |
end | |
def trigger(event) | |
@tactics[event].each do |tactic| | |
tactic.call self | |
end | |
end | |
def when(event, &tactic) | |
if @tactics[event] | |
@tactics[event] << tactic | |
else | |
@tactics[event] = [tactic] | |
end | |
end | |
end | |
__END__ | |
require 'bot' | |
b = Bot.new | |
b.evade | |
b.move_left 3 | |
b.move_up 1 | |
b.when :attacked do |bot| | |
bot.evade | |
bot.move_down 2 | |
bot.move_right 1 | |
end | |
b.trigger :attacked |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment