根据老师要求完成的案例作业,迷宫为自行设计的
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h> //getch()函数要用<conio.h> 头文件
int main ()
{
printf("w,s,a,d分别代表上,下,左,右\n请各位勇士攻克迷宫吧!\n");
char a[50][50] = {"###########", //a0
"#o # ", //a1
"# ## ## #",
"# # #",
"# ### # #",
"# # #",
"###########"};
int i,x = 1,y = 1,p = 1,q = 10; //x y表示小球初始位置 p q表示出口位置
for (i = 0;i <= 6; i++)
puts(a[i]);
char input;
while(x != p || y != q) //Q:why不是且? A:类似与交集的补集原理!
{
input = getch();
if(input == 's')
{
if (a[x+1][y] != '#') //如果往下走一格不是#的话
{
a[x][y] = ' '; //把原本这格的光标清除
x++;
a[x][y] = 'o';
}
}
if(input == 'w')
{
if (a[x-1][y] != '#')
{
a[x][y] = ' ';
x--;
a[x][y] = 'o';
}
}
if(input == 'a')
{
if (a[x][y-1] != '#')
{
a[x][y] = ' ';
y--;
a[x][y] = 'o';
}
}
if(input == 'd')
{
if (a[x][y+1] != '#')
{
a[x][y] = ' ';
y++;
a[x][y] = 'o';
}
}
system ("cls"); //注意每次按完一次键后要清屏重刷新
for (i = 0;i <= 6;i++)
puts(a[i]); //重新输出走完后的迷宫
}
system("cls");
printf("You have winned the game\n");
Sleep(700);
system("pause");
return 0;
}