Markus121 Markus121 - 1 month ago 6
Python Question

How to draw a Circle that's inside a class?

I am trying to draw a circle, that is within a class, which is meant to be the player.

However, I cannot get the circle to be drawn.

import pygame
pygame.init()

#Colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

display_width, display_height = 800, 600
screen = pygame.display.set_mode((display_width, display_height))
screen.fill(white)

class Player():
def __init__(self):
self.player_surface = screen
self.player_color = green
self.player_pos = ((display_height - self.player_radius * 3), (display_width/2))
self.player_radius = 5
self.player_width = 0

def character(self):
self.player_character = pygame.draw.circle(self.player_surface, self.player_color, self.player_pos, self.player_radius, self.player_width)

#Player Reference
player = Player()

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
#Background
screen.fill(white)

#Draw everything in order, each drawn object will be drawn beneath the next drawn object.

# Draw the player -----------------------------
player.character()
# Draw the player -----------------------------

#Update
pygame.display.update()

tao tao
Answer

Here I have modified your code to get the circle to show up.

import pygame
pygame.init()

#Colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

display_width, display_height = 800, 600
screen = pygame.display.set_mode((display_width, display_height))
screen.fill(white)

class Player():
    def __init__(self):
        self.player_surface = screen
        self.player_color = green
        self.player_radius = 25        
        self.player_pos = (int(display_height - self.player_radius * 3), int(display_width/2))
        self.player_width = 0

    def character(self):
        self.player_character = pygame.draw.circle(self.player_surface, self.player_color, self.player_pos, self.player_radius, self.player_width)

#Player Reference
player = Player()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False
    #Background
    screen.fill(white)

    #Draw everything in order, each drawn object will be drawn beneath the next drawn object.

    # Draw the player -----------------------------
    player.character()
    # Draw the player -----------------------------

    #Update
    pygame.display.update()

These were the problems with your code:

  1. You defined self.radius after you used it in the previous line
  2. pygame.draw.circle expects the x, y coordinates to be integer values however you calculated self.player_pos by dividing display_width by 2 which resulted in a float value. I explicitly converted the value to int and the player (circle) shows up on the screen
Comments