gpt4 book ai didi

python - position += heading*distance_moved 类型错误 : can only concatenate tuple (not "Vector") to tuple

转载 作者:行者123 更新时间:2023-11-28 17:48:07 26 4
gpt4 key购买 nike

*尽管该操作的所有部分都是元组,python 似乎认为在这种情况下其中一个不是。这是我第一次尝试在 python 中制作矢量类。我的意图是将我的简单鼠标图像移动到我在屏幕上单击的位置,方法是将速度 * 矢量的增量添加到它的位置,直到它到达目标距离 *

导入数学

类向量(对象):

#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)

#Ramon Cabral 的简单鼠标移动游戏

#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()

最佳答案

您必须定义 getitemsetitem在您的 Vector 类中支持索引的方法。

关于python - position += heading*distance_moved 类型错误 : can only concatenate tuple (not "Vector") to tuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15140766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com