Mercurial > rinkhals
comparison gamelib/animal.py @ 399:3294929223bd
Cache fox positions to avoid a repeated loop
author | Neil Muller <drnlmuller@gmail.com> |
---|---|
date | Tue, 17 Nov 2009 15:43:30 +0000 |
parents | 082b1ea5f98d |
children | 7405f7db469f |
comparison
equal
deleted
inserted
replaced
398:082b1ea5f98d | 399:3294929223bd |
---|---|
401 def _update_pos(self, gameboard, new_pos): | 401 def _update_pos(self, gameboard, new_pos): |
402 """Update the position, making sure we don't step on other foxes""" | 402 """Update the position, making sure we don't step on other foxes""" |
403 if new_pos == self.pos: | 403 if new_pos == self.pos: |
404 # We're not moving, so we can skip all the checks | 404 # We're not moving, so we can skip all the checks |
405 return new_pos | 405 return new_pos |
406 blocked = gameboard.is_fox_at_pos(new_pos) | |
407 if not blocked and new_pos.z == self.pos.z: | |
408 # We're only worried about loops when not on a ladder | |
409 blocked = new_pos in self.last_steps | |
406 final_pos = new_pos | 410 final_pos = new_pos |
407 blocked = False # We don't worry about loops on ladders | |
408 if new_pos.z != self.pos.z: | |
409 # We can only move up and down a ladder | |
410 moves = [Position(self.pos.x, self.pos.y, z) for z | |
411 in range(self.pos.z-1, self.pos.z + 2) if z >= 0] | |
412 else: | |
413 blocked = final_pos in self.last_steps | |
414 moves = [Position(x, y) for x in range(self.pos.x-1, self.pos.x + 2) | |
415 for y in range(self.pos.y-1, self.pos.y + 2) | |
416 if Position(x,y) != self.pos and | |
417 Position(x, y) not in self.last_steps and self.pos.z == 0] | |
418 for fox in gameboard.foxes: | |
419 if fox is not self and fox.pos == final_pos: | |
420 blocked = True | |
421 if fox.pos in moves: | |
422 moves.remove(fox.pos) | |
423 if blocked: | 411 if blocked: |
424 # find the cheapest point in moves to new_pos that's not blocked | 412 if new_pos.z != self.pos.z: |
413 # We can only move up and down a ladder | |
414 moves = [Position(self.pos.x, self.pos.y, z) for z | |
415 in range(self.pos.z-1, self.pos.z + 2) if z >= 0] | |
416 else: | |
417 moves = [Position(x, y) for x in range(self.pos.x-1, self.pos.x + 2) | |
418 for y in range(self.pos.y-1, self.pos.y + 2) | |
419 if Position(x,y) != self.pos and | |
420 Position(x, y) not in self.last_steps and | |
421 self.pos.z == 0] | |
422 # find the cheapest point in moves that's not blocked | |
425 final_pos = None | 423 final_pos = None |
426 min_cost = 1000 | 424 min_cost = 1000 |
427 for poss in moves: | 425 for poss in moves: |
426 if gameboard.is_fox_at_pos(poss): | |
427 continue # blocked | |
428 cost = self._cost_tile(poss, gameboard) | 428 cost = self._cost_tile(poss, gameboard) |
429 if cost < min_cost: | 429 if cost < min_cost: |
430 min_cost = cost | 430 min_cost = cost |
431 final_pos = poss | 431 final_pos = poss |
432 if cost == min_cost and random.randint(0, 1) > 0: | 432 if cost == min_cost and random.randint(0, 1) > 0: |