Десислава обнови решението на 13.10.2015 22:54 (преди над 9 години)
+def make_new_head(snake, direction)
+ [snake[-1][0] + direction[0], snake[-1][1] + direction[1]]
+end
+
+def generate_place(dimensions)
+ [rand(dimensions[:width]), rand(dimensions[:height])]
+end
+
+def move(snake, direction)
+ head_new = make_new_head(snake, direction)
+ snake[1 .. -1] << head_new
+end
+
+def grow(snake, direction)
+ head_new = make_new_head(snake, direction)
+ snake << head_new
+end
+
+def new_food(food, snake, dimensions)
+ busy_places = food + snake
+ new_food = generate_place(dimensions)
+ new_food = generate_place(dimensions) while busy_places.include? new_food
+ new_food
+end
+
+def obstacle_ahead?(snake, direction, dimensions)
+ snake_new = move(snake, direction)
+ head_new = snake_new[-1]
+ # snake_new[-1] is its new head
+
+ # Checking if it's outside the field or if it's bitten itself
+ outside_width = head_new[0] < 0 or head_new[0] >= dimensions[:width]
+ outside_height = head_new[1] < 0 or head_new[1] >= dimensions[:height]
+ snake_on_itself = snake_new.include? head_new
+ outside_width or outside_height or snake_on_itself
+end
+
+def danger?(snake, direction, dimensions)
+ danger_one_move = obstacle_ahead?(snake, direction, dimensions)
+ # If its first move is dangerous, we return immediately true
+ return true if danger_one_move
+
+ # Else we see what happens on the next move - with a new snake
+ # which has moved in the appropriate direction
+ snake_new = move(snake, direction)
+ obstacle_ahead?(snake_new, direction, dimensions)
+end
+