Python error: 'None Type' object does not support item assignment

Python error: 'None Type' object does not support item assignment

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

现在,我关注了大部分类似于游戏 'Squirrel eat Squirrel' 的代码,我相信它可以在 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']))

我希望输出的鱼会随机出现,就好像世界是 'infinite' 一样,但我却收到一条错误消息 allfish[i]['x'] = random.randint(0, screen_width)

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

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

对不起,如果我没有解释好。如果需要,我可以提供更多的代码,并尝试回答我没有解释的任何问题。

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

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 语句,函数的 return 值为 None 并且 None 附加到 allfish,当您执行以下操作时:

allfish.append(makeNewFish(camerax, cameray))