为了账号安全,请及时绑定邮箱和手机立即绑定

在 Python 中创建ConsoleScreenBuffer

在 Python 中创建ConsoleScreenBuffer

江户川乱折腾 2023-08-22 14:53:35
我用 Python 编写了一个在控制台上运行的 3D 游戏。为了阻止它闪烁,我必须将要显示的内容写入ConsoleScreenBuffer. 文档是这样的。我知道我必须使用:import win32consolebuffer = win32console.CreateConsoleScreenBuffer()但是 的参数是什么CreateConsoleScreenBuffer()?在文档中它说:HANDLE WINAPI CreateConsoleScreenBuffer(  _In_             DWORD                dwDesiredAccess,  _In_             DWORD                dwShareMode,  _In_opt_   const SECURITY_ATTRIBUTES *lpSecurityAttributes,  _In_             DWORD                dwFlags,  _Reserved_       LPVOID               lpScreenBufferData);那是在 C 中。help(win32console.CreateConsoleScreenBuffer)没有提供有用的信息。前两个参数是整数,第二个参数是“PySECURITY_ATTRIBUTES”对象,第三个参数也是整数。(我认为?)CreateConsoleScreenBuffer(DesiredAccess, ShareMode, SecurityAttributes, Flags)DesiredAccess=GENERIC_READ and GENERIC_WRITE : intGENERIC_READ and/or GENERIC_WRITEShareMode=FILE_SHARE_READ and FILE_SHARE_WRITE : intFILE_SHARE_READ and/or FILE_SHARE_WRITESecurityAttributes=None : PySECURITY_ATTRIBUTESSpecifies security descriptor and inheritance for handleFlags=CONSOLE_TEXTMODE_BUFFER : intCONSOLE_TEXTMODE_BUFFER is currently only valid flag我没有在网上找到任何实施此方法的示例。如果您知道任何其他使控制台绘制速度更快的方法,请告诉我们。这是我的(不是喷气机)游戏。它会闪烁,因为它绘制得不够快。我遵循的教程是用 c++ 编写的,并使用 CreateConsoleScreenBuffer 来消除闪烁,因为使用它,所有内容都是一次性绘制的,而不是连续绘制的。
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

有两种方法可以做到这一点。一种是使用win32console and win32con,另一种是使用 ANSI 转义序列。实际上,您要做的就是将光标移动到控制台上的 0,0 处/进行打印。这是方法一:

import win32console, win32con, time

myConsole = win32console.CreateConsoleScreenBuffer(DesiredAccess = win32con.GENERIC_READ | win32con.GENERIC_WRITE, ShareMode=0, SecurityAttributes=None, Flags=1) # create screen buffer

myConsole.SetConsoleActiveScreenBuffer() # set this buffer to be active

myConsole.WriteConsole("Hello World!") # Effectively the print func.

myConsole.WriteConsoleOutputCharacter(Characters="Hello World!\0", WriteCoord=win32console.PyCOORDType(5,5)) # Print at coordinates


time.sleep(3) # this must be called or you won't see results. This is because after running the code (because there is no loop) the cmd.exe takes the console over.

这应该可以在您的控制台 FPS 中正常工作(使用 WriteConsoleOutputCharacter)。只需将命令放在 javid 放置的位置即可,这样就可以正常工作。第二种方法是使用 colorama/ANSI 序列将光标返回到起始位置。这种方法可以概括为:os.system("echo \033[0;0H")。您不能使用该print函数使用转义序列,它们不受支持(使用colorama除外)。这是一个例子:


from colorama import init

from os import system

init() # I bother with this because I use colors too. Echo prints slower than print, so don't use echo if you can avoid it.


# ... game

# ... generate string to print

print(frame) # or just use you method of printing each line.

system("echo \033[0;0H") # return cursor to home position, ready for next frame.


查看完整回答
反对 回复 2023-08-22
  • 1 回答
  • 0 关注
  • 1535 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信