How do I make this pygame class and .self work

Question:

import pygame

pygame.init()

wn = pygame.display.set_mode((200,200))

x = 100
y = 100

class circle():
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def draw(self, x, y):
        pygame.draw.circle(wn, (255, 0, 0), (self.x, self.y), 5)

circle.draw(x, y)

What am I missing? I am new to all of this and I am really confused. The error I am getting is:

Traceback (most recent call last):
  File "c:UsersdaveyOneDriveDocumentsPythonGamemain.py", line 17, in <module>
    circle.draw(x, y)
TypeError: circle.draw() missing 1 required positional argument: 'y'

What is going wrong with it?

Asked By: Bugzooo

||

Answers:

To call draw method first you want to create circle object learn more here

circ = circle(x, y)

Now you can call circ methods like draw() as circ.draw(x, y)

But let’s look at draw method:

    def draw(self, x, y):
        pygame.draw.circle(wn, (255, 0, 0), (self.x, self.y), 5)

You are using self variables in (self.x, self.y) that means that arguments: x and y in def draw(self, x, y): are ignored because self.x refers to the one initalized here:

def __init__(self, x, y):
        self.x = x

So final code should look something like this:

import pygame

pygame.init()

wn = pygame.display.set_mode((200,200))

x = 100
y = 100

class Circle():
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def draw(self):
        pygame.draw.circle(wn, (255, 0, 0), (self.x, self.y), 5)

circle = Circle(x, y)
circle.draw()


# Workaround to keep window open. Exit by pressing ctrl+c in terminal
while True:
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

Notice I named class Circle(): with uppercase C because that’s naming convention for python

I advice to to learn about python classes from youtube or websites it will make more sense when to use self and what is difference between objects and classes etc.

Good luck in your programming journey!

Answered By: Combinacijus
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.