C 子数组意外删除,而不是按预期删除

问题描述 投票:0回答:1

我目前正在用 C 和 SDL2 编写游戏。在游戏中,屏幕的每一侧都会产生随机的墙壁,留下一个小间隙供玩家穿过。如果玩家撞到墙壁,游戏就结束。这是我希望游戏最终呈现的草图:

我目前正在研究横向卷轴。二维数组

grid
最多包含 255 个数组,这些数组由网格上块的 X 和 Y 坐标组成。例如,

[[0,5],[1,5],[2,5],[3,5],[6,5],[7,5],[8,5],[9,5]]

将在 Y 坐标 5 处创建两堵墙,并在 X 坐标 3 和 6 之间留出间隙。

我的游戏中横向滚动的计划是,网格上任何 Y 坐标低于 -30(30 是块的大小)的块都会被删除,所有其他子数组都会向左移动一位,并且最右边的值被设置为 null,以便可以再次使用。每六个空格生成行。

然而,每隔几排墙壁,所有的墙壁就会突然消失。这是发生这种情况的视频:https://youtu.be/Sb8XTU6zE3Y

相关代码如下:

float grid[GRID_MAX_ITEMS][2]; // GRID_MAX_ITEMS is 255

void delete_grid_space(int index) { // Delete block from grid array by index
    // Move each array in grid to the left
    for (int i = get_grid_length(); i > index; i--) {
        grid[i-1][0] = grid[i][0];
        grid[i-1][1] = grid[i][1];
    }

    // Delete the original array in grid by the index
    grid[index][0] = '\0';
    grid[index][1] = '\0';

}

void move_grid_down(float change) { // Move all blocks in grid down by given decimal
    int number_indexes_deleted = 0; // Number of blocks deleted from grid so we have the right index

    for (int i = 0; i < get_grid_length(); i++) { // Go through all blocks in grid
        int index = i - number_indexes_deleted; // Get index accounting for any deleted blocks
        grid[index][1] -= change; // Subtract change from block Y
        if (grid[index][1] < -GRID_SPACE_SIZE) { // If Y is below negative grid space size (30), it is not visible anymore and has no use
            delete_grid_space(index); // Delete the block using its index
            number_indexes_deleted++; // Increment the number of indexes deleted
        }
    }

    if (GRID_ROWS - grid[get_grid_length() - 1][1] >= 6) { // If it has been 6 spaces since a row last generated
        add_row(GRID_ROWS + 1); // Add a new row
    }
}

void update(SDL_Renderer *renderer) { // Update every frame
    ...
    move_grid_down((float)7 / FRAME_TARGET_TIME); // FRAME_TARGET_TIME is equal to the number of milliseconds to wait inbetween frames

}

int main(int argc, char *argv[]) { // Main function
    ...
    init_grid(); // Initialise grid

    running = true; // Game is running

    ...
    while (running) {
        update(renderer); // Update the screen
        ...
    }

}

我编辑了代码,以在每次添加新行时打印出

grid
的大小。我注意到,尽管行离开屏幕,长度仍然变大,直到达到 64,此时所有块都从屏幕上消失,长度然后恢复到 8。这是视频:https://youtu.be/2c7FK5XE9mg

if (GRID_ROWS - grid[get_grid_length() - 1][1] >= 6) { // If it has been 6 spaces since a row last generated
    add_row(GRID_ROWS + 1); // Add a new row
    printf("%d\n", get_grid_length());
}

这表明尽管

grid
数组中块的 Y 值低于 -30,但它们并未被删除。然而,这并不能解释意外的消失。如果有人能帮助我理解为什么行突然消失,我将不胜感激。

arrays c iteration sdl
1个回答
0
投票

带有

// Delete the original array in grid by the index
注释的部分可能会导致它。我不会将空字符移动到浮点数组中,即使它以某种方式隐式转换为浮点。

您还可以将值存储为结构,例如:

typedef struct{
  float x;
  float y;
} Vector2;

这将使处理坐标变得更容易。

© www.soinside.com 2019 - 2024. All rights reserved.