Skip to content

Instantly share code, notes, and snippets.

@knowlet
Last active August 29, 2015 14:22
Show Gist options
  • Save knowlet/a523705b8b1c851607c6 to your computer and use it in GitHub Desktop.
Save knowlet/a523705b8b1c851607c6 to your computer and use it in GitHub Desktop.
A sample mastermind game demo.
#include <iostream>
#include <string>
using namespace std;
void MasterMind(string master, string mind, int* b, int* w)
{
bool* checked1 = new bool[master.length()];
bool* checked2 = new bool[master.length()];
memset(checked1, false, master.length());
memset(checked2, false, master.length());
// 檢查黑針有幾個(相同位置一樣數字)
for (int i = 0; i < master.length(); ++i)
if (master.at(i) == mind.at(i)) {
++(*b);
// 相同則數量加一,並且在陣列設定說這個檢查過了
checked1[i] = checked2[i] = true;
}
// 檢查白針有幾個(不同位置相同數字)
for (int i = 0; i < master.length(); ++i)
for (int j = 0; j < mind.length(); ++j)
// 避免重複檢查
if (!checked1[i] && !checked2[j] && master.at(i) == mind.at(j)) {
// 數字相同且沒有重複檢查則加一
++(*w);
checked1[i] = checked2[j] = true;
}
}
int main(int argc, char const *argv[])
{
string master, mind;
cout << "請輸入題目: ";
cin >> master;
// 確認輸入就跑迴圈
while (master.length()) {
int b = 0, w = 0;
do {
cout << "請玩家猜色: ";
cin >> mind;
// 確定使用者輸入的猜測跟題目要猜測的數量是一樣
} while (master.length() != mind.length());
// 計算黑針白針
MasterMind(master, mind, &b, &w);
// 如果黑針數量跟字數相同代表猜對了
if (b == master.length()) {
cout << "恭喜猜對了!" << endl;
break;
}
else
cout << b << " 黑針 " << w << " 白針,再接再厲" << endl << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment