好吧,我很无聊,所以想在控制台窗口中制作动画。
现在,当我设置第一个位时,我注意到它非常慢,整个屏幕填充字符大约需要 333 毫秒。
我想知道是否有办法至少获得〜20 fps?
这是我的代码:
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <iostream>
#include <array>
#define WIDTH (100)
#define HEIGHT (35)
bool SetWindow(int Width, int Height) {
_COORD coord;
coord.X = Width; coord.Y = Height;
_SMALL_RECT Rect;
Rect.Left = 0; Rect.Top = 0;
Rect.Bottom = Height - 1; Rect.Right = Width - 1;
HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);
if (Handle == NULL)return FALSE;
SetConsoleScreenBufferSize(Handle, coord);
if(!SetConsoleWindowInfo(Handle, TRUE, &Rect)) return FALSE;
return TRUE;
}
std::array<std::array<unsigned char, WIDTH+1>, HEIGHT> Screen;//WIDTH+1 = prevent cout from undefined behaviour
void Putchars(unsigned char x){
for(int row = 0; row < HEIGHT; ++row){
std::fill(Screen[row].begin(),Screen[row].end(),x);
Screen[row].at(WIDTH) = 0;//here = prevent cout from undefined behaviour
}
}
void ShowFrame(DWORD delay = 0,bool fPutchars = false, unsigned char x = 0){
if(fPutchars)Putchars(x);
if(delay)Sleep(delay);
system("CLS");
for(int row = 0; row < HEIGHT; ++row)
std::cout << Screen[row].data() << std::flush;
}
int _tmain(int argc, _TCHAR* argv[]){//sould execute @~63 fps, yet it executes @~3-4 fps
if(SetWindow(100,HEIGHT)){
for(unsigned char i = 219; i != 0; --i)
ShowFrame(16,true, i);
}
return 0;
}
编辑:在阅读了无数答案、提示和评论后,我终于解决了,谢谢你们,这是我最终的“基础”代码:
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <iostream>
#include <array>
#define WIDTH (100)
#define HEIGHT (34)
HANDLE current;
HANDLE buffer;
bool SetWindow(int Width, int Height) {
_COORD coord;
coord.X = Width; coord.Y = Height;
_SMALL_RECT Rect;
Rect.Left = 0; Rect.Top = 0;
Rect.Bottom = Height - 1; Rect.Right = Width - 1;
HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);
if (Handle == NULL)return FALSE;
SetConsoleScreenBufferSize(Handle, coord);
if(!SetConsoleWindowInfo(Handle, TRUE, &Rect)) return FALSE;
return TRUE;
}
std::array<std::array<CHAR, WIDTH+1>, HEIGHT> Screen;//WIDTH+1 = prevent cout from undefined behaviour
void Putchars(CHAR x){
for(int row = 0; row < HEIGHT; ++row){
std::fill(Screen[row].begin(),Screen[row].end(),x);
Screen[row].at(WIDTH) = 0;//here = prevent cout from undefined behaviour
}
}
void ShowFrame(DWORD delay = 0, bool fPutchars = false, CHAR x = 0){
if(fPutchars)Putchars(x);
if(delay)Sleep(delay);
//system("CLS");
_COORD coord;
coord.X = 0;
for(int row = 0; row < HEIGHT; ++row)
{
coord.Y = row;
FillConsoleOutputCharacterA(buffer,Screen[row].data()[0],100,coord,NULL);
}
}
int _tmain(int argc, _TCHAR* argv[]){//sould execute @~63 fps, yet it executes @~3-4 fps
SetWindow(WIDTH, HEIGHT);
current = GetStdHandle (STD_OUTPUT_HANDLE);
buffer = CreateConsoleScreenBuffer (
GENERIC_WRITE,
0,
NULL,
CONSOLE_TEXTMODE_BUFFER,
NULL
);
SetConsoleActiveScreenBuffer (buffer);
if(SetWindow(WIDTH,HEIGHT)){
for(CHAR i = 219; i != 0; --i)
ShowFrame(250,true, i);
}
CloseHandle (buffer); //clean up
return 0;
}
它似乎工作得非常快:)