aboutsummaryrefslogtreecommitdiff
path: root/src/snake.c
blob: 549edb8636a603a2a461f3a193b1c7f2cd2776bb (plain)
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
#include <stdint.h>

#include "vga.h"
#include "map.h"
#include "entities.h"

#include "player.h"

#include "snake.h"

static const Rect frames[2 * 4] =
{
    /* right */
    { 0, 32, 144, 144 },
    { 16, 32, 144, 144 },
    /* not used */
    { 0, 0, 144, 144 },
    { 0, 0, 144, 144 },

    /* left */
    { 32, 32, 144, 144 },
    { 48, 32, 144, 144 },
    /* not used */
    { 0, 0, 144, 144 },
    { 0, 0, 144, 144 }
};

void snake_init(Entity *e)
{
    e->frames = (const Rect *)frames;
    e->update = snake_update;
}

void snake_update(Entity *e)
{
    if (e->delay & 1)
    {
        if (e->dir == DIR_RIGHT)
        {
            if (map_is_blocked(e->x + 16, e->y + 15)
                    || !map_is_blocked(e->x + 16, e->y + 16))
                e->dir = DIR_LEFT;
            else
                e->x++;
        }
        else
        {
            /* dir is LEFT */
            if (map_is_blocked(e->x - 1, e->y + 15)
                    || !map_is_blocked(e->x - 1, e->y + 16))
                e->dir = DIR_RIGHT;
            else
                e->x--;
        }
    }

    if (player_collision(e))
    {
        player_hit();
        /* change direction */
        e->dir ^= 1;
    }

    if (e->delay++ == WALK_DELAY + 4)
    {
        e->delay = 0;
        e->frame ^= 1;
    }
}