我的项目构造

我的项目的构造如下,以目录模式的模块包来组织代码,同时反对以目录或包来执行,两种形式具备对立入口。

\ptetris|---- .editorconfig|---- .gitignore|---- .vscode|    |---- launch.json|    |---- settings.json|---- LICENSE.rst|---- README.md|---- tetris|    |---- app.py|    |---- block.py|    |---- config.py|    |---- game.py|    |---- tetris.py|    |---- __init__.py|    |---- __main__.py

实现细节

咱们的程序位于tetris目录(包)中,能够作为一个文件夹来执行:

python tetris

也能够作为一个包(Package)来执行:

python -m tetris

__init__.py

若要 python 将一个文件夹作为 Package 看待,那么这个文件夹中必须蕴含一个名为 __init__.py 的文件,即便它是空的。
咱们在这个文件中定义main(),作为软件的对立入口。

from tetris.app import start   # 这个tetris目录下的文件都位于tetris包中了def main():    print("Hi I'm Tetris!")    start()                    #实在入口在app.py中

__main__.py

若要 python 运行一个文件夹,这个文件夹中必须蕴含一个名为 __main__.py 的文件
在__main__.py中调用__init__.py中的main(),对立程序入口。

import tetristetris.main()

这时以包形式运行没有问题,但以目录形式运行会出错:

Traceback (most recent call last):  File "C:\Users\zhoutk\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main    return _run_code(code, main_globals, None,  File "C:\Users\zhoutk\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code    exec(code, run_globals)  File "d:\codes\ptetris\tetris\__main__.py", line 7, in <module>    import tetris  File "d:\codes\ptetris\tetris\tetris.py", line 2, in <module>    from tetris.config import *ModuleNotFoundError: No module named 'tetris.config'; 'tetris' is not a package

起因在于,sys.path 的第一个搜寻门路,一个是包,一个是空字符串。对于 python -m tetris 的调用形式来说,因为 __init__.py 被当时载入,此时 python 解释器曾经晓得了这是一个包,
因而以后门路(空字符串)被蕴含在 sys.path 中。而后再调用 __main__.py ,这时 import pkg 这个包就没有问题了。
而对于 python tetris的调用形式来说,python 解释器并不知道本人正在一个 Package 上面工作。默认的,python 解释器将 __main__.py 的以后门路 tetris退出 sys.path 中,而后在这个门路上面寻找 tetris这个模块,因而出错。
在__main__.py结尾退出如下代码,就能解决这个问题:

import os, sysif not __package__:  path = os.path.join(os.path.dirname(__file__), os.pardir)  sys.path.insert(0, path)

vscode的配置

vscode来写python还是很不错的,做两步操作,就能够很好的编写python程序了。

装置插件

只有装置ms-python.python插件就好了,相干的另外几个会主动装置的。

配置launch.json

"configurations": [        {            "name": "Tetris",            "type": "python",            "request": "launch",            "program": "${workspaceFolder}/tetris",            "console": "integratedTerminal"        }    ]

这样就能够用vscode关上ptetris目录,按F5运行程序了。

我的项目地址

https://gitee.com/zhoutk/ptetris或https://github.com/zhoutk/ptetris

运行办法

1. install python3, git2. git clone https://gitee.com/zhoutk/ptetris (or download and unzip source code)3. cd ptetris4. python3 tetrisThis project surpport windows, linux, macOson linux, you must install tkinter first, use this command:  sudo apt install python3-tk

相干我的项目

曾经实现了C++版,我的项目地址:

https://gitee.com/zhoutk/qtetris