上次我发了一个移动小游戏,但我本人都觉得无聊,所以今天发一个推箱子吧(不知道用什么语气词)
首先,请看一下我的上一篇游戏文章,学一下基础
移动小游戏
看完了吗,好,开始我们今天的实战吧!
首先,我们要做好地图和头文件
#include <iostream>
#include <cstdio>
#include <conio.h>
#include <windows.h>
using namespace std;
char a[100][100]={
"################",
"#* #",
"# & ! #",
"# & ! #",
"# ! & #",
"################",
};
int main(){
for(int i=0;i<=15;i++)
puts(a[i]);
return 0;
}
这个我们以*为人,&为箱子,!为要把箱子推到的地方
接着,开始移动吧!
但是,我们不仅要让人走,箱子也要走,所以我们要再添几个判断:
如果前面有一个箱子,就推动它;
如果前面有两个及以上的箱子,就不动;
如果把箱子推到了要推到的地方,就清空箱子
我们可以在按下按键的同时判断
OK,现在我们只要先搞一个while循环,再用ch去_getch(),再判断是什么键和移动
这里建议用switch:
#include <iostream>
#include <cstdio>
#include <conio.h>
#include <windows.h>
using namespace std;
char ch;
int x=1,y=1;
char a[100][100]={
"################",
"#* #",
"# & ! #",
"# & ! #",
"# ! & #",
"################",
};
int main(){
system("title 推箱子小游戏");
for(int i=0;i<=10;i++)
puts(a[i]);
while(1){
ch=_getch();
switch(ch){
case 'w':
if(a[x-1][y]!='#'){
a[x][y]=' ';
x--;
a[x][y]='*';
}
break;
case 's':
if(a[x+1][y]!='#'){
a[x][y]=' ';
x++;
a[x][y]='*';
}
break;
case 'a':
if(a[x][y-1]!='#'){
a[x][y]=' ';
y--;
a[x][y]='*';
}
break;
case 'd':
if(a[x][y+1]!='#'){
a[x][y]=' ';
y++;
a[x][y]='*';
}
break;
}
system("cls");
for(int i=0;i<=10;i++)
puts(a[i]);
}
return 0;
}
调试一下,让小人再上面走走,哎呀,走遍整个地图后,小人怎么把东西都"吃掉"了啊,这可不行,因为我们少了点判断:
在每个按键的中间加一条判断,OK,先判断是不是箱子:
case 'w':
if(a[x-1][y]==' '){
a[x][y]=' ';
x--;
a[x][y]='*';
}
else if(a[x-1][y]=='&'){
//如果是箱子
if(a[x-2][y]==' '){
//如果前面都没有
a[x][y]=' ';//移动
x--;
a[x][y]='*';
a[x-1][y]='&';
}
}
break;
我这里示范了上移键,如果人前面是空的,那就走,是箱子的话,就再判断箱子前面是不是空的如果是就移动
好了,那还等啥,撸起袖子加油干,别的键也写一下吧!
好,先把目前代码放出来:
#include <iostream>
#include <cstdio>
#include <conio.h>
#include <windows.h>
using namespace std;
char ch;
int x=1,y=1;
char a[100][100]={
"################",
"#* #",
"# & ! #",
"# & ! #"