c语言做4x4数字华容道代码
时间: 2024-03-24 11:35:38 浏览: 102
好的,这里提供一份用C语言实现4x4数字华容道的代码,希望能够帮到您。
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 4
#define COL 4
void init(int board[ROW][COL])
{
int i, j, k, tmp;
srand(time(NULL));
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
board[i][j] = i * COL + j + 1;
}
}
board[ROW-1][COL-1] = 0; //最后一个位置是空格
for (k = 0; k < 100; k++) { //随机打乱
i = rand() % ROW;
j = rand() % COL;
tmp = board[i][j];
board[i][j] = board[ROW-1][COL-1];
board[ROW-1][COL-1] = tmp;
}
}
void show(int board[ROW][COL])
{
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
if (board[i][j] == 0) {
printf(" ");
} else {
printf("%2d ", board[i][j]);
}
}
printf("\n");
}
}
int check(int board[ROW][COL])
{
int i, j, num = 1;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
if (board[i][j] != num % (ROW*COL)) {
return 0;
}
num++;
}
}
return 1;
}
int move(int board[ROW][COL], char dir)
{
int i, j, x, y, tmp;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
if (board[i][j] == 0) {
x = i;
y = j;
}
}
}
switch (dir) {
case 'w': //上移
if (x == 0) {
return 0;
}
tmp = board[x-1][y];
board[x-1][y] = board[x][y];
board[x][y] = tmp;
break;
case 's': //下移
if (x == ROW-1) {
return 0;
}
tmp = board[x+1][y];
board[x+1][y] = board[x][y];
board[x][y] = tmp;
break;
case 'a': //左移
if (y == 0) {
return 0;
}
tmp = board[x][y-1];
board[x][y-1] = board[x][y];
board[x][y] = tmp;
break;
case 'd': //右移
if (y == COL-1) {
return 0;
}
tmp = board[x][y+1];
board[x][y+1] = board[x][y];
board[x][y] = tmp;
break;
default:
return 0;
}
return 1;
}
int main()
{
int board[ROW][COL];
char dir;
init(board);
while (!check(board)) {
show(board);
printf("请输入移动方向(w上 s下 a左 d右):");
scanf("%c", &dir);
if (move(board, dir)) {
system("clear"); //清屏
} else {
printf("移动无效!\n");
}
getchar(); //吃掉缓冲区的回车符
}
show(board);
printf("恭喜您完成华容道!\n");
return 0;
}
```
这份代码主要实现了4x4数字华容道的初始化、打乱、展示、移动以及检查是否完成的功能。其中移动操作使用了简单的交换法,检查是否完成则是对每个位置上的数字进行比较。在主函数中,使用while循环不断展示当前状态并读取用户输入的移动方向,直到完成华容道为止。
阅读全文