python - 不明白这个 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 3 中,将两个整数相除总是会产生一个浮点数,因此80/2
并且50/2
正在产生浮点数,而不是整数。要使它们成为整数,您可以使用地板除法 ( 80//2
) 或强制转换为整数 ( int(80/2)
)。
我猜您的教程是针对 Python 2 的,因为在 Python 2 中,将两个整数相除总是会产生一个整数。
更多细节
推荐阅读
- python - 如何在到达 mainloop() 之前更新 tkinter 窗口
- python - 如何正确处理多个运行时错误?
- python - 如何实现适用于python中谐波振荡器的速度Verlet积分器?
- javascript - 如何使用 react-navigation v5 设置初始状态以将屏幕包含为历史记录?
- c# - 如何将作用域 DbContext 添加到使用 EntityFrameworkCore 和 SSH 隧道进入 MySQL 的 ASP NET Core API 控制器?
- python - 无论它们是作为位置参数还是关键字参数传递,都可以不可知地提取 unittest.mock 调用参数
- python - 变量名内的变量字符串
- python-3.x - 从 2 点和一个角度得到 tird 的位置
- javascript - 如何将 react.js 文件的 HTML 部分用于另一个 react.js 文件
- reactjs - 是否有任何 eslint 规则可以防止“对象作为 React 子项无效”