tooltip and more (#94)

* restore button

* fix arrow buttons

* status labels

* tooltip

* tooltip

* tooltip

* tooltip

* tooltip

* tooltip

* cleanup

* use font

* use font

* dialog help message

* move unit fix

* move unit fix

* move unit fix

* clippy

* fix capture

* move units without dialog

* move units without dialog

* move units without dialog

* unit tooltip

* unit tooltip

* unit tooltip

* icon

* unit tooltip

* let chain

* cleanup

* cleanup

* cleanup
This commit is contained in:
Gregor Zeitlinger 2025-01-01 17:43:32 +01:00 • committed by GitHub
commit bd11ecbbcb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 520 additions and 283 deletions

8
client/Cargo.lock generated
View file

@ -738,9 +738,9 @@ checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
[[package]]
name = "serde"
version = "1.0.216"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b9781016e935a97e8beecf0c933758c97a5520d32930e460142b4cd80c6338e"
checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70"
dependencies = [
"serde_derive",
]
@ -758,9 +758,9 @@ dependencies = [
[[package]]
name = "serde_derive"
version = "1.0.216"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e"
checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0"
dependencies = [
"proc-macro2",
"quote",

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

View file

@ -1,6 +1,8 @@
use crate::client::Features;
use crate::resource_ui::ResourceType;
use macroquad::prelude::{load_texture, load_ttf_font, Color, Image, ImageFormat, RectOffset};
use macroquad::prelude::{
load_texture, load_ttf_font, Color, Font, Image, ImageFormat, RectOffset,
};
use macroquad::texture::Texture2D;
use macroquad::ui::{root_ui, Skin};
use server::map::Terrain;
@ -11,6 +13,7 @@ pub struct Assets {
pub terrain: HashMap<Terrain, Texture2D>,
pub units: HashMap<UnitType, Texture2D>,
pub skin: Skin,
pub font: Font,
// mood icons
pub angry: Texture2D,
@ -35,6 +38,7 @@ pub struct Assets {
pub right: Texture2D,
pub victory_points: Texture2D,
pub active_player: Texture2D,
pub restore_menu: Texture2D,
// Admin
pub import: Texture2D,
@ -47,10 +51,12 @@ pub struct Assets {
impl Assets {
pub async fn new(features: &Features) -> Self {
let happy = load_png(include_bytes!("../assets/happy-emoji-svgrepo-com.png"));
let font_name = features.get_asset("HTOWERT.TTF");
Self {
font: load_ttf_font(&font_name).await.unwrap(), // can't share font - causes panic
terrain: Self::terrain(features).await,
units: HashMap::new(),
skin: Self::skin(features).await,
skin: Self::skin(&load_ttf_font(&font_name).await.unwrap()),
// mood icons
angry: load_png(include_bytes!("../assets/angry-face-svgrepo-com.png")),
@ -93,7 +99,7 @@ impl Assets {
advances: load_png(include_bytes!("../assets/lab-svgrepo-com.png")),
end_turn: load_png(include_bytes!("../assets/hour-glass-svgrepo-com.png")),
log: load_png(include_bytes!("../assets/scroll-svgrepo-com.png")),
movement: load_png(include_bytes!("../assets/walk-svgrepo-com.png")),
movement: load_png(include_bytes!("../assets/route-start-svgrepo-com.png")),
redo: load_png(include_bytes!("../assets/redo-svgrepo-com.png")),
reset: load_png(include_bytes!("../assets/reset-svgrepo-com.png")),
undo: load_png(include_bytes!("../assets/undo-svgrepo-com.png")),
@ -113,6 +119,7 @@ impl Assets {
)),
victory_points: load_png(include_bytes!("../assets/trophy-cup-svgrepo-com.png")),
active_player: load_png(include_bytes!("../assets/triangle-svgrepo-com.png")),
restore_menu: load_png(include_bytes!("../assets/restore-svgrepo-com.png")),
// Admin
import: load_png(include_bytes!("../assets/import-3-svgrepo-com.png")),
@ -136,10 +143,7 @@ impl Assets {
map
}
async fn skin(features: &Features) -> Skin {
let font = load_ttf_font(&features.get_asset("HTOWERT.TTF"))
.await
.unwrap();
fn skin(font: &Font) -> Skin {
let image =
Image::from_file_with_format(include_bytes!("../assets/button_background.png"), None)
.unwrap();
@ -148,7 +152,7 @@ impl Assets {
.background(image.clone())
.background_margin(RectOffset::new(37.0, 37.0, 5.0, 5.0))
.margin(RectOffset::new(10.0, 10.0, 0.0, 0.0))
.with_font(&font)
.with_font(font)
.unwrap()
.text_color(Color::from_rgba(180, 180, 120, 255))
.font_size(20)
@ -186,7 +190,7 @@ impl Assets {
)
.unwrap(),
)
.with_font(&font)
.with_font(font)
.unwrap()
.text_color(Color::from_rgba(180, 180, 100, 255))
.font_size(20)
@ -195,7 +199,7 @@ impl Assets {
let editbox_style = root_ui()
.style_builder()
.background_margin(RectOffset::new(0., 0., 0., 0.))
.with_font(&font)
.with_font(font)
.unwrap()
.text_color(Color::from_rgba(120, 120, 120, 255))
.color_selected(Color::from_rgba(190, 190, 190, 255))

View file

@ -18,7 +18,9 @@ use crate::log_ui::show_log;
use crate::map_ui::{draw_map, show_tile_menu};
use crate::player_ui::{player_select, show_global_controls, show_top_center, show_top_left};
use crate::status_phase_ui::raze_city_confirm_dialog;
use crate::{combat_ui, dialog_ui, influence_ui, move_ui, recruit_unit_ui, status_phase_ui};
use crate::{
combat_ui, dialog_ui, influence_ui, move_ui, recruit_unit_ui, status_phase_ui, tooltip,
};
pub async fn init(features: &Features) -> State {
let state = State::new(features).await;
@ -47,6 +49,8 @@ pub fn render_and_update(
}
fn render(game: &Game, state: &mut State, features: &Features) -> StateUpdate {
tooltip::update(state);
clear_background(WHITE);
let player = &state.shown_player(game);
@ -58,19 +62,13 @@ fn render(game: &Game, state: &mut State, features: &Features) -> StateUpdate {
offset: state.offset,
..Default::default()
};
set_camera(&state.camera);
if matches!(state.active_dialog, ActiveDialog::None) || state.active_dialog.is_map_dialog() {
draw_map(game, state);
}
draw_map(game, state);
let mut updates = StateUpdates::new();
show_top_left(game, player);
show_top_left(game, player, state);
show_top_center(game, player, state);
updates.add(player_select(game, player, state));
updates.add(show_global_controls(game, state, features));
if !matches!(state.active_dialog, ActiveDialog::None) || state.active_dialog.is_map_dialog() {
updates.clear();
}
if player.can_control {
if let Some(u) = &state.pending_update {
@ -80,7 +78,7 @@ fn render(game: &Game, state: &mut State, features: &Features) -> StateUpdate {
}
updates.add(match &state.active_dialog {
ActiveDialog::None => StateUpdate::None,
ActiveDialog::None | ActiveDialog::MoveUnits(_) => StateUpdate::None,
ActiveDialog::Log => show_log(game, player),
ActiveDialog::TileMenu(p) => show_tile_menu(game, *p, player),
ActiveDialog::WaitingForUpdate => {
@ -95,7 +93,6 @@ fn render(game: &Game, state: &mut State, features: &Features) -> StateUpdate {
ActiveDialog::CollectResources(c) => collect_resources_dialog(game, c, player),
ActiveDialog::RecruitUnitSelection(s) => recruit_unit_ui::select_dialog(game, s, player),
ActiveDialog::ReplaceUnits(r) => recruit_unit_ui::replace_dialog(game, r, player),
ActiveDialog::MoveUnits(s) => move_ui::move_units_dialog(game, s, player),
ActiveDialog::CulturalInfluenceResolution(c) => {
influence_ui::cultural_influence_resolution_dialog(c, player)
}
@ -131,16 +128,15 @@ pub fn try_click(game: &Game, state: &State, player: &ShownPlayer) -> StateUpdat
return StateUpdate::None;
}
let (x, y) = mouse_position();
let pos = Position::from_coordinate(pixel_to_coordinate(
state.camera.screen_to_world(vec2(x, y)),
));
let mouse_pos = state.camera.screen_to_world(vec2(x, y));
let pos = Position::from_coordinate(pixel_to_coordinate(mouse_pos));
if !game.map.tiles.contains_key(&pos) {
return StateUpdate::None;
}
if player.can_control {
match &state.active_dialog {
ActiveDialog::MoveUnits(s) => move_ui::click(pos, s),
ActiveDialog::MoveUnits(s) => move_ui::click(pos, s, mouse_pos, game),
ActiveDialog::ReplaceUnits(r) => recruit_unit_ui::click_replace(pos, r),
ActiveDialog::RemoveCasualties(_s) => StateUpdate::None,
ActiveDialog::CollectResources(col) => click_collect_option(col, pos),

View file

@ -14,6 +14,7 @@ use crate::collect_ui::CollectResources;
use crate::combat_ui::RemoveCasualtiesSelection;
use crate::construct_ui::ConstructionPayment;
use crate::happiness_ui::IncreaseHappiness;
use crate::layout_ui::FONT_SIZE;
use crate::move_ui::MoveSelection;
use crate::recruit_unit_ui::{RecruitAmount, RecruitSelection};
use crate::status_phase_ui::ChooseAdditionalAdvances;
@ -81,6 +82,45 @@ impl ActiveDialog {
}
}
#[must_use]
pub fn help_message(&self) -> Option<&str> {
match self {
ActiveDialog::None => None,
ActiveDialog::TileMenu(_) => Some("Click on a tile to see options"),
ActiveDialog::Log => Some("Click on a log entry to see details"),
ActiveDialog::IncreaseHappiness(_) => Some("Click on a city to increase happiness"),
ActiveDialog::AdvanceMenu => Some("Click on an advance to see options"),
ActiveDialog::AdvancePayment(_) => Some("Click on an advance to pay"),
ActiveDialog::ConstructionPayment(_) => Some("Click on a city to pay for construction"),
ActiveDialog::CollectResources(_) => Some("Click on a city to collect resources"),
ActiveDialog::RecruitUnitSelection(_) => Some("Click on a unit to recruit"),
ActiveDialog::ReplaceUnits(_) => Some("Click on a unit to replace"),
ActiveDialog::MoveUnits(m) => {
if m.start.is_some() {
Some("Click on a highlighted tile to move units")
} else {
Some("Click on a unit to move")
}
}
ActiveDialog::CulturalInfluenceResolution(_) => {
Some("Click on a city to resolve cultural influence")
}
ActiveDialog::FreeAdvance => Some("Click on an advance to take it for free"),
ActiveDialog::RazeSize1City => Some("Click on a city to raze it"),
ActiveDialog::CompleteObjectives => Some("Click on an objective to complete it"),
ActiveDialog::DetermineFirstPlayer => {
Some("Click on a player to determine first player")
}
ActiveDialog::ChangeGovernmentType => Some("Click on a government type to change"),
ActiveDialog::ChooseAdditionalAdvances(_) => Some("Click on an advance to choose it"),
ActiveDialog::PlayActionCard => Some("Click on an action card to play it"),
ActiveDialog::PlaceSettler => Some("Click on a tile to place a settler"),
ActiveDialog::Retreat => Some("Click on a unit to retreat"),
ActiveDialog::RemoveCasualties(_) => Some("Click on a unit to remove it"),
ActiveDialog::WaitingForUpdate => panic!("no help message for dialog"),
}
}
#[must_use]
pub fn is_map_dialog(&self) -> bool {
matches!(
@ -93,6 +133,14 @@ impl ActiveDialog {
| ActiveDialog::RazeSize1City
)
}
#[must_use]
pub fn can_restore(&self) -> bool {
!matches!(
self,
ActiveDialog::MoveUnits(_) | ActiveDialog::ReplaceUnits(_) | ActiveDialog::None
)
}
}
pub struct PendingUpdate {
@ -206,10 +254,6 @@ impl StateUpdates {
}
}
pub fn clear(&mut self) {
self.updates.clear();
}
pub fn result(self) -> StateUpdate {
self.updates
.into_iter()
@ -235,6 +279,11 @@ impl ShownPlayer {
}
}
pub struct MousePosition {
pub position: Vec2,
pub time: f64,
}
pub struct State {
pub assets: Assets,
pub control_player: Option<usize>,
@ -245,6 +294,7 @@ pub struct State {
pub zoom: f32,
pub offset: Vec2,
pub screen_size: Vec2,
pub mouse_positions: Vec<MousePosition>,
}
pub const ZOOM: f32 = 0.001;
@ -264,6 +314,7 @@ impl State {
zoom: ZOOM,
offset: OFFSET,
screen_size: vec2(0., 0.),
mouse_positions: vec![],
}
}
@ -354,7 +405,11 @@ impl State {
}
fn close_dialog(&mut self) {
self.active_dialog = ActiveDialog::None;
if self.active_dialog.can_restore() {
self.active_dialog = ActiveDialog::None;
} else if let ActiveDialog::ReplaceUnits(r) = &mut self.active_dialog {
r.clear();
}
}
pub fn update_from_game(&mut self, game: &Game) -> GameSyncRequest {
@ -415,6 +470,25 @@ impl State {
}
}
#[must_use]
pub fn measure_text(&self, text: &str) -> TextDimensions {
measure_text(text, Some(&self.assets.font), FONT_SIZE, 1.0)
}
pub fn draw_text(&self, text: &str, x: f32, y: f32) {
draw_text_ex(
text,
x,
y,
TextParams {
font: Some(&self.assets.font),
font_size: FONT_SIZE,
color: BLACK,
..Default::default()
},
);
}
// fn execute_status_phase(&mut self, game: &Game, action: StatusPhaseAction) -> ActiveDialog {
// self.update(game, StateUpdate::status_phase(action));
// ActiveDialog::None

View file

@ -1,13 +1,15 @@
use crate::client_state::{ShownPlayer, State};
use crate::tooltip;
use macroquad::color::WHITE;
use macroquad::math::{vec2, Vec2};
use macroquad::math::{f32, vec2, Vec2};
use macroquad::prelude::*;
use macroquad::ui::root_ui;
pub const ICON_SIZE: f32 = 30.;
pub const MARGIN: f32 = 10.;
pub const FONT_SIZE: u16 = 20;
pub fn icon_offset(i: i8) -> f32 {
f32::from(i) * 1.4 * ICON_SIZE
}
@ -16,52 +18,55 @@ pub fn icon_pos(x: i8, y: i8) -> Vec2 {
vec2(icon_offset(x), icon_offset(y))
}
pub fn top_left_label(p: Vec2, label: &str) {
root_ui().label(p + vec2(-40., 0.), label);
pub fn top_center_texture(state: &State, texture: &Texture2D, p: Vec2, tooltip: &str) -> bool {
relative_texture(
state,
texture,
vec2(state.screen_size.x / 2., MARGIN),
p,
tooltip,
)
}
pub fn top_center_label(player: &ShownPlayer, p: Vec2, label: &str) {
root_ui().label(vec2(player.screen_size.x / 2.0, 0.) + p, label);
}
pub fn top_center_texture(state: &State, texture: &Texture2D, p: Vec2) -> bool {
relative_texture(state, texture, vec2(state.screen_size.x / 2., MARGIN), p)
}
pub fn top_right_texture(state: &State, texture: &Texture2D, p: Vec2) -> bool {
pub fn top_right_texture(state: &State, texture: &Texture2D, p: Vec2, tooltip: &str) -> bool {
relative_texture(
state,
texture,
vec2(state.screen_size.x - MARGIN, MARGIN),
p,
tooltip,
)
}
pub fn bottom_left_texture(state: &State, texture: &Texture2D, p: Vec2) -> bool {
pub fn bottom_left_texture(state: &State, texture: &Texture2D, p: Vec2, tooltip: &str) -> bool {
relative_texture(
state,
texture,
vec2(MARGIN, state.screen_size.y - MARGIN),
p,
tooltip,
)
}
pub fn bottom_left_button(player: &ShownPlayer, p: Vec2, label: &str) -> bool {
root_ui().button(vec2(MARGIN, player.screen_size.y - MARGIN) + p, label)
}
pub fn bottom_right_texture(state: &State, texture: &Texture2D, p: Vec2) -> bool {
pub fn bottom_right_texture(state: &State, texture: &Texture2D, p: Vec2, tooltip: &str) -> bool {
relative_texture(
state,
texture,
vec2(state.screen_size.x - MARGIN, state.screen_size.y - MARGIN),
p,
tooltip,
)
}
fn relative_texture(state: &State, texture: &Texture2D, anchor: Vec2, offset: Vec2) -> bool {
fn relative_texture(
state: &State,
texture: &Texture2D,
anchor: Vec2,
offset: Vec2,
tooltip: &str,
) -> bool {
let origin = anchor + offset;
set_default_camera();
draw_texture_ex(
texture,
origin.x,
@ -73,9 +78,9 @@ fn relative_texture(state: &State, texture: &Texture2D, anchor: Vec2, offset: Ve
},
);
let pressed = left_mouse_button(Rect::new(origin.x, origin.y, ICON_SIZE, ICON_SIZE));
set_camera(&state.camera);
pressed
let rect = Rect::new(origin.x, origin.y, ICON_SIZE, ICON_SIZE);
tooltip::show_tooltip_for_rect(state, tooltip, rect);
left_mouse_button(rect)
}
pub fn left_mouse_button(rect: Rect) -> bool {

View file

@ -30,4 +30,5 @@ mod recruit_unit_ui;
mod resource_ui;
mod select_ui;
mod status_phase_ui;
mod tooltip;
mod unit_ui;

View file

@ -6,6 +6,7 @@ use std::ops::{Add, Mul, Sub};
use server::action::Action;
use server::combat::Combat;
use server::consts::ARMY_MOVEMENT_REQUIRED_ADVANCE;
use server::game::{Game, GameState};
use server::map::Terrain;
use server::playing_actions::PlayingAction;
@ -36,6 +37,7 @@ fn terrain_name(t: &Terrain) -> &'static str {
}
pub fn draw_map(game: &Game, state: &State) {
set_camera(&state.camera);
for (pos, t) in &game.map.tiles {
let (base, exhausted) = match t {
Terrain::Exhausted(e) => (e.as_ref(), true),
@ -60,8 +62,10 @@ pub fn draw_map(game: &Game, state: &State) {
draw_city(p, city, state);
}
}
unit_ui::draw_units(game);
unit_ui::draw_units(game, state, false);
unit_ui::draw_units(game, state, true);
}
set_default_camera();
}
fn alpha(game: &Game, state: &State, pos: Position) -> f32 {
@ -144,8 +148,11 @@ pub fn show_generic_tile_menu(
|ui| {
let units: Vec<(&Unit, String)> = unit_ui::units_on_tile(game, position)
.map(|(p, u)| {
let army_move = game
.get_player(p)
.has_advance(ARMY_MOVEMENT_REQUIRED_ADVANCE);
let unit = game.get_player(p).get_unit(u).unwrap();
(unit, unit_ui::label(unit))
(unit, unit_ui::unit_label(unit, army_move))
})
.collect();

View file

@ -1,61 +1,14 @@
use macroquad::math::u32;
use macroquad::math::{u32, Vec2};
use crate::select_ui::{ConfirmSelection, SelectionConfirm};
use server::action::Action;
use server::game::Game;
use server::game::GameState::Movement;
use server::position::Position;
use server::unit::{MovementAction, Unit};
use server::unit::MovementAction;
use crate::client_state::{ActiveDialog, ShownPlayer, StateUpdate};
use crate::layout_ui::ok_pos;
use crate::unit_ui;
use crate::unit_ui::UnitSelection;
pub fn move_units_dialog(game: &Game, sel: &MoveSelection, player: &ShownPlayer) -> StateUpdate {
unit_ui::unit_selection_dialog::<MoveSelection>(
game,
player,
"Move Units",
sel,
|new| update_possible_destinations(game, new.clone()),
|_new| StateUpdate::None,
|ui| {
let Movement {
movement_actions_left,
moved_units: _,
} = game.state
else {
panic!("game is not in movement")
};
if ui.button(ok_pos(player), "End Move Units") {
StateUpdate::execute_with_warning(
Action::Movement(MovementAction::Stop),
if movement_actions_left > 0 {
vec![(format!("{movement_actions_left} movement actions left"))]
} else {
vec![]
},
)
} else {
StateUpdate::None
}
},
)
}
fn update_possible_destinations(game: &Game, mut sel: MoveSelection) -> StateUpdate {
if sel.units.is_empty() {
sel.destinations.clear();
} else if let Some(start) = sel.start {
sel.destinations = possible_destinations(game, start, sel.player_index, &sel.units);
} else {
sel.destinations.clear();
}
StateUpdate::SetDialog(ActiveDialog::MoveUnits(sel))
}
use crate::client_state::{ActiveDialog, StateUpdate};
use crate::unit_ui::unit_at_pos;
fn possible_destinations(
game: &Game,
@ -93,19 +46,36 @@ fn possible_destinations(
}
}
pub fn click(pos: Position, s: &MoveSelection) -> StateUpdate {
let mut new = s.clone();
if s.destinations.is_empty() {
new.start = Some(pos);
StateUpdate::SetDialog(ActiveDialog::MoveUnits(new))
} else if s.destinations.contains(&pos) {
pub fn click(pos: Position, s: &MoveSelection, mouse_pos: Vec2, game: &Game) -> StateUpdate {
if s.destinations.contains(&pos) {
let units = s.units.clone();
StateUpdate::execute(Action::Movement(MovementAction::Move {
units,
destination: pos,
}))
} else {
} else if s.start.is_some_and(|p| p != pos) {
// first need to deselect units
StateUpdate::None
} else {
let mut new = s.clone();
let p = game.get_player(s.player_index);
let unit = unit_at_pos(pos, mouse_pos, p);
unit.map_or(StateUpdate::None, |unit_id| {
new.start = Some(pos);
if new.units.contains(&unit_id) {
// deselect unit
new.units.retain(|&id| id != unit_id);
} else {
new.units.push(unit_id);
}
if new.units.is_empty() {
new.destinations.clear();
new.start = None;
} else {
new.destinations = possible_destinations(game, pos, new.player_index, &new.units);
}
StateUpdate::SetDialog(ActiveDialog::MoveUnits(new))
})
}
}
@ -128,23 +98,6 @@ impl MoveSelection {
}
}
impl UnitSelection for MoveSelection {
fn selected_units(&self) -> &[u32] {
&self.units
}
fn selected_units_mut(&mut self) -> &mut Vec<u32> {
&mut self.units
}
fn can_select(&self, game: &Game, unit: &Unit) -> bool {
!possible_destinations(game, unit.position, self.player_index, &vec![unit.id]).is_empty()
}
fn current_tile(&self) -> Option<Position> {
self.start
}
}
impl ConfirmSelection for MoveSelection {
fn confirm(&self, _game: &Game) -> SelectionConfirm {
SelectionConfirm::NoConfirm

View file

@ -2,10 +2,10 @@ use crate::client::Features;
use crate::client_state::{ActiveDialog, ShownPlayer, State, StateUpdate, OFFSET, ZOOM};
use crate::happiness_ui::start_increase_happiness;
use crate::layout_ui::{
bottom_left_button, bottom_left_texture, bottom_right_texture, icon_pos, left_mouse_button,
top_center_label, top_center_texture, top_left_label, top_right_texture, ICON_SIZE,
bottom_left_texture, bottom_right_texture, icon_pos, left_mouse_button, top_center_texture,
top_right_texture, ICON_SIZE,
};
use crate::resource_ui::ResourceType;
use crate::resource_ui::{resource_name, ResourceType};
use macroquad::math::{u32, vec2};
use macroquad::prelude::*;
use macroquad::ui::{root_ui, Ui};
@ -14,6 +14,7 @@ use server::game::{Game, GameState};
use server::player::Player;
use server::playing_actions::PlayingAction;
use server::resource_pile::ResourcePile;
use server::unit::MovementAction;
pub fn player_select(game: &Game, player: &ShownPlayer, state: &State) -> StateUpdate {
let i = game
@ -32,7 +33,6 @@ pub fn player_select(game: &Game, player: &ShownPlayer, state: &State) -> StateU
let pos = vec2(player.screen_size.x, player.screen_size.y / 2.0) + vec2(-20., y);
let color = player_color(pl.index);
set_default_camera();
let w = if shown { ICON_SIZE + 10. } else { ICON_SIZE };
let x = pos.x - w + ICON_SIZE;
@ -40,7 +40,7 @@ pub fn player_select(game: &Game, player: &ShownPlayer, state: &State) -> StateU
draw_rectangle_lines(x, pos.y, w, ICON_SIZE, 2.0, BLACK);
let text = format!("{}", pl.victory_points());
draw_text(&text, pos.x + 5., pos.y + 20., 20.0, BLACK);
state.draw_text(&text, pos.x + 5., pos.y + 20.);
let active = game.active_player();
if active == pl.index {
@ -56,8 +56,6 @@ pub fn player_select(game: &Game, player: &ShownPlayer, state: &State) -> StateU
);
}
set_camera(&state.camera);
if !shown && left_mouse_button(Rect::new(x, pos.y, w, ICON_SIZE)) {
return StateUpdate::SetShownPlayer(pl.index);
}
@ -81,6 +79,7 @@ pub fn resource_label(
label,
&state.assets.resources[&resource_type],
p,
resource_name(resource_type),
);
}
@ -90,48 +89,35 @@ pub fn top_icon_with_label(
label: &str,
texture: &Texture2D,
p: Vec2,
tooltip: &str,
) {
top_center_texture(state, texture, p);
top_center_label(player, p + vec2(-30. - label.len() as f32 * 5., 40.), label);
let dimensions = state.measure_text(label);
let x = (ICON_SIZE - dimensions.width) / 2.0;
state.draw_text(
label,
player.screen_size.x / 2.0 + p.x + x,
p.y + ICON_SIZE + 30.,
);
top_center_texture(state, texture, p, tooltip);
}
pub fn show_top_center(game: &Game, player: &ShownPlayer, state: &State) {
let p = game.get_player(player.index);
resource_label(
top_icon_with_label(
player,
state,
&resource_ui(p, |r| r.food),
ResourceType::Food,
icon_pos(-4, 0),
&format!("{}", &p.victory_points()),
&state.assets.victory_points,
icon_pos(3, 0),
"Victory Points",
);
resource_label(
player,
state,
&resource_ui(p, |r| r.wood),
ResourceType::Wood,
icon_pos(-3, 0),
);
resource_label(
player,
state,
&resource_ui(p, |r| r.ore),
ResourceType::Ore,
icon_pos(-2, 0),
);
resource_label(
player,
state,
&resource_ui(p, |r| r.ideas),
ResourceType::Ideas,
icon_pos(-1, 0),
);
resource_label(
player,
state,
&resource_ui(p, |r| r.gold as u32),
ResourceType::Gold,
icon_pos(0, 0),
&resource_ui(p, |r| r.culture_tokens),
ResourceType::CultureTokens,
icon_pos(2, 0),
);
resource_label(
player,
@ -143,46 +129,66 @@ pub fn show_top_center(game: &Game, player: &ShownPlayer, state: &State) {
resource_label(
player,
state,
&resource_ui(p, |r| r.culture_tokens),
ResourceType::CultureTokens,
icon_pos(2, 0),
&resource_ui(p, |r| r.gold as u32),
ResourceType::Gold,
icon_pos(0, 0),
);
top_icon_with_label(
resource_label(
player,
state,
&format!("{}", &p.victory_points()),
&state.assets.victory_points,
icon_pos(3, 0),
&resource_ui(p, |r| r.ideas),
ResourceType::Ideas,
icon_pos(-1, 0),
);
resource_label(
player,
state,
&resource_ui(p, |r| r.ore),
ResourceType::Ore,
icon_pos(-2, 0),
);
resource_label(
player,
state,
&resource_ui(p, |r| r.wood),
ResourceType::Wood,
icon_pos(-3, 0),
);
resource_label(
player,
state,
&resource_ui(p, |r| r.food),
ResourceType::Food,
icon_pos(-4, 0),
);
show_wonders(game, player, &mut root_ui());
}
pub fn show_top_left(game: &Game, player: &ShownPlayer) {
pub fn show_top_left(game: &Game, player: &ShownPlayer, state: &State) {
let mut y = 0.;
let mut label = |label: String| {
let p = vec2(0., y * 25.);
let mut label = |label: &str| {
let p = vec2(10., y * 25. + 20.);
y += 1.;
top_left_label(p, &label);
state.draw_text(label, p.x, p.y);
};
match &game.state {
GameState::Finished => label("Finished".to_string()),
_ => label(format!("Age {}", game.age)),
GameState::Finished => label("Finished"),
_ => label(&format!("Age {}", game.age)),
}
match &game.state {
GameState::StatusPhase(ref p) => label(format!("Status Phase: {p:?}")),
_ => label(format!("Round {}", game.round)),
GameState::StatusPhase(ref p) => label(&format!("Status Phase: {p:?}")),
_ => label(&format!("Round {}", game.round)),
}
let p = game.get_player(player.index);
label(p.get_name());
label(&p.get_name());
label(format!("Civ {}", p.civilization.name));
label(&format!("Civ {}", p.civilization.name));
label(format!(
label(&format!(
"Leader {}",
if let Some(l) = &p.active_leader {
&l.name
@ -192,26 +198,37 @@ pub fn show_top_left(game: &Game, player: &ShownPlayer) {
));
if game.current_player_index == p.index {
label("Your turn".to_string());
match &game.state {
GameState::StatusPhase(_) | GameState::Finished => {}
_ => label(format!("Actions {}", game.actions_left)),
_ => label(&format!("{} actions left", game.actions_left)),
}
match &game.state {
GameState::Movement { .. } => label("Movement".to_string()),
GameState::Movement {
movement_actions_left,
..
} => label(&format!("Move units: {movement_actions_left} moves left")),
GameState::CulturalInfluenceResolution(_) => {
label("Cultural Influence Resolution".to_string());
label("Cultural Influence Resolution");
}
GameState::Combat(c) => label(format!("Combat Round {} Phase {:?}", c.round, c.phase)),
GameState::PlaceSettler { .. } => label("Place Settler".to_string()),
GameState::Combat(c) => label(&format!(
"Combat Round {} Phase {:?}{}",
c.round,
c.phase,
moves_left(&game.state)
.map(|m| format!(", {m} moves left"))
.unwrap_or_default()
)),
GameState::PlaceSettler {
player_index: _,
movement_actions_left,
..
} => label(&format!(
"Place Settler: {movement_actions_left} moves left"
)),
_ => {}
}
if let Some(m) = moves_left(&game.state) {
label(format!("Moves left {m}"));
}
state.active_dialog.help_message().map(label);
}
}
@ -221,9 +238,9 @@ fn moves_left(state: &GameState) -> Option<u32> {
GameState::Movement {
movement_actions_left,
..
} => Some(*movement_actions_left),
GameState::PlaceSettler {
player_index: _player_index,
}
| GameState::PlaceSettler {
player_index: _,
movement_actions_left,
..
} => Some(*movement_actions_left),
@ -263,87 +280,138 @@ pub fn show_global_controls(game: &Game, state: &mut State, features: &Features)
let player = &state.shown_player(game);
let assets = &state.assets;
if bottom_left_texture(state, &assets.zoom_in, icon_pos(1, -1)) {
state.zoom *= 1.1;
return StateUpdate::None;
if let Some(tooltip) = can_end_move(game) {
if player.can_control
&& bottom_right_texture(state, &assets.end_turn, icon_pos(-4, -1), tooltip)
{
return end_move(game);
}
}
if bottom_left_texture(state, &assets.zoom_out, icon_pos(0, -1)) {
state.zoom /= 1.1;
return StateUpdate::None;
if game.can_redo() && bottom_right_texture(state, &assets.redo, icon_pos(-5, -1), "Redo") {
return StateUpdate::Execute(Action::Redo);
}
if bottom_left_texture(state, &assets.reset, icon_pos(2, -1)) {
state.zoom = ZOOM;
state.offset = OFFSET;
return StateUpdate::None;
if game.can_undo() && bottom_right_texture(state, &assets.undo, icon_pos(-6, -1), "Undo") {
return StateUpdate::Execute(Action::Undo);
}
if bottom_left_texture(state, &assets.up, icon_pos(4, -2)) {
state.offset += vec2(0., 0.1);
return StateUpdate::None;
let d = state.game_state_dialog(game, &ActiveDialog::None);
if d.can_restore()
&& d.title() != state.active_dialog.title()
&& bottom_right_texture(
state,
&assets.restore_menu,
icon_pos(-7, -1),
format!("Restore {}", d.title()).as_str(),
)
{
return StateUpdate::OpenDialog(d);
}
if bottom_left_texture(state, &assets.down, icon_pos(4, -1)) {
if player.can_play_action
&& bottom_left_texture(state, &assets.movement, icon_pos(0, -3), "Move units")
{
return StateUpdate::execute(Action::Playing(PlayingAction::MoveUnits));
}
if player.can_play_action
&& bottom_left_texture(state, &assets.happy, icon_pos(0, -2), "Increase happiness")
{
return start_increase_happiness(game, player);
}
if top_right_texture(state, &assets.log, icon_pos(-1, 0), "Show log") {
return StateUpdate::OpenDialog(ActiveDialog::Log);
};
if top_right_texture(
state,
&assets.advances,
icon_pos(-2, 0),
"Choose or show advances",
) {
return StateUpdate::OpenDialog(ActiveDialog::AdvanceMenu);
};
if features.import_export {
if bottom_right_texture(state, &assets.export, icon_pos(-1, -3), "Export") {
return StateUpdate::Export;
};
if bottom_right_texture(state, &assets.import, icon_pos(-2, -3), "Import") {
return StateUpdate::Import;
};
}
if bottom_left_texture(state, &assets.up, icon_pos(4, -2), "Move up") {
state.offset += vec2(0., -0.1);
return StateUpdate::None;
}
if bottom_left_texture(state, &assets.left, icon_pos(3, -1)) {
if bottom_left_texture(state, &assets.right, icon_pos(5, -1), "Move right") {
state.offset += vec2(-0.1, 0.);
return StateUpdate::None;
}
if bottom_left_texture(state, &assets.right, icon_pos(5, -1)) {
if bottom_left_texture(state, &assets.down, icon_pos(4, -1), "Move down") {
state.offset += vec2(0., 0.1);
return StateUpdate::None;
}
if bottom_left_texture(state, &assets.left, icon_pos(3, -1), "Move left") {
state.offset += vec2(0.1, 0.);
return StateUpdate::None;
}
if game.can_undo() && bottom_right_texture(state, &assets.undo, icon_pos(-6, -1)) {
return StateUpdate::Execute(Action::Undo);
if bottom_left_texture(
state,
&assets.reset,
icon_pos(2, -1),
"Reset zoom and offset",
) {
state.zoom = ZOOM;
state.offset = OFFSET;
return StateUpdate::None;
}
if game.can_redo() && bottom_right_texture(state, &assets.redo, icon_pos(-5, -1)) {
return StateUpdate::Execute(Action::Redo);
if bottom_left_texture(state, &assets.zoom_in, icon_pos(1, -1), "Zoom in") {
state.zoom *= 1.1;
return StateUpdate::None;
}
if player.can_control
&& matches!(game.state, GameState::Playing)
&& bottom_right_texture(state, &assets.end_turn, icon_pos(-4, -1))
if bottom_left_texture(state, &assets.zoom_out, icon_pos(0, -1), "Zoom out") {
state.zoom /= 1.1;
return StateUpdate::None;
}
StateUpdate::None
}
fn can_end_move(game: &Game) -> Option<&str> {
match game.state {
GameState::Movement { .. } => Some("End movement"),
GameState::Playing => Some("End turn"),
_ => None,
}
}
fn end_move(game: &Game) -> StateUpdate {
if let GameState::Movement {
movement_actions_left,
..
} = &game.state
{
let left = game.actions_left;
return StateUpdate::execute_with_warning(
Action::Playing(PlayingAction::EndTurn),
if left > 0 {
vec![format!("{left} actions left")]
Action::Movement(MovementAction::Stop),
if *movement_actions_left > 0 {
vec![(format!("{movement_actions_left} movement actions left"))]
} else {
vec![]
},
);
}
if player.can_play_action && bottom_left_texture(state, &assets.movement, icon_pos(0, -3)) {
return StateUpdate::execute(Action::Playing(PlayingAction::MoveUnits));
}
if player.can_play_action && bottom_left_texture(state, &assets.happy, icon_pos(0, -2)) {
return start_increase_happiness(game, player);
}
if top_right_texture(state, &assets.advances, icon_pos(-2, 0)) {
return StateUpdate::OpenDialog(ActiveDialog::AdvanceMenu);
};
if top_right_texture(state, &assets.log, icon_pos(-1, 0)) {
return StateUpdate::OpenDialog(ActiveDialog::Log);
};
let d = state.game_state_dialog(game, &ActiveDialog::None);
if !matches!(d, ActiveDialog::None)
&& d.title() != state.active_dialog.title()
&& bottom_left_button(player, vec2(0., -200.), &format!("Back to {}", d.title()))
{
return StateUpdate::OpenDialog(d);
}
if features.import_export {
if bottom_right_texture(state, &assets.import, icon_pos(-2, -3)) {
return StateUpdate::Import;
};
if bottom_right_texture(state, &assets.export, icon_pos(-1, -3)) {
return StateUpdate::Export;
};
}
StateUpdate::None
let left = game.actions_left;
StateUpdate::execute_with_warning(
Action::Playing(PlayingAction::EndTurn),
if left > 0 {
vec![format!("{left} actions left")]
} else {
vec![]
},
)
}
pub fn player_color(player_index: usize) -> Color {

View file

@ -172,6 +172,10 @@ impl RecruitSelection {
}
}
pub fn clear(&mut self) {
self.current_city = None;
}
pub fn is_finished(&self) -> bool {
self.need_replacement.is_empty()
}

View file

@ -114,12 +114,13 @@ pub fn selection_dialog<T: Selection>(
return on_change(new);
}
}
confirm_update(sel, || on_ok(sel.clone()), ui, &sel.confirm(game))
confirm_update(sel, player, || on_ok(sel.clone()), ui, &sel.confirm(game))
})
}
pub fn confirm_update<T: ConfirmSelection>(
sel: &T,
player: &ShownPlayer,
on_ok: impl FnOnce() -> StateUpdate,
ui: &mut Ui,
confirm: &SelectionConfirm,
@ -127,11 +128,11 @@ pub fn confirm_update<T: ConfirmSelection>(
match confirm {
SelectionConfirm::NoConfirm => StateUpdate::None,
SelectionConfirm::Invalid => {
ui.label(None, "Invalid selection");
ui.label(ok_pos(player), "Invalid selection");
may_cancel(sel, ui)
}
SelectionConfirm::Valid => {
if ui.button(None, "OK") {
if ui.button(ok_pos(player), "OK") {
on_ok()
} else {
may_cancel(sel, ui)

69
client/src/tooltip.rs Normal file
View file

@ -0,0 +1,69 @@
use crate::client_state::{MousePosition, State};
use macroquad::camera::{set_camera, set_default_camera};
use macroquad::color::{Color, GRAY};
use macroquad::input::mouse_position;
use macroquad::math::{bool, f32, f64, vec2, Rect, Vec2};
use macroquad::prelude::{draw_circle, draw_rectangle, get_time};
const TOOLTIP_DELAY: f64 = 0.5;
pub fn update(state: &mut State) {
let (x, y) = mouse_position();
let now = get_time();
state
.mouse_positions
.retain(|mp| now - mp.time < TOOLTIP_DELAY);
state.mouse_positions.push(MousePosition {
position: vec2(x, y),
time: now,
});
}
fn is_rect_tooltip_active(state: &State, rect: Rect) -> bool {
state
.mouse_positions
.iter()
.all(|mp| rect.contains(mp.position))
}
pub fn show_tooltip_for_rect(state: &State, tooltip: &str, rect: Rect) {
let origin = rect.point();
if is_rect_tooltip_active(state, rect) {
draw_rectangle(
origin.x,
origin.y,
rect.size().x,
rect.size().y,
Color::new(0.0, 0.0, 0.0, 0.5),
);
show_tooltip_text(state, tooltip, origin);
}
}
fn is_world_circle_tooltip_active(state: &State, center: Vec2, radius: f32) -> bool {
state
.mouse_positions
.iter()
.all(|mp| (center - state.camera.screen_to_world(mp.position)).length() < radius)
}
pub fn show_tooltip_for_world_circle(state: &State, tooltip: &str, center: Vec2, radius: f32) {
let screen_center = state.camera.world_to_screen(center);
if is_world_circle_tooltip_active(state, center, radius) {
draw_circle(center.x, center.y, radius, Color::new(0.0, 0.0, 0.0, 0.5));
set_default_camera();
show_tooltip_text(state, tooltip, screen_center + vec2(radius, radius));
set_camera(&state.camera);
}
}
fn show_tooltip_text(state: &State, tooltip: &str, origin: Vec2) {
let dimensions = state.measure_text(tooltip);
let tooltip_rect = Rect::new(origin.x, origin.y, dimensions.width, dimensions.height);
let w = tooltip_rect.size().x + 10.;
let sx = state.screen_size.x;
let x = tooltip_rect.left().min(sx - w);
let y = (tooltip_rect.top() - 10.).max(40.);
draw_rectangle(x, y, w, tooltip_rect.size().y + 10., GRAY);
state.draw_text(tooltip, x + 5., y + 20.);
}

View file

@ -1,6 +1,6 @@
use macroquad::color::BLACK;
use macroquad::math::{u32, vec2};
use macroquad::prelude::draw_text;
use macroquad::math::{u32, vec2, Vec2};
use macroquad::prelude::{draw_text, WHITE};
use macroquad::shapes::draw_circle;
use macroquad::ui::Ui;
@ -8,22 +8,48 @@ use server::game::Game;
use server::position::Position;
use server::unit::{Unit, UnitType};
use crate::client_state::{ShownPlayer, StateUpdate};
use crate::client_state::{ActiveDialog, ShownPlayer, State, StateUpdate};
use crate::dialog_ui::active_dialog_window;
use crate::select_ui::{confirm_update, ConfirmSelection};
use crate::{hex_ui, player_ui};
use crate::hex_ui::Point;
use crate::tooltip::show_tooltip_for_world_circle;
use itertools::Itertools;
use server::consts::ARMY_MOVEMENT_REQUIRED_ADVANCE;
use server::player::Player;
pub fn draw_unit(unit: &Unit, index: u32) {
let c = hex_ui::center(unit.position);
let r = 40.0;
let p = hex_ui::rotate_around(c, r, (40 * index) as i32 + 45);
draw_circle(p.x, p.y, 11.0, BLACK);
const UNIT_RADIUS: f32 = 11.0;
pub fn draw_unit(unit: &Unit, index: u32, selected: bool) {
let p = unit_center(index, unit.position);
draw_circle(p.x, p.y, UNIT_RADIUS, if selected { WHITE } else { BLACK });
draw_circle(p.x, p.y, 9.0, player_ui::player_color(unit.player_index));
draw_text(unit_symbol(unit), p.x - 5.0, p.y + 5.0, 20.0, BLACK);
}
fn unit_center(index: u32, position: Position) -> Point {
let r = 40.0;
hex_ui::rotate_around(hex_ui::center(position), r, (40 * index) as i32 + 45)
}
pub fn unit_at_pos(pos: Position, mouse_pos: Vec2, player: &Player) -> Option<u32> {
player
.units
.iter()
.filter(|u| u.position == pos)
.enumerate()
.find_map(|(i, u)| {
let p = unit_center(i.try_into().unwrap(), pos);
let d = vec2(p.x - mouse_pos.x, p.y - mouse_pos.y);
if d.length() <= UNIT_RADIUS {
Some(u.id)
} else {
None
}
})
}
fn unit_symbol(unit: &Unit) -> &str {
match unit.unit_type {
UnitType::Infantry => "I",
@ -45,17 +71,39 @@ pub fn non_leader_names() -> [(UnitType, &'static str); 5] {
]
}
pub fn draw_units(game: &Game) {
pub fn draw_units(game: &Game, state: &State, tooltip: bool) {
let selected_units = match state.active_dialog {
ActiveDialog::MoveUnits(ref s) => s.units.clone(),
ActiveDialog::ReplaceUnits(ref s) => s.replaced_units.clone(),
ActiveDialog::RemoveCasualties(ref s) => s.units.clone(),
_ => vec![],
};
for (_pos, units) in &game
.players
.iter()
.flat_map(|p| &p.units)
.sorted_by_key(|u| u.position)
.chunk_by(|a| a.position)
.flat_map(|p| p.units.iter().map(move |u| (p.index, u)))
.sorted_by_key(|(_, u)| u.position)
.chunk_by(|(_, a)| a.position)
{
let vec = units.collect::<Vec<_>>();
vec.iter().enumerate().for_each(|(i, u)| {
draw_unit(u, i.try_into().unwrap());
vec.iter().enumerate().for_each(|(i, (p, u))| {
if tooltip {
let army_move = game
.get_player(*p)
.has_advance(ARMY_MOVEMENT_REQUIRED_ADVANCE);
let point = unit_center(i.try_into().unwrap(), u.position);
let center = vec2(point.x, point.y);
show_tooltip_for_world_circle(
state,
&unit_label(u, army_move),
center,
UNIT_RADIUS,
);
} else {
let selected = *p == game.active_player() && selected_units.contains(&u.id);
draw_unit(u, i.try_into().unwrap(), selected);
}
});
}
}
@ -76,13 +124,16 @@ pub fn unit_selection_dialog<T: UnitSelection>(
on_ok: impl FnOnce(T) -> StateUpdate,
additional: impl FnOnce(&mut Ui) -> StateUpdate,
) -> StateUpdate {
active_dialog_window(player, title, |ui| {
if let Some(current_tile) = sel.current_tile() {
if let Some(current_tile) = sel.current_tile() {
active_dialog_window(player, title, |ui| {
for (i, (p, unit_id)) in units_on_tile(game, current_tile).enumerate() {
let unit = game.get_player(p).get_unit(unit_id).unwrap();
let can_sel = sel.can_select(game, unit);
let is_selected = sel.selected_units().contains(&unit_id);
let mut l = label(unit);
let army_move = game
.get_player(p)
.has_advance(ARMY_MOVEMENT_REQUIRED_ADVANCE);
let mut l = unit_label(unit, army_move);
if is_selected {
l += " (selected)";
}
@ -100,12 +151,12 @@ pub fn unit_selection_dialog<T: UnitSelection>(
return on_change(new);
}
}
confirm_update(sel, || on_ok(sel.clone()), ui, &sel.confirm(game)).or(|| additional(ui))
} else {
ui.label(None, "Select a starting tile");
additional(ui)
}
})
confirm_update(sel, player, || on_ok(sel.clone()), ui, &sel.confirm(game))
.or(|| additional(ui))
})
} else {
StateUpdate::None
}
}
pub fn units_on_tile(game: &Game, pos: Position) -> impl Iterator<Item = (usize, u32)> + '_ {
@ -131,12 +182,15 @@ pub fn name(u: &UnitType) -> &str {
.1
}
pub fn label(unit: &Unit) -> String {
pub fn unit_label(unit: &Unit, army_move: bool) -> String {
let name = name(&unit.unit_type);
let res = if !unit.can_move() {
" (can't move) "
let res = if unit.unit_type.is_army_unit() && !army_move {
" (research Tactics to move the unit) "
} else if !unit.can_move() {
" (can't move out of a Mountain this turn) "
} else if !unit.can_attack() && !unit.unit_type.is_settler() {
" (can't attack) "
" (can't attack again this turn) "
} else {
""
};

View file

@ -341,9 +341,10 @@ fn attacker_wins(game: &mut Game, c: &mut Combat) -> CombatControl {
.expect("attacker should have all attacking units");
unit.position = c.defender_position;
}
let control = end_combat(game, c);
capture_position(game, c.defender, c.defender_position, c.attacker);
//todo attacker wins
end_combat(game, c)
control
}
fn defender_wins(game: &mut Game, c: &mut Combat) -> CombatControl {