[英]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:我在 python 和 pygame 中有一个小程序,但是当我运行它时,出现此错误:
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/这是我的项目的完整代码https://pastebin.ubuntu.com/p/DHcRNT6948/
Even though you used the integer division operator ( //
) when setting radius = SQUARE_SIZE//2 - self.PADDING
, it's returning a float;即使您在设置
radius = SQUARE_SIZE//2 - self.PADDING
时使用了整数除法运算符 ( //
),它radius = SQUARE_SIZE//2 - self.PADDING
返回一个浮点数; that operator would normally return an int, but it still returns a float if you're dividing a float.该运算符通常会返回一个 int,但如果您正在除一个浮点数,它仍然返回一个浮点数。 In your case, you're dividing a float,
SQUARE_SIZE
.在您的情况下,您正在划分浮点数
SQUARE_SIZE
。 It's a float because SQUARE_SIZE = WIDTH/COLS
uses the regular division operator ( /
), which always returns a float.它是一个浮点数,因为
SQUARE_SIZE = WIDTH/COLS
使用常规除法运算符 ( /
),它总是返回一个浮点数。
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:然而,一种更精确的数学方法是使用浮点数,并且只在最后一刻舍入并转换为 int :
radius = int(round((WIDTH/COLS) / 2.0 - self.PADDING))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.