看看我写的,vc6编译通过,在文本模式下正常显示,本人觉得有很多地方写的不好,请大虾们指教
定义三个函数:void delayTime(int k); void gotoxy(int x, int y); void drunker();
为了方便判断是否进入死胡同,我用了“在可移动区四面加一堵墙”的方法。
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <windows.h>
#define WIDTH 80 //dos窗口的宽度
#define HEIGHT 25 //标准dos窗口的高度
using namespace std;
//控制光标
void gotoxy(int x, int y)
{ COORD c;
c.X = x - 1;
c.Y = y - 1;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
//精确度为秒的定时器
void delayTime(int k)
{
int i = 0, j = 0;
time_t start, end;
start = time(0);
while(k > i)
{
end = time(0);
i = int(end - start);
if(i == j)
continue;
else
j = i;
}
}
void drunker()
{
int a[WIDTH+2][HEIGHT+2];
int x , y, dx = 0, dy = 0, ch = '*', t = 0;
int i = 0, j = 0;
bool isImpasse = 0;
for (i = 0; i < WIDTH + 2; i++)
for (j = 0; j < HEIGHT + 2; j++)
a[i][j] = 0;
//生成一堵墙
for ( i = 0; i < WIDTH + 2; i ++)
a[i][0] = a[i][HEIGHT + 1] = 1;
for (i = 0; i < HEIGHT + 2; i ++)
a[0][i] = a[WIDTH + 1][i] = 1;
//随机初始点
srand(time(0));
x = rand() % WIDTH + 1;
y = rand() % HEIGHT + 1;
gotoxy(1, 26);
cout << " 初始点是:(" << x << "," << y << ") " << endl;
gotoxy(x, y);
putchar(ch);
a[x][y] = 1;
while( !isImpasse) //还没有到死胡同时循环
{
switch(t = rand() % 4)
{
case 0:
dx = 0; dy = -1; ch = 24;
break;
case 1:
dx = 0; dy = 1; ch = 25;
break;
case 2:
dx = -1; dy = 0; ch = 27;
break;
case 3:
dx = 1; dy = 0; ch = 26;
break;
}
if( a[x+dx][y+dy] == 0) // 如果下个点没走过
{
gotoxy(x + dx, y + dy);
a[x+dx][y+dy] = 1;
putchar(ch);
x += dx;
y += dy;
gotoxy(x, y);
delayTime(1); //定时1秒
}
//判断是否是死胡同
if((a[x+1][y]== 1) && (a[x-1][y] == 1) && (a[x][y-1] == 1) && (a[x][y+1] == 1))
isImpasse = true;
}
gotoxy(1, 27);
cout << endl << " 在点:(" << x << "," << y << ") 进入了死胡同! " << endl;
gotoxy(x, y);
getchar();
}
//主函数
int main()
{
drunker();
return 0;
}
[此贴子已经被作者于2007-11-21 9:16:41编辑过]