首页 > 解决方案 > 为什么屏幕缓冲区中出现额外的字母

问题描述

所以我尝试制作一个基本的游戏来测试控制台的运动。我决定使用屏幕缓冲区,但是当我编译并运行 c++ 代码时,字母 a 与播放器一起出现(字符 #) 这是代码:

#include "pch.h"
#include <iostream>
#include <stdio.h>
#include <Windows.h>

int width = 50, height = 20;
int main()
{
    wchar_t *screen = new wchar_t[width * height];
    HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
    SetConsoleActiveScreenBuffer(hConsole);
    DWORD bytesWritten = 0;
    int x = width / 2, y = height / 2;
    while (true) {
        screen[width * height - 1] = '\0';
        for (int i = 0; i < width * height; i++) screen[i] = L' ';
        if (GetAsyncKeyState('W') & 1) y--;
        else if (GetAsyncKeyState('S') & 1) y++;
        if (GetAsyncKeyState('A') & 1) x--;
        else if (GetAsyncKeyState('D') & 1) x++;
        // keep the character inside
        if (x < 0) x = 0;
        else if (x > width-1) x = width-1;
        if (y < 0) y = 0;
        else if (y > height - 1) y = height - 1;
        wsprintf(&screen[width * y + x], L"#");
        WriteConsoleOutputCharacter(hConsole, screen, width * height, { 0,0 }, &bytesWritten);
    }
    return 0;
}

运行它看起来像这样: 在此处输入图像描述

我使用视觉工作室 2017。

为什么会出现字母a?提前致谢!

标签: c++winapiconsole

解决方案


推荐阅读