My goal is to move a 'monster' (mX, mY
) in a 2d grid towards the player (pX, pY
). The monster can move 8 directions.
I have working code for this, but I'm very new to Python and have a strong inclination it is awful and there is faster ways to do it.
I do this by creating a 3 x 3 array around the monsters position (array slot 4), and filling it with the distance from that array position to the player. Then I check if any are lower than the monsters current distance, and if so, move the monster to it.
Here is my current code, apologies if it makes you puke, I'm still learning the ropes.
# get the distance between the monster and player
dist = math.hypot(pX - mX, pY - mY)
if dist > 1.5 and dist < 10:
# make an 'array' grid to store updated distances in
goto = np.full((3, 3), 10, dtype=float)
# if each position in the array passes a
# collision check, add each new distance
if collisionCheck(mID, (mX-1), (mY-1), mMap) == 0:
goto[0][0] = round(math.hypot(pX - (mX-1), pY - (mY-1)), 1)
if collisionCheck(mID, mX, (mY-1), mMap) == 0:
goto[0][1] = round(math.hypot(pX - mX, pY - (mY-1)), 1)
if collisionCheck(mID, (mX+1), (mY-1), mMap) == 0:
goto[0][2] = round(math.hypot(pX - (mX+1), pY - (mY-1)), 1)
if collisionCheck(mID, (mX-1), mY, mMap) == 0:
goto[1][0] = round(math.hypot(pX - (mX-1), pY - mY), 1)
# goto[1][1] is skipped since that is the monsters current position
if collisionCheck(mID, (mX+1), mY, mMap) == 0:
goto[1][2] = round(math.hypot(pX - (mX+1), pY - mY), 1)
if collisionCheck(mID, (mX-1), (mY+1), mMap) == 0:
goto[2][0] = round(math.hypot(pX - (mX-1), pY - (mY+1)), 1)
if collisionCheck(mID, mX, (mY+1), mMap) == 0:
goto[2][1] = round(math.hypot(pX - mX, pY - (mY+1)), 1)
if collisionCheck(mID, (mX+1), (mY+1), mMap) == 0:
goto[2][2] = round(math.hypot(pX - (mX+1), pY - (mY+1)), 1)
# get the lowest distance, and its key
lowest = goto.min()
lowestKey = goto.argmin()
# if the lowest distance is lower than monsters current position, move
if lowest < dist:
if lowestKey == 0:
newX = mX - 1
newY = mY - 1
if lowestKey == 1:
newY = mY - 1
if lowestKey == 2:
newX = mX + 1
newY = mY - 1
if lowestKey == 3:
newX = mX - 1
if lowestKey == 5:
newX = mX + 1
if lowestKey == 6:
newY = mY + 1
newX = mX - 1
if lowestKey == 7:
newY = mY + 1
if lowestKey == 8:
newX = mX + 1
newY = mY + 1
What is the cleanest, simplest, and fastest way to do what I'm doing? This is going to loop through many monsters at once!
d = math.degrees(math.atan((pY - mY) / (pX - mY)))
and'N NE E SE S SW W NW'.split()[int((d + 22.5) // 45)]
to know which direction you want to go if there are no collisions. \$\endgroup\$