Python说我创建的类没有属性
所以我用Pygame用Python制作了一个乒乓风格的游戏,我发现了一些东西。它说Python说我创建的类没有属性,python,pygame,pong,Python,Pygame,Pong,所以我用Pygame用Python制作了一个乒乓风格的游戏,我发现了一些东西。它说“function”对象没有属性“x”。我使用的类在这里。请帮助我,因为我已经很长时间没有使用Python了,我不知道这个错误意味着什么 from math import pi, sin, cos class Vector: def __init__ (self, x = 0, y = 0): self.x = x self.y = y @classmethod
“function”对象没有属性“x”
。我使用的类在这里。请帮助我,因为我已经很长时间没有使用Python了,我不知道这个错误意味着什么
from math import pi, sin, cos
class Vector:
def __init__ (self, x = 0, y = 0):
self.x = x
self.y = y
@classmethod
def random ():
angle = random(0, 2 * pi)
x = cos(angle)
y = sin(angle)
return Vector(x, y)
您的
Vector
类有一些错误,正如@juanpa.arrivillaga所说,您通过赋值…=Vector.random
与相对Vector.random()
如果使用内置的PyGame向量对象,您的代码可能会更好:
import pygame
import random
import math
class MyVector( pygame.math.Vector2 ):
def __init__( self, x, y ):
super().__init__( x, y )
@staticmethod
def getRandomVector():
angle = random.random() * math.pi
x = math.cos( angle )
y = math.sin( angle )
return MyVector( x, y )
v1 = MyVector( 3, 2 )
v2 = MyVector.getRandomVector()
print( "v1: "+str( v1 ) )
print( "v2: "+str( v2 ) )
将其细分以添加random()
函数。注意使用的是@staticmethod
,而不是@classmethod
。但是使用继承仅仅创建这个函数似乎增加了一些不必要的复杂性。我想如果您打算扩展向量
更多,那么请确定(基本向量对象已经有很多有用的函数)
而且
math
库没有random()
成员函数。但是使用random.random()
函数,它返回一个介于0.0
和1.0
之间的数字,很容易修复代码。self.velocity=Vector.random
将函数Vector.random
分配给self.velocity
。注意,您的@classmethod
签名也不正确。请不要用这样的话来回答你自己的问题:“StackOverflow希望我用更多的词”你为什么用Vector
而不是PyGame的Vector2
-?
import pygame
from Ball import Ball
def main ():
pygame.init()
size = (1600, 900)
window = pygame.display.set_mode(size)
pygame.display.set_caption("Pong")
ball = Ball(size)
frameRate = 60
run = True
while run:
pygame.time.delay(int(frameRate / 1000))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((0, 0, 0))
pygame.draw.rect(window, (255, 255, 255), (ball.position.x, ball.position.y, ball.scale.x, ball.scale.y))
pygame.display.update()
# This is where the error happened.
ball.position.x += ball.velocity.x
ball.position.y += ball.velocity.y
pygame.quit()
if __name__ == "__main__":
main()
import pygame
import random
import math
class MyVector( pygame.math.Vector2 ):
def __init__( self, x, y ):
super().__init__( x, y )
@staticmethod
def getRandomVector():
angle = random.random() * math.pi
x = math.cos( angle )
y = math.sin( angle )
return MyVector( x, y )
v1 = MyVector( 3, 2 )
v2 = MyVector.getRandomVector()
print( "v1: "+str( v1 ) )
print( "v2: "+str( v2 ) )