2013-02-28 1 views
3

* 작업의 모든 부분이 튜플 인 경우에도 파이썬은이 인스턴스 중 하나만 있다고 생각하는 것 같습니다. 파이썬에서 벡터 클래스를 만드는 것은 이번이 처음입니다. 이 목표 거리에 도달 할 때까지 내 의도는 위치에 속도 * 벡터의 그것에 단위를 추가하여 내가 화면에 클릭하는 위치에 내 간단한 마우스 이미지를 이동할 수 있습니다 *position + = heading * distance_moved TypeError : 터플 (벡터가 아님)을 터플로 연결하여

수입 수학

클래스 벡터 (객체) :

#defaults are set at 0.0 for x and y 
def __init__(self, x=0.0, y=0.0): 
    self.x = x 
    self.y = y 

#allows us to return a string for print 
def __str__(self): 
    return "(%s, %s)"%(self.x, self.y) 

# from_points generates a vector between 2 pairs of (x,y) coordinates 
@classmethod 
def from_points(cls, P1, P2): 
    return cls(P2[0] - P1[0], P2[1] - P1[1]) 

#calculate magnitude(distance of the line from points a to points b 
def get_magnitude(self): 
    return math.sqrt(self.x**2+self.y**2) 

#normalizes the vector (divides it by a magnitude and finds the direction) 
def normalize(self): 
    magnitude = self.get_magnitude() 
    self.x/= magnitude 
    self.y/= magnitude 

#adds two vectors and returns the results(a new line from start of line ab to end of line bc) 
def __add__(self, rhs): 
    return Vector(self.x +rhs.x, self.y+rhs.y) 

#subtracts two vectors 
def __sub__(self, rhs): 
    return Vector(self.x - rhs.x, self.y-rhs.y) 

#negates or returns a vector back in the opposite direction 
def __neg__(self): 
    return Vector(-self.x, -self.y) 

#multiply the vector (scales its size) multiplying by negative reverses the direction 
def __mul__(self, scalar): 
    return Vector(self.x*scalar, self.y*scalar) 

#divides the vector (scales its size down) 
def __div__(self, scalar): 
    return Vector(self.x/scalar, self.y/scalar) 

def points(self): 
    return (self.x, self.y) 

#imports 
import pygame, sys, Vector 
from pygame.locals import * 
from Vector import * 

#game init 
pygame.init() 

#screen 
screen = pygame.display.set_mode((800,600),0,32) 

#images 
mouse_file = 'mouse.png' 
MOUSE = pygame.image.load(mouse_file).convert_alpha() 


#variables 
bgcolor = (255,255,255) 
position = (100.0, 100.0) 
heading = Vector(0, 0) 

#clock and speed 
clock = pygame.time.Clock() 
speed = 250.0 


#main game function 
while True: 

    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 

     if event.type == MOUSEBUTTONDOWN: 
      destination = pygame.mouse.get_pos() 
      heading = Vector.from_points(position, destination) 
      heading.normalize() 

    screen.fill(bgcolor) 
    screen.blit(MOUSE, position) 

    time_passed = clock.tick(30.) 
    time_passed_seconds = time_passed/1000.0 

    distance_moved = time_passed_seconds*speed 
    position += heading*distance_moved 
    pygame.display.update() 
+0

당신이 줄 수 점의 튜플로 벡터를 치료하기 위해 필요, 당신은 그렇게 할 수있는 인스턴스 메서드를 만들 수 예를 들어 오류가 발생합니까? – BluePeppers

+0

다음은 잘못된 부분입니다 : if event.type == MOUSEBUTTONDOWN : destination = pygame.mouse.get_pos() heading = Vector.from_points (위치, 대상) heading.normalize() time_passed = clock.tick (30) .) time_passed_seconds = time_passed/1000.0 distance_moved = time_passed_seconds * 속도 위치 + = 제목 *는 – rrcm

+0

내가 그것을 – rrcm

답변

1

당신은이 라몬 카브 랄로 #The 간단한 마우스 이동 게임 정의 할 getitemsetitem 메서드를 사용하여 Vector 클래스에서 인덱싱을 지원할 수 있습니다.

+0

이것들을 만들었지 만 지금은 __getitem__에 오류가 있습니다. 어떻게 작동하는지 잘 모르겠습니다. DEF __getitem __ (자기 인덱스) 복귀 자기 [인덱스] DEF __setitem __ (자기, 인덱스 값) : 자기 [지수 = 1.0 * 값 DEF __iter __ (자기) 복귀 ITER (자기 [: ]) – rrcm

1

숫자 튜플을 원할 때 Vector.from_points Vector 객체를 전달하는 것처럼 보입니다. 이런 식으로 해봤습니까?

position_points = (position.x, position.y) 
heading = Vector.from_points(position_points, destination) 

Vector 색인 생성을 권장하지 않습니다. 대개 목록과 같은 객체 용으로 예약되어 있습니다. 어떤 Vector()[0]Vector()[1]이 있어야하는지 명확하지 않습니다. Vector().xVector().y입니다.

당신이 자주 (읽기 : "한 번 이상")를 찾을 경우 :

class Vector(object): 
    # ... 
    def points(self): 
     return (self.x, self.y) 
    # ... 
+0

나는 그것을 튜플에 전달했다. 나는 position = (100.0, 100.0)을 만들었다. 이것은 나에게 너무 혼란 스럽다. – rrcm

+0

'position + = heading * distance_moved' 명령문은'Vector'를 반환하는 것처럼 보입니다. 'heading'은'Vector'입니다, 안 그래요? –

+0

예, 제목은 지점 위치와 대상에서 생성 된 벡터입니다. 목적지에 도달 할 때까지 heading.normalize()를 증가시킬 수 있어야합니다. 기본적으로 내 마우스 이미지를 화면에서 클릭하는 위치로 옮기고 싶습니다. – rrcm