I think it would be easier to understand this if instead of
assigning the direction as an arbitrary number, you instead had
separate x and y directions, which could each have only the values
-1, 0, or 1.
A naive directional algorithm (which assumes no obstacles between
the monster and the ninja) could be something like:
monster.x_dir = cmp(ninja.x, monster.x)
monster.y_dir = cmp(ninja.y, monster.y)
That avoids all of the if/elif messiness entirely, and would
probably simplify the update logic that actually moves the monster
sprite as well. Also rather than using the rect x and y, which
ties the algorithm to the vagaries of where the sprites are drawn,
the x/y values above could be tile coordinates. This means it
would work correctly even if you change the orientation of the
tiles (e.g., use an isometric layout).
FWIW, I think the bug might be fixed by changing the second 'if'
to an 'elif', but I think it would be more worthwhile to simplify/
abstract out the approach.
hth,
-Casey
On Apr 27, 2007, at 9:53 AM, Samuel Mankins wrote:
I'm working on a sort of RPG/Roguelike game, and right now I'm
have problems with the monster's AI. It works just fine if the
Ninja (The player) is above, below, or to the left of the
monster, but if it's tot he right, the monster just goes up or
down, but not right. Here's the directional code, are there any
problems people can see? (For the monster's direction, 1 = right,
2 = up, 3 = left, and 4 = down)
if self.ninja.rect.x < monster.rect.x and monster.rect.x -
self.ninja.rect.x > monster.rect.y - self.ninja.rect.y:
monster.direction = 1
elif self.ninja.rect.x > monster.rect.x and monster.rect.x
- self.ninja.rect.x > monster.rect.y - self.ninja.rect.y:
monster.direction = 3
if self.ninja.rect.y < monster.rect.y and monster.rect.y -
self.ninja.rect.y > monster.rect.x - self.ninja.rect.x:
monster.direction = 2
elif self.ninja.rect.y > monster.rect.y and monster.rect.y
- self.ninja.rect.y > monster.rect.x - self.ninja.rect.x:
monster.direction = 4
elif self.ninja.rect.y < monster.rect.y and monster.rect.x
== self.ninja.rect.x:
monster.direction = 2
elif self.ninja.rect.y > monster.rect.y and monster.rect.x
== self.ninja.rect.x:
monster.direction = 4
elif self.ninja.rect.x < monster.rect.x and
self.ninja.rect.y == monster.rect.y:
monster.direction = 1
elif self.ninja.rect.x > monster.rect.x and
self.ninja.rect.y == monster.rect.y:
monster.direction = 3
If you can't see anything, thanks anyway!