我正在尝试使用pygame在python中获取我的漫步动画,并且我得到以下错误:
Traceback (most recent call last):
File "C:\Users\name\Desktop\game\game.py", line 37, in <module>
player1 = player()
File "C:\Users\name\Desktop\game\game.py", line 21, in __init__
self.img = pygame.image.load(self.ani[1])
IndexError: list index out of range
这是我的代码:
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
height = 400
width = 800
screen = pygame.display.set_mode((width, height), 0, 32)
class player:
def __init__(self):
self.x = 200
self.y = 300
self.ani_speed_init = 10
self.ani_speed = self.ani_speed_init
self.ani = glob.glob("game\redplayer*.png")
self.ani.sort()
self.ani_pos = 0
self.ani_max = len(self.ani) - 1
self.img = pygame.image.load(self.ani[1])
self.update(0)
def update(self, pos):
if pos != 0:
self.ani_speed -= 1
self.x += pos
if self.ani_speed == 0:
self.img = pygame.image.load(self.ani[self.ani_pos])
self.ani_speed = self.ani_speed_init
if self.ani_pos == self.ani_max:
self.ani_pos = 0
else:
self.ani_pos += 1
screen.blit(self.img,(self.x, self.y))
player1 = player()
pos = 0
我检查了文件名,我不这么认为,但它可能是
答案 0 :(得分:1)
“\ r”是一个回车符,使你的文件名为“game&lt;回车&gt; edplayer * .png”。
尝试“game \\ redplayer * .png”或r“game \ redplayer * .png”。
答案 1 :(得分:1)
看起来你在self.ani的索引上是一个接一个。列表中的第一项是索引0,因为您只加载了一个帧。
self.img = pygame.image.load(self.ani[0])
我在你的机器上搞乱你的代码让它运转起来,就在这里。 :) 将每个动画帧预加载到预渲染曲面列表中,然后将相应的帧blit到屏幕。 还添加了一个简单的游戏循环(按Q退出),包括FPS时钟。
import pygame
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
FPS = 30
width = 800
height = 600
screen = pygame.display.set_mode((width, height), 0, 32)
class player:
def __init__(self, init_pos = (10,10), init_ani_speed = 10):
self.x = init_pos[0]
self.y = init_pos[1]
self.ani_speed_init = init_ani_speed
self.ani_speed = self.ani_speed_init
self.ani = []
# nux-style code here! :)
# self.ani.append(glob.glob("game\\redplayer_01*.png"))
# self.ani.append(glob.glob("game\\redplayer_02*.png"))
self.ani.append("./ani/super_neko_01.png")
self.ani.append("./ani/super_neko_02.png")
self.ani_max = len(self.ani)-1
self.ani_pos = 0
self.img = []
for item in self.ani:
self.img.append(pygame.image.load(item))
self.update(0)
def update(self, pos = 0):
# init: starts at 10, immediately blits self to screen at x,y
if pos != 0:
self.ani_speed -= 1
self.x += pos # move right by pos pixels
if self.ani_speed == 0:
self.ani_speed = self.ani_speed_init
if self.ani_pos < self.ani_max:
self.ani_pos += 1
else:
self.ani_pos = 0
tempSurf = self.img[self.ani_pos]
screen.blit(tempSurf,(self.x, self.y))
player1 = player()
# Main Game Loop
quit = False
while quit == False:
for event in pygame.event.get():
if (event.type == KEYUP):
if (event.key == K_q):
quit = True
if quit == False:
player1.update(1)
pygame.display.update()
clock.tick(FPS)
pygame.quit()