Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make this pygame class and .self work

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:\Users\davey\OneDrive\Documents\Python\Game\main.py", line 17, in <module>
    circle.draw(x, y)
TypeError: circle.draw() missing 1 required positional argument: 'y'

What is going wrong with it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading