问题描述:
N块石头排成一行,每块石头有各自固定的位置。
两个玩家依次取石头,每个玩家可以取其中任意一块石头,或者相邻的两块石头,石头在游戏过程中不移位。
最后能将石头一次取光的玩家获胜。
C语言实现:
此处简化,将石头数设置为5,用一个长度为5的数组表示石头,当元素值为1的时候,代表有石头。为0时,代表没有石头。
#include<stdio.h>
//判断当前条件下是否胜利
int ifWin(int array[])
{
int sum=0;
for(int i=0;i<5;i++)
sum+=array[i];
if(sum==0)
return 1;
else
return 0;
}
//取石头操作
void getStone(int array[])
{
//要取的石头数(1个或2个)
int num_get;
int position=-1;
int position_2=-1;
printf("how many stones you want get (1 or 2):");
scanf("%d",&num_get);
printf("\n");
if(num_get==1){
printf("the position(1~5):");
scanf("%d",&position);
printf("\n");
if(array[position-1]==1)
//将当前位置的数组元素置为0,表示已经取走石头
array[position-1]=0;
else
printf("please obey the rules!\n");
}else if(num_get==2){
printf("the positions(1~5) must touched:");
scanf("%d,%d",&position,&position_2);
printf("\n");
if((array[position-1]==1)&&(array[position_2-1]==1))
{
array[position-1]=0;
array[position_2-1]=0;
}else{
printf("please obey the rules!\n");
}
}else{
printf("please obey the rules!\n");
}
}
//打印当前游戏状况
void gameSituation(int array[])
{
for(int i=0;i<5;i++)
printf("%d ",array[i]);
printf("\n");
}
int main()
{
int a[5]={1,1,1,1,1};
int flag=-1;
while(1)
{
flag=ifWin(a);
if(flag==1)
break;
gameSituation(a);
getStone(a);
}
printf("You win!\n");
return 0;
}
这个游戏先取者有必胜方法:
先取者只需要取中间的石头即可。
当石头为奇数时,取最中间的那颗石头。
当石头为偶数时,取最中间的两颗石头。