我收到此错误:
Traceback (most recent call last):
File "main.py", line 95, in <module>
if mPLocX > mPLocY:
TypeError: '>' not supported between instances of 'vectorize' and 'vectorize'
从这个程序:
import numpy as np
#For the array
import random as ran
#For random starting positions
import math
#To find the difference in position
field = np.array([
[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],
])
my = ran.randint(0, 5)
#Monster Y
mx = ran.randint(0, 5)
#Monster X
py = ran.randint(0, 5)
#Player Y
px = ran.randint(0, 5)
#Player X
if my != py and mx != my:
field[my, mx] = 1
field[py, px] = 2
else:
my = ran.randint(0, 5)
#Monster Y
mx = ran.randint(0, 5)
#Monster X
py = ran.randint(0, 5)
#Player Y
px = ran.randint(0, 5)
#Player X
field[my, mx] = 1
field[py, px] = 2
mPLocY = 0
#Monster Player Location Y
mPLocX = 0
#Monster Player Location X
turn = 0
for i in range(20):
turn += 1
trueTurn = turn % 2
if trueTurn == 1:
print ("Player's Turn")
else:
print ("Monster's turn")
print("Monster is at:" + str(mx) + ", " + str(my))
print("Player is at " + str(px) + ", " + str(py))
pLoc = np.where(field == 2)
#pLoc = Player Location (declared in loop)
mLoc = np.where(field == 1)
#mLoc = Monster Location (declared in loop)
(my, mx) = mLoc
if turn == 0:
mPLocX = math.fabs(mx - px)
#Monster Player Location X (declared out of loop)
mPLocY = math.fabs(my - py)
#Monster Player Location Y (declared out of loop)
else:
mPLocX = np.vectorize(math.fabs(mx - px))
#Monster Player Location X (declared out of loop)
mPLocY = np.vectorize(math.fabs(my - py))
#Monster Player Location Y (declared out of loop)
if trueTurn == 1:
drctn = input("Input a direction (wasd): ")
#drctn means Direction
if drctn == "w":
field[py, px] = 0
py = py + 1
field[py, px] = 2
elif drctn == "s":
field[py, px] = 0
py = py - 1
field[py, px] = 2
elif drctn == "a":
field[py, px] = 0
px = px - 1
field[py, px] = 2
elif drctn == "d":
field[py, px] = 0
px = px + 1
field[py, px] = 2
else:
print("Error!")
else:
if mPLocX > mPLocY:
if mx > px:
field[my, mx] = 0
mx = mx - 1
field[my, mx] = 2
else:
field[my, mx] = 0
mx = mx + 1
field[my, mx] = 2
else:
if my > py:
field[my, mx] = 0
py = py - 1
field[my, mx] = 2
else:
field[my, mx] = 0
py = py - 1
field[my, mx] = 2
循环代码第一次运行时没有错误,第二次运行时,mx
和my
变成了形状,错误出现在第62 - 71行。
我试着去掉vectorize
,但是不起作用,我试着在所有独立变量上使用astype
,但是不起作用,它只适用于if
/else
,因为在第一个循环中,它们不是形状。
1条答案
按热度按时间zi8p0yeb1#
在你写的代码里
这使得
mPLocX
和mPLocY
成为np.vectorize
的示例(它们是否有意义是另一个主题)。然后你写了
这将引发您看到的异常,因为
np.vectorize
的示例之间不支持>
运算符。看起来您打算获取数组的元素绝对值,即其他两个数组之间的元素绝对值之差(
mx
和px
等是否实际上是数组或只是单个数字是另一个主题)。NumPy已经可以进行开箱即用的元素级计算,不需要使用
np.vectorize
: