cwinapiwhitespacewidechar

Encounter a problem that print wide_character in C


Here is my code:

#include "snake.h"

void SetPos(short x, short y)
{
    //获得标准输出设备的句柄
    HANDLE houtput = NULL;
    houtput = GetStdHandle(STD_OUTPUT_HANDLE);

    //定位光标的位置
    COORD pos = { x, y };
    SetConsoleCursorPosition(houtput, pos);
}
  
void CreateMap()
{
    //上
    int i = 0;
    const int WIDTH = 29;
    const int HEIGHT = 27;

    SetPos(0, 0);
    for (i = 0; i < WIDTH; i++)
    {
        wprintf(L"%lc", L'□');
    }
    //下
    SetPos(0, HEIGHT-1);
    for (i = 0; i < WIDTH; i++)
    {
        wprintf(L"%lc", L'□');
    }
    //左
    for (i = 1; i < HEIGHT-1; i++)
    {
        SetPos(0, i);
        wprintf(L"%lc", L'□');
    }
    //右
    for (i = 1; i < HEIGHT-1; i++)
    {
        SetPos((WIDTH-1)*2, i);
        wprintf(L"%lc", L'□');
    }
    getchar();
}

When I tried to print the map, I encountered some problem. I have already included the setlocale(LC_ALL, ""); in the main function. The result is like this: enter image description here How can I print a rectangle successfully? My purpose is create a Snake game. And I want to snake move in the rectangle. But the rectangle is printed wrong. I also tried to debug, but there is no use, I couldn't find why it prints in this way.


Solution

  • The terminal spacing between characters is not the same horizontally as it is vertically, meaning each character fits into a rectangle on the screen and not a square. Given your shape is a square it cannot occupy its whole rectangular space and leaves blank space on the top and bottom.

    In this image you can visually see the height and width of each cell compared the square character.

    To fix your snake game problem you could try add spaces between each of the horizontal squares or try different character combinations like []

    I find the height of the cell is roughly twice its width so two characters usually make a square

    (no spaces)
    □
    □□
    □□□
    
    (with spaces)
    □
    □ □
    □ □ □
    
    (other characters)
    
    []
    [][]
    [][][]