Question

I have the following code

def set_goal
  x = sample_x
  y = sample_y
  sample_is_bad = @maze[y][x] == GOAL || @maze[y][x] == START || @maze[y][x].to_i >= 75
  if sample_is_bad
    set_goal
  end
  @maze[y][x] = GOAL
  @graphic_maze[y][x] = GOAL
  puts "***Goal point initialized.***\n"
end

def sample_x
  x = rand(@x-1)
end

def sample_y
  y = rand(@y-1)
end

When I run the "set_goal" method, if the "sample_is_bad" variable is true, I want to run the method again in order to get new x,y values and place the goal in a valid position. My problem is that often the additionally to what I want it to do, it created multiple goal opoints. Same thing happens with a similar method I have for placing a "start_point". I want ot create a random maze.

***Start point initialized.***
***Goal point initialized.***
***Goal point initialized.***
***************
*#   ## # ##  *
*  ##   ##    *
*###       #  *
*  #  #    #  *
* ##        #S*
*          #  *
*     G       *
* ## G       #*
*  # # ###   #*
* ##         #*
*  ###   #    *
* ##         #*
*#      ###  #*
***************

No correct solution

OTHER TIPS

Use a loop instead, something like:

def bad_goal_point?(x, y)
  @maze[y][x] == GOAL || @maze[y][x] == START || @maze[y][x].to_i >= 75
end

def set_goal
  loop do
    x = sample_x
    y = sample_y
    break unless bad_goal_point?(x, y)
  end
  @maze[y][x] = GOAL
  @graphic_maze[y][x] = GOAL
  puts "***Goal point initialized.***\n"
end

I actually solved this by placing the following part of my code

@maze[y][x] = GOAL
@graphic_maze[y][x] = GOAL
puts "***Goal point initialized.***\n"

in an else clause.

But isn't there another way to solve this? Or even implement it? I mean, a more "ruby" way...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top