我试图创建一个程序,显示一个 10x10 的字符矩阵,并在其中显示一个字符,并且每 600 毫秒该字符会随机移动。但我的问题是,每次我运行程序时,都是同一个动作。
如果您查看函数 Random_move,我使用了函数 Rand()... 我也尝试使用 srand(time(null)); 以前,但这只会使两个字符 a 和 b 始终朝同一个方向移动。有人可以帮忙吗。
#include <iostream>
#include <windows.h>
#include <time.h>
using namespace std;
class mapa
{
private :
char map[10][10];
char background[10][10];
public :
mapa();
void cpy_btom();
void copy_to_map(int, int, char);
void print();
};
class character
{
private :
int posx;
int posy;
char type;
public :
character(char,int,int);
void send_print(mapa &);
void random_move(mapa &);
void delay(int);
};
int main()
{
character C1('A', 5, 5);
character C2('B', 8, 2);
mapa Mapa;
while(!GetAsyncKeyState(VK_ESCAPE))
{
Mapa.print();
C1.delay(750);
C1.random_move(Mapa);
C2.random_move(Mapa);
}
}
void mapa :: cpy_btom()
{
for(int a = 0;a < 10;a++)
{
for(int b = 0;b<10;b++)
{
map[a][b] = background[a][b];
}
}
}
void mapa :: print()
{
system("cls");
for(int a = 0;a<10;a++)
{
for(int b = 0;b<10;b++)
{
cout << map[a][b];
}
cout << endl;
}
cpy_btom();
}
character :: character(char kind = 'a', int x = 5, int y = 5)
{
type = kind;
posx = x;
posy = y;
}
void character :: send_print(mapa & mapa)
{
mapa.copy_to_map(posx, posy, type);
}
void character :: random_move(mapa & MAP)
{
int a = rand() % 5;
int b = rand() % 50;
if(a == 0) //x --
{
if(b < 45)
{
if(posx > 0)
posx--;
}
else
{
if(posx > 1)
posx = posx - 2;
}
}
else if(a == 1)
{
if(b < 45)
{
if(posx < 10)
posx++;
}
else
{
if(posx < 9)
posx = posx + 2;
}
}
else if(a == 2)
{
if(b < 45)
{
if(posy > 0)
posy--;
}
else
{
if (posy > 1)
posy = posy - 2;
}
}
else if(a == 3)
{
if(b < 45)
{
if(posy < 10)
posy++;
}
else
{
if(posy < 9)
posy = posy + 2;
}
}
send_print(MAP);
}
void character :: delay(int time)
{
int a = clock();
int b = clock() + time;
while(a < b)
{
a = clock();
}
}
mapa :: mapa()
{
for(int a = 0;a < 10;a++)
{
for(int b = 0;b < 10;b++)
{
map[a][b] = ' ';
background[a][b] = ' ';
}
}
}
void mapa :: copy_to_map(int x, int y, char kind)
{
map[x][y] = kind;
}