Живка обнови решението на 19.10.2015 15:01 (преди над 9 години)
+def move(snake, direction)
+ new_snake = snake.dup
+ new_snake.push(next_position(new_snake.last, direction)).drop(1)
+end
+
+def grow(snake, direction)
+ new_snake = snake.dup + next_position(snake.last, direction)
+end
+
+def new_food(food, snake, dimensions)
+ width = dimensions[:width]
+ height = dimensions[:height]
+
+ all_positions = (0...width).to_a.product((0...height).to_a)
+ available_positions = all_positions - (food | snake)
+
+ available_positions.sample
+end
+
+def obstacle_ahead?(snake, direction, dimensions)
+ next_head_position = next_position(snake.last, direction)
+
+ out_of_playground?(next_head_position, dimensions) or
+ snake.include?(next_head_position)
+end
+
+def danger?(snake, direction, dimensions)
+ obstacle_ahead?(snake, direction, dimensions) or
+ obstacle_ahead?(move(snake, direction), direction, dimensions)
+end
+
+def next_position(current_position, direction)
+ current_position.map.with_index { |item, index| item + direction[index] }
+end
+
+def out_of_playground?(position, dimensions)
+ xs = position[0]
+ ys = position[1]
+ xs < 0 or ys < 0 or xs >= dimensions[:width] or ys >= dimensions[:height]
+end
http://fmi.ruby.bg/topics/169 Тези полезни редове ги видях малко късно.
- Индентирай с два space-a
- Бяха ли нужни
new_snake
присвояванията?