2017-10-06 174 views
0

爲了提高我的對象技能,我試圖在python中製作一個遊戲來學習如何處理對象,其中我有一個名爲Player的精靈,它顯示從一個名爲使用這個類image.gifPygame:加載圖像的精靈

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 

我在做什麼錯?我怎樣才能讓用圖像的精靈,而不會遇到這個錯誤?

+1

您似乎只用2個參數調用Rect,它應該有4. – jgritty

+0

https://www.pygame.org/docs/ref/rect.html – jgritty

+0

Rect(left,top,width,height) - >矩形 或 RECT((左,上),(寬度,高度)) - >矩形 – jgritty

回答

2

pygame.Rect()文件說只接受3層不同的參數,其中沒有一個是你試圖做只涉及提供兩個值的組合之一。

我想你應該在Player__init__()方法已經使用self.rect = pygame.Rect(0, 0, width, height)提供,預計lefttopwidth,並height參數組合。