C++的代码
时间: 2023-07-10 22:12:12 浏览: 75
C++代码
以下是一个基于C++语言的九宫格程序代码,供参考:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int board[3][3];
// 初始化九宫格的函数
void init_board() {
int nums[8] = {1, 2, 3, 4, 5, 6, 7, 8};
srand(time(NULL));
random_shuffle(nums, nums + 8);
int k = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (k < 8) {
board[i][j] = nums[k];
k++;
}
else {
board[i][j] = 0;
}
}
}
}
// 判断是否为目标状态的函数
bool is_target() {
int k = 1;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] != k) {
return false;
}
k++;
}
}
return true;
}
// 输出当前九宫格状态的函数
void print_board() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
// 接收用户输入的函数
char get_input() {
while (true) {
cout << "请输入移动方向(w/s/a/d):";
char move;
cin >> move;
if (move == 'w' || move == 's' || move == 'a' || move == 'd') {
return move;
}
else {
cout << "输入有误,请重新输入!" << endl;
}
}
}
// 移动数字的函数
void move_num(char move) {
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (board[i][j] == 0) {
break;
}
}
if (board[i][j] == 0) {
break;
}
}
switch (move) {
case 'w':
if (i < 2) {
board[i][j] = board[i+1][j];
board[i+1][j] = 0;
}
break;
case 's':
if (i > 0) {
board[i][j] = board[i-1][j];
board[i-1][j] = 0;
}
break;
case 'a':
if (j < 2) {
board[i][j] = board[i][j+1];
board[i][j+1] = 0;
}
break;
case 'd':
if (j > 0) {
board[i][j] = board[i][j-1];
board[i][j-1] = 0;
}
break;
}
}
// 主函数
int main() {
init_board();
print_board();
while (!is_target()) {
char move = get_input();
move_num(move);
print_board();
}
cout << "恭喜你,完成游戏!" << endl;
return 0;
}
```
以上代码实现了一个简单的九宫格游戏,可以通过在命令行界面输入移动方向来控制数字的移动,直到完成游戏。
阅读全文