Snake

What if snake was a 1980s text adventure game?

This is the classic snake game, but it's turn based and played on a hex grid where you can only see your immediate surroundings.

A game start:

Welcome to snake

Type one of 'ne', 'nw', 'w', 'e', 'se', 'sw' followed by enter to move in that
direction You can also ask to 'draw' the map

.   f

.   h   .

.   .

> ne
You ate some food.

.   .

.   h   o

.   .

And after getting some power up:

> ne
Uh oh, you got shorter

.

o   v   .   .   .   o

.   .   o   .   F   .   .

o   o   .   o   o   .   o   .

.   o   o   .   F   .   .   v   o

o   F   o   o   v   .   .   o   o   o

.   o   o   o   o   h   .   o   o   .   .

o   o   v   .   s   o   .   o   o   .

o   o   o   s   o   .   .   o   .

o   o   o   s   o   o   f   o

o   .   .   s   .   o   .

o   o   .   .   .   .

.
68
69
70
71
72
73
74
75
76
77
78
79
#include <planet/connection.hpp>
#include <planet/map/hex.hpp>
#include <planet/stdin.hpp>

#include <felspar/coro/task.hpp>

#include <charconv>
#include <iostream>
#include <random>


namespace {

Some configuration

83
84
    using prng_type = std::mt19937;
    using distribution_type = std::uniform_real_distribution<float>;

The probability increases with distance

 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
    inline auto increasing(float control) {
        return [control](
                       auto &generator, auto &distribution,
                       float const distance) -> bool {
            auto const probability = distance / (distance + control);
            return distribution(generator) < probability;
        };
    }
    inline auto decreasing(float control) {
        return [control](
                       auto &generator, auto &distribution,
                       float const distance) -> bool {
            auto const probability = distance / (distance + control);
            return distribution(generator) > probability;
        };
    }

Feature within the hex -- keep player last when adding new ones

107
    enum class feature { none, rock, food, food_plus, vision_plus };

Determine how a feature is generated.

109
110
111
112
113
114
115
116
    struct generate_feature {
        feature creates;
        std::function<auto(std::mt19937 &,
                           std::uniform_real_distribution<float> &,
                           float)
                              ->bool>
                determine;
    };

Functions for creating each type of feature in precedence order. The first to return true will determine the feature in that hex tile.

121
122
123
124
125
126
127
128
129
130
    std::array<generate_feature, 5> const map_options = {
            generate_feature{
                    feature::none,
                    [](auto &, auto &, float const distance) {
                        return distance <= 1.0f;
                    }},
            generate_feature{feature::rock, increasing(16.0f)},
            generate_feature{feature::food, decreasing(0.6f)},
            generate_feature{feature::food_plus, increasing(100.0f)},
            generate_feature{feature::vision_plus, increasing(200.0f)}};

Data structure describing a single hex tile

134
135
136
137
138
139
140
    struct snake;
    struct hex {
        feature features = feature::none;
        snake *player = nullptr;

        using world_type = planet::hexmap::world_type<hex, 32>;
    };

Player state

144
    enum class player { alive, dead_self, dead_health };

Message from game engine to UI

148
149
150
    struct message {
        player state = player::alive;
        feature consumed = feature::none;

The view distance from the head of the snake for this move

152
        long view_distance = 0;

Difference in length between this turn and the last

154
        long length_delta = 0;

Change in health

156
        long health_delta = 0;

Change in score

158
        long score_delta = {};

Error message

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
        std::string error = {};

        message() {}
        message(long vd) : view_distance{vd} {}
        message(std::string e) : error{std::move(e)} {}
    };
    std::ostream &operator<<(std::ostream &os, message const &m) {
        if (m.health_delta < -2) {
            os << "Ouch. ";
        } else if (m.health_delta < -10) {
            os << "OUCH!!! ";
        }
        switch (m.consumed) {
        case feature::none: break;
        case feature::food: os << "You ate some food. "; break;
        case feature::food_plus:
            os << "You ate some really tasty food! ";
            break;
        case feature::vision_plus:
            os << "Ooh, that carrot made your eyesight better. ";
            break;
        case feature::rock:
            if (m.state == player::dead_health) {
                return os << "You ate a rock which disagreed with you, and now "
                             "you're dead :-(\n";
            } else {
                os << "You ate a rock? Not good for you. ";
            }
        }
        if (not m.error.empty()) {
            return os << m.error << '\n';
        } else if (m.state == player::dead_health) {
            return os << "Oh no, you died from exhaustion :-( You need to eat "
                         "more\n";
        } else if (m.state == player::dead_self) {
            return os << "You tried to eat yourself? Eeeewwww, you dead....\n";
        } else if (m.length_delta < -2) {
            return os << "Uh oh, you got a lot shorter!\n";
        } else if (m.length_delta < 0) {
            return os << "Uh oh, you got shorter\n";
        } else if (m.length_delta > 0) {
            return os << "You grew in length!\n";
        } else if (m.health_delta >= -2) {
            return os << "Nothing special happened\n";
        } else {
            return os;
        }
    }


