【问题标题】:Pygame: Loading Sprites With ImagesPygame:加载带有图像的精灵
【发布时间】:2017-10-06 21:13:06
【问题描述】:

为了提高我对对象的技能,我正在尝试用 python 制作一个游戏来学习如何处理对象,其中我有一个名为 Player 的精灵,它显示从名为 image.gif 的文件中获取的图像,使用这个类:

class Player(pygame.sprite.Sprite):
    def __init__(self, width, height):
        super().__init__()
        self.rect = pygame.Rect(width, height)
        self.image = pygame.Surface([width, height])
        self.image = pygame.image.load("image.gif").convert_alpha()
        # More sprites will be added.

然后我将该类用于以下代码:

import Pysprites as pys
pygame.init()
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
GRAY = (255,255,255)
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Game")
all_sprites_list = pygame.sprite.Group()
player = pys.Player(44,22)
all_sprites_list.add(player)
carryOn = True
clock=pygame.time.Clock()
while carryOn:
    for event in pygame.event.get():
            if event.type==pygame.QUIT:
                carryOn=False
    all_sprites_list.update()
    clock.tick(60)
    all_sprites_list.draw(screen)
    pygame.display.flip()
    pygame.display.update()
pygame.quit()

并得到错误:

Traceback (most recent call last):
  File "Game1.py", line 14, in <module>
    player = pys.Player(44,22)
  File "Pysprites.py", line 9, in __init__
    self.rect = pygame.Rect(width, height)
TypeError: Argument must be rect style object

我做错了什么?如何在不遇到此错误的情况下制作带有图像的精灵?

【问题讨论】:

  • 你似乎只用 2 个参数调用 Rect,它应该有 4 个。
  • Rect(left, top, width, height) -> Rect or Rect((left, top), (width, height)) -> Rect

标签: python python-3.x pygame sprite


【解决方案1】:

pygame.Rect() 文档说它只接受 3 种不同的参数组合中的一种,其中没有一种涉及只提供两个值,就像您尝试做的那样。

我认为您应该在Player__init__() 方法中使用self.rect = pygame.Rect(0, 0, width, height) 来提供它所期望的lefttopwidthheight 参数组合。

【讨论】:

    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多