比较2个复数的操作数出现错误。我确信两者都是复数,因为当我在VS Code中将变量悬停时,每个实例中都清楚地显示“ Complex”。
所以我创建了以下课程
class Snake(object):
def __init__(self):
self.pos = [random.randint(1, (width-sqr_size)/sqr_size)*sqr_size,
random.randint(1, (height-sqr_size)/sqr_size)*sqr_size]
self.mov = 1 + 0j
self.body = [self.pos[:]]
def move(self, key): #Snake movement
if key + self.mov != 0 + 0j:
self.mov = copy.copy(key)
self.pos += self.mov*SPEED
self.body.insert(0, self.pos[:])
以及以下功能
def whatkey(event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
return (-1 + 0j)
if event.key == pygame.K_RIGHT:
return (1 + 0j)
if event.key == pygame.K_UP:
return (0 + 1j)
if event.key == pygame.K_DOWN:
return (0 - 1j)
我这样称呼他们
key1 = 0 + 0j
key1 = whatkey(event)
snake.move(key1)
问题可能出在if copy.copy(key) + self.mov != 0 + 0j:
当我尝试运行游戏时,标题中出现以下错误。
unsupported operand type(s) for +: 'NoneType' and 'complex'
我不明白,key1总是一个复数,它永远不会是None
答案 0 :(得分:0)
按如下所示更改代码,您将看到错误:
def whatkey(event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
return (-1 + 0j)
if event.key == pygame.K_RIGHT:
return (1 + 0j)
if event.key == pygame.K_UP:
return (0 + 1j)
if event.key == pygame.K_DOWN:
return (0 - 1j)
print("event.key is ", event.key)
print("Crap... I have to return None!")
# code ends now and python returns whatkey(event) = None