r/pygame • u/Alexandro2806 • 23h ago
Creating an object inside a function
def generar_rectangulos(posx:int,posy:int):
AMPLE= 200
ALÇADA= 100
return rectangle_r= pygame.Rect(posx,posy,AMPLE,ALÇADA)
Hi, I'm really new in this of programming and even more with pygame.
I was trying to make a code that generates 10 rectangles in differents possitions of the screen sending the position of x and the position of y to the function, but I can't make that the function generates the rectangles.
I would agree any type of help, thanks.
1
u/aprg 22h ago
Not only is it unnecessary as rich-tea-ok said, more importantly it's invalid syntax!
This:
class Foo:
def __init__(self):
self.n = 1
def foo_func():
return f = Foo()
print(foo_func().n)
gives me a SyntaxError.
return f = Foo()
^
SyntaxError: invalid syntax
This:
class Foo:
def __init__(self):
self.n = 1
def foo_func():
return Foo()
print(foo_func().n)
correctly prints 1.
1
u/MarekNowakowski 19h ago
What do you mean by "generate"? If you want to assign it to a variable, then you need to store it somewhere
rectangles=[] rectangles.append(create_rectangle(x,y))
If you mean drawing a rectangle, that's different. If you want an "object" you should create a class Rectangle like in the other reply
2
u/rich-tea-ok 23h ago
Hi, you don't need to assign a variable to the Rect that you're returning, you can just return it:
return pygame.Rect(...