2017-12-31 14 views
1

'Sprite'객체에 'add_internal'속성이 없다는 내용의 코드에 문제가 있습니다. 변수 active_sprite_list.add에서 트리거됩니다. 이 오류가 발생하는 이유와 해결 방법을 알고 싶었습니다. 여기서 스프라이트 클래스와 에러가 발생하기 시작하는 특정 라인을 포함시켰다.파이 게임에서 add_internal 오류를 해결하는 방법은 무엇입니까?

class Sprite(object): 
    def __init__(self, pos): 
     super(Sprite, self).__init__() # platform 
     self.width = width 
     self.height = height 
     self.platform = pygame.Surface((width, height)) 
     self.platform.fill(WHITE) 
     # set a reference to the image rect 
     self.rect = self.platform.get_rect() 
     # Assign the global image to `self.image`. 
     self.image = sprite_image 

     # Create a rect which will be used as blit 
     # position and for the collision detection. 
     self.rect = self.image.get_rect() 
     # Set the rect's center to the passed `pos`. 
     self.rect.center = pos 
     self._vx = 0 
     self._vy = 0 
     # Assign the pos also to these attributes. 
     self._spritex = pos[0] 
     self._spritey = pos[1] 
     # set of sprites sprite can bump against 
     self.level = None 


sprite = Sprite([400, 550]) 
level_list = [] 
level_list.append(Level_01) 

# Set the current level 
current_level_no = 0 
current_level = level_list[current_level_no] 

active_sprite_list = pygame.sprite.Group() 
sprite.level = current_level 

sprite.rect.x = 340 
sprite.rect.y = H - sprite.rect.height 
active_sprite_list.add(sprite) 

# Loop until the user clicks the close button. 
done = False 

while not done: 
    events() 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      done = True 

     key = pygame.key.get_pressed() 
     if key == [pygame.K_RIGHT]: 
      sprite.go_right() 
     if key == [pygame.K_LEFT]: 
      sprite.go_left() 
     if key == [pygame.K_UP]: 
      sprite.jump() 
      # If the player gets near the right side, shift the world left (-x) 
     if sprite.rect.right > W: 
      sprite.rect.right = W 

      # If the player gets near the left side, shift the world right (+x) 
     if sprite.rect.left < 0: 
      sprite.rect.left = 0 

     current_level.draw(DS) 
     active_sprite_list.draw(DS) 
    # Call the `update` method of the sprite to move it. 

    sprite.update() 
    # Update the player. 
    active_sprite_list.update() 

    # Update items in the level 
    current_level.update() 

    DS.fill(BLACK) 

    # Blit the sprite's image at the sprite's rect.topleft position. 
    DS.blit(sprite.image, sprite.rect) 

    pygame.display.flip() 

    clock.tick(FPS) 

*이 그것이 위치 인수 내가이 오류를 해결하기 위해 무엇을 할 것이다 '자기',이 코드 전체에 스프라이트 클래스 다음에 위치 할 것을 요구 current_level_update 오류를 유발하는 코드입니다 버전의 코드 자체. 클래스 Level_01 (레벨) : "" "레벨 1에 대한 정의" ""당신이 pygame.sprite.Group에 추가하려는 경우

def __init__(self): 
    """ Create level 1. """ 

    # Call the parent constructor 
    Level.__init__(self, Sprite) 

    # Array with width, height, x, and y of platform 
    level = [[210, 70, 500, 500], 
      [210, 70, 200, 400], 
      [210, 70, 600, 300], 
      ] 

    # Go through the array above and add platforms 
    for p in level: 
     block = platform(p[0], p[1]) 
     block.rect.x = p[2] 
     block.rect.y = p[3] 
     block.player = self.sprite 
     self.platform_list.add(block) 
+0

오류를 재현하는 데 필요한 코드 만 포함 된 [최소, 실행 가능한 예] (https://stackoverflow.com/help/mcve)로 코드를 변환하십시오. 또한 전체 추적을 게시하십시오. 코드가 정확하게 들여 쓰기되었는지 확인하십시오 (제출 창에서 코드를 선택하고 Ctrl + K를 누르십시오). 'key = pygame.key.get_pressed()'항목과 아래의 줄은 이벤트 루프에 있어서는 안됩니다. – skrx

답변

2

당신의 Sprite 클래스 pygame.sprite.Sprite에서 상속해야합니다. 여기

class Sprite(pygame.sprite.Sprite): 
    def __init__(self, pos): 
     # Don't forget to call the __init__ method of the parent class. 
     super(Sprite, self).__init__() 

는 완벽한 예입니다 : 대신 pygame.key.get_pressed()

import pygame 

pygame.init() 

class Sprite(pygame.sprite.Sprite): 
    def __init__(self, pos): 
     super(Sprite, self).__init__() 
     self.image = pygame.Surface((30, 50)) 
     self.image.fill((40, 60, 140)) 
     self.rect = self.image.get_rect() 
     self.rect.center = pos 
     self._vx = 3 # The x-velocity. 
     self._spritex = pos[0] 
     self._spritey = pos[1] 

    def go_right(self): 
     # Update the _spritex position first and then the rect. 
     self._spritex += self._vx 
     self.rect.centerx = self._spritex 

    def go_left(self): 
     self._spritex -= self._vx 
     self.rect.centerx = self._spritex 


BLACK = pygame.Color('black') 
clock = pygame.time.Clock() 
display = pygame.display.set_mode((800, 600)) 
sprite = Sprite([340, 550]) 
active_sprite_list = pygame.sprite.Group() 
active_sprite_list.add(sprite) 

done = False 

while not done: 
    # Handle events. 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      done = True 

    # get_pressed() returns a list with the keys 
    # that are currently held down. 
    key = pygame.key.get_pressed() 
    # Use pygame.K_RIGHT etc. as the index. 
    if key[pygame.K_RIGHT]: 
     sprite.go_right() 
    elif key[pygame.K_LEFT]: 
     sprite.go_left() 
    if key[pygame.K_UP]: 
     sprite.jump() # Not implemented. 

    # Update the game. 
    # This calls the update methods of all contained sprites. 
    active_sprite_list.update() 

    # Draw everything. 
    display.fill(BLACK) 
    # This blits the images of all sprites at their rect.topleft coords. 
    active_sprite_list.draw(display) 

    pygame.display.flip() 
    clock.tick(30) 

당신은 또한 이벤트 루프를 사용하고 pygame.KEYDOWN 이벤트가 발생 된 경우 확인할 수 있습니다 그것은 pygame.K_LEFT 또는 K_RIGHT 다음 인 경우 스프라이트의 _vx 속성을 원하는 값으로 설정하십시오. 그런 다음 위치는 스프라이트의 update 메소드에서 업데이트 될 수 있습니다.

+0

도움을 주셔서 감사합니다. 이제는 키 = pygame.get_pressed()에서 운동을 정의한 클래스로 이동해야합니까? 또한 변경 사항을 적용했으며 오류 줄 218이 나타납니다. current_level.update() TypeError : update() missing 1 필수 위치 인수 : 'self' –

+0

이제 오류가 발생합니다. line 218, in current_level.update() TypeError : update() missing 1 필수 위치 인수 : 'self'도움이 될 수 있는지 확인하기 위해 관련 클래스를 오류에 추가하겠습니까? –

+0

나는 원래 질문과 관련이 없으므로 새로운 질문을 게시하는 것이 더 좋을 것이라고 생각합니다. 코드를 복사하여 실행할 수있는 [최소한의 완전하고 검증 가능한 예제] (https://stackoverflow.com/help/mcve)로 바꾸십시오. – skrx

관련 문제