我的目标是在2d网格中将一个“怪物”(mX, mY
)移向玩家(pX, pY
)。怪物可以向8个不同的方向移动。你知道吗
我有这方面的工作代码,但我对Python非常陌生。我有一个强烈的倾向,我的代码是可怕的,而且有更快的方法来做它。你知道吗
我通过在怪物的位置(阵位4)周围创建一个3 x 3的阵法来完成这个任务,并用阵法位置到玩家的距离来填充它。然后我检查是否有低于怪物当前距离的,如果是,移动怪物到它那里。你知道吗
这是我现在的密码。抱歉,如果让你呕吐,我还在学。你知道吗
# 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 main.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
做我正在做的事情,最干净、最简单、最快的方法是什么?这是要循环通过许多怪物一次!你知道吗
编辑:添加collisionCheck()
:
def collisionCheck(mobID, newX, newY, mapName):
blocked = 0
if mobs.mobPos_arr[mapName][newX,newY] > -1:
blocked = 1
if mapCollision_arr[mapName][newX,newY] > 0:
blocked = 1
return int(blocked)
您可以使用阵列广播一次计算潜在的新位置:
相关问题 更多 >
编程相关推荐