yappy twan
yappy twan

Reputation: 1211

Type error in python/pygame - float instead of integer

I have a small program in python and pygame but when I run my it I get this error:

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "main.py", line 31, in <module>
    main()
  File "main.py", line 25, in main
    board.draw(WIN)
  File "/home/ether/Desktop/checkersai/checker/board.py", line 42, in draw
    piece.draw(win)
  File "/home/ether/Desktop/checkersai/checker/piece.py", line 32, in draw
    pygame.draw.circle(win, GREY, (self.x, self.y), radius + self.OUTLINE)
TypeError: integer argument expected, got float

and this is the function where the error is:

def draw(self, win):
        radius = SQUARE_SIZE//2 - self.PADDING
        pygame.draw.circle(win, GREY, (self.x, self.y), radius + self.OUTLINE)
        pygame.draw.circle(win, self.color, (self.x, self.y), radius)

and these are the variables I use:

WIDTH, HEIGHT = 800,800
ROWS, COLS = 8,8
SQUARE_SIZE = WIDTH/COLS

So I don't see how I get this error nor do I have any idea where I need to start looking for the error.

Here is the full code to my project https://pastebin.ubuntu.com/p/DHcRNT6948/

Upvotes: 0

Views: 278

Answers (1)

Random Davis
Random Davis

Reputation: 6857

Even though you used the integer division operator (//) when setting radius = SQUARE_SIZE//2 - self.PADDING, it's returning a float; that operator would normally return an int, but it still returns a float if you're dividing a float. In your case, you're dividing a float, SQUARE_SIZE. It's a float because SQUARE_SIZE = WIDTH/COLS uses the regular division operator (/), which always returns a float.

To fix your issue, do something like this:

SQUARE_SIZE = WIDTH//COLS  # SQUARE_SIZE is an int now

However, a more mathematically accurate approach would be to work with floats, and round & convert to int only at the last moment:

radius = int(round((WIDTH/COLS) / 2.0 - self.PADDING))

Upvotes: 5

Related Questions