Python中的CreateConsoleScreenBuffer

如何解决Python中的CreateConsoleScreenBuffer

我用Python编写了一个3D游戏,可以在控制台中运行。为了防止其闪烁,我必须将要显示的内容写到ConsoleScreenBuffer中。该文档为this。我知道我必须使用:

import win32console
buffer = 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 : int
GENERIC_READ and/or GENERIC_WRITE
ShareMode=FILE_SHARE_READ and FILE_SHARE_WRITE : int
FILE_SHARE_READ and/or FILE_SHARE_WRITE
SecurityAttributes=None : PySECURITY_ATTRIBUTES
Specifies security descriptor and inheritance for handle
Flags=CONSOLE_TEXTMODE_BUFFER : int
CONSOLE_TEXTMODE_BUFFER is currently only valid flag

我没有发现任何在线实施示例。

如果您知道使控制台绘制更快的其他方法,请告诉我们。

这是我的游戏(不是喷气机)。它闪烁,因为绘制得不够快。我遵循的教程是用c ++编写的,并使用CreateConsoleScreenBuffer消除了闪烁,因为使用它,所有内容都立即绘制出来,而不是

import os
import time
import math
import threading


hardMap = [
    ["#","#","#"],["#",".",]


gameMap = "".join(["".join(hardMap[n]) for n in range(len(hardMap))])

notDone = True

rotationSpeed = 0.02

playerX = 5
playerY = 5
playerA = 0

fov = 4
fov = math.pi / fov

depth = 20

fps = 30

screenWidth = 120
screenHeight = 40
os.system(f'mode con: cols={screenWidth} lines={screenHeight}')

screen = [" " for n in range(screenHeight * screenWidth)]
mapWidth = len(hardMap[0])
mapHeight = len(hardMap)



def printScreen(string):
    os.system('cls')
    time.sleep(0.01)
    for x in [string[i:i+screenWidth] for i in range(0,len(string),screenWidth)]:
        print("".join(x))
    
c = 0
while(notDone):
    c += 1
    playerA = playerA + rotationSpeed
    startTime = time.time()
    
    for x in range(screenWidth):
        rayAngle = (playerA - fov / 2) + ((x / screenWidth) * fov)
        distanceToWall = 0
        hitWall = False
        shade = " "
        
        eyeX = math.sin(rayAngle)
        eyeY = math.cos(rayAngle)

        """
        with open("log.txt","a") as f:
            f.write("x"+str(eyeX)+"\n")
            f.write("y"+str(eyeY)+"\n")
            f.write("h"+str(mapHeight)+"\n")
            f.write("w"+str(mapWidth)+"\n")
            f.write("\n")
        """
        
        while not hitWall and distanceToWall < depth:
            distanceToWall = distanceToWall + 0.1
 
            testX = int(playerX + eyeX * distanceToWall)
            testY = int(playerY + eyeY * distanceToWall)

            if testX < 0 or testX >= mapWidth or testY < 0 or testY>= mapHeight:
                hitWall = True
                distanceToWall = depth
                 
            elif gameMap[testY * mapWidth + testX] == "#":    
                    hitWall = True
                
                
        ceiling = int((screenHeight / 2.0) - (screenHeight / distanceToWall))
        floor = screenHeight - ceiling  

        for y in range(screenHeight):

    
            

            
            if y < ceiling:
                screen[y * ceiling + x] = " "
            elif y > ceiling and y <= floor:
                
                if distanceToWall <= depth / 4: shade = u"\u2588"
                elif distanceToWall < depth / 3: shade = u"\u2593"
                elif distanceToWall < depth / 2: shade = u"\u2592"
                elif distanceToWall < depth / 1: shade = u"\u2591"
                else: shade = " "
        
                screen[y * screenWidth + x] = shade
                
            else:

                b = 1.0 - ((y - screenHeight / 2.0) / (screenHeight/2))

                if b < 0.25: shade = "#"
                elif b < 0.5: shade = "X"
                elif b < 0.75: shade = "."
                elif b < 0.9: shade = "-"
                else: shade = " "
                
                screen[y * screenWidth + x] = shade
                
    printScreen(screen)
    """
    with open("log.txt","a") as f:
            f.write(str("\n".join(screen)))
            f.write("\n\n\n\n\n\n\n\n")
    """
    time.sleep(max(1./fps - (time.time() - startTime),0))

解决方法

我假设您正在关注javid / OLC的控制台FPS教程。

简单的答案是:您需要win32conwin32console,下面是一个更好的答案。

有点晚了,但是本页:win32console docs @ Tim GoldenPyConsoleScreenBuffer Object @ Tim Golden对于解决这一问题非常有用。有两种方法可以做到这一点。一种使用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.

我希望这会有所帮助! -天空

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-