我正在使用python在pygame中创建像pacman这样的游戏。我想将一个宝石的图像分配给jewel
类。在迷宫中'J'代表jewel
。所以,为了明确我如何将图像分配给宝石类,以便迷宫图中的所有J都是该图像?
宝石的课程是
class Jewel(object):
"""Class to hold Jewel sprite properties"""
def __init__(self, pos):
jewels.append(self)
self.rect = pygame.Rect(pos[0], pos[1], 16, 16)
墙和迷宫的课程是
class Wall(object):
"""Class to hold Wall sprite properties"""
def __init__(self, pos):
walls.append(self)
self.rect = pygame.Rect(pos[0], pos[1], 16, 16)
walls = [] #List to contain walls
jewels = []#List to contain Jewels
#!-----------------------Maze Layout----------------------!
#Table used to create the level, where W = wall
level = [
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"W J W JJJ W",
"W W W W",
"W WWWW WWWWW WWWWW W WWWWWWWWWW W",
"W W W W W W W",
"W W JJJJ W WWWWWWW W W",
"W W WW W W W",
"W W W WWWW W W W",
"W WWW W W W W W WWWWW W",
"W W W W W",
"WWWW WWWWWWWWWWWWWWWWWWWWWW W",
"W W WW W W",
"W WW W WWWWWWWWWWWWWWWWW",
"W WWW W W",
"W WW WW WWW W W",
"W W WWW WWWWWWW WWWWWWWWWWWWWWWW W",
"W W W WWW WW W W W",
"W WW W W W W",
"W W W WWWWWWWWWWWWWWWWWWWWWWWW W W",
"WWWW WWWWW WW WWW W W",
"W W W W WWWWWWWWWWWWWWWWW W",
"W W WWWW W W W W W",
"W W W WWW W W W",
"W WWWW W W WWWWWWWWWWWWWWWWWWWWWWW",
"W WW W WWW W W JJJ W",
"W W W W W J W",
"W W WWW W WWW W",
"W WWW WWWWWWWWWW WWWW W",
"W W W WWWWWWW W W",
"WW W WWWW WWWWWW WWWW WWWW W",
"WJ W W W W W",
"W W J WWW WWWWW W W WWWW",
"WWW W W W W WWWW W",
"W W WWWWWW WWWW W W W",
"W WWW W W WWWWW WWWW WWWWW W",
"W WWW W W W W",
"W W W W W",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
]
#Draw the wall rects as shown in the table above
x = y = 0
for row in level:
for column in row:
if column == "W":
Wall((x, y))
if column == "J":
Jewel((x, y))
x += 16
y += 16
x = 0
#Draw walls and jewels
for wall in walls:
pygame.draw.rect(screen, (WHITE), wall.rect)
for jewel in jewels:
pygame.draw.rect(screen, (BLUE), jewel.rect)
答案 0 :(得分:3)
只需将图片添加为对象的属性 -
例如,您可以使用__init__
方法加载它们,如:
def __init__(self, pos):
walls.append(self)
self.rect = pygame.Rect(pos[0], pos[1], 16, 16)
self.image = pygame.image.load("/path/to/image_file.png")
然后,在你的游戏循环中,而不是画一个矩形,调用
传递图像的“屏幕”blit
方法(pygame.Surface
对象):
for jewel in jewels:
screen.blit(jewel.image, jewel.rect)
稍后当你在游戏中获得更多结构时,你应该将你的游戏对象放在专门的精灵组中,然后可以使用sprite的.image
和.rect
属性来当调用组draw
方法时,将它们blit到屏幕。
(查看http://www.pygame.org/docs/ref/sprite.html上的文档),而不是直接调用blit
。