推箱子游戏编写思路总结
1.显示游戏地图
2.显示小人移动的方向
3.移动小人
第一、简单的界面输出时可以用指针数组,指针数组map中含十个指针map[0]、map[1]...map[9],分别是这是个字符串的起始地址
char *map[row] = {
"##########",
"# ox ####",
"### ##",
"## ###",
"### ######",
"# #",
"# #",
"#### #####",
"#### ",
"##########"};
但最后改变位置时不太方便,还是使用c以二维数组输出比较简洁。
第二、用c写代码需要保证定义变量在函数最前面,标准化看起来可以一目了然否则会出现错误,error c2143。
最终代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define row 10
#define list 10
//const定义的是不能直接被修改的变量,此变量具有常量属性,但在C语言程序中以变量对待,所以数组不能用const定义大小
char map[row][list]=
{
"##########",
"# ####",
"###x ##",
"## o ###",
"### ######",
"# #",
"# #",
"#### ####",
"#### ",
"##########"
};
int perRow=3;
int perList=4;
int boxRow=2;
int boxList=3;
void showMap()
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<list;j++)
printf("%c",map[i][j]);
printf("\n");
}
}
char enterDirection()
{
char dir;
printf("请输入小人的前进方向:w.上 s.下 a.左 d.右 q.退出\n");
//scanf("%c",&dir);
//dir=getche();//带回显
dir=getch();//省回车,自动输入电脑,不带回显
fflush(stdin);
return dir;
}
void moveUp()
{
if(map[perRow-1][perList]==' ')
{
map[perRow-1][perList]='o';
map[perRow][perList]=' ';
perRow-=1;
}
else if(map[perRow-1][perList]=='x')
{
if(map[boxRow-1][boxList]==' ')
{
map[boxRow-1][boxList]='x';
map[perRow-1][perList]='o';
map[perRow][perList]=' ';
perRow-=1;
boxRow-=1;
}
}
}
void moveDown()
{
if(map[perRow+1][perList]==' ')
{
map[perRow+1][perList]='o';
map[perRow][perList]=' ';
perRow+=1;
}
else if(map[perRow+1][perList]=='x')
{
if(map[boxRow+1][boxList]==' ')
{
map[boxRow+1][boxList]='x';
map[perRow+1][perList]='o';
map[perRow][perList]=' ';
perRow+=1;
boxRow+=1;
}
}
}
void moveLeft()
{
if(map[perRow][perList-1]==' ')
{
map[perRow][perList-1]='o';
map[perRow][perList]=' ';
perList-=1;
}
else if(map[perRow][perList-1]=='x')
{
if(map[boxRow][boxList-1]==' ')
{
map[boxRow][-1]='x';
map[perRow][perList-1]='o';
map[perRow][perList]=' ';
perList-=1;
boxList-=1;
}
}
}
void moveRight()
{
if(map[perRow][perList+1]==' ')
{
map[perRow][perList+1]='o';
map[perRow][perList]=' ';
perList+=1;
}
else if(map[perRow][perList+1]=='x')
{
if(map[boxRow][boxList+1]==' ')
{
map[boxRow][boxList+1]='x';
map[perRow][perList+1]='o';
map[perRow][perList]=' ';
perList+=1;
boxList+=1;
}
}
}
void stop()
{
printf("智商捉急呀。。。\n");
printf("Game Over!\n");
}
int main()
{
char dir;
while(1)
{
system("CLS");
showMap();
dir=enterDirection();
switch(dir)
{
case 'w':
case 'W':moveUp();
break;
case 's':
case 'S':moveDown();
break;
case 'a':
case 'A':moveLeft();
break;
case 'd':
case 'D':moveRight();
break;
case 'q':
case 'Q':stop();
return 0;
}
if(map[8][9]=='x')
{
printf("恭喜过关!\n");
return 0;
}
}
}