首页 > 解决方案 > 不明白这个 TypeError: an integer is required

问题描述

尝试运行时收到 TypeError:

File "/home/XX/PycharmProjects/rogue_like/venv/lib64/python3.7/site-packages/tcod/libtcodpy.py", line 1236, in console_put_char
    lib.TCOD_console_put_char(_console(con), x, y, _int(c), flag)
TypeError: an integer is required
Class Object:

    def __init__(self, x, y, char, color):
        self.x = x
        self.y = y
        self.char = char
        self.color = color

    def draw(self):
        libtcod.console_set_default_foreground(con, self.color)
        libtcod.console_put_char(con, self.x, self.y, self.char, libtcod.BKGND_NONE)

# later...

SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50
player = Object(SCREEN_WIDTH/2, SCREEN_HEIGHT/2, '@', libtcod.yellow)

遵循一个roguelike教程并遇到了这个。尝试通过将“@”更改为数字和其他内容来传递整数。已尝试将其交给int(self.char)其他选项,但似乎碰壁了。

任何帮助都会很棒!尝试包含相关代码,如果还有其他内容,请告诉我。

编辑:

"""
...
   Args:
    con (Console): Any Console instance.
    x (int): Character x position from the left.
    y (int): Character y position from the top.
    c (Union[int, AnyStr]): Character to draw, can be an integer or string.
    flag (int): Blending mode to use, defaults to BKGND_DEFAULT.
"""
lib.TCOD_console_put_char(_console(con), x, y, _int(c), flag)

标签: python

解决方案


在 Python 3 中,将两个整数相除总是会产生一个浮点数,因此80/2并且50/2正在产生浮点数,而不是整数。要使它们成为整数,您可以使用地板除法 ( 80//2) 或强制转换为整数 ( int(80/2))。

我猜您的教程是针对 Python 2 的,因为在 Python 2 中,将两个整数相除总是会产生一个整数。

更多细节


推荐阅读