Python错误:“None Type”对象不支持项赋值

2024-10-01 02:35:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

现在,我关注了大部分类似于“松鼠吃松鼠”游戏的代码,我相信可以在树莓皮上玩,也可以在YouTube上关注sentdex的一些视频。我一直在用任何方法调试它来阻止问题,但我不明白这个错误意味着什么,也不知道如何修复它。在

现在我运行以下代码:

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']))

我希望输出中的fish会随机出现,好像世界是“无限的”,但是我得到的错误是allfish[i]['x'] = random.randint(0, screen_width)

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

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

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


Tags: 代码import游戏错误randomwidthscreenpygame
1条回答
网友
1楼 · 发布于 2024-10-01 02:35:41

您错过了函数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))

相关问题 更多 >