Кристъфър обнови решението на 18.10.2015 23:08 (преди над 9 години)
+def move(snake, direction)
+ new_head_place = get_new_head_position(snake, direction)
+ new_snake = snake + [new_head_place]
+ new_snake.delete_at(0)
+
+ new_snake
+end
+
+def grow(snake, direction)
+ new_head_place = get_new_head_position(snake, direction)
+ new_snake = snake + [new_head_place]
+end
+
+def new_food(food, snake, dimensions)
+ not_empty = snake + food
+ height = dimensions[:height]
+ width = dimensions[:width]
+ field = Array.new(height * width)
+ empty_positions = Array.new()
+
+ not_empty.each { |elem| field[elem.first * width + elem.last] = :block }
+ empty_positions = field.each_index.select{ |index| field[index].nil? }
+ choose_random_position(empty_positions, width)
+end
+
+def obstacle_ahead?(snake, direction, dimensions)
+ new_head_place = get_new_head_position(snake, direction)
+ is_head_in_front_of_wall?(new_head_place, dimensions, snake)
+end
+
+def danger?(snake, direction, dimensions)
+ if(obstacle_ahead?(snake, direction, dimensions))
+ return true
+ else
+ new_head_place = get_new_head_position(snake, direction)
+ obstacle_ahead?(snake + [new_head_place], direction, dimensions)
+ end
+end
+
+def get_new_head_position(snake, direction)
+ new_head_place = snake.last.map.with_index { |m, i| m + direction[i] }
+end
+
+def is_head_in_front_of_wall?(head_place, dimensions, snake)
+ in_front_of_snake = snake.include?(head_place)
+ w_walls = head_place.first < 0 || head_place.first >= dimensions[:width]
+ h_walls = head_place.last < 0 || head_place.last >= dimensions[:height]
+
+ in_front_of_snake || w_walls || h_walls
+end
+
+def choose_random_position(positions, width)
+ rand_index = 0 + rand(positions.length)
+ chosen_position = positions[rand_index]
+ x_position = chosen_position / width
+ y_position = chosen_position.remainder(width)
+ [x_position, y_position]
+end