我正在开发一些简单的基于 2D 数组的游戏。它们的主要特征是盒子里有一个弹跳的“球”(简单来说就是一个 char ball_char='O')。结构体 BALL 有 2 个变量:X 和 Y,它们表示其数组位置。每个时钟( sleep (毫秒))过程都会更改其 X 和 Y(例如 +1),清除控制台窗口,然后再次绘制所有数组来模拟球的运动。
这是部分代码:
#include <iostream.h> //cout
#include <windows.h> //Sleep(ms) and clearscreen()
#define H 51
#define W 51
char box[H][W];
struct ball
{
char ball_char;
int x, y, movx, movy;
}b;
void clearscreen() //MY TEACHER SUGGESTED ME THIS CODE TO "CLEAR" THE SCREEN
{
HANDLE hOut;
COORD Position;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut, Position);
}
void draw() //here comes the bad "graphic engine" lol
{
int i;
clearscreen();
for(i=0;i<H;i++)
{
for(int j=0;j<W;j++)
cout<<box[i][j];
cout<<"|"<<endl; //DRAWING EDGES <---this is on the right side
}
for(i=0;i<W;i++)
cout<<"-"; //this is on the bottom side
}
正如你所看到的,盒子越大,再次绘制整个数组所需的时间就越长。正如我所评论的,我向我的教授提到了这个项目,他建议我使用代码来清除控制台。但这不是真正的清理,但据我所知,它只是将光标放在开头。
主要代码:
main()
{
b.ball_char='O';
b.x=10;
b.y=0;
b.movx=1;
b.movy=1;
do //this is what I call "the clock"
{
move() //my procedure to simulate the ball movements (it simply adds movements force to their coordinates with some controls etc.)
draw();
Sleep(100);
}while(1);
}
所以问题是:你知道有什么更快的方法来清理控制台吗?我已经知道要避免使用 system("cls")。
最佳答案
效果非常好:
#include <windows.h>
void clearscreen()
{
HANDLE hOut;
COORD Position;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut, Position);
}
关于c++ - 有没有更快的方法来清除控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28196983/