Files
2048/ui.c
T

72 lines
1.9 KiB
C

#include "ui.h"
#include "game.h"
#include <math.h>
#include <raylib.h>
#include <stdbool.h>
static bool is_dragging;
static Vector2 drag_start_pos;
void handle_mouse_input(GameState_t *game_state) {
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) {
drag_start_pos = GetMousePosition();
// Check for the normal reset button
if (game_state->status == PLAYING) {
if (drag_start_pos.x >= 500 && drag_start_pos.x <= 775 && drag_start_pos.y >= 455 && drag_start_pos.y <= 479) {
reset_board(game_state);
return;
}
} else {
// Check for the "Play again" button
if (drag_start_pos.x >= 300 && drag_start_pos.x <= 500 && drag_start_pos.y >= 450 && drag_start_pos.y <= 490) {
reset_board(game_state);
return;
}
}
if (game_state->status == PLAYING)
is_dragging = true;
} else if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON) && is_dragging) {
Vector2 current_pos = GetMousePosition();
float dx = current_pos.x - drag_start_pos.x;
float dy = current_pos.y - drag_start_pos.y;
float drag_distance = sqrt(dx * dx + dy * dy);
// We don't want to register single clicks as a move
if (drag_distance >= 30) {
if (fabs(dx) > fabs(dy)) {
if (dx > 0) {
move(game_state, RIGHT);
} else {
move(game_state, LEFT);
}
} else {
if (dy > 0) {
move(game_state, DOWN);
} else {
move(game_state, UP);
}
}
if (!spawn_tile(game_state) && !can_move(game_state)) {
game_state->status = LOST;
return;
}
// TODO: Allow for infinite play
for(int y = 0; y < BOARD_HEIGHT; y++) {
for(int x = 0; x < BOARD_WIDTH; x++) {
if(game_state->board[y][x] == 2048) {
game_state->status = WON;
return;
}
}
}
}
is_dragging = false;
}
}