學習c++也有一段日子了,從毫無頭緒到現在剛剛入門已經過去將近一年了。不知是學校老師太差還是自己不夠積極,總覺得毫無長進!常在網上加些同樣不想在學校僅僅是混個畢業的朋友,沒事討論討論(身邊大多都是想混混日子的)。
井字游戲其實原理相當簡單,九個格子,不管橫豎還對角線上的三個子全是一方的,這方九贏的game。
#include<iostream>
using namespace std;
class line{
private:
char box[9];
public:
int step,pps,temp; //標志量控制條件
int setline(){ //構造函數用于下棋過程中顯示每個位置的數字,方便弈者選擇
for(int i=0;i<9;++i)
box[i]=i+'1'; //將數字的ascii碼放入數組,這樣解決了char類型數組中放數字的矛盾
return(0);
}
int check(int);
int showTable();
int showChange();
int winLost();
int continueAbort();
};
//用于每次開盤時顯示棋盤
int line::showTable(){
cout<<" *************"<<endl;
cout<<" | 1 | 2 | 3 |"<<endl;
cout<<" -------------"<<endl;
cout<<" | 4 | 5 | 6 |"<<endl;
cout<<" -------------"<<endl;
cout<<" | 7 | 8 | 9 |"<<endl;
cout<<" *************"<<endl;
return(0);
}
//每步棋盤上棋子的變化
int line::showChange(){
int num=0;
cin>>num;
--num;
while(box[num]=='a'||box[num]=='b'||num<0||num>8){
cout<<"\nThis number have been chosen!please take another one: ";
cin>>num;
--num;
}
if(step==1)box[num]='a';
else box[num]='b';
cout<<"\n *************"<<endl;
for(int i=0,j=0;j<3;++j){
cout<<" | "<<box[i]<<" | "<<box[i+1]<<" | "<<box[i+2]<<" |"<<endl;
i=i+3;
cout<<" *************"<<endl;}
winLost(); // 每次棋盤變化判斷一下輸贏
return(0);
}
//判斷輸贏條件
int line::check(int ch){
return((box[0]+box[1]+box[2]==ch||
box[0]+box[3]+box[6]==ch||
box[0]+box[4]+box[8]==ch||
box[3]+box[4]+box[5]==ch||
box[7]+box[8]+box[6]==ch||
box[2]+box[4]+box[6]==ch||
box[1]+box[4]+box[7]==ch||
box[2]+box[8]+box[5]==ch));
}
// 顯示輸贏結果,設置pps跳出單次下棋過程,即有一方贏了就結束該輪比賽
int line::winLost(){
if(check(3*'a')){
pps=1;
cout<<"player a win the game"<<endl;
}
else if(check(3*'b')){
pps=1;
cout<<"player b win the game"<<endl;
}
return(0);
}
// 再來一盤
int line::continueAbort(){
char pos;
cout<<"press c to continue_press anykey to abort"<<endl;
cin>>pos;
if(pos=='c'){
pps=0;
temp=0;
showTable();
setline();
return (1);
}
else return(0);
}
int main(){
line player;
player.setline();
cout<<"let us play the game"<<endl;
player.showTable();
do
{
for( int i=0;i<9;++i){
if(i%2==0){
player.step=1;
cout<<"\nplayer a,please choose the number you fit: ";
}
else{
player.step=0;
cout<<"\nplayer b,please choose the number you fit: ";
}
player.showChange();
if(player.pps==1)break;
player.temp=i;
}
if(player.temp==8){
cout<<"no one win the game!"<<endl;
break;
}
}while(player.continueAbort());
return (0);
}
修修補補終于完工,但總讓我感覺很差勁:
1.能否減少函數
2.winLost( )能簡化嗎
3.能使所有變量step和pps放在私有里嗎
4.showChange()內調用winLost()導致每下一個子顯示no one win the game!
ps1:又改了一下,解決了第4個問題。不過又增加了一個標志量和一個函數!有必要減少函數嗎?其他問題估計不能解決,除非重新寫了。就算完成了吧!
ps2:鑒于評論添加了一些注釋,原本打算自己學學而已,沒想到還有人關注,頗有些驚喜
4月26日想做個人機對弈,發現了原來代碼里平局有錯誤,遂將temp=9 改成8,這樣就解決了平局問題