This is a minimalist implementation of a karel-the-robot system in ruby.
require_relative "./karel"
Karel.run("world1") do
move
move
turn_left
move
move
if next_to_a_beeper?
pickup_beeper
end
endA command tells karel to take an action that affects his world:
moveMoves karel one space in the direction he is facing. If the space is blocked, will cause karel to crash.turn_leftpickup_beeperMoves a beeper from karel's current space to his beeper bag. If there are no beepers present, will cause karel to crash.put_beeperMoves a beeper from karel's beeper bag to his current space. If there are no beepers in his bag, will cause karel to crash.
A query allows us to ask questions about karel's world:
front_clear?front_blocked?left_clear?left_blocked?right_clear?right_blocked?back_clear?back_blocked?next_to_a_beeper?not_next_to_a_beeper?any_beepers_in_beeper_bag?no_beepers_in_beeper_bag?facing_north?facing_south?facing_east?facing_west?not_facing_north?not_facing_south?not_facing_east?not_facing_west?
while <predicate>
endMove until we're about to hit a wall:
while front_clear?
move
endTurn until we can move:
while front_blocked?
turn_left
endPick up all the beepers on the current space:
while next_to_a_beeper?
pickup_beeper
endWe can build our own version of the built-in methods using def. Place these before the call to Karel.run.
def about_face
turn_left
turn_left
end
Karel.run("world1") do
about_face
end