所以我正在尝试为我的贪吃蛇游戏打印 map 。这是代码:
#define WIDTH 20
#define HEIGHT 20
struct coordinate {
int x;
int y;
};
typedef struct coordinate coordinate;
coordinate map[HEIGHT][WIDTH];
void init_map(){ // Function initializes the map with the corresponding coordinates
for(int i = 0; i < HEIGHT; i++){
for(int j = 0; j < WIDTH; j++){
map[i][j].y = i;
map[i][j].x = j;
}
}
} /* init_map */
// Function initializes the first snake with the corresponding coordinates
void init_snake1(coordinate snake1[], int snake1_length){
snake1[0].x = WIDTH/2;
snake1[0].y = HEIGHT/2;
snake1[1].x = snake1[0].x;
snake1[1].y = snake1[0].y+1;
} /* init_snake1 */
void print_map(coordinate snake1[], int snake1_length){
for(int i = 0; i < HEIGHT; i ++){
for(int j = 0; j < WIDTH; j++){
if(map[i][j].x == 0 && map[i][j].y == 0){
printf("#");
}else if(map[i][j].x == WIDTH-1 && map[i][j].y == HEIGHT-1){
printf("#");
}else if(map[i][j].y == 0 || map[i][j].y == HEIGHT-1){
printf("#");
}else if(map[i][j].x == 0 || map[i][j].x == WIDTH-1){
printf("#");
}else if(map[i][j].x > 0 && map[i][j].x < WIDTH-1 && map[i][j].y > 0 || map[i][j].y < HEIGHT-1){
for(int k = 0; k < snake1_length; k++){
if(map[i][j].x == snake1[k].x && map[i][j].y == snake1[k].y){
printf("x");
}else{
printf(" ");
}
}
}
}
printf("\n");
}
}/* print_map */
我的问题是,当打印 map 时, map 中似乎打印了很多空白,因此当顶部或底部边框结束时,右边框不会开始。除了蛇的尾部也移动了,只有蛇头似乎在正确的位置。为了更好地理解我在这里提供的问题 Console Output
最佳答案
我不太确定为什么要为此存储坐标。您可以仅使用蛇列表和已知的边框大小来完成。如果你愿意,你可以“打印”到你的二维数组中以便稍后进行碰撞检查,并将数组打印为字符串列表,但现在:
// These should be "int" types should be "bool", but am using old-school int values for old C standards
#define WIDTH 20
#define HEIGHT 20
struct coordinate {
int x;
int y;
};
typedef struct coordinate coordinate;
int isBorder(int x, int y)
{
return x == 0 || x == WIDTH-1 || y == 0 || y == HEIGHT - 1;
}
int isSnake(int x, int y, coordinate snake[], int snake_length)
{
for(int i = 0; i < snake_length; i++)
{
if(x == snake[i].x && y == snake[i].y)
{
return 1;
}
}
return 0;
}
void print_map(coordinate snake1[], int snake1_length)
{
for(int y = 0; y < HEIGHT; y++)
{
for(int x = 0; x < WIDTH; x++)
{
if(isBorder(x, y))
{
printf("#");
}
else if(isSnake(x, y, snake1, snake1_length))
{
printf("x");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
int main(void)
{
coordinate snake1[2] = {{3,3},{3,4}};
print_map(snake1, 2);
return 0;
}
请注意如何使用函数来使工作更清晰、更清晰。这也使得将来添加更多蛇变得微不足道——只需更改 isSnake() 函数以获取更多数组。如果您绝对必须使用全局映射进行存储,则可以更改所有 printf() 值以改为打印到该数组。尽管让您的 map 成为坐标的二维数组列表没有任何好处 - 它应该是类型。我认为您可能误解了那部分的说明。
int map[HEIGHT][WIDTH];
if(isBorder(x, y))
{
map[y][x] = BorderType;
}
else if(isSnake(x, y, snake1, snake1_length))
{
map[y][x] = SnakeType;
}
else
{
map[y][x] = EmptyType;
}
有了这张 map ,以后进行碰撞检测和杀死蛇就更容易了。在这种情况下,您只想打印一次边框并检查蛇的新方 block 是否已经为空 - 我猜您将在几周内完成此操作。
关于c - 用 C 编写的蛇视频游戏 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54258590/