1

So I am trying to plan a path on a 9x9 grid, so boardSize is 9. The while loop should stop path list has a length of 81 or more so why is it possible that it can get to a length of 3531when the creature is at 7,5 and the goal is at 5,2 and elevations are 0? Is my while loop wrong or do you think it might be elsewhere?

def planPath(self, creature, goal, board):
        print("in the path")      
        path = [board[creature.x][creature.y]]       
        while goal not in path or len(path) < self.boardSize ** 2:
            print("path length")
            print(len(path))
            nextPossible = {}
            for neighbor in path[-1].neighbors:
                if type(neighbor) is not Land.Water:
                    nextPossible[neighbor] = abs(neighbor.location[0] - goal.location[0]) + abs(neighbor.location[1] - goal.location[1]) + abs(neighbor.elevation - goal.elevation)      
            path.append(min(nextPossible, key=nextPossible.get))
        return path
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
EasilyBaffled
  • 3,822
  • 10
  • 50
  • 87
  • 5
    I think you just need to change `or` to `and` in your `while` statement. – Marius Mar 28 '13 at 04:42
  • 1
    *sign* I was afraid it was going to be something dumb like that, thanks. – EasilyBaffled Mar 28 '13 at 04:51
  • 3
    @Marius -- why not post as an answer? Questions with closure are better than questions without :) – mgilson Mar 28 '13 at 05:48
  • @mgilson: Yeah, sorry, I don't like posting answers I haven't tested, but I realise having unanswered questions with a bunch of comments on them is not ideal. – Marius Mar 28 '13 at 07:34

1 Answers1

2

You wanted the while loop to end when the path length reached the number of squares on the board- using and instead of or in your while loop it will end when either this expression:

goal not in path

or this expression:

len(path) < self.boardSize ** 2

evaluates to False. Using or, as long as one of those expressions is true, the loop would keep running. So your fixed code would be:

def planPath(self, creature, goal, board):
        print("in the path")      
        path = [board[creature.x][creature.y]]       
        while goal not in path and len(path) < self.boardSize ** 2:
            print("path length")
            print(len(path))
            nextPossible = {}
            for neighbor in path[-1].neighbors:
                if type(neighbor) is not Land.Water:
                    nextPossible[neighbor] = abs(neighbor.location[0] - goal.location[0]) + abs(neighbor.location[1] - goal.location[1]) + abs(neighbor.elevation - goal.elevation)      
            path.append(min(nextPossible, key=nextPossible.get))
        return path
Marius
  • 58,213
  • 16
  • 107
  • 105