我正在嘗試編寫一個需要通過函數進行輸入驗證的程序。背後的想法很像21石,只有13石,而且電腦總是贏。遊戲以13個寶石開始,並且電腦在第一回閤中總是選擇1,創建4個場景的倍數。這意味着,如果用戶需要3臺電腦需要1臺,用戶需要2臺電腦需要2臺,直到沒有石塊留下。我的問題是我很難得到我的頭部功能以及如何從參數中調用數據,因此任何幫助都將不勝感激!C++中的函數 - 13 Sone遊戲
這是我的沙發。
#include <iostream>
using namespace std;
//function prototypes
bool validPick(int numStones);
int computerPick(int stones_in_pile, int player2taken);
int playerPick(int stones_in_pile);
int main()
{
int stones_left = 13, P1Taken, P2Taken;
cout << "You have shosen to play the game 13 stones against me, the MIGHTY "
<< "COMPUTER!\nThe object of the game is to take 1, 2 or 3 stones from"
<< " the pile on your turn.\nThe player that removes the last stone "
<< "or stones from the pile wins the game.\nGood Luck... You will need"
<< " it! I NEVER LOOSE!!"
<< endl << endl;
computerPick(stones_left, P2Taken);
playerPick(P1Taken);
validPick(stones_left);
//game logic here -- This is far from done.
stones_left -= P1Taken;
stones_left -= P2Taken;
return 0;
}
/******************************************************************************\
* Validate the picked number 1-3 are only valid numbers to choose from. *
\******************************************************************************/
bool validPick(int numStones)
{
if((numStones < 1) || (numStones >3))
cout << "Invalid Selection. 1-3 is all you can have!";
else
return numStones;
}
/******************************************************************************\
* Computer's function calls. Should start with 1. We always want the computer *
* to win the game. *
\******************************************************************************/
int computerPick(int stones_in_pile, int player2taken)
{
if(player2taken == 0)
stones_in_pile -= 1;
else
{
if(player2taken == 1)
stones_in_pile -= 3;
else
if(player2taken == 2)
stones_in_pile -= 2;
else
stones_in_pile -=1;
}
return stones_in_pile;
}
/******************************************************************************\
* Player's Pick function call goes here. The player goes second *
\******************************************************************************/
int playerPick(int stones_in_pile)
{
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
return stones_in_pile;
}
*我的問題是我很難得到我的頭部函數以及如何從*中的參數調用數據 - 那麼爲什麼不寫一個調用函數並從函數返回的簡單示例,然後熟悉它?這就是任何C++程序員如何接近C++的一個新的或未知的方面 - 簡單程序首先被寫入,然後被學習,然後*新技術被用在實際程序中。 – PaulMcKenzie