summaryrefslogtreecommitdiffstats
path: root/src/snake.cpp
blob: 79ced0d265cadedc931df3144b2862b6642d047a (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#include "snake.h"

#include <QWidget>
#include <QPaintEvent>
#include <QPainter>
#include <QRectF>
#include <QTimer>
#include <QDebug>
#include <QDateTime>

#define SCALING (16)

#define DIR_UP 0
#define DIR_DOWN 1
#define DIR_LEFT 2
#define DIR_RIGHT 3

#define CELL_FREE 0
#define CELL_WALL 1
#define CELL_SNAKE 2
#define CELL_FOOD 3

struct Cell
{
    int type;
    QBrush color;
    Cell(int t, QColor c) : type(t), color(QBrush(c)) {}
    bool isFood() const { return type == CELL_FOOD; }
    bool willKill() const { return type == CELL_WALL || type == CELL_SNAKE; }
    bool isFree() const { return type == CELL_FREE; }
    bool isWall() const { return type == CELL_WALL; }
};

const Cell empty(CELL_FREE, QColor());
const Cell wall(CELL_WALL, QColor::fromRgb(80, 80, 90));
const Cell food[] = {
    Cell(CELL_FOOD, QColor::fromRgb(0, 255, 0)),
    Cell(CELL_FOOD, QColor::fromRgb(0, 200, 0)),
    Cell(CELL_FOOD, QColor::fromRgb(0, 160, 0)),
    Cell(CELL_FOOD, QColor::fromRgb(0, 120, 0)),
};

#define FIELD(x,y) _field[(x) + ((y) * _width)]

class RealSnake
{
public:
    int _x, _y;
    int _direction;
    int _snakeLen;
    QList<QPoint> _snake;
    Cell *cell;
    RealSnake(int sx, int sy) : _x(sx), _y(sy), _direction(DIR_UP), _snakeLen(5), _snake(),
        cell(new Cell(CELL_SNAKE, QColor::fromHsv(qrand() % 360, 128 + qrand() % 128, 128 + qrand() % 128))) {}
    virtual ~RealSnake() { delete cell; }
};

Snake::Snake(QWidget *widget)
   : _widget(widget),
     _field(nullptr),
     _deaths(0),
     _lastMeal(QDateTime::currentMSecsSinceEpoch())
{
    _width = widget->width() / SCALING;
    _height = widget->height() / SCALING;
    if (_width <= 0 || _height <= 0)
        return;
    initField();
    qDebug() << "Field:" << _width << _height;
    addFood();
    QTimer *t = new QTimer(widget);
    t->start(100);
    // Game logic
    QTimer::connect(t, &QTimer::timeout, [this]() {
        for (RealSnake *snake : _snakes) {
            // AI
            const Cell* what[4];
            int dist[4];
            int best = 0;
            scanDir(snake, 0, -1, what[DIR_UP], dist[DIR_UP]);
            scanDir(snake, 0, 1, what[DIR_DOWN], dist[DIR_DOWN]);
            scanDir(snake, -1, 0, what[DIR_LEFT], dist[DIR_LEFT]);
            scanDir(snake, 1, 0, what[DIR_RIGHT], dist[DIR_RIGHT]);
            for (int i = 1; i < 4; ++i) {
                if (what[i]->isFood()) {
                    if (!what[best]->isFood() || dist[best] > dist[i]) {
                        best = i;
                    }
                } else if (!what[best]->isFood() && (dist[i] > dist[best] || (dist[i] > 10 && qrand() % (4 * (4 - i)) == 0))) {
                    best = i;
                }
            }
            if (what[best]->isFood()) {
                snake->_direction = best;
            } else if (dist[snake->_direction] <= 1 || qrand() % 20 == 0) {
                snake->_direction = best;
            }
            // Move
            switch (snake->_direction) {
            case DIR_UP:
                snake->_y--; break;
            case DIR_DOWN:
                snake->_y++; break;
            case DIR_LEFT:
                snake->_x--; break;
            case DIR_RIGHT:
                snake->_x++; break;
            }
            if (snake->_x < 0 || snake->_x >= _width || snake->_y < 0 || snake->_y >= _height ||
                    FIELD(snake->_x, snake->_y)->willKill()) {
                // Snek ded
                qDebug() << "DEATH";
                _snakes.removeAll(snake);
                for (const QPoint &p : snake->_snake) {
                    if (FIELD(p.x(), p.y())->isFood())
                        continue;
                    FIELD(p.x(), p.y()) = &wall;
                    _widget->update(p.x() * SCALING, p.y() * SCALING, SCALING, SCALING);
                }
                delete snake;
                if (_snakes.isEmpty()) {
                    initField();
                    addSnake();
                    addFood();
                }
                return; // Skip rest of list for this tick since we removed a snake from the list while iterating
            }
            // Remove tail from field if snake reached desired length
            if (snake->_snake.size() >= snake->_snakeLen) {
                const QPoint &p = snake->_snake.front();
                if (FIELD(p.x(), p.y()) == snake->cell) {
                    FIELD(p.x(), p.y()) = &empty;
                    _widget->update(p.x() * SCALING, p.y() * SCALING, SCALING, SCALING);
                }
                snake->_snake.pop_front();
            }
            // Eat
            if (FIELD(snake->_x, snake->_y)->isFood()) {
                _lastMeal = QDateTime::currentMSecsSinceEpoch();
                if (qrand() % snake->_snakeLen > 40) {
                    // Snake break!
                    snake->_snakeLen = 10;
                    while (snake->_snake.size() > snake->_snakeLen) {
                        const QPoint &p = snake->_snake.front();
                        if (FIELD(p.x(), p.y())->isFood())
                            continue;
                        FIELD(p.x(), p.y()) = &wall;
                        _widget->update(p.x() * SCALING, p.y() * SCALING, SCALING, SCALING);
                        snake->_snake.pop_front();
                    }
                    addFood();
                } else {
                    snake->_snakeLen += 5;
                }
                addFood();
            }
            FIELD(snake->_x, snake->_y) = snake->cell;
            snake->_snake.append(QPoint(snake->_x, snake->_y));
            _widget->update(snake->_x * SCALING, snake->_y * SCALING, SCALING, SCALING);
        }
        // If no food was picked up within a minute, spawn more
        if (QDateTime::currentMSecsSinceEpoch() - _lastMeal > 60000) {
            _lastMeal = QDateTime::currentMSecsSinceEpoch();
            addFood();
        }
    });
}

Snake::~Snake()
{
    free(_field);
}

void Snake::scanDir(RealSnake *snake, int dx, int dy, const Cell* &what, int &dist)
{
    int x = snake->_x;
    int y = snake->_y;
    dist = 0;
    for (;;) {
        x += dx;
        y += dy;
        dist++;
        if (x < 0 || x >= _width || y < 0 || y >= _height) {
            what = &wall;
            return;
        }
        if (!FIELD(x, y)->isFree()) {
            what = FIELD(x, y);
            return;
        }
    }
}

void Snake::addSnake()
{
    for (int i = 0; i < 10; ++i) {
        int x = qrand() % _width;
        int y = qrand() % _height;
        if (FIELD(x, y)->isFree()) {
            _snakes.append(new RealSnake(x, y));
            break;
        }
    }
}

void Snake::initField()
{
    if (_field == nullptr) {
        _field = (const Cell**)calloc(_width * _height, sizeof(*_field));
    }
    for (int i = 0; i < _width; ++i) {
        FIELD(i, 0) = &wall;
        FIELD(i, _height - 1) = &wall;
    }
    for (int i = 0; i < _height; ++i) {
        FIELD(0, i) = &wall;
        FIELD(_width - 1, i) = &wall;
    }
    for (int y = 1; y < _height - 1; ++y) {
        for (int x = 1; x < _width - 1; ++x) {
            FIELD(x, y) = &empty;
        }
    }
    _widget->update();
}

void Snake::addFood()
{
    for (int i = 0; i < 10; ++i) {
        int x = qrand() % _width;
        int y = qrand() % _height;
        if (!FIELD(x, y)->isWall()) {
            FIELD(x, y) = &food[qrand() % (sizeof(food) / sizeof(*food))];
            _widget->update(x * SCALING, y * SCALING, SCALING, SCALING);
            break;
        }
    }
}

void Snake::paint(QPaintEvent *event)
{
    QPainter p(_widget);
    const int width = qMin(_width, (event->rect().x() + event->rect().width() + SCALING - 1) / SCALING);
    const int height = qMin(_height, (event->rect().y() + event->rect().height() + SCALING - 1) / SCALING);
    for (int y = event->rect().y() / SCALING; y < height; ++y) {
        if (y < 0)
            continue;
        for (int x = event->rect().x() / SCALING; x < width; ++x) {
            if (x < 0)
                continue;
            const Cell *c = FIELD(x, y);
            if (c->isFree())
                continue;
            p.setBrush(c->color);
            p.drawRect(x * SCALING, y * SCALING, SCALING-1, SCALING-1);
        }
    }
}