重复导入模块-Python/Pygame [英] Repeating Import Module - Python / Pygame

查看:212
本文介绍了重复导入模块-Python/Pygame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在Pygame中开发一款简单的游戏,目前我处于为每个级别的事件(例如死亡)增加结果的阶段.目前,我已设置为在按下回车键时导入相同的模块,如果发生死亡,则级别被重新启动".该代码可在第一次重新启动"时正常运行,但是如果我再次尝试,则第二次不会导入相同的级别.

Ive been working on a simple game in Pygame and I am currently at the stage of adding outcomes to events in each level (eg. Death). Currently I have it set to import the same module when enter is pressed, if a death occurs so the level is 'restarted'. The code functions properly for the first 'restart' however if I play through again it does not import the same level for a second time.

这里是我到目前为止的代码:

Heres the code I have so far:

    elif event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN and health == 0:
        import PracticeLevel

我对python还是很陌生,所以如果出现任何错误,我深表歉意,不胜感激:)

I am quite new to python so I apologise if any mistakes are present, any help is appreciated :)

推荐答案

这是一种非常奇怪的方法,但是您的问题是python在导入方面很聪明"(不会两次导入相同的模块) .导入更多是为了从模块中检索函数和类,并且不应真正像执行操作那样仅用于执行python文件.进行此类操作的一般方法是创建一个run_level(filename)函数,该函数将加载级别数据并运行它,但是,如果您不想更改当前格式,则应仅使用execfile("PracticeLevel.py")而不是import声明.

This is a very odd way to do this, but your problem is that python is 'smart' about importing (it won't import the same module twice). Importing is more for retrieving functions and classes from the module, and shouldn't really be used to just execute a python file like you are doing. The general way of doing something like this would be to create a run_level(filename) function which would load the level data and run it, however if you don't want to change your current format, you should just use execfile("PracticeLevel.py") instead of the import statement.

如果您使用的是Python 3(其中execfile不是内置函数),则可以编写

If you are using Python 3 (in which execfile is not a builtin function), you can write

 exec(open(filename).read())

这篇关于重复导入模块-Python/Pygame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