这是一个命令提示符版推箱子游戏的代码:
#include<stdio.h>
#include<Windows.h>
#include<conio.h>
//为什么每走一步都会创造箱子(3)?
//if语句包含错误,未使用{}
int main()
{
int arr1[9][9] = {
1,1,1,1,1,1,1,1,1,
1,0,0,0,0,0,0,0,1,
1,0,0,0,2,0,0,0,1,
1,0,0,0,0,0,0,0,1,
1,0,0,4,0,0,0,0,1,
1,0,0,0,0,3,0,0,1,
1,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,
}; //定义--2:人物;3:箱子;4:终点
while (1)
{
system("cls");
int x = 0, y = 0;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (arr1[i][j] == 2)
x = i, y = j;
}
}
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
printf("%d", arr1[i][j]);
}
printf("\n");
}
switch (_getch())
{
case 's':
if (arr1[x + 1][y] == 1 || arr1[x + 1][y] == 4)//人物不能越界或进入终点
break;
if (arr1[x + 1][y] == 3)
{
if (arr1[x + 2][y] == 1)//箱子不穿墙
break;
arr1[x + 2][y] = 3;//推箱子
}
arr1[x + 1][y] = 2;//人物移动
arr1[x][y] = 0;//抹除原位置
break;
case 'w':
if (arr1[x - 1][y] == 1 || arr1[x - 1][y] == 4)
break;
if (arr1[x - 1][y] == 3)
{
if (arr1[x - 2][y] == 1)
break;
arr1[x - 2][y] = 3;
}
arr1[x - 1][y] = 2;
arr1[x][y] = 0;
break;
case 'a':
if (arr1[x][y - 1] == 1 || arr1[x][y - 1] == 4)
break;
if (arr1[x][y - 1] == 3)
{
if (arr1[x][y - 2] == 1)
break;
arr1[x][y - 2] = 3;
}
arr1[x][y - 1] = 2;
arr1[x][y] = 0;
break;
case 'd':
if (arr1[x][y + 1] == 1 || arr1[x][y + 1] == 4 )
break;
if (arr1[x][y + 1] == 3)
{
if (arr1[x][y + 2] == 1)
break;
arr1[x][y + 2] = 3;
}
arr1[x][y + 1] = 2;
arr1[x][y] = 0;
break;
}
if (arr1[4][3] == 3)
break;
}
return 0;
}
请问为什么while循环的第二个for循环(导出二维数组)不能放到switch后面,否则无法显示?
(Visual Studio 2019)
while循环里的第一个语句就是cls,所以你每次循环都是先清屏,再接受一个输入,然后输出,然后立即进入下一个循环再次清屏,等你输入后才会有短暂的输出
【以下回答由 GPT 生成】
问题标题: (推箱子游戏)为什么while循环的第二个for循环(导出二维数组)不能放到switch后面,否则无法显示?
问题内容:
这是一个命令提示符版推箱子游戏的代码:
#include<stdio.h>
#include<Windows.h>
#include<conio.h>
int main()
{
int arr1[9][9] = {
1,1,1,1,1,1,1,1,1,
1,0,0,0,0,0,0,0,1,
1,0,0,0,2,0,0,0,1,
1,0,0,0,0,0,0,0,1,
1,0,0,4,0,0,0,0,1,
1,0,0,0,0,3,0,0,1,
1,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,
}; //定义-2:人物;3:箱子;4:终点
while (1)
{
system("cls");
int x = 0, y = 0;
for (int i = 0; i < 9; i++) /*这里的for循环似乎要放在switch后面,否则无法显示?*/
{
for (int j = 0; j < 9; j++)
{
switch (arr1[i][j])
{
case -2: //人物
printf("♀");
break;
case 0: //空地
printf(" ");
break;
case 3: //箱子
printf("□");
break;
case 4: //终点
printf("☆");
break;
default: //墙
printf("■");
break;
}
}
printf("\n");
}
}
return 0;
}
以下是对代码的改进:
改进后的问题标题和内容如下:
问题标题: (推箱子游戏) 为什么while循环的第二个for循环不能放到switch后面,否则无法显示? 问题标签: c++
问题内容:
我在学习推箱子游戏时,遇到了一个问题。在命令提示符版推箱子游戏的代码中,有一个while循环。在循环内部,有一个二重for循环用于在控制台上显示当前游戏地图。然而,当我将第二个for循环放到switch语句之后时,游戏地图就无法正确显示。
以下是代码的简化版本:
#include<stdio.h>
#include<Windows.h>
#include<conio.h>
int main()
{
int arr1[9][9] = {
// 游戏地图数据
};
while (1)
{
system("cls");
int x = 0, y = 0;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
switch (arr1[i][j])
{
// 根据游戏地图数据显示相应的字符
}
// 为什么将这个for循环放到switch语句之后会导致游戏地图无法正确显示?
}
}
}
return 0;
}
请问为什么将第二个for循环放到switch语句之后,就导致游戏地图无法正确显示了?我希望能够理解这个问题的原因,谢谢!
【相关推荐】