SOLVED: "ds_grid_get" to check if the next move is on the grid

Bentley

Member
I'm moving the player on a ds_grid. I want to keep him inside the grid. I saw the function ds_grid_get and thought it could work: "If you pass invalid grid coordinates, then the value returned will be 0." I'd use what ds_grid_get returns to check if the player's planned move is on the board.
Code:
    // Is the next move on the grid?
    var on_grid = ( ds_grid_get(global.grid, next_cell_x, next_cell_y) != 0 );
    if (on_grid)
    {
        // Move to that cell
    }
I must be misunderstanding how the function works. Does anyone know where I'm going wrong? Thanks for reading.
 
Last edited:
C

CedSharp

Guest
What are the values stored in the grid itself.
If you have the value '0' stored inside the grid, then of course it will return 0.
You might want to make a better check than this:
Code:
var on_grid = point_in_rectangle( next_cell_x, next_cell_y, 0, 0, ds_grid_width(global.grid)-1, ds_grid_height(global.grid)-1 );
if (on_grid)
{
    // Move to that cell
}
This doesn't even check for a grid cell, it just checks if the next move is inside the grid size.
Say you have a 10x10 grid, the coordinate (-1, 5) will return false because cell_x (-1) is smaller than 0. The coordinate (5, 10) would also fail because cell_y (10) is equal to the grid's height (starts at 0 and ends at 'n-1' so 9 is the actual last valid position).
 

Bentley

Member
What are the values stored in the grid itself.
If you have the value '0' stored inside the grid, then of course it will return 0.
You might want to make a better check than this:
Code:
var on_grid = point_in_rectangle( next_cell_x, next_cell_y, 0, 0, ds_grid_width(global.grid)-1, ds_grid_height(global.grid)-1 );
if (on_grid)
{
    // Move to that cell
}
This doesn't even check for a grid cell, it just checks if the next move is inside the grid size.
Say you have a 10x10 grid, the coordinate (-1, 5) will return false because cell_x (-1) is smaller than 0. The coordinate (5, 10) would also fail because cell_y (10) is equal to the grid's height (starts at 0 and ends at 'n-1' so 9 is the actual last valid position).
That's actually very clever and likely the best way. As you said, it ensures that a grid value of 0 won't screw it up.
What are the values stored in the grid itself.
That thought did cross my mind, so I made sure the grid values were -5 to -10 (or something like that) depending on their state. But regardless, I like what you posted a lot, and I will do it like that : )

Solved.
 
Last edited:
Top