gpt4 book ai didi

Python错误: 'None Type' object does not support item assignment

转载 作者:太空宇宙 更新时间:2023-11-03 20:38:41 26 4
gpt4 key购买 nike

目前我正在使用 pygame 制作一个游戏,目前我正在尝试将鱼显示到屏幕上,使其随机出现在屏幕周围。随后,这些鱼会加分来得分。但是,当我尝试将一些鱼加载到游戏中时,出现类型错误。我该如何解决这个问题?

现在,我正在关注与游戏“松鼠吃松鼠”类似的大部分代码,我相信该游戏可以在 Raspberry Pi 上玩,并且还关注了 YouTube 上的一些 senddex 视频。我一直在通过任何方式调试它以阻止问题,但我不明白这个错误意味着什么或如何修复它。

现在我运行以下代码:

global screen, grasspic, bearImg, fishpic, screen_width, screen_height
import random
import pygame
import sys
import math
pygame.init()

camerax = 0
cameray = 0
screen_width = 640
screen_height = 480

fishpic = []
for i in range(1, 3):
fishpic.append(pygame.image.load('fish%s.png' % i))

for i in range(3):
allfish.append(makeNewFish(camerax, cameray))
allfish[i]['x'] = random.randint(0, screen_width)
allfish[i]['y'] = random.randint(0, screen_height)

def getRandomOffCameraPos(camerax, cameray, objWidth, objHeight):
cameraRect = pygame.Rect(camerax, cameray, screen_width, screen_height)
while True:
x = random.randint(camerax - screen_width, camerax + (2*screen_width))
y = random.randint(cameray - screen_height, cameray + (2*screen_height))
objRect = pygame.Rect(x, y, objWidth, objHeight)
if not objRect.colliderect(cameraRect):
return x, y

def makeNewFish(camerax, cameray):
fi = {}
fi['fishPicture'] = random.randint(0, len(fishpic) - 1)
fi['width'] = 150
fi['height'] = 150
fi['x'], fi['y'] = getRandomOffCameraPos(camerax, cameray, fi['width'], fi['height'])
fi['rect'] = pygame.Rect((fi['x'], fi['y'], fi['width'], fi['height']))

我希望输出会让鱼随机出现,就好像世界是“无限”一样,但我收到一个错误,内容为 allfish[i]['x'] = random.randint(0, screen_width)

TypeError: 'None Type' object does not support item assignment"

有没有简单的方法可以解决这个问题?

如果我没有解释清楚,我很抱歉。如果需要,我可以提供更多代码并尝试回答我没有解释的任何问题。

最佳答案

您错过了函数 makeNewFish 中的 return 语句:

def makeNewFish(camerax, cameray):
fi = {}
fi['fishPicture'] = random.randint(0, len(fishpic) - 1)
fi['width'] = 150
fi['height'] = 150
fi['x'], fi['y'] = getRandomOffCameraPos(camerax, cameray, fi['width'], fi['height'])
fi['rect'] = pygame.Rect((fi['x'], fi['y'], fi['width'], fi['height']))

return fi # <-----

如果没有 return 语句,函数的返回值为 None 并且 None 会附加到 allfish,当您执行以下操作时:

allfish.append(makeNewFish(camerax, cameray))

关于Python错误: 'None Type' object does not support item assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56997627/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com