Решение на Втора задача от Димитър Ангелов

Обратно към всички решения

Към профила на Димитър Ангелов

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 20 успешни тест(а)
  • 0 неуспешни тест(а)

Код

def dimensions(x, y)
{width: x, height: y}
end
def snake(*array)
array
end
def direction(x, y)
if (x+y).abs == 1 then [x, y]
end
end
def food(*array)
array
end
def in_front(snake, direction)
new_snake = snake.clone
top = new_snake.pop
[top[0] + direction[0], top[1] + direction[1]]
end
def move(snake, direction)
new_snake = snake.clone
new_snake.shift
new_snake<<in_front(snake, direction)
end
def grow(snake, direction)
new_snake = snake.clone
new_snake<<in_front(snake, direction)
end
def new_food(food, snake, dimensions)
more_food = [rand(0...dimensions[:width]), rand(0...dimensions[:height])]
while (food.include? more_food or snake.include? more_food) do
more_food = [rand(0...dimensions[:width]), rand(0...dimensions[:height])]
end
more_food
end
def obstacle_ahead?(snake, direction, dimensions)
next_position = in_front(snake, direction)
next_position[0] < 0 or next_position[0] >= dimensions[:width] or
next_position[1] < 0 or next_position[1] >= dimensions[:height] or
snake.include? next_position
end
def danger?(snake, direction, dimensions)
obstacle_ahead?(snake, direction, dimensions)
new_snake = move(snake, direction)
obstacle_ahead?(new_snake, direction, dimensions)
end

Лог от изпълнението

....................

Finished in 0.01446 seconds
20 examples, 0 failures

История (1 версия и 0 коментара)

Димитър обнови решението на 18.10.2015 22:35 (преди над 9 години)

+def dimensions(x, y)
+ {width: x, height: y}
+end
+
+def snake(*array)
+ array
+end
+
+def direction(x, y)
+ if (x+y).abs == 1 then [x, y]
+ end
+end
+
+def food(*array)
+ array
+end
+
+def in_front(snake, direction)
+ new_snake = snake.clone
+ top = new_snake.pop
+ [top[0] + direction[0], top[1] + direction[1]]
+end
+
+def move(snake, direction)
+ new_snake = snake.clone
+ new_snake.shift
+ new_snake<<in_front(snake, direction)
+end
+
+def grow(snake, direction)
+ new_snake = snake.clone
+ new_snake<<in_front(snake, direction)
+end
+
+def new_food(food, snake, dimensions)
+ more_food = [rand(0...dimensions[:width]), rand(0...dimensions[:height])]
+ while (food.include? more_food or snake.include? more_food) do
+ more_food = [rand(0...dimensions[:width]), rand(0...dimensions[:height])]
+ end
+ more_food
+end
+
+def obstacle_ahead?(snake, direction, dimensions)
+ next_position = in_front(snake, direction)
+ next_position[0] < 0 or next_position[0] >= dimensions[:width] or
+ next_position[1] < 0 or next_position[1] >= dimensions[:height] or
+ snake.include? next_position
+end
+
+def danger?(snake, direction, dimensions)
+ obstacle_ahead?(snake, direction, dimensions)
+ new_snake = move(snake, direction)
+ obstacle_ahead?(new_snake, direction, dimensions)
+end