player index

This commit is contained in:
AlphaCodingPilot 2023-01-21 14:29:30 +01:00
commit b8f079dd14
9 changed files with 215 additions and 202 deletions

View file

@ -4,7 +4,7 @@ use crate::hexagon::Position;
#[derive(Serialize, Deserialize)]
pub struct Unit {
pub player: String,
pub player: usize,
pub unit_type: UnitType,
pub transporter: Option<Position>,
pub can_attack: bool,

View file

@ -1,7 +1,7 @@
use std::fmt::Display;
use crate::{
content::wonders, game::Game, hexagon::Position, player, player::Player,
content::wonders, game::Game, hexagon::Position, player::Player,
resource_pile::ResourcePile, wonder::Wonder,
};
@ -14,7 +14,7 @@ pub struct City {
pub city_pieces: CityPieces,
pub mood_state: MoodState,
pub is_activated: bool,
pub player: String,
pub player: usize,
pub position: Position,
}
@ -39,7 +39,7 @@ impl City {
)
}
pub fn new(player: String, position: Position) -> Self {
pub fn new(player: usize, position: Position) -> Self {
Self {
city_pieces: CityPieces::default(),
mood_state: Neutral,
@ -109,8 +109,7 @@ impl City {
}
pub fn conquer(mut self, new_player: &mut Player, old_player: &mut Player) {
let new_player_name = new_player.name();
self.player = new_player_name.clone();
self.player = new_player.id;
self.mood_state = Angry;
for wonder in self.city_pieces.wonders.iter() {
(wonder.player_deinitializer)(old_player);
@ -119,14 +118,14 @@ impl City {
new_player.wonders.push(wonder.name.clone());
}
if let Some(player) = &self.city_pieces.obelisk {
if player == &old_player.name() {
if player == &old_player.id {
old_player.influenced_buildings += 1;
}
}
let previously_influenced_building =
self.city_pieces.buildings(Some(&new_player.name())).len() as u32;
self.city_pieces.buildings(Some(new_player.id)).len() as u32;
new_player.influenced_buildings -= previously_influenced_building;
self.city_pieces.change_player(new_player_name);
self.city_pieces.change_player(new_player.id);
new_player.cities.push(self)
}
@ -171,12 +170,12 @@ impl City {
}
pub fn uninfluenced_buildings(&self) -> u32 {
self.city_pieces.buildings(Some(&self.player)).len() as u32
self.city_pieces.buildings(Some(self.player)).len() as u32
}
//this function assumes action is legal
pub fn influence_culture(&mut self, influencer: &mut Player, building: &Building) {
self.city_pieces.set_building(building, influencer.name());
self.city_pieces.set_building(building, influencer.id);
if matches!(building, Building::Obelisk) {
panic!("obelisks cannot be culturally influenced")
}
@ -189,7 +188,7 @@ pub struct CityData {
city_pieces: CityPiecesData,
mood_state: MoodState,
is_activated: bool,
player: String,
player: usize,
position: Position,
}
@ -198,7 +197,7 @@ impl CityData {
city_pieces: CityPiecesData,
mood_state: MoodState,
is_activated: bool,
player: String,
player: usize,
position: Position,
) -> Self {
Self {
@ -290,13 +289,13 @@ impl Display for BuildingData {
#[derive(Default)]
pub struct CityPieces {
pub academy: Option<String>,
pub market: Option<String>,
pub obelisk: Option<String>,
pub observatory: Option<String>,
pub fortress: Option<String>,
pub port: Option<String>,
pub temple: Option<String>,
pub academy: Option<usize>,
pub market: Option<usize>,
pub obelisk: Option<usize>,
pub observatory: Option<usize>,
pub fortress: Option<usize>,
pub port: Option<usize>,
pub temple: Option<usize>,
pub wonders: Vec<Wonder>,
}
@ -346,7 +345,7 @@ impl CityPieces {
}
}
fn set_building(&mut self, building: &Building, player: String) {
fn set_building(&mut self, building: &Building, player: usize) {
match building {
Building::Academy => self.academy = Some(player),
Building::Market => self.market = Some(player),
@ -362,7 +361,7 @@ impl CityPieces {
(self.buildings(None).len() + self.wonders.len()) as u32
}
fn change_player(&mut self, new_player: String) {
fn change_player(&mut self, new_player: usize) {
for b in self.buildings(None) {
if !matches!(b, Building::Obelisk) {
self.set_building(&b, new_player.clone());
@ -370,7 +369,7 @@ impl CityPieces {
}
}
pub fn buildings(&self, owned_by: Option<&str>) -> Vec<Building> {
pub fn buildings(&self, owned_by: Option<usize>) -> Vec<Building> {
vec![
(Building::Academy, self.academy.clone()),
(Building::Market, self.market.clone()),
@ -384,7 +383,7 @@ impl CityPieces {
.filter_map(|(building, owner)| {
owner
.filter(|owner| match owned_by {
Some(want_owner) => owner == want_owner,
Some(want_owner) => owner == &want_owner,
None => true,
})
.map(|_| building)
@ -395,13 +394,13 @@ impl CityPieces {
#[derive(Serialize, Deserialize)]
pub struct CityPiecesData {
academy: Option<String>,
market: Option<String>,
obelisk: Option<String>,
observatory: Option<String>,
fortress: Option<String>,
port: Option<String>,
temple: Option<String>,
academy: Option<usize>,
market: Option<usize>,
obelisk: Option<usize>,
observatory: Option<usize>,
fortress: Option<usize>,
port: Option<usize>,
temple: Option<usize>,
wonders: Vec<String>,
}
@ -411,3 +410,44 @@ pub enum MoodState {
Neutral,
Angry,
}
#[cfg(test)]
mod city_tests {
use super::{Building, City, MoodState};
use crate::civilization::Civilization;
use crate::hexagon::Position;
use crate::player::Player;
use crate::resource_pile::ResourcePile;
use crate::wonder::Wonder;
#[test]
fn conquer_test() {
let mut old = Player::new(Civilization::new("old civ", vec![], vec![]), 0);
let mut new = Player::new(Civilization::new("new civ", vec![], vec![]), 0);
let wonder = Wonder::builder("wonder", ResourcePile::default(), vec![]).build();
let position = Position::new(0, 0, 0);
old.cities.push(City::new(old.id, position.clone()));
old.with_city(&position, |p, c| {
c.build_wonder(wonder, p);
c.increase_size(&Building::Academy, p);
c.increase_size(&Building::Obelisk, p);
});
assert_eq!(6.0, old.victory_points());
old.conquer_city(&position, &mut new);
let c = new.get_city(&position).unwrap();
assert_eq!(1, c.player);
assert_eq!(MoodState::Angry, c.mood_state);
assert_eq!(3.0, old.victory_points());
assert_eq!(3.0, new.victory_points());
assert_eq!(0, old.wonders.len());
assert_eq!(1, new.wonders.len());
assert_eq!(1, old.influenced_buildings);
assert_eq!(0, new.influenced_buildings);
}
}

View file

@ -1,39 +0,0 @@
use crate::city::{Building, City, MoodState};
use crate::civilization::Civilization;
use crate::hexagon::Position;
use crate::player::Player;
use crate::resource_pile::ResourcePile;
use crate::wonder::Wonder;
#[test]
fn conquer_test() {
let mut old = Player::new(Civilization::new("old civ", vec![], vec![]));
old.set_name(String::from("old"));
let mut new = Player::new(Civilization::new("new civ", vec![], vec![]));
new.set_name(String::from("new"));
let wonder = Wonder::builder("wonder", ResourcePile::default(), vec![]).build();
let position = Position::new(0, 0, 0);
old.cities.push(City::new(old.name(), position.clone()));
old.with_city(&position, |p, c| {
c.build_wonder(wonder, p);
c.increase_size(&Building::Academy, p);
c.increase_size(&Building::Obelisk, p);
});
assert_eq!(6.0, old.victory_points());
old.conquer_city(&position, &mut new);
let c = new.get_city(&position).unwrap();
assert_eq!(String::from("new"), c.player);
assert_eq!(MoodState::Angry, c.mood_state);
assert_eq!(3.0, old.victory_points());
assert_eq!(3.0, new.victory_points());
assert_eq!(0, old.wonders.len());
assert_eq!(1, new.wonders.len());
assert_eq!(1, old.influenced_buildings);
assert_eq!(0, new.influenced_buildings);
}

View file

@ -1,8 +1,8 @@
use rand::{rngs::StdRng, Rng, SeedableRng};
use rand::{rngs::StdRng, Rng, SeedableRng, seq::SliceRandom};
use serde::{Deserialize, Serialize};
use crate::{
content::{self, civilizations, wonders},
content::{civilizations, wonders},
player::{Player, PlayerData},
playing_actions::PlayingAction::*,
status_phase_actions::StatusPhaseAction,
@ -44,22 +44,23 @@ impl Game {
.as_bytes()
.try_into()
.expect("seed should be of length 32");
let mut random_number_generator = StdRng::from_seed(seed);
let mut rng = StdRng::from_seed(seed);
let mut players = Vec::new();
let mut civilizations = civilizations::get_civilizations();
for _ in 0..player_amount {
let civilization = random_number_generator.gen_range(0..civilizations.len());
players.push(Player::new(civilizations.remove(civilization)));
for i in 0..player_amount {
let civilization = rng.gen_range(0..civilizations.len());
players.push(Player::new(civilizations.remove(civilization), i));
}
let starting_player = random_number_generator.gen_range(0..players.len());
let starting_player = rng.gen_range(0..players.len());
let mut dice_roll_outcomes = Vec::new();
for _ in 0..DICE_ROLL_BUFFER {
dice_roll_outcomes.push(random_number_generator.gen_range(1..=12));
dice_roll_outcomes.push(rng.gen_range(1..=12));
}
let wonders = wonders::get_wonders();
let mut wonders = wonders::get_wonders();
wonders.shuffle(&mut rng);
let wonder_amount = wonders.len();
Self {
@ -302,14 +303,6 @@ impl Game {
}
}
pub fn get_player(&mut self, name: &str) -> Option<&mut Player> {
let position = self
.players
.iter()
.position(|player| player.name() == name)?;
Some(&mut self.players[position])
}
pub fn get_available_custom_actions(&self) -> Vec<String> {
let custom_actions = &self.players[self.current_player].custom_actions;
custom_actions
@ -318,6 +311,15 @@ impl Game {
.cloned()
.collect()
}
pub fn draw_wonder_card(&mut self, player: usize) {
let wonder = match self.wonders_left.pop() {
Some(wonder) => wonder,
None => return,
};
self.wonder_amount_left -= 1;
self.players[player].wonder_cards.push(wonder);
}
}
#[derive(Serialize, Deserialize)]

View file

@ -1,8 +1,6 @@
mod advance;
mod army;
mod city;
#[cfg(test)]
mod city_tests;
mod civilization;
mod content;
mod events;
@ -13,8 +11,6 @@ mod leader;
mod player;
mod playing_actions;
mod resource_pile;
#[cfg(test)]
mod resource_pile_tests;
mod special_advance;
mod status_phase_actions;
mod wonder;

View file

@ -11,7 +11,7 @@ use crate::{
army::Unit,
city::{Building, City, CityData},
civilization::Civilization,
content::{advances, civilizations},
content::{advances, civilizations, wonders},
events::EventMut,
game::Game,
hexagon::Position,
@ -31,7 +31,6 @@ pub const BUILDING_COST: ResourcePile = ResourcePile {
};
const ADVANCE_COST: u32 = 2;
const BUILDING_VICTORY_POINTS: f32 = 1.0;
const ADVANCE_VICTORY_POINTS: f32 = 0.5;
const OBJECTIVE_VICTORY_POINTS: f32 = 2.0;
@ -40,6 +39,7 @@ const DEFEATED_LEADER_VICTORY_POINTS: f32 = 2.0;
pub struct Player {
name: Option<String>,
pub id: usize,
resources: ResourcePile,
pub resource_limit: ResourcePile,
events: Option<PlayerEvents>,
@ -60,13 +60,14 @@ pub struct Player {
pub defeated_leaders: Vec<String>,
pub event_victory_points: f32,
pub custom_actions: Vec<String>,
pub wonder_cards: Vec<String>,
pub wonder_cards: Vec<Wonder>,
}
impl Player {
pub fn from_data(data: PlayerData) -> Self {
let mut player = Self {
name: data.name,
id: data.id,
resources: data.resources,
resource_limit: data.resource_limit,
events: Some(PlayerEvents::default()),
@ -98,7 +99,7 @@ impl Player {
defeated_leaders: data.defeated_leaders,
event_victory_points: data.event_victory_points,
custom_actions: data.custom_actions,
wonder_cards: data.wonder_cards,
wonder_cards: data.wonder_cards.iter().map(|wonder| wonders::get_wonder_by_name(wonder).expect("player data should have valid wonder cards")).collect(),
};
let advances = mem::take(&mut player.advances);
for advance in advances.iter() {
@ -122,6 +123,7 @@ impl Player {
pub fn data(self) -> PlayerData {
PlayerData {
name: self.name,
id: self.id,
resources: self.resources,
resource_limit: self.resource_limit,
cities: self.cities.into_iter().map(|city| city.data()).collect(),
@ -144,13 +146,14 @@ impl Player {
defeated_leaders: self.defeated_leaders,
event_victory_points: self.event_victory_points,
custom_actions: self.custom_actions,
wonder_cards: self.wonder_cards,
wonder_cards: self.wonder_cards.into_iter().map(|wonder| wonder.name).collect(),
}
}
pub fn new(civilization: Civilization) -> Self {
pub fn new(civilization: Civilization, id: usize) -> Self {
Self {
name: None,
id,
resources: ResourcePile::food(2),
resource_limit: ResourcePile::new(2, 7, 7, 7, 7, 7, 7),
events: Some(PlayerEvents::default()),
@ -439,6 +442,7 @@ impl Player {
#[derive(Serialize, Deserialize)]
pub struct PlayerData {
name: Option<String>,
id: usize,
resources: ResourcePile,
resource_limit: ResourcePile,
cities: Vec<CityData>,

View file

@ -45,7 +45,6 @@ pub enum PlayingAction {
impl PlayingAction {
pub fn execute(self, player: &mut Player, game: &mut Game) {
let player_name = player.name();
match self {
Advance { advance, payment } => {
if !player.can_advance(&advance)
@ -65,7 +64,7 @@ impl PlayingAction {
let city = City::from_data(city);
let building = Building::from_data(&city_piece);
let cost = player.building_cost(&building, &city);
if city.player != player_name
if city.player != player.id
|| !city.can_increase_size(&building, player)
|| !payment.can_afford(&cost)
{
@ -90,7 +89,7 @@ impl PlayingAction {
for (city, steps) in cities {
let city = City::from_data(city);
let cost = ResourcePile::mood_tokens(city.size()) * steps;
if city.player != player_name || !player.resources().can_afford(&cost) {
if city.player != player.id || !player.resources().can_afford(&cost) {
panic!("Illegal action");
}
player.loose_resources(cost);
@ -117,7 +116,7 @@ impl PlayingAction {
if matches!(building, Obelisk)
|| starting_city.position.distance(&target_city.position)
> starting_city.size() + range_boost
|| starting_city.player != player_name
|| starting_city.player != player.id
|| !player.resources().can_afford(&cost)
{
panic!("Illegal action");
@ -128,8 +127,7 @@ impl PlayingAction {
player.loose_resources(cost);
//todo! in the future get the city directly from its position on the map instead
let target_player = &target_city.player;
let target_player = game.get_player(target_player).expect("player should exist");
let target_player = &mut game.players[target_city.player];
let target_city = target_player
.get_city(&target_city.position)
.expect("city should exist");
@ -165,6 +163,14 @@ pub struct ActionType {
}
impl ActionType {
pub fn free() -> Self {
Self::new(true, false)
}
pub fn once_per_turn() -> Self {
Self::new(false, true)
}
pub fn new(free: bool, once_per_turn: bool) -> Self {
Self {
free,

View file

@ -298,3 +298,106 @@ impl PaymentOptions {
}
}
}
#[cfg(test)]
mod resource_pile_tests {
use super::{PaymentOptions, ResourcePile};
fn assert_can_afford(name: &str, cost: ResourcePile) {
let player_has = ResourcePile::new(1, 2, 3, 4, 5, 6, 7);
assert!(player_has.can_afford(&cost), "{name}");
}
fn assert_cannot_afford(name: &str, cost: ResourcePile) {
let player_has = ResourcePile::new(1, 2, 3, 4, 5, 6, 7);
assert!(!player_has.can_afford(&cost), "{name}");
}
fn assert_payment_options(name: &str, cost: ResourcePile, options: PaymentOptions) {
let budget = ResourcePile::new(1, 2, 3, 4, 5, 6, 7);
assert_eq!(options, cost.get_payment_options(&budget), "{name}");
}
fn assert_to_string(resource_pile: ResourcePile, expected: &str) {
assert_eq!(
expected.to_string(),
resource_pile.to_string(),
"expected {expected} but found {resource_pile}"
);
}
#[test]
fn can_afford_test() {
assert_can_afford("use 6 gold as wood", ResourcePile::wood(7));
assert_cannot_afford("6 gold is not enough", ResourcePile::wood(8));
assert_cannot_afford(
"gold cannot be converted to mood",
ResourcePile::mood_tokens(7),
);
assert_cannot_afford(
"gold cannot be converted to culture",
ResourcePile::culture_tokens(8),
);
assert_can_afford(
"negative gold means rebate",
ResourcePile::gold(-2) + ResourcePile::wood(9),
);
assert_cannot_afford(
"negative gold cannot rebate mood",
ResourcePile::gold(-2) + ResourcePile::mood_tokens(9),
);
assert_cannot_afford(
"negative gold cannot rebate culture",
ResourcePile::gold(-2) + ResourcePile::mood_tokens(8),
);
assert_can_afford("payment costs gold", ResourcePile::wood(5));
assert_cannot_afford(
"gold cannot be converted, because it's already used for payment",
ResourcePile::wood(7) + ResourcePile::gold(1),
);
}
#[test]
fn resource_limit_test() {
let mut resources = ResourcePile::new(3, 6, 9, 9, 0, 10, 6);
resources.apply_resource_limit(&ResourcePile::new(7, 5, 7, 10, 3, 7, 6));
assert_eq!(ResourcePile::new(3, 5, 7, 9, 0, 7, 6), resources);
}
#[test]
fn payment_options_test() {
assert_payment_options(
"no gold use",
ResourcePile::new(1, 1, 3, 2, 0, 2, 4),
PaymentOptions::new(ResourcePile::new(1, 1, 3, 2, 0, 2, 4), 5, 0),
);
assert_payment_options(
"use some gold",
ResourcePile::new(2, 2, 3, 5, 2, 0, 0),
PaymentOptions::new(ResourcePile::new(1, 2, 3, 4, 4, 0, 0), 1, 0),
);
assert_payment_options(
"jokers",
ResourcePile::ore(4) + ResourcePile::ideas(4) + ResourcePile::gold(-3),
PaymentOptions::new(ResourcePile::ore(3) + ResourcePile::ideas(4), 5, 2),
)
}
#[test]
fn resource_pile_display_test() {
assert_to_string(ResourcePile::default(), "nothing");
assert_to_string(ResourcePile::ore(1), "1 ore");
assert_to_string(ResourcePile::mood_tokens(2), "2 mood tokens");
assert_to_string(
ResourcePile::food(3) + ResourcePile::culture_tokens(1),
"3 food and 1 culture token",
);
assert_to_string(
ResourcePile::ideas(5) + ResourcePile::wood(1) + ResourcePile::gold(10),
"1 wood, 5 ideas and 10 gold",
);
}
}

View file

@ -1,99 +0,0 @@
use crate::resource_pile::{PaymentOptions, ResourcePile};
fn assert_can_afford(name: &str, cost: ResourcePile) {
let player_has = ResourcePile::new(1, 2, 3, 4, 5, 6, 7);
assert!(player_has.can_afford(&cost), "{name}");
}
fn assert_cannot_afford(name: &str, cost: ResourcePile) {
let player_has = ResourcePile::new(1, 2, 3, 4, 5, 6, 7);
assert!(!player_has.can_afford(&cost), "{name}");
}
fn assert_payment_options(name: &str, cost: ResourcePile, options: PaymentOptions) {
let budget = ResourcePile::new(1, 2, 3, 4, 5, 6, 7);
assert_eq!(options, cost.get_payment_options(&budget), "{name}");
}
fn assert_to_string(resource_pile: ResourcePile, expected: &str) {
assert_eq!(
expected.to_string(),
resource_pile.to_string(),
"expected {expected} but found {resource_pile}"
);
}
#[test]
fn can_afford_test() {
assert_can_afford("use 6 gold as wood", ResourcePile::wood(7));
assert_cannot_afford("6 gold is not enough", ResourcePile::wood(8));
assert_cannot_afford(
"gold cannot be converted to mood",
ResourcePile::mood_tokens(7),
);
assert_cannot_afford(
"gold cannot be converted to culture",
ResourcePile::culture_tokens(8),
);
assert_can_afford(
"negative gold means rebate",
ResourcePile::gold(-2) + ResourcePile::wood(9),
);
assert_cannot_afford(
"negative gold cannot rebate mood",
ResourcePile::gold(-2) + ResourcePile::mood_tokens(9),
);
assert_cannot_afford(
"negative gold cannot rebate culture",
ResourcePile::gold(-2) + ResourcePile::mood_tokens(8),
);
assert_can_afford("payment costs gold", ResourcePile::wood(5));
assert_cannot_afford(
"gold cannot be converted, because it's already used for payment",
ResourcePile::wood(7) + ResourcePile::gold(1),
);
}
#[test]
fn resource_limit_test() {
let mut resources = ResourcePile::new(3, 6, 9, 9, 0, 10, 6);
resources.apply_resource_limit(&ResourcePile::new(7, 5, 7, 10, 3, 7, 6));
assert_eq!(ResourcePile::new(3, 5, 7, 9, 0, 7, 6), resources);
}
#[test]
fn payment_options_test() {
assert_payment_options(
"no gold use",
ResourcePile::new(1, 1, 3, 2, 0, 2, 4),
PaymentOptions::new(ResourcePile::new(1, 1, 3, 2, 0, 2, 4), 5, 0),
);
assert_payment_options(
"use some gold",
ResourcePile::new(2, 2, 3, 5, 2, 0, 0),
PaymentOptions::new(ResourcePile::new(1, 2, 3, 4, 4, 0, 0), 1, 0),
);
assert_payment_options(
"jokers",
ResourcePile::ore(4) + ResourcePile::ideas(4) + ResourcePile::gold(-3),
PaymentOptions::new(ResourcePile::ore(3) + ResourcePile::ideas(4), 5, 2),
)
}
#[test]
fn resource_pile_display_test() {
assert_to_string(ResourcePile::default(), "nothing");
assert_to_string(ResourcePile::ore(1), "1 ore");
assert_to_string(ResourcePile::mood_tokens(2), "2 mood tokens");
assert_to_string(
ResourcePile::food(3) + ResourcePile::culture_tokens(1),
"3 food and 1 culture token",
);
assert_to_string(
ResourcePile::ideas(5) + ResourcePile::wood(1) + ResourcePile::gold(10),
"1 wood, 5 ideas and 10 gold",
);
}