Ангел обнови решението на 19.10.2015 15:49 (преди над 9 години)
+def move(snake, direction)
+ new_snake = snake.drop(1)
+ new_snake.push([snake.last[0] + direction[0], snake.last[1] + direction[1]])
+end
+
+def grow(snake, direction)
+ new_snake = snake.clone
+ new_snake.push([snake.last[0] + direction[0], snake.last[1] + direction[1]])
+end
+
+def new_food(food, snake, dimensions)
+ food_position = snake[0]
+ until not food.include? food_position and not snake.include? food_position
+ width_position = Random.rand(dimensions[:width])
+ height_position = Random.rand(dimensions[:height])
+ food_position = [width_position, height_position]
+ end
+ food_position
+end
+
+def obstacle_ahead?(snake, direction, dimensions)
+ next_position = [snake.last[0] + direction[0], snake.last[1] + direction[1]]
+ if next_position[0] < 0 or next_position[0] == dimensions[:width]
+ return true
+ elsif next_position[1] < 0 or next_position[1] == dimensions[:height]
+ return true
+ end
+ false
+end
+
+def danger?(snake, direction, dimensions)
+ check_for_first_turn = obstacle_ahead?(snake, direction, dimensions)
+ new_snake = move(snake, direction)
+ check_for_second_turn = obstacle_ahead?(new_snake, direction, dimensions)
+ check_for_first_turn or check_for_second_turn
+end