about summary refs log tree commit diff stats
path: root/c/sand/sand.c
blob: 2c31f264dcb4b05516060c46fffdf3a3bca74769 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <emscripten.h>

#define CANVAS_WIDTH 800
#define CANVAS_HEIGHT 600
#define GRID_SIZE 10
#define GRID_WIDTH (CANVAS_WIDTH / GRID_SIZE)
#define GRID_HEIGHT (CANVAS_HEIGHT / GRID_SIZE)

int grid[GRID_HEIGHT][GRID_WIDTH] = {{0}};

EM_BOOL mouseDown = EM_FALSE;

EM_BOOL canvasMouseDown(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) {
    mouseDown = EM_TRUE;
    int x = mouseEvent->canvasX / GRID_SIZE;
    int y = mouseEvent->canvasY / GRID_SIZE;
    if (x >= 0 && x < GRID_WIDTH && y >= 0 && y < GRID_HEIGHT) {
        grid[y][x] = 1;
    }
    return EM_TRUE;
}

EM_BOOL canvasMouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) {
    if (mouseDown) {
        int x = mouseEvent->canvasX / GRID_SIZE;
        int y = mouseEvent->canvasY / GRID_SIZE;
        if (x >= 0 && x < GRID_WIDTH && y >= 0 && y < GRID_HEIGHT) {
            grid[y][x] = 1;
        }
    }
    return EM_TRUE;
}

EM_BOOL canvasMouseUp(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) {
    mouseDown = EM_FALSE;
    return EM_TRUE;
}

void addPlayer() {
    for (int y = 0; y < GRID_HEIGHT; y++) {
        for (int x = 0; x < GRID_WIDTH; x++) {
            if (grid[y][x] == 1) {
                grid[y - 10 >= 0 ? y - 10 : 0][x] = 3;
                return;
            }
        }
    }
}

EM_BOOL keyCallback(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData) {
    if (eventType == EMSCRIPTEN_EVENT_KEYDOWN) {
        if (keyEvent->keyCode == 32) {
            addPlayer();
        } else if (keyEvent->keyCode == 82) { // 'r' key
            for (int y = 0; y < GRID_HEIGHT; y++) {
                for (int x = 0; x < GRID_WIDTH; x++) {
                    grid[y][x] = 0;
                }
            }
        }
    }
    return EM_TRUE;
}

void updateGrid() {
    // Update grid logic
}

void drawGrid() {
    // Draw grid logic
}

int main() {
    // Set event listeners
    emscripten_set_mousemove_callback("#sand", NULL, EM_TRUE, canvasMouseMove);
    emscripten_set_mousedown_callback("#sand", NULL, EM_TRUE, canvasMouseDown);
    emscripten_set_mouseup_callback("#sand", NULL, EM_TRUE, canvasMouseUp);
    emscripten_set_keydown_callback(NULL, NULL, EM_TRUE, keyCallback);

    // Main loop
    emscripten_set_main_loop(updateGrid, 60, 1);

    return 0;
}