2012-09-11 6 views
0

잘못된 정보를 유효하지 않은 목표 위치는 다음과 같습니다파이 게임 : 블릿

Traceback (most recent call last): 
    File "C:\Documents and Settings\Administrator.MICRO-C17310A13\桌面\pygame例子\vectorfish.py", line 24, in <module> 
    screen.blit(sprite, position) 
TypeError: invalid destination position for blit 

코드는 다음과 같습니다

background_image_filename = 'sushiplate.jpg'  
sprite_image_filename = 'fugu.bmp'  
import pygame  
from pygame.locals import *  
from sys import exit  
from vector2 import Vector2  
pygame.init()  
screen = pygame.display.set_mode((640, 480), 0, 32)  
background = pygame.image.load(background_image_filename).convert()  
sprite = pygame.image.load(sprite_image_filename).convert_alpha()  
clock = pygame.time.Clock() 

position = Vector2(100.0, 100.0) 

speed = 250.0 

heading = Vector2() 

while True: 

    for event in pygame.event.get(): 
     if event.type == QUIT: 
      exit() 
    if event.type == MOUSEBUTTONDOWN: 
     destination = Vector2(*event.pos) - Vector2(*sprite.get_size())/2. 
     heading = Vector2.from_points(position, destination) 
     heading.normalize() 
    screen.blit(background, (0,0)) 
    screen.blit(sprite, position) 
    time_passed = clock.tick() 
    time_passed_seconds = time_passed/1000.0 
    distance_moved = time_passed_seconds * speed 
    position += heading * distance_moved 
    pygame.display.update() 

vector2의 코드는 다음과 같습니다

import math 

class Vector2(object): 

    def __init__(self, x=0.0, y=0.0): 
     self.x = x 
     self.y = y 
    def __str__(self): 
     return "(%s, %s)"%(self.x, self.y) 
    @staticmethod 
    def from_points(P1, P2): 
     return Vector2(P2[0] - P1[0], P2[1] - P1[1]) 
    def get_magnitude(self): 
     return math.sqrt(self.x**2 + self.y**2) 
    def normalize(self): 
     magnitude = self.get_magnitude() 
     self.x /= magnitude 
     self.y /= magnitude 

뿐만 아니라이 코드 그러나 vector2가 필요한 모든 코드는이 질문을 만났습니다. blit의 대상 위치가 잘못되었습니다.

내가 잘못 했나요?

도움이 필요합니다.

길버트 짱

답변

3

Surface.blittupledest로 매개 변수를 기대하고있다.

class Vector2(tuple): 

    def __new__(typ, x=1.0, y=1.0): 
     n = tuple.__new__(typ, (int(x), int(y))) 
     n.x = x 
     n.y = y 
     return n 

    def __mul__(self, other): 
     return self.__new__(type(self), self.x*other, self.y*other) 

    def __add__(self, other): 
     return self.__new__(type(self), self.x+other.x, self.y+other.y) 

    def __str__(self): 
     return "(%s, %s)"%(self.x, self.y) 
    @staticmethod 
    def from_points(P1, P2): 
     return Vector2(P2[0] - P1[0], P2[1] - P1[1]) 
    def get_magnitude(self): 
     return math.sqrt(self.x**2 + self.y**2) 
    def normalize(self): 
     magnitude = self.get_magnitude() 
     self.x /= magnitude 
     self.y /= magnitude 

지금은 tuple에서 서브 클래스 그리고 당신은 blit 함수에 전달할 수 있습니다 : 당신이 당신의 자신의 벡터 클래스 작업 할 경우이로 변경. (튜플에는 반드시 int이 포함되어야합니다).

또한 덧셈과 곱셈을 지원하기 위해 __add____mul__을 추가했습니다.

이렇게하면 코드를 더 이상 수정할 필요가 없으므로 벡터 클래스를 의도 한대로 사용할 수 있습니다.

+0

정말 고맙습니다. 모든 코드가 작동했습니다. – user1662213

+0

@ user1662213 기꺼이 도와 드리겠습니다. 'x'와'y'에 대한 속성을 사용하여 불변으로 만들면 클래스를 더 향상시킬 수 있습니다. 그러나이 질문/답변의 범위를 벗어납니다 :-) – sloth

1

는 다음을 시도해보십시오

screen.blit(sprite, (position.x, position.y)) 

문제는 당신 Vector2 당신이 당신의 객체에 tuple를 호출 할 수 있도록하는 반복자입니다 __iter__에 대한 과부하가없는 것입니다. 즉, blit 함수 호출로 튜플로 변환 할 수 없으므로 매개 변수가 유효하지 않습니다.

def __iter__(self): 
     return [self.x, self.y].__iter__() 

을 그리고 당신의 블릿은 다음과 같습니다 :

귀하의 Vector2은 포함됩니다

screen.blit(sprite, tuple(position)) 
+0

Vector2 (객체) 클래스를 Vector (튜플)로 변경했으며 작동합니다. 감사합니다. – user1662213

+0

예, iterator를 통해 객체를 튜플로 변환 할 필요가 없기 때문에 가능합니다. 사실이 튜토리얼이 나왔을 때, 올바르게 기억한다면 파이썬으로 __tuple__ 캐스트를 오버로드 할 수 있습니다. –