nyble

A snake game for the terminal.


nyble

/

src

/

game

/

world.hh

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 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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
/*
                                    88888888
                                  888888888888
                                 88888888888888
                                8888888888888888
                               888888888888888888
                              888888  8888  888888
                              88888    88    88888
                              888888  8888  888888
                              88888888888888888888
                              88888888888888888888
                             8888888888888888888888
                          8888888888888888888888888888
                        88888888888888888888888888888888
                              88888888888888888888
                            888888888888888888888888
                           888888  8888888888  888888
                           888     8888  8888     888
                                   888    888

                                   OCTOBANANA

Licensed under the MIT License

Copyright (c) 2019 Brett Robinson <https://octobanana.com/>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef GAME_WORLD_HH
#define GAME_WORLD_HH

#include "ob/parg.hh"
#include "ob/text.hh"
#include "ob/term.hh"
#include "ob/lispp.hh"
#include "ob/timer.hh"
#include "ob/color.hh"
#include "ob/readline.hh"
#include "ob/ordered_map.hh"
#include "ob/belle/io.hh"
#include "ob/belle/signal.hh"

#include <cstddef>
#include <cstdint>

#include <deque>
#include <regex>
#include <chrono>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <utility>
#include <fstream>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <filesystem>
#include <functional>
#include <unordered_map>

namespace Nyble {

using Read = OB::Belle::IO::Read;
using Key = OB::Belle::IO::Read::Key;
using Mouse = OB::Belle::IO::Read::Mouse;
using Tick = std::chrono::nanoseconds;
using Clock = std::chrono::steady_clock;
using Readline = OB::Readline;
using Timer = OB::Belle::asio::steady_timer;
using error_code = OB::Belle::error_code;
using namespace std::chrono_literals;
using namespace std::string_literals;
namespace fs = std::filesystem;
namespace Text = OB::Text;
namespace Term = OB::Term;
namespace Belle = OB::Belle;
namespace iom = OB::Term::iomanip;
namespace aec = OB::Term::ANSI_Escape_Codes;

struct Pos {
  // TODO use signed integer
  std::size_t x {0};
  std::size_t y {0};
  Pos(std::size_t const x, std::size_t const y) : x {x}, y {y} {}
  Pos() = default;
  Pos(Pos&&) = default;
  Pos(Pos const&) = default;
  ~Pos() = default;
  Pos& operator=(Pos&&) = default;
  Pos& operator=(Pos const&) = default;
};

struct Size {
  std::size_t w {0};
  std::size_t h {0};
  Size(std::size_t const w, std::size_t const h) : w {w}, h {h} {}
  Size() = default;
  Size(Size&&) = default;
  Size(Size const&) = default;
  ~Size() = default;
  Size& operator=(Size&&) = default;
  Size& operator=(Size const&) = default;
};

struct Color {
  std::uint8_t r {0};
  std::uint8_t g {0};
  std::uint8_t b {0};
  Color(std::uint8_t const r, std::uint8_t const g, std::uint8_t const b) : r {r}, g {g}, b {b} {}
  Color() = default;
  Color(Color&&) = default;
  Color(Color const&) = default;
  ~Color() = default;
  Color& operator=(Color&&) = default;
  Color& operator=(Color const&) = default;
};

Color hex_to_rgb(std::string const& str);

struct Style {
  friend std::ostream& operator<<(std::ostream& os, Style const& obj);
  enum Type : std::uint8_t {
    Bit_2 = 0,
    Bit_4,
    Bit_8,
    Bit_24,
  };
  enum Attr : std::uint8_t {
    Null = 0,
    Bold = 1 << 0,
    Reverse = 1 << 1,
  };
  std::uint8_t type {Bit_24};
  std::uint8_t attr {Null};
  Color fg;
  Color bg;
};

class Scene;

struct Cell {
  Scene* scene;
  int zidx;
  Style style;
  std::string text;
};

class Buffer {
public:
  Buffer() = default;
  Buffer(Buffer&&) = default;
  Buffer(Buffer const&) = default;
  ~Buffer() = default;
  Buffer& operator=(Buffer&&) = default;
  Buffer& operator=(Buffer const&) = default;
  void operator()(Cell const& cell);
  Cell& at(Pos const& pos);
  std::vector<Cell>& row(std::size_t y);
  Cell& col(Pos const& pos);
  Pos cursor();
  void cursor(Pos const& pos);
  Size size();
  void size(Size const& size);
  bool empty();
  void clear();

private:
  Pos _pos;
  Size _size;
  std::vector<std::vector<Cell>> _value;
}; // class Buffer

class Engine;

using Ctx = Engine*;

class Scene {
public:
  Scene(Ctx ctx) : _ctx {ctx} {}
  Scene(Scene&&) = default;
  Scene(Scene const&) = default;
  virtual ~Scene() = default;
  Scene& operator=(Scene&&) = default;
  Scene& operator=(Scene const&) = default;
  virtual void on_winch(Size const& size) = 0;
  virtual bool on_input(Read::Ctx const& ctx) = 0;
  virtual bool on_update(Tick const delta) = 0;
  virtual bool on_render(Buffer& buf) = 0;

  Ctx _ctx;
  Pos _pos;
  Size _size;
}; // class Scene

using Scenes = OB::Ordered_map<std::string, std::shared_ptr<Scene>>;

class Background : public Scene {
public:
  Background(Ctx ctx);
  Background(Background&&) = default;
  Background(Background const&) = default;
  ~Background();
  Background& operator=(Background&&) = default;
  Background& operator=(Background const&) = default;
  void on_winch(Size const& size);
  bool on_input(Read::Ctx const& ctx);
  bool on_update(Tick const delta);
  bool on_render(Buffer& buf);

// private:
  Cell _cell {this, 0, Style{Style::Bit_24, Style::Null, Color{}, hex_to_rgb("031323")}, " "};
}; // class Background

class Board : public Scene {
public:
  Board(Ctx ctx);
  Board(Board&&) = default;
  Board(Board const&) = default;
  ~Board();
  Board& operator=(Board&&) = default;
  Board& operator=(Board const&) = default;
  void on_winch(Size const& size);
  bool on_input(Read::Ctx const& ctx);
  bool on_update(Tick const delta);
  bool on_render(Buffer& buf);

// private:
  Style _style {Style::Bit_24, Style::Null, hex_to_rgb("0b253d"), hex_to_rgb("031323")};
  Style _block1 {Style::Bit_24, Style::Null, Color(), hex_to_rgb("031323")};
  Style _block2 {Style::Bit_24, Style::Null, Color(), hex_to_rgb("0b253d")};
  bool _init {true};
}; // class Board

class Snake : public Scene {
public:
  Snake(Ctx ctx);
  Snake(Snake&&) = default;
  Snake(Snake const&) = default;
  ~Snake();
  Snake& operator=(Snake&&) = default;
  Snake& operator=(Snake const&) = default;
  void on_winch(Size const& size);
  bool on_input(Read::Ctx const& ctx);
  bool on_update(Tick const delta);
  bool on_render(Buffer& buf);

// private:

  struct {
    std::size_t idx {0};
    std::vector<Style> body {
      Style{Style::Bit_24, Style::Null, Color(), hex_to_rgb("43c7c3")},
      Style{Style::Bit_24, Style::Null, Color(), hex_to_rgb("3aaca8")}
    };
    Style head {Style::Bit_24, Style::Bold, hex_to_rgb("031323"), hex_to_rgb("4feae7")};
  } _style;

  struct {
    std::vector<std::string> head {"․․", "˙˙", " ⁚", "⁚ "};
    std::string body {"  "};
  } _text;

  struct Block {
    Pos pos;
    Style* style;
    std::string_view value;
  };

  std::deque<Block> _sprite;

  bool _init {true};
  enum Dir {Up, Down, Left, Right};
  Dir _dir_prev {Up};
  std::deque<Dir> _dir;
  enum State {Stopped, Moving, Fixed};
  State _state {Stopped};
  std::size_t _ext {2};
  Tick _delta {0ms};
  Tick _interval {300ms};
  std::unordered_map<char32_t, Xpr> _input;

  bool _hit_wall {false};
  bool _hit_wall_egg {true};
  bool _hit_wall_portal {false};
  bool _hit_body {true};

  enum Special {Normal, Rainbow, Flicker};
  int _special {Special::Normal};
  Tick _special_time {0ms};
  Tick _special_delta {0ms};
  Tick _special_interval {_interval / 2};
  OB::Color _color;

  std::size_t _state_eyes_idx {0};
  std::vector<std::pair<std::function<void(Cell&)>, Tick>> _state_eyes {{[](Cell&) {}, 3000ms}, {[](Cell& cell) {cell.style.attr = Style::Null;}, 100ms}, {[](Cell& cell) {cell.text = " ";}, 50ms}, {[](Cell& cell) {cell.style.attr = Style::Null;}, 100ms}};
  Tick _blink_delta {0ms};
  Tick _blink_interval {3000ms};

  // TODO move duplicate code to separate function
  void state_stopped();
  void state_moving();

  void rainbow(bool const val);
}; // class Snake

class Egg : public Scene {
public:
  Egg(Ctx ctx);
  Egg(Egg&&) = default;
  Egg(Egg const&) = default;
  ~Egg();
  Egg& operator=(Egg&&) = default;
  Egg& operator=(Egg const&) = default;
  void on_winch(Size const& size);
  bool on_input(Read::Ctx const& ctx);
  bool on_update(Tick const delta);
  bool on_render(Buffer& buf);

// private:

  struct Styles {
    enum Type {Normal, Rainbow};
    Type type {Normal};
    std::vector<OB::Color> color_map {{"#c8c213"}, {}};
    enum Dir {Darken, Lighten};
    Dir dir {Lighten};
    std::size_t idx {0};
    std::size_t max {20};
    OB::Color color {"#c8c213"};
    Style style {Style::Bit_24, Style::Null, Color(), Color()};
  } _style;
  std::string _text {"  "};
  bool _init {true};
  Tick _delta {0ms};
  Tick _interval {0ms};
  Tick _duration {2000ms};
  std::size_t count {0};

  void spawn();
}; // class Egg

class Prompt : public Scene {
public:
  Prompt(Ctx ctx);
  Prompt(Prompt&&) = default;
  Prompt(Prompt const&) = default;
  ~Prompt();
  Prompt& operator=(Prompt&&) = default;
  Prompt& operator=(Prompt const&) = default;
  void on_winch(Size const& size);
  bool on_input(Read::Ctx const& ctx);
  bool on_update(Tick const delta);
  bool on_render(Buffer& buf);

// private:
  Readline _readline;
  enum State {Clear, Typing, Display};
  State _state {Clear};
  struct {
    Style prompt {Style::Bit_24, Style::Null, hex_to_rgb("ff5500"), hex_to_rgb("031323")};
    Style text {Style::Bit_24, Style::Null, hex_to_rgb("f0f0f0"), hex_to_rgb("031323")};
    Style success {Style::Bit_24, Style::Null, hex_to_rgb("55ff00"), hex_to_rgb("031323")};
    Style error {Style::Bit_24, Style::Null, hex_to_rgb("ff0000"), hex_to_rgb("031323")};
  } _style;
  std::string _buf;
  bool _status {false};
  Tick _delta {0ms};
  Tick _interval {8000ms};

  void draw();
}; // class Prompt

class Status : public Scene {
public:
  Status(Ctx ctx);
  Status(Status&&) = default;
  Status(Status const&) = default;
  ~Status();
  Status& operator=(Status&&) = default;
  Status& operator=(Status const&) = default;
  void on_winch(Size const& size);
  bool on_input(Read::Ctx const& ctx);
  bool on_update(Tick const delta);
  bool on_render(Buffer& buf);

// private:
  struct {
    Style line {Style::Bit_24, Style::Null, Color(), hex_to_rgb("0b253d")};
    Style name {Style::Bit_24, Style::Bold, hex_to_rgb("031323"), hex_to_rgb("6735a4")};
    Style key {Style::Bit_24, Style::Bold, hex_to_rgb("8242cf"), hex_to_rgb("0b253d")};
    Style val {Style::Bit_24, Style::Null, hex_to_rgb("b140a2"), hex_to_rgb("0b253d")};
  } _style;
  struct {
    std::string line {" "};
    std::string name {" NYBLE 0.5.0 "};
    std::string fps {" FPS "};
    std::string fpsv;
    std::string frames;
    std::string time;
    std::string dir;
  } _text;
  struct {
    std::string up {"↑"};
    std::string down {"↓"};
    std::string left {"←"};
    std::string right {"→"};
  } _sym;

  void widget_fps();
  void widget_dir();
}; // class Status

class Root : public Scene {
public:
  Root(Ctx ctx);
  Root(Root&&) = default;
  Root(Root const&) = default;
  ~Root();
  Root& operator=(Root&&) = default;
  Root& operator=(Root const&) = default;
  void on_winch(Size const& size);
  bool on_input(Read::Ctx const& ctx);
  bool on_update(Tick const delta);
  bool on_render(Buffer& buf);

  bool on_read(Read::Null const& ctx);
  bool on_read(Read::Mouse const& ctx);
  bool on_read(Read::Key const& ctx);

// private:
  Buffer _buf;
  Scenes _scenes;
  bool _dirty {true};
  std::string _focus;
  std::unordered_map<char32_t, Xpr> _input;

  std::vector<std::pair<char32_t, Tick>> _code {{0, 0ms}, {0, 0ms}, {0, 0ms}, {0, 0ms}, {0, 0ms}, {0, 0ms}, {0, 0ms}, {0, 0ms}, {0, 0ms}, {0, 0ms}};
  std::chrono::time_point<Clock> _code_begin {(Clock::time_point::min)()};
}; // class Root

class Engine final {
public:
  Engine(OB::Parg& pg);
  Engine(Engine&&) = delete;
  Engine(Engine const&) = delete;
  ~Engine() = default;
  Engine& operator=(Engine&&) = delete;
  Engine& operator=(Engine const&) = delete;
  void run();

  std::shared_ptr<Scene> _root;
  Tick _time {0ms};
  std::size_t _frames {0};
  int _fps_actual {0};
  int _fps_dropped {0};
  std::shared_ptr<Env> _env {std::make_shared<Env>()};

// private:
  void start();
  void stop();
  void winch();
  void screen_init();
  void screen_deinit();
  void lang_init();
  void await_signal();
  void await_read();
  void await_tick();
  void on_tick();
  bool on_read(Read::Null& ctx);
  bool on_read(Read::Mouse& ctx);
  bool on_read(Read::Key& ctx);
  void write();

  OB::Parg& _pg;
  Belle::asio::io_context _io {1};
  Belle::Signal _sig {_io};
  Read _read {_io};
  Term::Mode _term_mode;
  Size _size;
  OB::Timer<std::chrono::steady_clock> _tick_timer;
  std::chrono::time_point<Clock> _tick_begin {(Clock::time_point::min)()};
  std::chrono::time_point<Clock> _tick_end {(Clock::time_point::min)()};
  int _fps {30};
  Tick _tick {static_cast<Tick>(1000000000 / _fps)};
  Timer _timer {_io};
  std::unordered_map<char32_t, Xpr> _input;

  std::size_t _bsize {0};
  Buffer _buf;
  Buffer _buf_prev;
  Style _style;
  std::string _line;
}; // class Engine

}; // namespace Nyble

#endif
Back to Top