推箱子游戏(控制台操作) 源码

推箱子游戏在控制台上的实现。8 上 ,5下,6右,4左。

将箱子推到 10*10列地图的右上角就算胜利。 X 代表人, 0 代表箱子。


#include<stdio.h>
int arr[12][12] = {0};   // map
void showMap(){          //显示地图
   int i,j;
   for (i = 1;i <= 10;i++){
   	   for (j = 1;j <= 10;j++){
	   		if(arr[i][j] == 1){
			    printf("X");
			}
	   		if(arr[i][j] == 0){
			    printf("0");
			}
	   		if(arr[i][j] == 2){
				printf("*");
			}
	   }
	   printf("\n");
   }
}

int main(){
   int x,y;           // position of man    man = 1; baox = 2
   srand(time(0));
   arr[rand() % 8 + 2][rand() % 8 +2] = 2;   // 产生人和盒子的随机位置,使人和盒子都不会在边角。
   x = rand() % 8 + 2;
   y = rand() % 8 + 2;
   while(arr[x][y] == 2){
       x = rand() % 8 + 2;
       y = rand() % 8 + 2;
   }
   arr[x][y] = 1;
   showMap();
   int stepx,stepy;
   while(arr[1][10] != 2){
        printf("up = 8; down = 5; left = 4; right = 6\n");
        printf("please input the number to choose your next direction.\n");
        int dir;           //direction 
        scanf("%d",&dir);
   		switch(dir){          // diffirent of direction
	   		case 4:
		  		stepx =  0;
		  		stepy = -1;
		  		break;
	   		case 8:
				stepx = -1;
		  		stepy =  0;
		  		break;
	   		case 5:
		  		stepx =  1;
		  		stepy =  0;
		  		break;
	   		case 6:	
		  		stepx =  0;
		  		stepy =  1;
		  		break;
  		 }
   		if(!(arr[x + stepx ][y + stepy]) && x + stepx >= 1 && x + stepx <= 10 && y + stepy >= 1 && y + stepy <= 10){            // next step is empty;
        	arr[x][y] = 0;
			x = x + stepx;
			y = y + stepy;
			arr[x][y] = 1;
   		}
   		if(arr[x + stepx][y + stepy] == 2){   // next step is the position of box;
			int tmpx = x + 2 * stepx;
	    	int tmpy = y + 2 * stepy;
			if(tmpx <=10 && tmpx >= 1 && tmpy >= 1 && tmpx <= 10){  // not beyond the board
				arr[tmpx][tmpy] = 2;
		    	arr[x + stepx][y + stepy] = 1;
		    	arr[x][y] = 0;
		    	x = x + stepx;
		    	y = y + stepy;
			}
		}
		showMap();
    }
   if(arr[1][10] == 2){
	    printf("YOU WIN\n");
   }
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值