用户可自己移动汉诺塔上盘子的移动,并且当完成汉诺塔时,会给出恭喜字样
时间: 2024-03-15 12:46:18 浏览: 19
以下是一个带用户交互的 C++ 汉诺塔小游戏的代码:
```c++
#include <iostream>
#include <stack>
using namespace std;
void move(stack<int>& source, stack<int>& target, char s, char t) {
int disk = source.top();
source.pop();
target.push(disk);
cout << "Move disk " << disk << " from " << s << " to " << t << endl;
}
void hanoi(stack<int>& source, stack<int>& target, stack<int>& auxiliary, int n) {
if (n == 1) {
move(source, target, 'A', 'C');
return;
}
hanoi(source, auxiliary, target, n-1);
move(source, target, 'A', 'C');
hanoi(auxiliary, target, source, n-1);
}
int main() {
int n;
cout << "Enter the number of disks: ";
cin >> n;
stack<int> A, B, C;
for (int i = n; i >= 1; i--) {
A.push(i);
}
while (true) {
cout << "Current state of the towers:" << endl;
cout << "A: ";
stack<int> tempA = A;
while (!tempA.empty()) {
cout << tempA.top() << " ";
tempA.pop();
}
cout << endl;
cout << "B: ";
stack<int> tempB = B;
while (!tempB.empty()) {
cout << tempB.top() << " ";
tempB.pop();
}
cout << endl;
cout << "C: ";
stack<int> tempC = C;
while (!tempC.empty()) {
cout << tempC.top() << " ";
tempC.pop();
}
cout << endl;
if (C.size() == n) {
cout << "Congratulations, you have completed the game!" << endl;
break;
}
char s, t;
cout << "Enter the tower to move from (A/B/C): ";
cin >> s;
cout << "Enter the tower to move to (A/B/C): ";
cin >> t;
stack<int>* source, *target;
if (s == 'A') {
source = &A;
} else if (s == 'B') {
source = &B;
} else {
source = &C;
}
if (t == 'A') {
target = &A;
} else if (t == 'B') {
target = &B;
} else {
target = &C;
}
if (source->empty() || (!target->empty() && source->top() > target->top())) {
cout << "Invalid move, please try again." << endl;
continue;
}
move(*source, *target, s, t);
}
return 0;
}
```
运行该程序后,会要求用户输入盘子的数量,然后输出当前汉诺塔的状态。用户可以输入要移动的盘子的来源和目的地,程序会判断是否合法并移动盘子,直到用户完成汉诺塔。