目前,我正在使用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:“无类型”对象不支持项目分配”
有简单的方法可以解决此问题吗?
很抱歉,如果我没有解释这个好处。如果需要,我可以提供更多代码,并尝试回答我没有解释的任何事情。
答案 0 :(得分:0)
您错过了函数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))