运行效果如下,玩法和数字华容道一样👇
源码如下👇
//author:Mitchell_Donovan
//Date:2021.3.13
#include<iostream>
#include<stdlib.h>
using namespace std;
class HUARONG {
private:
int index;
int* array;
public:
HUARONG(int n) {
index = n;
array = new int [index * index];
for (int i = 0; i < index * index; i++) {
array[i] = i;
}
for (int i = 0; i < index * index; i++) {
int x = array[i];
int pos = rand() % (n * n);
array[i] = array[pos];
array[pos] = x;
}
}
void print() {
for (int i = 0; i < index * index; i++) {
if (array[i] == 0) {
cout.width(4);
cout<<" ";
}
else {
cout.width(4);
cout << array[i];
}
if (i % index == index - 1) {
cout << endl;
}
}
}
bool isCorrect(){
for (int i = 0; i < index * index - 1; i++) {
if (array[i] != i + 1) {
return false;
}
}
return true;
}
void play() {
print();
while (isCorrect() != true) {
move();
print();
}
cout << "成功!" << endl;
}
void move() {
char a;
do {
cout << "请输入移动方向↑(w)↓(s)←(a)→(d)——";
cin >> a;
} while (!((a == 's' && (whereBlank() - index) >= 0) || (a == 'w' && (whereBlank() + index) < index * index) || (a == 'd' && (whereBlank() - 1) >= 0 && whereBlank() % index != 0) || (a == 'a' && (whereBlank() + 1) < index * index && (whereBlank() + 1) % index != 0)));
if (a == 'w') {
int pos = whereBlank();
int x = array[pos];
array[pos] = array[pos + index];
array[pos + index] = x;
}
else if (a == 's') {
int pos = whereBlank();
int x = array[pos];
array[pos] = array[pos - index];
array[pos - index] = x;
}
else if (a == 'a') {
int pos = whereBlank();
int x = array[pos];
array[pos] = array[pos + 1];
array[pos + 1] = x;
}
else if (a == 'd') {
int pos = whereBlank();
int x = array[pos];
array[pos] = array[pos - 1];
array[pos - 1] = x;
}
}
int whereBlank() {
for (int i = 0; i < index * index; i++) {
if (array[i] == 0 ) {
return i;
}
}
}
};
int main() {
int n;
cout << "请输入华容道的阶数:";
cin >> n;
HUARONG a(n);
a.play();
}
知识补充
👉如何在C++中创建一个指定范围内的随机数?
假设要创建[a,b]范围内的随机数,公式如下👇
#include<stdlib.h> int x = rand() % (b - a + 1) + a
👉如何生成不重复的随机数组?
在这个问题上往往会产生误区,只想着怎么把随机数值赋值给数组值,这样做的后果就是重复
我们不妨先将数组初始化,然后将数组打乱(该过程中用到随机数),这样一来就得到了一个不重复的随机数组,具体做法如下👇
for (int i = 0; i < index * index; i++) { array[i] = i; } for (int i = 0; i < index * index; i++) { int x = array[i]; int pos = rand() % (n * n); array[i] = array[pos]; array[pos] = x; }
👉为什么要设置pos变量?
构造函数里的pos是为了记录下这一次循环的随机数,因为如果第二次调用rand(),其值必然改变,达不到我们交换变量值的目的
move函数里的pos也同理,因为0的位置是变化的,第二次调用whereBlank(),其值也会改变,同样达不到我们的目的