handle_keypress - 1Fr3aK2/Cub3d GitHub Wiki

📝 handle_keypress

Handles keyboard input events during gameplay and triggers the corresponding movement or exit actions.

⚙️ Parameters

Parameter Type Description
key int The keycode of the pressed key. Determines which action to execute.
data t_data * Pointer to the main game data structure containing player and map information.

🔁 Returns

Return value Description
int Always returns 0. Used as a callback return for event handling.

📖 Description

The handle_keypress function processes user input by detecting which key was pressed and calling the appropriate movement or action function.
It is typically registered as a keyboard event handler in the game loop.

  • If key == XK_w: moves the player forward by calling move_forward(data).
  • If key == XK_s: moves the player backward by calling move_backward(data).
  • If key == XK_a: moves the player left by calling move_left(data).
  • If key == XK_d: moves the player right by calling move_right(data).
  • If key == XK_Escape: calls exit_error(data, "GAME OVER!") to terminate the game safely.

If the data pointer is NULL, the function immediately returns 0 without performing any action.

This function ensures responsive and safe handling of player input, linking keyboard events to in-game actions.

💡 Example Usage

int main(void)
{
    t_data data;

    // Initialize game data...
    // Register handle_keypress as key event callback:
    mlx_hook(data.win, KeyPress, KeyPressMask, handle_keypress, &data);

    // Start main game loop
    mlx_loop(data.mlx);

    return (0);
}