【发布时间】:2025-12-16 06:25:01
【问题描述】:
下面是我设计后编写的一个简单的寻路算法。它旨在获取一个点或“单位”的位置,并在给定计算机位置的情况下,将计算 X 值和 Y 值的差异,并首先通过最短的差异(由于游戏,是自上而下的转弯基于游戏,单位需要排队进行攻击)。
boardArray = [[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]]
# 0 shows an empty space, G is the goal, and C is the computer
boardArray[3][6] = "G"
boardArray[7][7] = "C"
def printBoard():
for r in boardArray:
for c in r:
print(c,end = " ")
print()
printBoard()
row = 0
for i in boardArray:
column = 0
for k in i:
if k == "G":
print(row, column)
goalpos = [row, column]
if k == "C":
print(row, column)
computerpos = [row, column]
column = column + 1
row = row + 1
def updatePositions(currentx, currenty, valrow, valcolumn):
print(currentx)
print(currenty)
boardArray[valrow][valcolumn] = 0
boardArray[currentx][currenty] = "C"
valrow = currentx
valcolumn = currenty
printBoard()
return valrow, valcolumn
def findPath(outscoperow, outscopecolumn):
DifferenceX = computerpos[0] - goalpos[0]
DifferenceY = computerpos[1] - goalpos[1]
CurrentCompX = computerpos[0]
CurrentCompY = computerpos[1] + 1
TemporaryX = DifferenceX
TemporaryY = DifferenceY
if DifferenceX < 0:
DifferenceX = DifferenceX *(-1)
if DifferenceY < 0:
DifferenceY = DifferenceY *(-1)
pathfinding = True
while pathfinding:
if DifferenceX < DifferenceY:
if TemporaryX > 0:
CurrentCompX = CurrentCompX - 1
outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
DifferenceX = DifferenceX - 1
elif TemporaryX < 0:
CurrentCompX = CurrentCompX + 1
outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
DifferenceX = DifferenceX - 1
elif DifferenceX > DifferenceY:
if TemporaryY > 0:
CurrentCompY = CurrentCompY - 1
outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
DifferenceY = DifferenceY - 1
elif TemporaryY < 0:
CurrentCompY = CurrentCompY + 1
outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
DifferenceY = DifferenceY - 1
if DifferenceX == 0 and DifferenceY == 0:
pathfinding = False
findPath(row, column)
当代码运行时,它应该实时移动计算机位置,打印出二维数组,然而,当改变位置时,解释器也会指出当前坐标在数组之外索引(或列表,因为 Python 很奇怪)。
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 G 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 C
3 6
7 7
7
7
Traceback (most recent call last):
File "C:/Users/Cameron/Desktop/Basic RPG/pathfindingTest.py", line 88, in <module>
findPath(row, column)
File "C:/Users/Cameron/Desktop/Basic RPG/pathfindingTest.py", line 77, in findPath
outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
File "C:/Users/Cameron/Desktop/Basic RPG/pathfindingTest.py", line 44, in updatePositions
boardArray[valrow][valcolumn] = 0
IndexError: list index out of range
如果有人能提供最有用的帮助。
【问题讨论】:
标签: python arrays path-finding