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 callingmove_forward(data). - If
key == XK_s: moves the player backward by callingmove_backward(data). - If
key == XK_a: moves the player left by callingmove_left(data). - If
key == XK_d: moves the player right by callingmove_right(data). - If
key == XK_Escape: callsexit_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);
}