亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 1638 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號