bettola/client/src/game_state.cpp

114 lines
2.9 KiB
C++

#include <cstdio>
#include <memory>
#include <sstream>
#include "game_state.h"
#include "gfx/shape_renderer.h"
#include "gfx/txt_renderer.h"
#include "terminal.h"
#include "ui/desktop.h"
#include "ui/ui_window.h"
void GameState::_init_desktop(void) {
_desktop = std::make_unique<Desktop>();
auto term = std::make_unique<Terminal>(_network.get());
auto term_window = std::make_unique<UIWindow>("Terminal", 100, 100, 800, 500);
term_window->set_content(std::move(term));
_desktop->add_window(std::move(term_window));
}
GameState::GameState(void) : _current_screen(Screen::MAIN_MENU) {}
GameState::~GameState(void) = default;
void GameState::init(void) {
/* Create and connect the network client. */
_network = std::make_unique<ClientNetwork>();
/* TODO: For now, connect immediately, later, trigger by menu option. */
if(!_network->connect("127.0.0.1", 1337)) {
/* TODO: Handle connection failure. */
}
_current_screen = Screen::DESKTOP;
_init_desktop();
}
void GameState::handle_event(SDL_Event* event) {
switch(_current_screen) {
case Screen::MAIN_MENU:
/* TODO: */
break;
case Screen::BOOTING:
/* TODO: */
break;
case Screen::DESKTOP:
if(_desktop) {
_desktop->handle_event(event);
}
break;
}
}
void GameState::update(void) {
switch(_current_screen) {
case Screen::MAIN_MENU:
/* TODO: */
break;
case Screen::BOOTING:
/* TODO: */
break;
case Screen::DESKTOP:
std::string server_msg;
while(_network->poll_message(server_msg)) {
UIWindow* focused_window = _desktop->get_focused_window();
if(!focused_window)
continue;
Terminal* terminal = focused_window->get_content();
if(!terminal)
continue;
/* Server sends "output\nprompt", split them. */
size_t last_newline = server_msg.find_last_of('\n');
if(last_newline != std::string::npos) {
std::string prompt = server_msg.substr(last_newline+1);
terminal->set_prompt(prompt);
std::string output = server_msg.substr(0, last_newline);
if(!output.empty()) {
/* Split multiline output and push each line to history. */
std::stringstream ss(output);
std::string line;
while(std::getline(ss, line, '\n')) {
terminal->add_history(line);
}
}
} else {
terminal->add_history(server_msg);
}
}
if(_desktop) {
_desktop->update();
}
break;
}
}
void GameState::render(ShapeRenderer* shape_renderer, TextRenderer* txt_renderer,
int screen_height, bool show_cursor) {
switch(_current_screen) {
case Screen::MAIN_MENU:
/* TODO: */
break;
case Screen::BOOTING:
/* TODO: */
break;
case Screen::DESKTOP:
if(_desktop) {
_desktop->render(shape_renderer, txt_renderer, screen_height, show_cursor);
}
break;
}
}