注册 登录
编程论坛 C语言论坛

我想让数字2上下左右移动,但运行时会让周围的墙改变(1代表墙2表示空位)

x258xfj 发布于 2023-08-12 16:50, 615 次点击
代码在下面求大佬解答



#include<stdio.h>
#include<Windows.h>
#include<conio.h>
int main()
{
    int arr[5][5]{
        1,1,1,1,1,
        1,0,0,0,1,
        1,0,2,0,1,
        1,0,0,0,1,
        1,1,1,1,1,
    };
    int x = 0;
    int y = 0;
    while (1) {
        system("cls");
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++)
            {
                printf("%d\t", arr[i][j]);
                if (arr[i][j] == 2) {
                    x = i;
                    y = j;
                }
            }
            printf("\n");
        }
        switch (_getch()) {
        case 'w':
            if (arr[x-1][y] == 0) {
                arr[x - 1][y] += 2;
                arr[x][y] -= 2;
            }
        case 's':
            if (arr[x - 1][y] == 0) {
                arr[x + 1][y] += 2;
                arr[x][y] -= 2;
            }
        case 'a':
            if (arr[x][y - 1] == 0) {
                arr[x][y - 1] += 2;
                arr[x][y] -= 2;
            }
        case 'd':
            if (arr[x][y + 1] == 0) {
                arr[x][y + 1] += 2;
                arr[x][y] -= 2;
            }
        }

    }

    return 0;
}
1 回复
#2
forever742023-08-12 19:24
首先,你的case末尾缺少break,
其次,第二个case里面的if里面应该是x+1吧?
1