01刷屏
2025-10-05 18:29:09
发布于:福建
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <ctime>
#include <vector>
// 设置控制台文本颜色
void setColor(int color) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
}
// 设置光标位置
void setCursorPosition(int x, int y) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(hConsole, coord);
}
// 隐藏光标
void hideCursor() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(hConsole, &cursorInfo);
cursorInfo.bVisible = FALSE;
SetConsoleCursorInfo(hConsole, &cursorInfo);
}
// 获取控制台尺寸
void getConsoleSize(int& width, int& height) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsole, &csbi);
width = csbi.srWindow.Right - csbi.srWindow.Left + 1;
height = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
}
int main() {
// 初始化随机数生成器
srand(time(NULL));
// 隐藏光标
hideCursor();
// 设置绿色文本
setColor(FOREGROUND_GREEN);
// 获取初始控制台尺寸
int width, height;
getConsoleSize(width, height);
// 清除屏幕
system("cls");
// 主循环
while (true) {
// 检查是否按下了'q'键(非阻塞方式)
if (GetAsyncKeyState('Q') & 0x8000) {
break;
}
// 检查窗口大小是否改变
int newWidth, newHeight;
getConsoleSize(newWidth, newHeight);
if (newWidth != width || newHeight != height) {
width = newWidth;
height = newHeight;
system("cls"); // 窗口大小改变时清屏
}
// 随机位置输出0或1
int x = rand() % width;
int y = rand() % height;
char ch = (rand() % 2 == 0) ? '0' : '1';
// 移动到随机位置并输出字符
setCursorPosition(x, y);
std::cout << ch;
// 短暂延迟控制速度
}
// 恢复控制台默认设置
setColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
system("cls");
return 0;
}
这里空空如也









有帮助,赞一个