我有一个if语句,它检查.txt文件的某一行是否==“true”,但它似乎工作不正常。。此处:
configfile=open("FirstGameConfig.txt")
config_lines=configfile.readlines()
speed_of_object=float(config_lines[5])
acceleration_of_object=float(config_lines[7])
show_coordinates=str(config_lines[9]) #####
acceleration_mode=str(config_lines[11])
configfile.close()
这一切都在上面,而show\u coordinates字符串在下面似乎有问题:
font=pygame.font.Font(None, 40)
if acceleration_mode=="true":
speedblit=font.render("Speed:", True, activeblitcolor)
screen.blit(speedblit, [0, 0])
rectyspeedtext=font.render(str(abs(rectyspeed)), True, activeblitcolor)
screen.blit(rectyspeedtext, [100, 0])
if show_coordinates=="true":
rectycoord=font.render(str(recty), True, activeblitcolor)
screen.blit(rectycoord, [360, 570])
rectxcoord=font.render(str(rectx), True, activeblitcolor)
screen.blit(rectxcoord, [217, 570])
coordblit=font.render("Coordinates: x= y=", True, activeblitcolor)
screen.blit(coordblit, [0, 570])
脚本检查加速模式是否打开。如果加速度模式的值为真,则对象的速度将打印在屏幕的左上角。activeblitcolor已经定义,所以这没有问题。 if show\u coordinates语句下的内容将在屏幕左下角打印对象的坐标,假设我拥有的.txt文件中的值为“true”。你知道吗
所以问题是,即使在.txt文件中show\u coordinates设置为true,这个语句也会被跳过。加速模式也在.txt文件中,它工作得很好。如果检查加速度模式是否为真的语句工作得很好,那么show\u coordinates的语句为什么工作得不一样呢?如果我删除If语句,但在脚本中保留它下面的代码,那么坐标确实会打印在屏幕的左下角,就像它们应该显示的那样,如果show\u coordinates==“true”。你知道吗
我当然在.txt文件的正确行上有“true”。如果我加上“print(show\ u coordinates)”,那么“true”就是输出。脚本识别show_coordinates的值为true,但if语句不识别?任何帮助都将不胜感激!我是初学者。你知道吗
readlines
方法将换行保留在行的末尾。我怀疑您的文件结尾没有换行符,而acceleration_mode
是最后一行,这就是为什么该行可以工作的原因。你知道吗为了证实我的怀疑,加上
甚至
你可能会看到
show_coordinates
看起来像'true\n'
。你知道吗要解决这个问题,可以添加对
strip()
的调用来清理字符串。例如:相关问题 更多 >
编程相关推荐