I now have a semi-functional GUI system that uses the ECS style to build gui elements rather than inheritance.

This commit is contained in:
Zed A. Shaw 2025-02-18 01:10:56 -05:00
parent 615599084a
commit 46de98e6f4
12 changed files with 213 additions and 146 deletions

View file

@ -4,62 +4,30 @@
namespace gui {
CombatUI::CombatUI(GameLevel level) :
$layout(RAY_VIEW_X, RAY_VIEW_HEIGHT,
RAY_VIEW_WIDTH, SCREEN_HEIGHT - RAY_VIEW_HEIGHT),
$level(level),
$font{FONT_FILE_NAME}
$level(level)
{
bool good = $layout.parse($grid);
dbc::check(good, "failed to parse combat layout");
$gui.position(RAY_VIEW_X, RAY_VIEW_HEIGHT, RAY_VIEW_WIDTH, SCREEN_HEIGHT - RAY_VIEW_HEIGHT);
$gui.layout(
"[*%(100,150)button_attack1 | *%(100,150)button_attack2 | *%(100,150)button_attack3 | *%(100,150)button_heal]"
"[ >.%(100,50)label_hp | *%.(200,50)bar_hp | _ ]");
render();
}
void CombatUI::render() {
$background.setPosition({float($layout.grid_x), float($layout.grid_y)});
$background.setSize({float($layout.grid_w), float($layout.grid_h)});
$background.setFillColor({0, 0, 0});
auto& world = $gui.world();
for(auto& [name, cell] : $layout.cells) {
if(name == "bar_hp") {
$meters.try_emplace(name, cell);
} else if(name == "label_hp") {
gui::Label label(cell, "hp:", $font);
$labels.emplace_back(cell, "hp:", $font);
} else if(name.starts_with("button_")) {
$buttons.try_emplace(name, cell, name, $font);
}
for(auto& [name, cell] : $gui.cells()) {
auto button = $gui.entity(name);
world.set<lel::Cell>(button, cell);
world.set<Rectangle>(button, {});
world.set<Clickable>(button, {100});
world.set<Textual>(button, {name});
}
$gui.init();
}
void CombatUI::draw(sf::RenderWindow& window) {
window.draw($background);
auto &player = $level.world->get_the<components::Player>();
auto &combat = $level.world->get<components::Combat>(player.entity);
float hp_now = float(combat.hp) / float(combat.max_hp);
auto& bar_hp = $meters.at("bar_hp");
bar_hp.set_percent(hp_now);
for(auto& [name, button] : $buttons) {
button.draw(window);
}
for(auto& [name, meter] : $meters) {
meter.draw(window);
}
for(auto& label : $labels) {
label.draw(window);
}
}
void CombatUI::click(int x, int y) {
if(auto name = $layout.hit(x, y)) {
if((*name).starts_with("button_")) {
auto& button = $buttons.at(*name);
button.shape.setFillColor({100, 0, 0});
}
}
$gui.render(window);
}
}