aboutsummaryrefslogtreecommitdiffstats
path: root/src/game.cpp
blob: 964401040b7ff8110fd6fe52a00443b31f8d6424 (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
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "game.h"
#include "boxii/boxii.h"

#include <cstdio>
#include <cstring>
#include <sys/ioctl.h>

bool Game::m_running;

std::unordered_map<std::string, std::shared_ptr<Screen>> Game::m_screens;
std::deque<std::weak_ptr<Screen>> Game::m_order;
bool Game::m_dirty;

void
Game::init()
{
    m_running = true;
    m_dirty = false;

    Boxii::cursor(false);
    Boxii::echo(false);
    Boxii::canon(false);
    Boxii::sig(true);
}

void
Game::loop()
{
    while(m_running)
    {
        Boxii::refresh();
        update();
    }
}

void
Game::update()
{
    std::shared_ptr<Screen> locked = nullptr;
    while(!m_order.empty()){
        if((locked = m_order.back().lock())) break;
        m_order.pop_back();
    }

    if(locked == nullptr) {
        stop();
        return;
    }

    locked->update();
}

void 
Game::addScreen(const std::string &key, std::shared_ptr<Screen> value)
{
    m_screens.emplace(key, value);
}

bool 
Game::pushScreen(const std::string &key)
{
    auto it = m_screens.find(key);
    if(it != m_screens.end()){
        m_order.push_back(it->second);
        it->second->activate();
        return true;
    }
    return false;
}

bool
Game::popScreen()
{
    if(auto lock = m_order.back().lock()){
        lock->deactivate();
    }
    m_order.pop_back();
    m_dirty = true;
    return m_order.empty();
}

bool
Game::popUpto(const std::string &key)
{
    auto find = m_screens.find(key);
    if(find == m_screens.end()){
        return false;
    }

    while(!m_order.empty()){
        auto lock = m_order.back().lock();
        if(lock == nullptr){
            m_order.pop_back();
            continue;
        }

        if(lock == find->second) break;
        lock->deactivate();
        m_order.pop_back();
    }
    m_dirty = true;
    return true;
}

bool
Game::popUptoIncluding(const std::string &key)
{
    bool r = popUpto(key);
    if(!r) return r;

    auto lock = m_order.back().lock();
    if(lock != nullptr) lock->deactivate();
    m_order.pop_back();
    return true;
}