python/pygame 中的类型错误 - 浮点数而不是整数

我在 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

这是错误所在的函数:


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)

这些是我使用的变量:


WIDTH, HEIGHT = 800,800

ROWS, COLS = 8,8

SQUARE_SIZE = WIDTH/COLS

所以我不知道如何得到这个错误,也不知道我需要从哪里开始寻找错误。


这是我的项目的完整代码 https://pastebin.ubuntu.com/p/DHcRNT6948/



呼啦一阵风
浏览 76回答 1
1回答

猛跑小猪

即使您//在设置时使用了整数除法运算符()radius = SQUARE_SIZE//2 - self.PADDING,它也会返回一个浮点数;该运算符通常会返回一个 int,但如果您要除以一个 float,它仍然会返回一个 float。在你的例子中,你要除以一个浮点数,SQUARE_SIZE.&nbsp;它是浮点数,因为SQUARE_SIZE = WIDTH/COLS使用常规除法运算符 (&nbsp;/),它始终返回浮点数。要解决您的问题,请执行以下操作:SQUARE_SIZE&nbsp;=&nbsp;WIDTH//COLS&nbsp;&nbsp;#&nbsp;SQUARE_SIZE&nbsp;is&nbsp;an&nbsp;int&nbsp;now然而,数学上更准确的方法是使用浮点数,并仅在最后一刻舍入并转换为 int:radius&nbsp;=&nbsp;int(round((WIDTH/COLS)&nbsp;/&nbsp;2.0&nbsp;-&nbsp;self.PADDING))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python