    struct snake {
        planet::hexmap::coordinates position = {};
        std::vector<hex *> occupies;
        long vision_distance = 2;
        long health = 8;
        long score = {};

Initialise the snake position on the world

218
219
220
221
        explicit snake(hex::world_type &world) {
            occupies.push_back(&world[position]);
            occupies.back()->player = this;
        }

The snake has moved

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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
        felspar::coro::stream<message>
                move(hex::world_type &world, planet::hexmap::coordinates by) {
            position = position + by;
            auto &h = world[position];
            message outcome{vision_distance};
            if (h.player) {
                outcome.state = player::dead_self;
            } else {
                occupies.push_back(&world[position]);
                occupies.back()->player = this;
                outcome.length_delta += 1;
                outcome.health_delta -= 2;

                switch (h.features) {
                case feature::none: break;
                case feature::food:
                    outcome.health_delta += 9;
                    outcome.score_delta += 5;
                    break;
                case feature::food_plus:
                    outcome.health_delta += 14;
                    outcome.score_delta += 6;
                    break;
                case feature::vision_plus:
                    outcome.view_distance = (vision_distance += 2);
                    outcome.health_delta += 6;
                    outcome.score_delta += 9;
                    break;
                case feature::rock: outcome.health_delta -= 12; break;
                }
                outcome.consumed = std::exchange(h.features, feature::none);
            }
            co_yield outcome;
        }

        felspar::coro::stream<message>
                process_outcome(felspar::coro::stream<message> stream) {
            while (auto outcome = co_await stream.next()) {
                health += outcome->health_delta;
                score += outcome->score_delta;
                if (health < 0) { outcome->state = player::dead_health; }
                std::size_t const length = health / 8;
                while (occupies.size() > length) {
                    occupies.front()->player = nullptr;
                    occupies.erase(occupies.begin());
                    outcome->length_delta = -1;
                }
                co_yield *outcome;
            }
        }
    };


    void
            draw(hex::world_type const &world,
                 snake const &player,
                 planet::hexmap::coordinates::value_type range) {
        auto const top_left =
                player.position + planet::hexmap::coordinates{-range, range};
        auto const bottom_right = player.position
                + planet::hexmap::coordinates{range + 1, -range - 1};
        bool spaces = true;
        std::optional<long> current_row;
        std::string line;
        for (auto const loc :
             planet::hexmap::coordinates::by_column(top_left, bottom_right)) {
            if (loc.row() != current_row) {
                if (line.find_first_not_of(' ') != std::string::npos) {
                    std::cout << line << "\n\n";
                }
                line.clear();
                current_row = loc.row();
                if (spaces = not spaces; spaces) { line += "  "; }
            }
            auto const &cell = world[loc];
            if ((player.position - loc).mag2() > range * range) {
                line += ' ';
            } else if (player.position == loc) {
                line += 'h';
            } else if (cell.player) {
                line += 's';
            } else {
                switch (cell.features) {
                case feature::none: line += '.'; break;
                case feature::rock: line += 'o'; break;
                case feature::food: line += 'f'; break;
                case feature::food_plus: line += 'F'; break;
                case feature::vision_plus: line += 'v'; break;
                }
            }
            line += "   ";
        }
        if (line.find_first_not_of(' ') != std::string::npos) {
            std::cout << line << '\n';
        }
    }


    felspar::coro::task<int>
            print(hex::world_type &world,
                  snake &player,
                  felspar::coro::stream<message> messages) {
        while (auto message = co_await messages.next()) {
            std::cout << *message << '\n';
            if (message->state == player::dead_health
                or message->state == player::dead_self) {
                std::cout << "Your final score was " << player.score << '\n';
                co_return 1;
            }
            if (message->error.empty()) {
                draw(world, player, message->view_distance);
            }
        }
        co_return 0;
    }


    felspar::coro::task<int> co_main() {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_real_distribution<float> distribution(0.0f, 1.0f);

        hex::world_type world{
                {}, [&gen, distribution](auto const p) mutable {
                    auto const dist = std::sqrt(p.mag2());
                    for (auto const &f : map_options) {
                        if (f.determine(gen, distribution, dist)) {
                            return hex{f.creates};
                        }
                    }
                    return hex{};
                }};
        snake player{world};

        std::cout << "Welcome to snake\n\n";
        std::cout << "Type one of 'ne', 'nw', 'w', 'e', 'se', 'sw' followed by "
                     "enter to move in that direction\n";
        std::cout << "You can also ask to 'draw' the map\n\n";
        draw(world, player, player.vision_distance);

        planet::client::command_mapping<message> commands;
        commands["e"] = [&world, &player](auto) {
            return player.move(world, planet::hexmap::east);
        };
        commands["ne"] = [&world, &player](auto) {
            return player.move(world, planet::hexmap::north_east);
        };
        commands["nw"] = [&world, &player](auto) {
            return player.move(world, planet::hexmap::north_west);
        };
        commands["w"] = [&world, &player](auto) {
            return player.move(world, planet::hexmap::west);
        };
        commands["sw"] = [&world, &player](auto) {
            return player.move(world, planet::hexmap::south_west);
        };
        commands["se"] = [&world, &player](auto) {
            return player.move(world, planet::hexmap::south_east);
        };
        commands["draw"] = [](auto args) -> felspar::coro::stream<message> {
            std::string_view const sv = args.next().value_or("8");
            message distance{};
            auto const [_, ec] = std::from_chars(
                    sv.data(), sv.data() + sv.size(), distance.view_distance);
            if (ec != std::errc{}) {
                co_yield message{
                        "Sorry, I could not understand the distance, using 8"};
                distance.view_distance = 8;
            }
            distance.health_delta -= distance.view_distance;
            co_yield distance;
        };

        co_return co_await print(
                world, player,
                player.process_outcome(planet::client::connection(
                        planet::io::commands(), commands)));
    }


}


int main() { return co_main().get(); }