Python 如何将精灵(图像)指定给矩形?
我正在尝试学习如何为一个项目使用python和pygame创建一个迷宫游戏。我遇到的问题是,在所有的例子中,我发现它们只有一个简单的正方形作为字符。我有一个16x16px的图像(我想要使用的角色精灵),所以对于我正在使用的示例来说,它的大小是正确的,我甚至设法让精灵加载一次。但当它发生时,我的角色无法移动 那么,如何将这个rect表示为16x16px图像,并将其存储在与代码相同的文件夹中,而不是彩色正方形 以下是我在尝试更改玩家精灵时给出的两个结果:Python 如何将精灵(图像)指定给矩形?,python,pygame,sprite,Python,Pygame,Sprite,我正在尝试学习如何为一个项目使用python和pygame创建一个迷宫游戏。我遇到的问题是,在所有的例子中,我发现它们只有一个简单的正方形作为字符。我有一个16x16px的图像(我想要使用的角色精灵),所以对于我正在使用的示例来说,它的大小是正确的,我甚至设法让精灵加载一次。但当它发生时,我的角色无法移动 那么,如何将这个rect表示为16x16px图像,并将其存储在与代码相同的文件夹中,而不是彩色正方形 以下是我在尝试更改玩家精灵时给出的两个结果: class Player(object):
class Player(object):
def __init__(self):
self.rect = pygame.Rect(32, 32, 16, 16)
任何帮助都将不胜感激
(更新)完整游戏:
import os
import random
import pygame
IMAGE = pygame.image.load('mudkip.png')
all_sprites = pygame.sprite.Group()
# Class for character
class Player(pygame.sprite.Sprite):
def __init__(self, pos):
super().__init__(all_sprites)
# Get the image from the variable
self.image = IMAGE
# Get the rect from the image
self.rect = self.image.get_rect(topleft=pos)
def draw(self):
screen.blit(self.image, self.rect)
def move(self, dx, dy):
# Move each axis separately. Note that this checks for collisions both times.
if dx != 0:
self.move_single_axis(dx, 0)
if dy != 0:
self.move_single_axis(0, dy)
def move_single_axis(self, dx, dy):
# Move the rect
self.rect.x += dx
self.rect.y += dy
# If you collide with a wall, move out based on velocity
for wall in walls:
if self.rect.colliderect(wall.rect):
if dx > 0: # Moving right; Hit the left side of the wall
self.rect.right = wall.rect.left
if dx < 0: # Moving left; Hit the right side of the wall
self.rect.left = wall.rect.right
if dy > 0: # Moving down; Hit the top side of the wall
self.rect.bottom = wall.rect.top
if dy < 0: # Moving up; Hit the bottom side of the wall
self.rect.top = wall.rect.bottom
# Nice class to hold a wall rect
class Wall(object):
def __init__(self, pos):
walls.append(self)
self.rect = pygame.Rect(pos[0], pos[1], 16, 16)
# Initialise pygame
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
# Set up the display
pygame.display.set_caption("Get to the red square!")
screen = pygame.display.set_mode((560, 240))
clock = pygame.time.Clock()
walls = [] # List to hold the walls
player = Player((30, 30)) # Create the player
# Holds the level layout in a list of strings.
level = [
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"W W W",
"W W WWWWWW W",
"W WWWW W W",
"W W WWWW wwwwww W",
"W WWW WWWW W",
"W W W W W",
"WE W W WWW W W",
"W WWW WWW W W W",
"W W W W W W",
"WWW W WWWWW W W",
"W W WW WWWWWWWWW W",
"W W WWWW WWW W",
"W W W W",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
]
# Parse the level string above. W = wall, E = exit
x = y = 0
for row in level:
for col in row:
if col == "W":
Wall((x, y))
if col == "E":
end_rect = pygame.Rect(x, y, 16, 16)
x += 16
y += 16
x = 0
running = True
while running:
clock.tick(60)
for e in pygame.event.get():
if e.type == pygame.QUIT:
running = False
if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
running = False
# Move the player if an arrow key is pressed
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
player.move(-2, 0)
if key[pygame.K_RIGHT]:
player.move(2, 0)
if key[pygame.K_UP]:
player.move(0, -2)
if key[pygame.K_DOWN]:
player.move(0, 2)
# Just added this to make it slightly fun ;)
if player.rect.colliderect(end_rect):
raise SystemExit('You win!')
# Draw the scene
all_sprites.draw(0)
screen.fill((0, 0, 0))
for wall in walls:
pygame.draw.rect(screen, (255, 255, 255), wall.rect)
pygame.draw.rect(screen, (255, 0, 0), end_rect)
pygame.display.flip()
所有精灵出现错误。绘制(0):
第129行,在
所有精灵。绘制(0)
“lib\site packages\pygame\sprite.py”,绘图中第474行
surface\u blit=surface.blit
AttributeError:“int”对象没有属性“blit”
好的,那么您需要做的第一件事就是加载一个图像,看起来您已经这样做了
要将其放入雪碧中,您必须执行以下操作:
class Player(pygame.sprite.Sprite):
def __init__(self, pos): # Additional position argument, formatted like (x, y)
# Get the image from the variable
self.image = IMAGE
# Get the rect from the image
self.rect = self.image.get_rect(topleft=pos)
然后,添加一个draw
函数,将您的角色添加到屏幕上。这相对简单
def draw(self):
screen.blit(self.image, self.rect)
# Note, you may have move your global vars before the sprite classes to prevent a NameError now.
最后,您将它们与一些添加的内容放在一起,以便让新基类在以后添加内容
您不应该将def draw
添加到主游戏循环中;)
官方域名的可能副本-它为您提供
Surface
图像,您可以使用screen.blit(Surface,rect)
BTW:加载图像后,您可以执行rect=Surface.get\rect()
创建具有图像大小的rect
。@Pygasm所以我添加了图像和精灵类,但它仍然加载了一个正方形。我需要更改我共享的播放器对象和绘图区域中的某些内容,但我无法确定需要更改的内容。我现在有一些内容:请不要将代码放在注释中。单击“编辑”b在你的帖子上点击按钮,然后自己添加@MikeS@MikeS很抱歉,我现在有一个贴纸盒:我很感谢你的帮助,但我真的很难理解在我完成后如何将精灵应用于我的角色。我添加了一个位置参数(self,pos(0,0)):我得到了一个语法错误。如果我不添加它,我也会得到一个请求它们的错误。我太没用了,谢谢你的支持。当我指的是参数时,我的意思是pos将保留为类代码中的占位符,但是在构造类时,你会将参数传递到那些括号中,所以player=player((0,0))
,而不是(self,pos(0,0)
。顺便说一句:更改pos
也会更改播放器的显示位置,因此请确保值与您希望的位置对齐!;)@MikeSI已经给了我的玩家一个pos值,不再出现任何错误。问题是我的玩家不可见。我知道玩家还在,因为我可以到达终点,但你必须猜你的角色在哪里。我已经用我更改的部分更新了帖子。如果我删除draw.rect或用screen.blit替换它,我没有sp如果我把它放在我的播放器里,让它变成一个彩色的方块。添加screen.blit似乎没有任何作用。@MikeS进行了编辑,你不应该添加draw()
到主游戏循环,但是是精灵。还忘了精灵组需要存在,所以我也加入了。我试着到处玩来修复它,但我又卡住了…它说当我运行游戏时只需要一个参数。我试着从create player函数中删除一组括号,然后它说需要“2个位置参数,但3个被给出“即使我有(30,30)。我已经在帖子中添加了错误。我知道你为我写了这篇文章,但在此之前我没有Pygame的经验,你的解释真的很有帮助。再次感谢。
line 129, in <module>
all_sprites.draw(0)
lib\site-packages\pygame\sprite.py", line 474, in draw
surface_blit = surface.blit
AttributeError: 'int' object has no attribute 'blit'
class Player(pygame.sprite.Sprite):
def __init__(self, pos): # Additional position argument, formatted like (x, y)
# Get the image from the variable
self.image = IMAGE
# Get the rect from the image
self.rect = self.image.get_rect(topleft=pos)
def draw(self):
screen.blit(self.image, self.rect)
# Note, you may have move your global vars before the sprite classes to prevent a NameError now.
# Earlier in the code...
all_sprites = pygame.sprite.Group() # This will allow all the sprites to be drawn in one fell swoop instead of it being done manually.
class Player(pygame.sprite.Sprite): # Make sure to inherit the sprite object!
def __init__(self, pos):
super().__init__(all_sprites) # Add the new sprite to the sprite group
self.image = IMAGE
# Get the rect from the image
self.rect = self.image.get_rect(topleft=pos)
def draw(self):
screen.blit(self.image, self.rect)
# Then in the game loop...
all_sprites.draw() # This will call draw() in every active sprite object.