gpt4 book ai didi

c++ - 矩阵中字符的随机移动

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:16:13 24 4
gpt4 key购买 nike

我试图创建一个程序来显示一个 10x10 的字符矩阵,并在其中显示一个字符,并且该字符每 600 毫秒随机移动一次。但我的问题是,每次我运行该程序时,都是相同的 Action 。

如果你看一下 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;
}

最佳答案

尝试在 main 的开头调用 srand(time(0))

关于c++ - 矩阵中字符的随机移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12886596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com