【来自oschina】c++基础编程 拼图小游戏

4*4拼图小游戏 没有随机排序,开局只有一种情况。
#include <iostream>
#include <conio.h>
using namespace std;

int Find(int com,int size,int zeroIndex)
{
	switch (com)
	{
	case 'w': //上移 就是找到零下面的那个数字的位置 也就是序号增加一行 也就是+4
		{
		if ( zeroIndex<size - 4)
		{
			return zeroIndex + 4;
		}
		}
		break;
	case 's': //下移
		{
		if ( zeroIndex>3)
		{
			return zeroIndex - 4;
		}
		}
		break;
	case 'd': //左移 主要是判断空白是否在右边缘
		{
		if ( zeroIndex%4!=0 )
		{
			return zeroIndex - 1;
		}
		}
		break;
	case 'a': //右移
		{
		if (zeroIndex%4!=3)
		{
			return zeroIndex + 1;
		}
		}
		break;
	default:
		break;
	}	
	return -1;
}


//交换数组中zero和next的位置
void SwapIndex(int *ary,int zero, int next)
{
	if (-1 == next)
	{
		return ;
	}
	int t = ary[zero];
	ary[zero] = ary[next];
	ary[next] = t; 
}

void Update(int *ary, int size, int com)
{
	int zeroIndex = 0; //零的序号
	for (int i = 0.; i< size ; i++)
	{
		if (ary[i] == 0)
		{
			zeroIndex = i;
			break;
		}
	}
	
	int nextIndex = Find(com,size,zeroIndex); //获取跟零相邻(根据com不同 取上下左右)的那个数字的序号
	SwapIndex(ary,zeroIndex,nextIndex);

}

void Show(int *ary, int size)
{
	for (int i  = 0 ; i <size; i++)
	{
		if(i % 4 == 0) //假设每行4个数字
		{
			cout<<endl<<endl;
		}
		if (ary[i]!=0)
		{
		cout<<"\t"<<ary[i];
		}
		else
		{
			cout<<"\t";
		}
	}
	cout<<endl<<"请输入方向(wsad):";
}

bool ProcessCommand(int *ary, int size, int com)
{
	system("cls");
	Update(ary,size,com); //更新地图
	Show(ary,size); //显示新的地图
	return true;
}

bool IsWin(int *ary){
	for (int i=0;i<15;i++)
		if (ary[i] != i+1 )
			return false;
	cout << "you are win, press any key to exit." << endl;
	return true;
}
int GetCommand() //假设只返回4个值 代表四个方向
{
	char com = 'w';
	com=getch();//先测试一下
	return com;
}


void Process(int ary[], int size)
{
	for (int i=0;i<16; i++)
	{
		ary[i] = i;
	}ary[14]^=ary[15]^=ary[14]^=ary[15];
	char com = 'w';
	while(ProcessCommand(ary,size,com))
	{
		if (IsWin(ary))return;
		com = GetCommand();
	}

}


int main()
{
	int ary[16]; //数字0 代表空白
	Process(ary,16);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值