Skip to content

Instantly share code, notes, and snippets.

@ohthatjames
Created July 8, 2013 17:43
Show Gist options
  • Save ohthatjames/5950870 to your computer and use it in GitHub Desktop.
Save ohthatjames/5950870 to your computer and use it in GitHub Desktop.
A DSL to get you through the first 6 levels of http://bitsquest.bitbucket.org/index.html
class Dsl
Change = Struct.new(:state, :new_directions)
def initialize
@state_count = 0
@sensor_changes = {}
end
def start(directions)
@start_directions = [directions].flatten
@state_count = 1
end
def after(sensor_direction, directions_to_go)
@sensor_changes[sensor_direction] ||= []
@sensor_changes[sensor_direction] << Change.new(@state_count, [directions_to_go].flatten)
@state_count += 1
end
def print
[
complete_stop_function,
initialize_state_variable,
start_direction,
sensor_directions,
].join("\n")
end
def complete_stop_function
<<-EOF
function completeStop(thrusters) {
thrusters.left(false);
thrusters.top(false);
thrusters.right(false);
thrusters.bottom(false);
}
EOF
end
def start_direction
<<-EOF
this.on('start', function() {
#{start_thrusters(@start_directions)}
this.state += 1;
});
EOF
end
def sensor_directions
output = @sensor_changes.map do |sensor_change|
key, changes = sensor_change
sensor_direction(key, changes)
end
output.join("\n\n")
end
def sensor_direction(direction, changes)
start_out = <<-EOF
this.on('sensor:#{direction}', function() {
EOF
content = ""
changes.each do |change|
content += <<-EOF
if(this.state == #{change.state}) {
completeStop(this.thrusters);
#{start_thrusters(change.new_directions)}
this.state += 1;
}
EOF
end
end_out = <<-EOF
});
EOF
[start_out, content, end_out].join("\n")
end
def start_thrusters(directions)
directions.map do |direction|
"this.thrusters.#{thruster_for_direction(direction)}(true);"
end.join("\n")
end
def thruster_for_direction(direction)
case direction
when :up then :bottom
when :down then :top
when :left then :right
when :right then :left
else raise "WHAT IS #{direction}"
end
end
def initialize_state_variable
"this.state = 0;"
end
end
def run(&block)
dsl = Dsl.new
dsl.instance_eval(&block)
puts dsl.print
end
# Level 6:
run do
start :down
after :bottom, :right
after :right, :up
after :left, :right
after :right, :down
after :bottom, :left
after :left, :up
after :top, :right
after :right, :down
after :left, :right
after :right, :up
after :top, :right
after :right, [:right, :down]
end
# Level 5:
# run do
# start :down
# after :bottom, :right
# after :right, :up
# after :top, :left
# after :left, :down
# after :bottom, :right
# after :right, :up
# after :top, :left
# after :left, :down
# after :bottom, :right
# after :right, :up
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment