返回列表 發帖

猜拳遊戲 (二)

請簡化第一種版本的寫法
試著讓程式碼大幅減少
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.    // 1:剪刀 2:石頭 3:布
  7.    srand(time(NULL));

  8.    int player =0;
  9.    int com =0;
  10.    string mora[] = {"剪刀","石頭","布"};
  11.    cout << "請選擇想要出的拳 (1:剪刀 2:石頭 3:布)"<< endl;
  12.    cin >> player;
  13.    cout << "電腦出拳中..." << endl;
  14.    com = (rand()%3)+1;
  15.    cout << "你出:" << mora[player-1] << endl;
  16.    cout << "電腦出:" << mora[com-1] << endl;
  17.    
  18.    if(player == 1 && com==3) {
  19.      cout << "你贏了" << endl;
  20.    }
  21.    else if(player == 2 && com==1) {
  22.      cout << "你贏了" << endl;
  23.    }
  24.    else if(player == 3 && com==2) {
  25.      cout << "你贏了" << endl;
  26.    }
  27.    else if(player == com) {
  28.     cout << "平手" << endl;
  29.    }
  30.    else {
  31.     cout << "你輸了" << endl;
  32.    }
  33.    
  34.    system("pause");
  35.    return 0;   
  36. }
複製代碼

返回列表