使用windows api库绕过windows终端

问题描述 投票:0回答:1

条件:使用windows api库对带“*”符号的windows操作系统终端进行可视化旁路。 该程序是在 Clion IDE 中用 C 编程语言编写的。控制台尺寸取标准80*25(最后一行不能填)。游览从控制台的常规中心开始,逐渐顺时针螺旋,在左上角结束。

解决方法如下:

节目正文:

#include <stdio.h>
#include <windows.h>

// Function to print '*' at a specific position in the console
void Paint(HANDLE hout, int i, int j) {
    COORD pos; // Structure to store coordinates
    pos.X = j; // Set X coordinate
    pos.Y = i; // Set Y coordinate
    SetConsoleCursorPosition(hout, pos); // Set cursor position in the console
    printf("*"); // Print '*'
    Sleep(50); // Delay for a better visual effect
}

int main() {
    int centerX, centerY;

    HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE); // Get handle to standard output
    CONSOLE_SCREEN_BUFFER_INFO csbi; // Structure to store information about the console screen buffer
    GetConsoleScreenBufferInfo(hout, &csbi); // Get information about the console screen buffer

    centerX = csbi.srWindow.Right / 2; // Find the center of the console horizontally
    centerY = csbi.srWindow.Bottom / 2; // Find the center of the console vertically

    int width = csbi.srWindow.Right - csbi.srWindow.Left; // Determine the width of the console
    int height = csbi.srWindow.Bottom - csbi.srWindow.Top; // Determine the height of the console

    // Loop to draw a pattern in the console
    for (int size = 1; size <= width && size <= height; size += 2) {
        int x = centerX - size / 2; // Determine the starting X coordinate for the pattern
        int y = centerY - size / 2; // Determine the starting Y coordinate for the pattern

        // Draw the top line of the pattern
        for (int i = 0; i < size; i++) {
            Paint(hout, y, x + i);
        }

        // Draw the right line of the pattern
        for (int i = 1; i < size; i++) {
            Paint(hout, y + i, x + size - 1);
        }

        // Draw the bottom line of the pattern
        for (int i = size - 2; i >= 0; i--) {
            Paint(hout, y + size - 1, x + i);
        }

        // Draw the left line of the pattern
        for (int i = size - 2; i > 0; i--) {
            Paint(hout, y + i, x);
        }
    }

    getchar(); // Wait for user input before closing the program
    return 0; // End the program
}

程序不会在控制台的整个大小上执行,并且不完全按照方案执行。

c algorithm winapi optimization data-structures
1个回答
0
投票

根据你的描述,当你在控制台循环绘制图案时,应该先画右边。并在最后画上顶线。

    // Draw the right line of the pattern
    for (int i = 1; i < size; i++) {
        Paint(hout, y  + i, x+ size - 1);
    }

   
    // Draw the bottom line of the pattern
    for (int i = size - 2; i >= 0; i--) {
        Paint(hout, y  + size - 1, x + i);
    }

    // Draw the left line of the pattern
    for (int i = size - 2; i > 0; i--) {
        Paint(hout, y  + i, x );
    }

    // Draw the top line of the pattern
    for (int i = 0; i < size; i++) {
        Paint(hout, y, x  + i);
    }
© www.soinside.com 2019 - 2024. All rights reserved.