📄 nimgame.cpp
字号:
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
//double random(double a,double b);
int random(int a,int b);
int is_two_power(int n);
void easymode();
void hardmode();
class game
{
private:
int stones;
public:
game()
{
stones = random(10,100);
}
void easy()
{
if ( stones!=1 )
{
int a = random(1,stones/2);
cout<<"电脑取了"<<a<<"块石子"<<endl;
stones-=a;
}
else
{
cout<<"电脑取了"<<1<<"块石子"<<endl;
stones-=1;
}
}
void hard()
{
if ( stones==1 )
{
cout<<"电脑取了"<<1<<"块石子"<<endl;
stones-=1;
}
else if ( is_two_power(stones+1) )
{
int a = random(1,stones/2);
cout<<"电脑取了"<<a<<"块石子"<<endl;
stones-=a;
}
else
{
for(int i=1; i<=stones/2; i++)
{
if ( is_two_power(stones-i+1) )
{
cout<<"电脑取了"<<i<<"块石子"<<endl;
stones-=i;
break;
} //end of if
} //end for
} //end of else
}
void man()
{
int a;
cout<<"轮到你取石子了,你要取多少块? ";
if (stones == 1)
{
cout<<"你只能取1块石子了"<<endl;
cout<<"你取了1块石子"<<endl;
stones-=1;
}
else
{
while(1)
{
cin>>a;
if (a >= 1 && a <= stones/2)
{
cout<<"你取了"<<a<<"块石子"<<endl;
stones-=a;
break;
}
else if(a > stones/2)
cout<<"你最多取"<<stones/2<<"块石子,请重新取:";
else
cout<<"你取的石子数不可以为零或负,请重新取"<<endl;
} //end of while
}
}
int getstones()
{
return stones;
}
};
void main()
{
cout<<"========================================================================"<<endl;
cout<<" NIM 游戏 "<<endl;
cout<<"========================================================================"<<endl;
cout<<" 游戏规则:"<<endl;
cout<<" 两名参与者交替从一堆石子中取出若干数目,由参与者自己决定。"<<endl;
cout<<" 但是,要求参与者每次至少取出一个,至多取出一半,然后另一名参"<<endl;
cout<<" 与者继续。拿到最后一个石子的参与者将输掉该游戏。"<<endl;
cout<<endl;
char continu = 'y';
while(continu=='y'||continu=='Y')
{
cout<<"选择难度:[ 1,简单2,困难 ]"<<endl;
int select;
cin>>select;
if(select==1)
{
cout<<"游戏开始了,Good Luck!"<<endl;
easymode();
cout<<"游戏结束,继续吗?[Y/N]"<<endl;
cin>>continu;
}
else if(select==2)
{
cout<<"游戏开始了,Good Luck!"<<endl;
hardmode();
cout<<"游戏结束,继续吗?[Y/N]"<<endl;
cin>>continu;
}
else
cout<<"选项不正确,请重新输入。"<<endl;
}
}
//double random(double a,double b)
//{
// srand( (unsigned)time( NULL ) );
// return a+(b-a)*rand()*(1.0/RAND_MAX);
//}
int random(int a,int b)
{
srand( (unsigned)time( NULL ) );
return rand()%(b-a+1)+a;
}
int is_two_power(int n)
{
while(n%2!=1)
{
n = n/2;
}
if ( n == 1)
return 1;
else
return 0;
}
void easymode()
{
game games;
while ( games.getstones() > 0 )
{
cout<<"目前有"<<games.getstones()<<"块石子"<<endl;
games.man();
if (games.getstones() <= 0)
{
cout<<"哈哈,你输了哦!"<<endl;
break;
}
games.easy();
if (games.getstones() <= 0)
{
cout<<"恭喜,你赢了,好厉害!"<<endl;
break;
}
} //end of while
}
void hardmode()
{
game games;
while ( games.getstones() > 0 )
{
cout<<"目前有"<<games.getstones()<<"块石子"<<endl;
games.man();
if (games.getstones() <= 0)
{
cout<<"哈哈,你输了哦!"<<endl;
break;
}
games.hard();
if (games.getstones() <= 0)
{
cout<<"恭喜,你赢了,好厉害!"<<endl;
break;
}
} //end of while
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -