Skip to content

Instantly share code, notes, and snippets.

@fvaletk
Last active March 1, 2021 22:37
Show Gist options
  • Save fvaletk/f6fb701d06a757b8b2fb114f0b1f77d5 to your computer and use it in GitHub Desktop.
Save fvaletk/f6fb701d06a757b8b2fb114f0b1f77d5 to your computer and use it in GitHub Desktop.
Ant Game
# Ant Game
#
# Board
# w w w w w
# w w w w w
# w w w w w
# w w w w w
# w w w w w
def ant_game(map_size, moves)
board = Hash.new do |h, k|
size = k - 1
(0..size).each do |m|
(0..size).each do |n|
h["#{m},#{n}"] = true
end
end
end
board[map_size]
current_point = "#{map_size/2},#{map_size/2}"
facing = "north"
counter = 0
print_board(board, current_point, map_size)
while counter < moves do
previous_point = current_point
current_point, facing = set_direction(facing, board[previous_point], previous_point)
board[previous_point] = !board[previous_point]
print_board(board, current_point, map_size)
counter = counter + 1
end
end
def set_direction(facing, white, coordinates)
current_coordinates = coordinates.split(",").map{|z| z.to_i}
new_facing_direction = facing
case facing
when "east"
if white
current_coordinates[0] = current_coordinates[0] + 1
new_facing_direction = "south"
else
current_coordinates[0] = current_coordinates[0] - 1
new_facing_direction = "north"
end
when "south"
if white
current_coordinates[1] = current_coordinates[1] - 1
new_facing_direction = "west"
else
current_coordinates[1] = current_coordinates[1] + 1
new_facing_direction = "east"
end
when "west"
if white
current_coordinates[0] = current_coordinates[0] - 1
new_facing_direction = "north"
else
current_coordinates[0] = current_coordinates[0] + 1
new_facing_direction = "south"
end
when "north"
if white
current_coordinates[1] = current_coordinates[1] + 1
new_facing_direction = "east"
else
current_coordinates[1] = current_coordinates[1] - 1
new_facing_direction = "west"
end
else
puts "Error"
end
[current_coordinates.join(","), new_facing_direction]
end
def print_board(board, ant_position, map_size)
print_array = []
board.each do |key, value|
if key == ant_position
print_array << "A"
elsif value
print_array << "w"
else
print_array << "b"
end
if print_array.length == map_size
puts print_array.join(", ")
print_array = []
end
end
puts "-------------------------------"
end
ant_game(5, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment