[C++][東方哈佛電機系] 資概作業5_彈珠台




/************************************************************/
/* 程式名稱:    */
/* 作者姓名:    */
/* 學號:    */
/************************************************************/

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main(void)
{
cout << "系級:    " << endl;
cout << "學號:    " << endl;
cout << "姓名:    " << endl << endl;
cout << "第 6 次作業" << endl;
cout << "=============" << endl << endl;

char ans;                    // 輸入 play or not
int choice;                  // 判斷輸入
int position[10];            // 落點
int marble, count, i, j;     // 彈珠、落點計數器、迴圈計數器

// 隨機種子
srand(time(0));

cout << "Do you like to play (Y/N) ? ";
cin >> ans;

// 判斷輸入是否正確
choice = (ans=='Y' || ans=='y' || ans=='N' || ans=='n');
 
// 若輸入不正確,則要求重新輸入
while (choice!=1){
cout << "Do you like to play (Y/N) ? ";
cin >> ans;
choice = (ans==89 || ans==121 || ans==78 || ans==110);
}

/*********************
* 進入遊戲
**********************/
while (ans=='Y' || ans=='y'){
// 每一輪遊戲,先將各位置清空
for (i=0 ; i<10 ; i++){
position[i]=0;
}

/********************
* 彈珠開始發射
********************/
for (marble=1 ; marble<=50 ; marble++){

// 落點歸零
count = 0;

// 碰撞釘子
for (i=0 ; i<9 ; i++){
count += rand()%2;    // rand()產生隨機整數,%2兩個亂數(from 0 to 1)
}

// 確定該顆彈珠的落點位置
for (i=0 ; i<10 ; i++){
if (count == i){
position[i]++;
}
}// 該顆彈珠之操作完成

}// 50顆彈珠完成

/******************
* 印出結果
*******************/
for (i=0 ; i<10 ; i++){
printf("%-2d | ", i+1);
for (j=1 ; j<=position[i] ; j++){
cout << "*";
}
cout << endl;
}
cout << endl;

/**********************
* 是否進入下一輪遊戲
***********************/
cout << "Do you like to play (Y/N) ? ";
cin >> ans;
choice = (ans==89 || ans==121 || ans==78 || ans==110);

// 若輸入不正確,則要求重新輸入
while (choice!=1){
cout << "Do you like to play (Y/N) ? ";
cin >> ans;
choice = (ans==89 || ans==121 || ans==78 || ans==110);
}

}// 不玩了則離開,繼續以下description

system("pause");
return 0;
}