Pygame:使用精灵时出错
嘿,我正在用pygame做一个小游戏项目,但每次我运行代码时,使用我的精灵(sprite)时就会出错:
class Sprite:
def _init_(self, xposition, yposition, name):
self.x = xposition
self.y = yposition
self.bitmap = image.load(name)
self.bitmap.set_colorkey ((0,0,0))
def set_position(self, xposition, yposition):
self.x = xposition
self.y = yposition
def render(self):
screen.blit(self.bitmap, (self.x, self.y))
这是我调用它的方式
hero = Sprite(20,400, 'spaceship.bmp')
herobullet = Sprite(0,480, 'bulete.bmp')
enemiebullet = Sprite(0,480, 'bulete.bmp')
更新
这是在命令行中出现的错误信息
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_debugger.py:720: UnicodeWarning: Unicode相等比较失败,无法将两个参数转换为Unicode - 解释为不相等 if filename == frame.f_code.co_filename or (not bound and breakpoint_path_match(filename, frame.f_code.co_filename)): C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_util.py:265: RuntimeWarning: 使用surfarray时找不到模块numpy或Numeric (ImportError: 找不到模块numpy或Numeric) obj_repr = repr(obj) C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_util.py:265: RuntimeWarning: 使用sndarray时找不到模块numpy或Numeric (ImportError: 找不到模块numpy或Numeric) obj_repr = repr(obj) 程序'[6344] python.exe'已退出,代码为-1073741510 (0xc000013a)。
这是完整的代码
from pygame import *
import random
from Space_invader import *
#create the sprite for both enemy and hero
class Sprite:
def _init_(self, xposition, yposition, name):
self.x = xposition
self.y = yposition
self.bitmap = image.load(name)
self.bitmap.set_colorkey ((0,0,0))
def set_position(self, xposition, yposition):
self.x = xposition
self.y = yposition
def render(self):
screen.blit(self.bitmap, (self.x, self.y))
# colision detection betwee two 32*32 sprite
def Intersect(o1_x, o1_y, o2_x, o2_y):
if (o1_x > o2_x - 32) and (o1_x < o2_x + 32) and (o1_y > o2_y - 32) and (o1_y < o2_y + 32):
return 1
else:
return 0
#initialise pygame
init()
screen = display.set_mode((640,480))
key.set_repeat(1,1) #make sure you can press the same key more then one and that there is a delay between each action
display.set_caption('UON Invader') #set windows name
background = image.load('background.png') #load background picture
hero = Sprite(20,400, 'spaceship.bmp')
herobullet = Sprite(0,480, 'bulete.bmp')
enemiebullet = Sprite(0,480, 'bulete.bmp')
1 个回答
首先,记得总是加上合适的错误信息,这样我们才能知道该去哪里查找问题哦 :)
一个可能出现的错误可能是
self.bitmap = image.load(name)
如果你是这样导入pygame的:
import pygame
这行代码应该改成:
self.bitmap = pygame.image.load(name)
希望这能帮到你!
亚历克斯
(补充) 在查找你的运行时错误时,一个可能的解决办法是下载并安装这个模块 链接。
(补充2) 在查找你的问题后,我觉得你需要检查一下你的程序,看看有没有unicode或非ascii字符。这些字符看起来像这样 "çö"。检查一下你是否不小心插入了这些字符,试着修复一下 :)