summaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: a9b5d3bf3090408aaf6941e04336d3891b4fc14b (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
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
#include "CApi.h"
#include "Level.h"
#include "LuaApi.h"
#include <SFML/Graphics.hpp>
#include <filesystem>
#include <iostream>
#include <lua.hpp>

const char *DEFAULT_PROC = "include/defaults.lua";

std::shared_ptr<Level> lvl;

Scene scene;

int main(int argc, char **argv) {

  if (argc <= 1) {
    return -1;
  }

  std::string lvl_pfx = argv[1];

  std::filesystem::path mapFile{lvl_pfx + "/dng.map"};
  std::filesystem::path luaFile{lvl_pfx + "/proc.lua"};

  lvl = std::make_shared<Level>();
  scene = Scene::INTRO;

  lvl->loadLevelFromFile(mapFile.c_str());

  lua_State *L_lvl = luaL_newstate();
  luaL_openlibs(L_lvl);
  init_c_api(L_lvl);

  lua_State *L_default = luaL_newstate();
  luaL_openlibs(L_default);
  init_c_api(L_default);

  if (std::filesystem::exists(luaFile) &&
      luaL_dofile(L_default, DEFAULT_PROC) != LUA_OK) {
    std::cout << "Failed to load default proc" << std::endl;
    luaL_error(L_default, "Error: %s", lua_tostring(L_default, -1));
    return EXIT_FAILURE;
  }

  // Initialize to default
  LState *l_state = init_default(L_default);

  if (std::filesystem::exists(luaFile) &&
      luaL_dofile(L_lvl, luaFile.c_str()) == LUA_OK) {
    override_file_fns(L_lvl, l_state);
  } else if (std::filesystem::exists(luaFile)) {
    std::cout << "[C] No Good" << std::endl;
    luaL_error(L_lvl, "Error: %s\n", lua_tostring(L_lvl, -1));
    return EXIT_FAILURE;
  }

  bool quit = false;

  char in;

  do {
    if (scene == Scene::INTRO) {
      if (!lua_onintro(l_state->onintro)) {
        quit = true;
      }
      std::cin >> in;
      if (!lua_onkeypress(l_state->onkeypress, in)) {
        quit = true;
      }
    } else if (scene == Scene::LEVEL) {
      lvl->print();

      std::cin >> in;
      if (!lua_onkeypress(l_state->onkeypress, in)) {
        quit = true;
      }
      if (!lua_onupdate(l_state->onupdate)) {
        quit = true;
      }
    } else if (scene == Scene::WIN) {
      lvl->player.x = -1; // hide
      lvl->player.y = -1; // hide
      lvl->print();
      lua_onwin(l_state->onwin);
      quit = true;
    } else if (scene == Scene::LOSS) {
      lvl->player.x = -1; // hide
      lvl->player.y = -1; // hide
      lvl->print();
      lua_onloss(l_state->onloss);
      quit = true;
    }
    if (!quit && in == 'q') {
      quit = true;
    }
  } while (!quit);

  std::cout << "[C] Quit" << std::endl;

  return EXIT_SUCCESS;
}