repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/defenders/states/walking/mod.rs | src/core/src/match/engine/player/strategies/defenders/states/walking/mod.rs | use crate::r#match::defenders::states::DefenderState;
use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity};
use crate::r#match::player::events::PlayerEvent;
use crate::r#match::{ConditionContext, MatchPlayerLite, PlayerDistanceFromStartPosition, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, VectorExtensions};
use crate::IntegerUtils;
use nalgebra::Vector3;
const INTERCEPTION_DISTANCE: f32 = 150.0;
const MARKING_DISTANCE: f32 = 50.0;
const PRESSING_DISTANCE: f32 = 80.0;
const TACKLE_DISTANCE: f32 = 25.0;
const RUNNING_TO_THE_BALL_DISTANCE: f32 = 150.0;
#[derive(Default)]
pub struct DefenderWalkingState {}
impl StateProcessingHandler for DefenderWalkingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
let mut result = StateChangeResult::new();
// Emergency: if ball is nearby, slow-moving, and unowned, go for it immediately
if ctx.ball().distance() < 50.0 && !ctx.ball().is_owned() {
let ball_velocity = ctx.tick_context.positions.ball.velocity.norm();
if ball_velocity < 3.0 { // Increased from 1.0 to catch slow rolling balls
// Ball is stopped or slow-moving - take it directly
return Some(StateChangeResult::with_defender_state(
DefenderState::TakeBall,
));
}
}
if ctx.ball().distance() < RUNNING_TO_THE_BALL_DISTANCE {
return Some(StateChangeResult::with_defender_state(
DefenderState::TakeBall
));
}
// Priority 1: Check for opponents with the ball nearby - be aggressive!
if let Some(opponent) = ctx.players().opponents().with_ball().next() {
let distance_to_opponent = ctx.player.position.distance_to(&opponent.position);
// Tackle if very close
if distance_to_opponent < TACKLE_DISTANCE {
return Some(StateChangeResult::with_defender_state(
DefenderState::Tackling,
));
}
// Press if nearby
if distance_to_opponent < PRESSING_DISTANCE {
return Some(StateChangeResult::with_defender_state(
DefenderState::Pressing,
));
}
// Mark if within marking range
if distance_to_opponent < MARKING_DISTANCE {
return Some(StateChangeResult::with_defender_state(
DefenderState::Marking,
));
}
}
// Priority 2: Check for nearby opponents without the ball to mark
if let Some(opponent_to_mark) = ctx.players().opponents().without_ball().next() {
let distance = ctx.player.position.distance_to(&opponent_to_mark.position);
if distance < MARKING_DISTANCE / 2.0 {
return Some(StateChangeResult::with_defender_state(
DefenderState::Marking,
));
}
}
// Priority 3: Intercept ball if it's coming towards player
if ctx.ball().is_towards_player_with_angle(0.8)
&& ctx.ball().distance() < INTERCEPTION_DISTANCE
{
return Some(StateChangeResult::with_defender_state(
DefenderState::Intercepting,
));
}
// Priority 4: Return to position if far away and no immediate threats
if ctx.player().position_to_distance() != PlayerDistanceFromStartPosition::Small
&& !self.has_nearby_threats(ctx)
{
return Some(StateChangeResult::with_defender_state(
DefenderState::Returning,
));
}
// Priority 5: Adjust position if needed
let optimal_position = self.calculate_optimal_position(ctx);
if ctx.player.position.distance_to(&optimal_position) > 2.0 {
result
.events
.add_player_event(PlayerEvent::MovePlayer(ctx.player.id, optimal_position));
return Some(result);
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// Implement neural network logic if necessary
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
// Check if player should follow waypoints
if ctx.player.should_follow_waypoints(ctx) {
let waypoints = ctx.player.get_waypoints_as_vectors();
if !waypoints.is_empty() {
// Player has waypoints defined, follow them
return Some(
SteeringBehavior::FollowPath {
waypoints,
current_waypoint: ctx.player.waypoint_manager.current_index,
path_offset: 5.0 // Some randomness for natural movement
}
.calculate(ctx.player)
.velocity,
);
}
}
// 1. If this is the first tick in the state, initialize wander behavior
if ctx.in_state_time % 100 == 0 {
return Some(
SteeringBehavior::Wander {
target: ctx.player.start_position,
radius: IntegerUtils::random(5, 15) as f32,
jitter: IntegerUtils::random(1, 5) as f32,
distance: IntegerUtils::random(10, 20) as f32,
angle: IntegerUtils::random(0, 360) as f32,
}
.calculate(ctx.player)
.velocity,
);
}
// Fallback to moving towards optimal position
let optimal_position = self.calculate_optimal_position(ctx);
let direction = (optimal_position - ctx.player.position).normalize();
let walking_speed = (ctx.player.skills.physical.acceleration + ctx.player.skills.physical.stamina) / 2.0 * 0.1;
let speed = Vector3::new(walking_speed, walking_speed, 0.0).normalize().norm();
Some(direction * speed)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Walking at low speed allows some recovery, velocity-based to account for pace
DefenderCondition::with_velocity(ActivityIntensity::Low).process(ctx);
}
}
impl DefenderWalkingState {
fn calculate_optimal_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
// This is a simplified calculation. You might want to make it more sophisticated
// based on team formation, tactics, and the current game situation.
let team_center = self.calculate_team_center(ctx);
let ball_position = ctx.tick_context.positions.ball.position;
// Position between team center and ball, slightly closer to team center
(team_center * 0.7 + ball_position * 0.3).into()
}
fn calculate_team_center(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let all_teammates: Vec<MatchPlayerLite> = ctx.players().teammates().all().collect();
let sum: Vector3<f32> = all_teammates.iter().map(|p| p.position).sum();
sum / all_teammates.len() as f32
}
fn has_nearby_threats(&self, ctx: &StateProcessingContext) -> bool {
let threat_distance = 20.0; // Adjust this value as needed
if ctx.players().opponents().exists(threat_distance){
return true;
}
// Check if the ball is close and moving towards the player
let ball_distance = ctx.ball().distance();
let ball_speed = ctx.ball().speed();
let ball_towards_player = ctx.ball().is_towards_player();
if ball_distance < threat_distance && ball_speed > 10.0 && ball_towards_player {
return true;
}
false
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/mod.rs | src/core/src/match/engine/player/strategies/forwarders/mod.rs | pub mod states;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/state.rs | src/core/src/match/engine/player/strategies/forwarders/states/state.rs | use crate::r#match::forwarders::states::{
ForwardAssistingState, ForwardCreatingSpaceState, ForwardCrossReceivingState,
ForwardDribblingState, ForwardFinishingState, ForwardHeadingState, ForwardHeadingUpPlayState,
ForwardInterceptingState, ForwardOffsideTrapBreakingState, ForwardPassingState,
ForwardPressingState, ForwardReturningState, ForwardRunningInBehindState, ForwardRunningState,
ForwardShootingState, ForwardStandingState, ForwardTacklingState, ForwardTakeBallState,
};
use crate::r#match::{StateProcessingResult, StateProcessor};
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ForwardState {
Standing, // Standing still
Passing, // Passing the ball
Dribbling, // Dribbling the ball past opponents
Shooting, // Taking a shot on goal
Heading, // Heading the ball, often during crosses or set pieces
HoldingUpPlay, // Holding up the ball to allow teammates to join the attack
RunningInBehind, // Making a run behind the defense to receive a pass
Running, // Running in the direction of the ball
Pressing, // Pressing defenders to force a mistake or regain possession
Finishing, // Attempting to score from a close range
CreatingSpace, // Creating space for teammates by pulling defenders away
CrossReceiving, // Positioning to receive a cross
OffsideTrapBreaking, // Trying to beat the offside trap by timing runs
Tackling, // Tackling the ball
Assisting, // Providing an assist by passing or crossing to a teammate
TakeBall, // Take the ball,
Intercepting, // Intercepting the ball,
Returning, // Returning the ball
}
pub struct ForwardStrategies {}
impl ForwardStrategies {
pub fn process(state: ForwardState, state_processor: StateProcessor) -> StateProcessingResult {
match state {
ForwardState::Standing => state_processor.process(ForwardStandingState::default()),
ForwardState::Passing => state_processor.process(ForwardPassingState::default()),
ForwardState::Dribbling => state_processor.process(ForwardDribblingState::default()),
ForwardState::Shooting => state_processor.process(ForwardShootingState::default()),
ForwardState::Heading => state_processor.process(ForwardHeadingState::default()),
ForwardState::HoldingUpPlay => {
state_processor.process(ForwardHeadingUpPlayState::default())
}
ForwardState::RunningInBehind => {
state_processor.process(ForwardRunningInBehindState::default())
}
ForwardState::Pressing => state_processor.process(ForwardPressingState::default()),
ForwardState::Finishing => state_processor.process(ForwardFinishingState::default()),
ForwardState::CreatingSpace => {
state_processor.process(ForwardCreatingSpaceState::default())
}
ForwardState::CrossReceiving => {
state_processor.process(ForwardCrossReceivingState::default())
}
ForwardState::OffsideTrapBreaking => {
state_processor.process(ForwardOffsideTrapBreakingState::default())
}
ForwardState::Tackling => state_processor.process(ForwardTacklingState::default()),
ForwardState::Assisting => state_processor.process(ForwardAssistingState::default()),
ForwardState::Running => state_processor.process(ForwardRunningState::default()),
ForwardState::TakeBall => state_processor.process(ForwardTakeBallState::default()),
ForwardState::Intercepting => {
state_processor.process(ForwardInterceptingState::default())
}
ForwardState::Returning => state_processor.process(ForwardReturningState::default()),
}
}
}
impl Display for ForwardState {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
ForwardState::Standing => write!(f, "Standing"),
ForwardState::Dribbling => write!(f, "Dribbling"),
ForwardState::Shooting => write!(f, "Shooting"),
ForwardState::Heading => write!(f, "Heading"),
ForwardState::HoldingUpPlay => write!(f, "Holding Up Play"),
ForwardState::RunningInBehind => write!(f, "Running In Behind"),
ForwardState::Pressing => write!(f, "Pressing"),
ForwardState::Finishing => write!(f, "Finishing"),
ForwardState::CreatingSpace => write!(f, "Creating Space"),
ForwardState::CrossReceiving => write!(f, "Cross Receiving"),
ForwardState::OffsideTrapBreaking => write!(f, "Offside Trap Breaking"),
ForwardState::Assisting => write!(f, "Assisting"),
ForwardState::Passing => write!(f, "Passing"),
ForwardState::Tackling => write!(f, "Tackling"),
ForwardState::Running => write!(f, "Running"),
ForwardState::TakeBall => write!(f, "Take Ball"),
ForwardState::Intercepting => write!(f, "Intercepting"),
ForwardState::Returning => write!(f, "Returning"),
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/mod.rs | pub mod assisting;
pub mod common;
pub mod creating_space;
pub mod cross_receiving;
pub mod dribbling;
pub mod finishing;
pub mod heading;
pub mod heading_up_play;
pub mod offside_trap_breaking;
pub mod passing;
pub mod pressing;
pub mod running;
pub mod running_in_behind;
pub mod shooting;
pub mod standing;
pub mod state;
pub mod tackling;
pub mod takeball;
pub mod walking;
pub mod intercepting;
pub mod returning;
pub use assisting::*;
pub use creating_space::*;
pub use cross_receiving::*;
pub use dribbling::*;
pub use finishing::*;
pub use heading::*;
pub use heading_up_play::*;
pub use intercepting::*;
pub use offside_trap_breaking::*;
pub use passing::*;
pub use pressing::*;
pub use returning::*;
pub use running::*;
pub use running_in_behind::*;
pub use shooting::*;
pub use standing::*;
pub use state::*;
pub use tackling::*;
pub use takeball::*;
pub use walking::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/intercepting/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/intercepting/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardInterceptingState {}
impl StateProcessingHandler for ForwardInterceptingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
if ctx.player.has_ball(ctx) {
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
if ctx.team().is_control_ball() {
return Some(StateChangeResult::with_forward_state(
ForwardState::Returning,
));
}
let ball_distance = ctx.ball().distance();
if ball_distance > 150.0 {
return Some(StateChangeResult::with_forward_state(
ForwardState::Returning,
));
}
if ball_distance < 30.0 && ctx.tick_context.ball.is_owned {
return Some(StateChangeResult::with_forward_state(
ForwardState::Tackling,
));
}
// 2. Check if the defender can reach the interception point before any opponent
if !self.can_reach_before_opponent(ctx) {
// If not, transition to Pressing or HoldingLine state
return Some(StateChangeResult::with_forward_state(
ForwardState::Pressing,
));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// Implement neural network logic if necessary
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
Some(
SteeringBehavior::Pursuit {
target: ctx.tick_context.positions.ball.position,
target_velocity: ctx.tick_context.positions.ball.velocity,
}
.calculate(ctx.player)
.velocity,
)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Intercepting is moderate intensity - reading and reacting
ForwardCondition::with_velocity(ActivityIntensity::Moderate).process(ctx);
}
}
impl ForwardInterceptingState {
fn can_reach_before_opponent(&self, ctx: &StateProcessingContext) -> bool {
// Calculate time for defender to reach interception point
let interception_point = self.calculate_interception_point(ctx);
let defender_distance = (interception_point - ctx.player.position).magnitude();
let defender_speed = ctx.player.skills.physical.pace.max(0.1); // Avoid division by zero
let defender_time = defender_distance / defender_speed;
// Find the minimum time for any opponent to reach the interception point
let opponent_time = ctx
.players()
.opponents()
.all()
.map(|opponent| {
let player = ctx.player();
let skills = player.skills(opponent.id);
let opponent_speed = skills.physical.pace.max(0.1);
let opponent_distance = (interception_point - opponent.position).magnitude();
opponent_distance / opponent_speed
})
.min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
.unwrap_or(f32::MAX);
// Return true if defender can reach before any opponent
defender_time < opponent_time
}
/// Calculates the interception point of the ball
fn calculate_interception_point(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
// For aerial balls, use the precalculated landing position
let ball_position = ctx.tick_context.positions.ball.position;
let landing_position = ctx.tick_context.positions.ball.landing_position;
// Check if ball is aerial (high enough that landing position differs significantly)
let is_aerial = (ball_position - landing_position).magnitude() > 5.0;
if is_aerial {
// For aerial balls, target the landing position
landing_position
} else {
// For ground balls, do normal interception calculation
let ball_velocity = ctx.tick_context.positions.ball.velocity;
let defender_speed = ctx.player.skills.physical.pace.max(0.1);
// Relative position and velocity
let relative_position = ball_position - ctx.player.position;
let relative_velocity = ball_velocity;
// Time to intercept
let time_to_intercept = relative_position.magnitude()
/ (defender_speed + relative_velocity.magnitude()).max(0.1);
// Predict ball position after time_to_intercept
ball_position + ball_velocity * time_to_intercept
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/tackling/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/tackling/mod.rs | use crate::r#match::events::Event;
use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::player::events::PlayerEvent;
use crate::r#match::{
ConditionContext, MatchPlayerLite, StateChangeResult, StateProcessingContext,
StateProcessingHandler, SteeringBehavior,
};
use nalgebra::Vector3;
use rand::Rng;
const TACKLE_DISTANCE_THRESHOLD: f32 = 20.0; // Maximum distance to attempt a tackle
const CLOSE_TACKLE_DISTANCE: f32 = 10.0; // Distance for immediate tackle attempt
const FOUL_CHANCE_BASE: f32 = 0.15; // Base chance of committing a foul
const CHASE_DISTANCE_THRESHOLD: f32 = 100.0; // Maximum distance to chase for tackle
const PRESSURE_DISTANCE: f32 = 20.0; // Distance to apply pressure without tackling
#[derive(Default)]
pub struct ForwardTacklingState {}
impl StateProcessingHandler for ForwardTacklingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// If player has gained possession, transition to running
if ctx.player.has_ball(ctx) {
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
let opponents = ctx.players().opponents();
let opponents_with_ball: Vec<MatchPlayerLite> = opponents.with_ball().collect();
if let Some(opponent) = opponents_with_ball.first() {
let opponent_distance = ctx.tick_context.distances.get(ctx.player.id, opponent.id);
// Immediate tackle if very close
if opponent_distance <= CLOSE_TACKLE_DISTANCE {
let (tackle_success, committed_foul) = self.attempt_tackle(ctx, opponent);
if committed_foul {
return Some(StateChangeResult::with_forward_state_and_event(
ForwardState::Standing,
Event::PlayerEvent(PlayerEvent::CommitFoul),
));
}
if tackle_success {
return Some(StateChangeResult::with_forward_state_and_event(
ForwardState::Running,
Event::PlayerEvent(PlayerEvent::ClaimBall(ctx.player.id)),
));
}
// Failed tackle - continue pressuring
return None;
}
// If within tackle range but not close enough for immediate attempt
if opponent_distance <= TACKLE_DISTANCE_THRESHOLD {
// Wait for better opportunity or attempt tackle based on situation
if self.should_attempt_tackle_now(ctx, opponent) {
let (tackle_success, committed_foul) = self.attempt_tackle(ctx, opponent);
if committed_foul {
return Some(StateChangeResult::with_forward_state_and_event(
ForwardState::Standing,
Event::PlayerEvent(PlayerEvent::CommitFoul),
));
}
if tackle_success {
return Some(StateChangeResult::with_forward_state_and_event(
ForwardState::Running,
Event::PlayerEvent(PlayerEvent::ClaimBall(ctx.player.id)),
));
}
}
// Continue positioning for tackle
return None;
}
// If opponent is further but still chaseable, continue pursuit
if opponent_distance <= CHASE_DISTANCE_THRESHOLD {
return None; // Continue chasing
}
}
// Check for loose ball interception opportunities
if !ctx.ball().is_owned() && self.can_intercept_ball(ctx) {
return Some(StateChangeResult::with_forward_state_and_event(
ForwardState::Running,
Event::PlayerEvent(PlayerEvent::ClaimBall(ctx.player.id)),
));
}
let ball_distance = ctx.ball().distance();
if ctx.team().is_control_ball() {
if ball_distance > CHASE_DISTANCE_THRESHOLD {
return Some(StateChangeResult::with_forward_state(ForwardState::Returning));
}
return Some(StateChangeResult::with_forward_state(ForwardState::Assisting));
} else if ball_distance <= PRESSURE_DISTANCE {
return Some(StateChangeResult::with_forward_state(ForwardState::Pressing));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
let opponents = ctx.players().opponents();
let opponents_with_ball: Vec<MatchPlayerLite> = opponents.with_ball().collect();
if let Some(opponent) = opponents_with_ball.first() {
let opponent_distance = ctx.tick_context.distances.get(ctx.player.id, opponent.id);
// If very close, move more carefully to avoid overrunning
if opponent_distance <= TACKLE_DISTANCE_THRESHOLD {
return Some(
SteeringBehavior::Arrive {
target: opponent.position,
slowing_distance: 1.0,
}
.calculate(ctx.player)
.velocity,
);
} else {
// Chase more aggressively when further away
return Some(
SteeringBehavior::Pursuit {
target: opponent.position,
target_velocity: Vector3::zeros(), // Opponent velocity not available in lite struct
}
.calculate(ctx.player)
.velocity,
);
}
}
// If no opponent with ball, go for loose ball
if !ctx.ball().is_owned() {
return Some(
SteeringBehavior::Pursuit {
target: ctx.tick_context.positions.ball.position,
target_velocity: ctx.tick_context.positions.ball.velocity,
}
.calculate(ctx.player)
.velocity,
);
}
// Default movement toward ball position
Some(
SteeringBehavior::Arrive {
target: ctx.tick_context.positions.ball.position,
slowing_distance: 20.0,
}
.calculate(ctx.player)
.velocity,
)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Tackling is very high intensity - explosive action
ForwardCondition::new(ActivityIntensity::VeryHigh).process(ctx);
}
}
impl ForwardTacklingState {
/// Determine if the player should attempt a tackle right now
fn should_attempt_tackle_now(&self, ctx: &StateProcessingContext, opponent: &MatchPlayerLite) -> bool {
let tackling_skill = ctx.player.skills.technical.tackling / 20.0;
let aggression = ctx.player.skills.mental.aggression / 20.0;
// More skilled/aggressive players tackle more readily
let tackle_eagerness = (tackling_skill * 0.7) + (aggression * 0.3);
// Check opponent's situation
let opponent_velocity = ctx.tick_context.positions.players.velocity(opponent.id);
let opponent_is_stationary = opponent_velocity.magnitude() < 0.5;
// More likely to tackle if opponent is stationary or moving slowly
if opponent_is_stationary {
return rand::random::<f32>() < tackle_eagerness * 1.2;
}
// Check if opponent is moving toward our goal (more urgent to tackle)
let to_our_goal = ctx.ball().direction_to_own_goal() - opponent.position;
let opponent_direction = opponent_velocity.normalize();
let threat_level = to_our_goal.normalize().dot(&opponent_direction);
if threat_level > 0.5 {
// Opponent moving toward our goal - tackle more eagerly
return rand::random::<f32>() < tackle_eagerness * 1.4;
}
// Standard tackle decision
rand::random::<f32>() < tackle_eagerness * 0.8
}
/// Attempt a tackle with improved physics and skill-based calculation
fn attempt_tackle(
&self,
ctx: &StateProcessingContext,
opponent: &MatchPlayerLite,
) -> (bool, bool) {
let mut rng = rand::rng();
// Player skills
let tackling_skill = ctx.player.skills.technical.tackling / 20.0;
let aggression = ctx.player.skills.mental.aggression / 20.0;
let composure = ctx.player.skills.mental.composure / 20.0;
let pace = ctx.player.skills.physical.pace / 20.0;
// Opponent skills
let player = ctx.player();
let opponent_skills = player.skills(opponent.id);
let opponent_dribbling = opponent_skills.technical.dribbling / 20.0;
let opponent_agility = opponent_skills.physical.agility / 20.0;
let opponent_balance = opponent_skills.physical.balance / 20.0;
let opponent_composure = opponent_skills.mental.composure / 20.0;
// Calculate relative positioning advantage
let distance = ctx.tick_context.distances.get(ctx.player.id, opponent.id);
let distance_factor = (TACKLE_DISTANCE_THRESHOLD - distance) / TACKLE_DISTANCE_THRESHOLD;
let distance_factor = distance_factor.clamp(0.0, 1.0);
// Calculate angle advantage (tackling from behind is harder but less likely to be seen)
let opponent_velocity = ctx.tick_context.positions.players.velocity(opponent.id);
let tackle_angle_factor = if opponent_velocity.magnitude() > 0.1 {
let to_opponent = (opponent.position - ctx.player.position).normalize();
let opponent_direction = opponent_velocity.normalize();
let angle_dot = to_opponent.dot(&opponent_direction);
// Tackling from the side (perpendicular) is most effective
1.0 - angle_dot.abs()
} else {
0.8 // Stationary opponent - moderate advantage
};
// Calculate tackle effectiveness
let player_tackle_ability = (tackling_skill * 0.5) + (pace * 0.2) + (composure * 0.3);
let opponent_evasion_ability = (opponent_dribbling * 0.4) + (opponent_agility * 0.3) +
(opponent_balance * 0.2) + (opponent_composure * 0.1);
// Final success calculation
let base_success = player_tackle_ability - opponent_evasion_ability;
let situational_bonus = distance_factor * 0.3 + tackle_angle_factor * 0.2;
let success_chance = (0.5 + base_success * 0.4 + situational_bonus).clamp(0.05, 0.95);
let tackle_success = rng.random::<f32>() < success_chance;
// Calculate foul probability - more refined
let foul_base_risk = FOUL_CHANCE_BASE;
let aggression_risk = aggression * 0.1;
let desperation_risk = if ctx.team().is_loosing() && ctx.context.time.is_running_out() {
0.05 // More desperate when losing late in game
} else {
0.0
};
let skill_protection = composure * 0.05; // Better composure reduces foul risk
let situation_risk = if tackle_angle_factor < 0.3 {
0.08 // Higher risk when tackling from behind
} else {
0.0
};
let foul_chance = if tackle_success {
// Lower foul chance for successful tackles, but still possible
(foul_base_risk * 0.3) + aggression_risk + desperation_risk + situation_risk - skill_protection
} else {
// Higher foul chance for failed tackles
foul_base_risk + aggression_risk + desperation_risk + situation_risk + 0.05 - skill_protection
};
let foul_chance = foul_chance.clamp(0.0, 0.4); // Cap maximum foul chance
let committed_foul = rng.random::<f32>() < foul_chance;
(tackle_success, committed_foul)
}
/// Check if player can intercept a loose ball
fn can_intercept_ball(&self, ctx: &StateProcessingContext) -> bool {
// Don't try to intercept if ball is owned or in flight
if ctx.ball().is_owned() || ctx.ball().is_in_flight() {
return false;
}
let ball_position = ctx.tick_context.positions.ball.position;
let ball_velocity = ctx.tick_context.positions.ball.velocity;
let player_position = ctx.player.position;
let player_speed = ctx.player.skills.physical.pace / 20.0 * 10.0; // Convert to game units
// If ball is moving, calculate interception
if ball_velocity.magnitude() > 0.5 {
// Calculate if player can reach ball before it goes too far
let time_to_ball = (ball_position - player_position).magnitude() / player_speed;
let ball_future_position = ball_position + ball_velocity * time_to_ball;
let intercept_distance = (ball_future_position - player_position).magnitude();
// Check if interception is feasible
if intercept_distance <= TACKLE_DISTANCE_THRESHOLD * 2.0 {
// Also check if any opponent is closer to the interception point
let closest_opponent_distance = ctx.players().opponents().all()
.map(|opp| (ball_future_position - opp.position).magnitude())
.min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
.unwrap_or(f32::MAX);
return intercept_distance < closest_opponent_distance * 0.9; // Need to be clearly closer
}
} else {
// Ball is stationary - simple distance check
let ball_distance = (ball_position - player_position).magnitude();
if ball_distance <= TACKLE_DISTANCE_THRESHOLD {
// Check if any opponent is closer
let closest_opponent_distance = ctx.players().opponents().all()
.map(|opp| (ball_position - opp.position).magnitude())
.min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
.unwrap_or(f32::MAX);
return ball_distance < closest_opponent_distance * 0.8;
}
}
false
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/dribbling/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/dribbling/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext,
StateProcessingHandler, SteeringBehavior,
};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardDribblingState {}
impl StateProcessingHandler for ForwardDribblingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
if !ctx.player.has_ball(ctx) {
// Transition to Running state if the player doesn't have the ball
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
// Prevent infinite dribbling - timeout after 40 ticks to reassess
if ctx.in_state_time > 40 {
// Check for shooting opportunity first
if ctx.ball().distance_to_opponent_goal() < 250.0 && ctx.player().has_clear_shot() {
return Some(StateChangeResult::with_forward_state(ForwardState::Shooting));
}
// Otherwise try passing
return Some(StateChangeResult::with_forward_state(ForwardState::Passing));
}
if ctx.ball().distance_to_opponent_goal() < 35.0 && ctx.player().has_clear_shot() {
return Some(StateChangeResult::with_forward_state(ForwardState::Shooting));
}
// Check if the player is under pressure from multiple defenders
// Reduced check from nearby_raw to more accurate close defenders
let close_defenders = ctx.players().opponents().nearby(8.0).count();
if close_defenders >= 2 {
// Transition to Passing state if under pressure from multiple close defenders
return Some(StateChangeResult::with_forward_state(ForwardState::Passing));
}
// Check if there's space to dribble forward
if !self.has_space_to_dribble(ctx) {
// Transition to HoldingUpPlay state if there's no space to dribble
return Some(StateChangeResult::with_forward_state(
ForwardState::HoldingUpPlay,
));
}
// Check if there's an opportunity to shoot
if self.can_shoot(ctx) {
// Transition to Shooting state if there's an opportunity to shoot
return Some(StateChangeResult::with_forward_state(
ForwardState::Shooting,
));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
Some(
SteeringBehavior::Arrive {
target: ctx.player().opponent_goal_position(),
slowing_distance: 150.0,
}
.calculate(ctx.player)
.velocity,
)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Dribbling is high intensity - sustained movement with ball
ForwardCondition::with_velocity(ActivityIntensity::High).process(ctx);
}
}
impl ForwardDribblingState {
fn has_space_to_dribble(&self, ctx: &StateProcessingContext) -> bool {
let dribble_distance = 15.0;
!ctx.players().opponents().exists(dribble_distance)
}
fn can_shoot(&self, ctx: &StateProcessingContext) -> bool {
let shot_distance = 35.0;
let distance_to_goal = ctx.ball().distance_to_opponent_goal();
// Check if the player is within shooting distance and has a clear shot
distance_to_goal < shot_distance && ctx.player().has_clear_shot()
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/cross_receiving/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/cross_receiving/mod.rs | use crate::r#match::events::Event;
use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::player::events::PlayerEvent;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler,
};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardCrossReceivingState {}
impl StateProcessingHandler for ForwardCrossReceivingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
let ball_ops = ctx.ball();
if !ball_ops.is_towards_player_with_angle(0.8) || ctx.ball().distance() > 100.0 {
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
if ball_ops.distance() <= 10.0 {
return Some(StateChangeResult::with_event(Event::PlayerEvent(PlayerEvent::RequestBallReceive(ctx.player.id))));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
Some(Vector3::new(0.0, 0.0, 0.0))
}
fn process_conditions(&self, ctx: ConditionContext) {
// Cross receiving is moderate intensity - positioning and timing
ForwardCondition::with_velocity(ActivityIntensity::Moderate).process(ctx);
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/heading_up_play/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/heading_up_play/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler,
};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardHeadingUpPlayState {}
impl StateProcessingHandler for ForwardHeadingUpPlayState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// Check if the player has the ball
if !ctx.player.has_ball(ctx) {
// Transition to Running state if the player doesn't have the ball
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
// Check if there's support from teammates
if !self.has_support(ctx) {
// Transition to Dribbling state if there's no support
return Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
// Instead of standing completely still, shield the ball with subtle movement
// Move away from nearest defender to protect possession
if let Some(nearest_opponent) = ctx.players().opponents().nearby(10.0).next() {
let away_from_opponent = (ctx.player.position - nearest_opponent.position).normalize();
// Slow, controlled movement to shield the ball (like a real forward holding up play)
return Some(away_from_opponent * 1.0 + ctx.player().separation_velocity() * 0.5);
}
// If no immediate pressure, use slight separation to avoid collisions
Some(ctx.player().separation_velocity() * 0.3)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Heading up play is low intensity - holding and distributing
ForwardCondition::new(ActivityIntensity::Low).process(ctx);
}
}
impl ForwardHeadingUpPlayState {
fn has_support(&self, ctx: &StateProcessingContext) -> bool {
let min_support_distance = 10.0;
ctx.players().teammates().exists(min_support_distance)
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/creating_space/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/creating_space/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{
ConditionContext, MatchPlayerLite, PlayerSide, StateChangeResult,
StateProcessingContext, StateProcessingHandler, SteeringBehavior,
};
// Movement patterns for forwards
#[derive(Debug, Clone, Copy)]
enum ForwardMovementPattern {
DirectRun, // Direct run behind defense
DiagonalRun, // Diagonal run to create space and angles
ChannelRun, // Run between defenders
DriftWide, // Drift wide to create central space
CheckToFeet, // Come short to receive
OppositeMovement, // Move opposite to defensive shift
}
use nalgebra::Vector3;
const MAX_DISTANCE_FROM_BALL: f32 = 80.0;
const MIN_DISTANCE_FROM_BALL: f32 = 15.0;
const OPTIMAL_PASSING_DISTANCE_MIN: f32 = 15.0; // Wider ideal passing range start (was 20.0)
const OPTIMAL_PASSING_DISTANCE_MAX: f32 = 60.0; // Wider ideal passing range end (was 45.0)
const SPACE_SCAN_RADIUS: f32 = 100.0;
const CONGESTION_THRESHOLD: f32 = 3.0;
const PASSING_LANE_IMPORTANCE: f32 = 15.0; // High weight for clear passing lanes
#[derive(Default)]
pub struct ForwardCreatingSpaceState {}
impl StateProcessingHandler for ForwardCreatingSpaceState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// Check if player has the ball
if ctx.player.has_ball(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Running,
));
}
// Check if team lost possession
if !ctx.team().is_control_ball() {
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
// If ball is close and moving toward player
if ctx.ball().distance() < 100.0 && ctx.ball().is_towards_player_with_angle(0.8) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Intercepting,
));
}
// Check if created good space
if self.has_created_good_space(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Assisting,
));
}
// Check for forward run opportunity
if self.should_make_forward_run(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::RunningInBehind,
));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
let player_pos = ctx.player.position;
let goal_pos = ctx.player().opponent_goal_position();
let field_width = ctx.context.field_size.width as f32;
let field_height = ctx.context.field_size.height as f32;
// PRIORITY: When teammate has ball, make aggressive run toward goal
if let Some(ball_holder) = self.get_ball_holder(ctx) {
let holder_pos = ball_holder.position;
// Calculate attacking direction
let attacking_direction = match ctx.player.side {
Some(PlayerSide::Left) => Vector3::new(1.0, 0.0, 0.0),
Some(PlayerSide::Right) => Vector3::new(-1.0, 0.0, 0.0),
None => (goal_pos - player_pos).normalize(),
};
// Determine if we're ahead of or behind ball holder
let is_ahead = match ctx.player.side {
Some(PlayerSide::Left) => player_pos.x > holder_pos.x + 10.0,
Some(PlayerSide::Right) => player_pos.x < holder_pos.x - 10.0,
None => false,
};
// Calculate target: run TOWARD the goal with lateral spread
let target_position = if is_ahead {
// Already ahead - run further toward goal
let forward_distance = 80.0;
let lateral_offset = if player_pos.y < field_height / 2.0 {
-25.0 // Stay on left side
} else {
25.0 // Stay on right side
};
Vector3::new(
(player_pos.x + attacking_direction.x * forward_distance)
.clamp(50.0, field_width - 50.0),
(player_pos.y + lateral_offset).clamp(50.0, field_height - 50.0),
0.0,
)
} else {
// Behind ball holder - get ahead of them quickly
let overtake_distance = 100.0;
let lateral_spread = if player_pos.y < field_height / 2.0 {
-40.0 // Spread to left
} else {
40.0 // Spread to right
};
Vector3::new(
(holder_pos.x + attacking_direction.x * overtake_distance)
.clamp(50.0, field_width - 50.0),
(holder_pos.y + lateral_spread).clamp(50.0, field_height - 50.0),
0.0,
)
};
// Check for offside - if would be offside, come back slightly
let final_target = if self.would_be_offside(ctx, target_position) {
// Stay just onside
let defensive_line = self.get_defensive_line_position(ctx);
let safe_x = match ctx.player.side {
Some(PlayerSide::Left) => defensive_line - 5.0,
Some(PlayerSide::Right) => defensive_line + 5.0,
None => defensive_line,
};
Vector3::new(safe_x, target_position.y, 0.0)
} else {
target_position
};
// Use Pursuit for aggressive movement
let base_velocity = SteeringBehavior::Pursuit {
target: final_target,
target_velocity: Vector3::zeros(),
}
.calculate(ctx.player)
.velocity;
// Add separation to avoid clustering
return Some(base_velocity + ctx.player().separation_velocity() * 1.5);
}
// Fallback: use the existing complex logic when no teammate has ball
let target_position = self.find_optimal_free_zone(ctx);
let avoidance_vector = self.calculate_dynamic_avoidance(ctx);
let movement_pattern = self.get_intelligent_movement_pattern(ctx);
match movement_pattern {
ForwardMovementPattern::DirectRun => {
let base_velocity = SteeringBehavior::Pursuit {
target: target_position,
target_velocity: Vector3::zeros(),
}
.calculate(ctx.player)
.velocity;
Some(base_velocity + avoidance_vector * 1.2 + ctx.player().separation_velocity())
}
ForwardMovementPattern::DiagonalRun => {
let diagonal_target = self.calculate_diagonal_run_target(ctx, target_position);
let base_velocity = SteeringBehavior::Arrive {
target: diagonal_target,
slowing_distance: 15.0,
}
.calculate(ctx.player)
.velocity;
Some(base_velocity + avoidance_vector)
}
ForwardMovementPattern::ChannelRun => {
let channel_target = self.find_defensive_channel(ctx);
Some(
SteeringBehavior::Pursuit {
target: channel_target,
target_velocity: Vector3::zeros(),
}
.calculate(ctx.player)
.velocity + avoidance_vector * 0.8
)
}
ForwardMovementPattern::DriftWide => {
let wide_target = self.calculate_wide_position(ctx);
Some(
SteeringBehavior::Arrive {
target: wide_target,
slowing_distance: 20.0,
}
.calculate(ctx.player)
.velocity + avoidance_vector * 0.6
)
}
ForwardMovementPattern::CheckToFeet => {
let check_target = self.calculate_check_position(ctx);
Some(
SteeringBehavior::Arrive {
target: check_target,
slowing_distance: 10.0,
}
.calculate(ctx.player)
.velocity
)
}
ForwardMovementPattern::OppositeMovement => {
let opposite_target = self.calculate_opposite_movement(ctx);
Some(
SteeringBehavior::Arrive {
target: opposite_target,
slowing_distance: 15.0,
}
.calculate(ctx.player)
.velocity + avoidance_vector * 1.5
)
}
}
}
fn process_conditions(&self, ctx: ConditionContext) {
// Creating space is moderate intensity - tactical movement
ForwardCondition::with_velocity(ActivityIntensity::Moderate).process(ctx);
}
}
impl ForwardCreatingSpaceState {
/// Find optimal free zone for a forward
/// Find optimal free zone for a forward - optimized to search gaps between opponents
fn find_optimal_free_zone(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let field_width = ctx.context.field_size.width as f32;
let field_height = ctx.context.field_size.height as f32;
let player_pos = ctx.player.position;
let goal_pos = ctx.player().opponent_goal_position();
// Collect relevant opponents (defenders and midfielders in forward zones)
let opponents: Vec<Vector3<f32>> = ctx.players()
.opponents()
.all()
.filter(|opp| {
let is_relevant_position = opp.tactical_positions.is_defender()
|| opp.tactical_positions.is_midfielder();
let distance = (opp.position - player_pos).magnitude();
is_relevant_position && distance < SPACE_SCAN_RADIUS
})
.map(|opp| opp.position)
.collect();
// If no nearby opponents, move toward goal
if opponents.is_empty() {
let forward_direction = (goal_pos - player_pos).normalize();
return self.apply_forward_tactical_adjustment(
ctx,
player_pos + forward_direction * 30.0,
);
}
// Find gaps between opponents using improved multi-strategy approach
let mut candidate_positions = Vec::with_capacity(40);
// Strategy 1: Midpoints between adjacent opponents (existing)
for i in 0..opponents.len() {
for j in (i + 1)..opponents.len() {
let midpoint = (opponents[i] + opponents[j]) * 0.5;
let gap_width = (opponents[i] - opponents[j]).magnitude();
// Widened gap consideration (was 15-60, now 12-80)
if gap_width > 12.0 && gap_width < 80.0 {
candidate_positions.push(midpoint);
// NEW: Also add positions pushed forward through the gap
let to_goal = (goal_pos - midpoint).normalize();
candidate_positions.push(midpoint + to_goal * 10.0);
}
}
}
// Strategy 2: Positions offset from opponents (existing, improved)
for &opp_pos in &opponents {
let to_goal = (goal_pos - opp_pos).normalize();
let perpendicular = Vector3::new(-to_goal.y, to_goal.x, 0.0);
// Wider lateral positions and deeper runs
candidate_positions.push(opp_pos + perpendicular * 25.0 + to_goal * 20.0);
candidate_positions.push(opp_pos - perpendicular * 25.0 + to_goal * 20.0);
// NEW: Positions directly behind defenders (in space behind)
candidate_positions.push(opp_pos + to_goal * 15.0);
}
// Strategy 3: NEW - Grid-based open space detection
// Create grid of positions in attacking third and find truly open ones
let forward_direction = (goal_pos - player_pos).normalize();
for x_offset in [20.0, 35.0, 50.0] {
for y_offset in [-30.0, -15.0, 0.0, 15.0, 30.0] {
let lateral = Vector3::new(-forward_direction.y, forward_direction.x, 0.0);
let candidate = player_pos + forward_direction * x_offset + lateral * y_offset;
candidate_positions.push(candidate);
}
}
// Add current player position as fallback
candidate_positions.push(player_pos);
// Evaluate candidates and pick best
let mut best_position = player_pos;
let mut best_score = f32::MIN;
for candidate in candidate_positions {
// Ensure position is within bounds
let clamped = Vector3::new(
candidate.x.clamp(20.0, field_width - 20.0),
candidate.y.clamp(20.0, field_height - 20.0),
0.0,
);
let score = self.evaluate_forward_position(ctx, clamped);
if score > best_score {
best_score = score;
best_position = clamped;
}
}
// Apply tactical adjustments
self.apply_forward_tactical_adjustment(ctx, best_position)
}
/// Evaluate a position for forward play
fn evaluate_forward_position(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> f32 {
let mut score = 0.0;
// Space score (inverse of congestion)
let congestion = self.calculate_position_congestion(ctx, position);
score += (10.0 - congestion.min(10.0)) * 3.0;
// Goal threat score
let goal_threat = self.calculate_goal_threat(ctx, position);
score += goal_threat * 4.0;
// Offside avoidance
if !self.would_be_offside(ctx, position) {
score += 15.0;
}
// Channel positioning bonus
if self.is_in_dangerous_channel(ctx, position) {
score += 10.0;
}
// Behind defensive line bonus
if self.is_behind_defensive_line(ctx, position) {
score += 20.0;
}
// IMPROVED: Ball holder awareness - CRITICAL for receiving passes
if let Some(ball_holder) = self.get_ball_holder(ctx) {
let holder_distance = (position - ball_holder.position).magnitude();
// MAJOR BONUS for optimal passing distance (20-45m)
if holder_distance >= OPTIMAL_PASSING_DISTANCE_MIN
&& holder_distance <= OPTIMAL_PASSING_DISTANCE_MAX {
score += 25.0; // STRONG incentive to be in passing range
} else if holder_distance < OPTIMAL_PASSING_DISTANCE_MIN {
// Penalty for being too close (harder to receive)
score -= (OPTIMAL_PASSING_DISTANCE_MIN - holder_distance) * 0.5;
} else if holder_distance > OPTIMAL_PASSING_DISTANCE_MAX {
// Progressive penalty for being too far
score -= (holder_distance - OPTIMAL_PASSING_DISTANCE_MAX) * 0.8;
}
// MAJOR BONUS for clear passing lane from ball holder
if self.has_clear_passing_lane(ball_holder.position, position, ctx) {
score += PASSING_LANE_IMPORTANCE;
} else {
// Penalty for blocked passing lane
score -= 10.0;
}
// BONUS for good receiving angle (diagonal/forward from holder)
let angle_quality = self.calculate_receiving_angle_quality(ctx, ball_holder.position, position);
score += angle_quality * 8.0; // Up to 8 bonus points for perfect angle
// BONUS if holder is under pressure (need to offer option quickly)
if self.is_ball_holder_under_pressure(ctx, ball_holder.id) {
score += 12.0;
}
} else {
// Fallback: distance from ball (when no clear holder)
let ball_distance = (position - ctx.tick_context.positions.ball.position).magnitude();
if ball_distance > MAX_DISTANCE_FROM_BALL {
score -= (ball_distance - MAX_DISTANCE_FROM_BALL) * 0.5;
}
}
score
}
/// Calculate dynamic avoidance vector
fn calculate_dynamic_avoidance(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let mut avoidance = Vector3::zeros();
let player_pos = ctx.player.position;
// Strong avoidance of defenders
for opponent in ctx.players().opponents().all() {
if opponent.tactical_positions.is_defender() {
let distance = (opponent.position - player_pos).magnitude();
if distance < 25.0 && distance > 0.1 {
let direction = (player_pos - opponent.position).normalize();
let weight = 1.0 - (distance / 25.0);
// Predict defender movement
let future_pos = opponent.position + opponent.velocity(ctx) * 0.3;
let future_direction = (player_pos - future_pos).normalize();
avoidance += (direction + future_direction * 0.5) * weight * 20.0;
}
}
}
// Moderate avoidance of midfielders
for opponent in ctx.players().opponents().all() {
if opponent.tactical_positions.is_midfielder() {
let distance = (opponent.position - player_pos).magnitude();
if distance < 15.0 && distance > 0.1 {
let direction = (player_pos - opponent.position).normalize();
let weight = 1.0 - (distance / 15.0);
avoidance += direction * weight * 10.0;
}
}
}
// Light avoidance of teammates to maintain spacing
for teammate in ctx.players().teammates().all() {
if teammate.id == ctx.player.id || !teammate.tactical_positions.is_forward() {
continue;
}
let distance = (teammate.position - player_pos).magnitude();
if distance < 20.0 && distance > 0.1 {
let direction = (player_pos - teammate.position).normalize();
let weight = 1.0 - (distance / 20.0);
avoidance += direction * weight * 5.0;
}
}
avoidance
}
/// Get intelligent movement pattern for forward - IMPROVED to prioritize being a passing option
fn get_intelligent_movement_pattern(&self, ctx: &StateProcessingContext) -> ForwardMovementPattern {
let congestion = self.calculate_local_congestion(ctx);
let defensive_line_height = self.get_defensive_line_height(ctx);
let ball_in_wide_area = self.is_ball_in_wide_area(ctx);
let time_factor = ctx.in_state_time % 100;
// Analyze defender positioning
let defenders_compact = self.are_defenders_compact(ctx);
let has_space_behind = self.has_space_behind_defense(ctx);
// NEW: Check ball holder situation
let ball_holder_under_pressure = if let Some(holder) = self.get_ball_holder(ctx) {
self.is_ball_holder_under_pressure(ctx, holder.id)
} else {
false
};
// NEW: Check if we're in good passing range
let in_passing_range = if let Some(holder) = self.get_ball_holder(ctx) {
let distance = (ctx.player.position - holder.position).magnitude();
distance >= OPTIMAL_PASSING_DISTANCE_MIN && distance <= OPTIMAL_PASSING_DISTANCE_MAX
} else {
false
};
// PRIORITIZE: If ball holder under pressure, offer immediate support
if ball_holder_under_pressure {
if in_passing_range {
// Already in range - maintain position with diagonal movement
return ForwardMovementPattern::DiagonalRun;
} else {
// Not in range - check to feet immediately
return ForwardMovementPattern::CheckToFeet;
}
}
// PRIORITIZE: Exploit space behind defense if available
if has_space_behind && !self.would_be_offside_now(ctx) {
ForwardMovementPattern::ChannelRun
} else if defenders_compact && ball_in_wide_area {
ForwardMovementPattern::DiagonalRun
} else if congestion > CONGESTION_THRESHOLD && time_factor < 30 {
ForwardMovementPattern::DriftWide
} else if defensive_line_height > 0.6 && ctx.player().skills(ctx.player.id).mental.off_the_ball > 14.0 {
ForwardMovementPattern::DirectRun
} else if !in_passing_range && ctx.ball().distance() < 60.0 {
// IMPROVED: CheckToFeet more often when not in optimal passing range
ForwardMovementPattern::CheckToFeet
} else if self.detect_defensive_shift(ctx) {
ForwardMovementPattern::OppositeMovement
} else {
ForwardMovementPattern::DiagonalRun
}
}
/// Find channel between defenders
fn find_defensive_channel(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let defenders: Vec<MatchPlayerLite> = ctx.players().opponents().all()
.filter(|p| p.tactical_positions.is_defender())
.collect();
if defenders.len() < 2 {
return self.get_forward_search_center(ctx);
}
let mut best_channel = ctx.player.position;
let mut max_gap = 0.0;
// Find gaps between defenders
for i in 0..defenders.len() {
for j in i + 1..defenders.len() {
let def1 = &defenders[i];
let def2 = &defenders[j];
let gap_center = (def1.position + def2.position) * 0.5;
let gap_width = (def1.position - def2.position).magnitude();
if gap_width > max_gap && gap_width > 15.0 {
// Check if channel is progressive
if self.is_progressive_position(ctx, gap_center) {
max_gap = gap_width;
best_channel = gap_center;
}
}
}
}
// Move slightly ahead of the channel
let attacking_direction = self.get_attacking_direction(ctx);
best_channel + attacking_direction * 10.0
}
/// Calculate diagonal run target
fn calculate_diagonal_run_target(&self, ctx: &StateProcessingContext, base_target: Vector3<f32>) -> Vector3<f32> {
let player_pos = ctx.player.position;
let field_height = ctx.context.field_size.height as f32;
// Determine diagonal direction based on current position
let diagonal_offset = if player_pos.y < field_height / 2.0 {
Vector3::new(0.0, 20.0, 0.0) // Diagonal toward center from left
} else {
Vector3::new(0.0, -20.0, 0.0) // Diagonal toward center from right
};
let attacking_direction = self.get_attacking_direction(ctx);
base_target + diagonal_offset + attacking_direction * 15.0
}
/// Calculate wide position to create central space
fn calculate_wide_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let field_height = ctx.context.field_size.height as f32;
let ball_pos = ctx.tick_context.positions.ball.position;
// Determine which wing to drift to
let target_y = if ball_pos.y < field_height / 2.0 {
field_height * 0.85 // Drift to right wing
} else {
field_height * 0.15 // Drift to left wing
};
let attacking_direction = self.get_attacking_direction(ctx);
let forward_position = ball_pos.x + attacking_direction.x * 30.0;
Vector3::new(forward_position, target_y, 0.0)
}
/// Calculate check position (coming short) - IMPROVED for better receiving angles
fn calculate_check_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let player_pos = ctx.player.position;
// Prioritize positioning relative to ball holder, not just ball
if let Some(ball_holder) = self.get_ball_holder(ctx) {
let holder_pos = ball_holder.position;
let to_player = (player_pos - holder_pos).normalize();
let attacking_direction = self.get_attacking_direction(ctx);
// Calculate optimal check distance (within passing range)
let current_distance = (player_pos - holder_pos).magnitude();
let target_distance = OPTIMAL_PASSING_DISTANCE_MIN + 10.0; // 30m
// Create diagonal angle for easier passing
let lateral_direction = Vector3::new(-to_player.y, to_player.x, 0.0);
// Blend forward movement with lateral movement for diagonal angle
let ideal_direction = if current_distance > target_distance {
// Too far - come closer, but at an angle
(-to_player * 0.6 + lateral_direction * 0.4 + attacking_direction * 0.3).normalize()
} else {
// Right distance - maintain angle and move slightly forward
(lateral_direction * 0.5 + attacking_direction * 0.5).normalize()
};
let target_position = player_pos + ideal_direction * 15.0;
// Ensure we're not moving into congested area
if self.calculate_position_congestion(ctx, target_position) < 4.0 {
return target_position;
}
}
// Fallback: original logic if no ball holder found
let ball_pos = ctx.tick_context.positions.ball.position;
let to_ball = (ball_pos - player_pos).normalize();
let check_distance = 20.0;
let lateral_offset = if player_pos.y < ctx.context.field_size.height as f32 / 2.0 {
Vector3::new(0.0, -5.0, 0.0)
} else {
Vector3::new(0.0, 5.0, 0.0)
};
player_pos + to_ball * check_distance + lateral_offset
}
/// Calculate opposite movement to defensive shift
fn calculate_opposite_movement(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let defensive_shift = self.calculate_defensive_shift_vector(ctx);
let player_pos = ctx.player.position;
// Move opposite to defensive shift
let opposite_direction = -defensive_shift.normalize();
let movement_distance = 25.0;
let target = player_pos + opposite_direction * movement_distance;
// Ensure progressive movement
let attacking_direction = self.get_attacking_direction(ctx);
target + attacking_direction * 10.0
}
/// Calculate position congestion
fn calculate_position_congestion(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> f32 {
let mut congestion = 0.0;
for opponent in ctx.players().opponents().all() {
let distance = (opponent.position - position).magnitude();
if distance < 30.0 {
congestion += (30.0 - distance) / 30.0;
}
}
congestion
}
/// Calculate goal threat from position
fn calculate_goal_threat(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> f32 {
let goal_pos = ctx.player().opponent_goal_position();
let distance_to_goal = (position - goal_pos).magnitude();
// Ideal shooting distance is 15-25 meters
if distance_to_goal < 15.0 {
8.0
} else if distance_to_goal < 25.0 {
10.0
} else if distance_to_goal < 35.0 {
6.0
} else {
(100.0 - distance_to_goal).max(0.0) / 20.0
}
}
// Helper methods
fn get_forward_search_center(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let ball_pos = ctx.tick_context.positions.ball.position;
let attacking_direction = self.get_attacking_direction(ctx);
// Search ahead of ball position
ball_pos + attacking_direction * 30.0
}
fn get_attacking_direction(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
match ctx.player.side {
Some(PlayerSide::Left) => Vector3::new(1.0, 0.0, 0.0),
Some(PlayerSide::Right) => Vector3::new(-1.0, 0.0, 0.0),
None => Vector3::new(1.0, 0.0, 0.0),
}
}
fn would_be_offside(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> bool {
let attacking_direction = self.get_attacking_direction(ctx);
let is_attacking_left = attacking_direction.x > 0.0;
// Find last defender position
let last_defender_x = ctx.players().opponents().all()
.filter(|p| p.tactical_positions.is_defender())
.map(|p| p.position.x)
.fold(if is_attacking_left { f32::MIN } else { f32::MAX },
|acc, x| if is_attacking_left { acc.max(x) } else { acc.min(x) });
if is_attacking_left {
position.x > last_defender_x + 2.0
} else {
position.x < last_defender_x - 2.0
}
}
/// Get the defensive line X position
fn get_defensive_line_position(&self, ctx: &StateProcessingContext) -> f32 {
let attacking_direction = self.get_attacking_direction(ctx);
let is_attacking_left = attacking_direction.x > 0.0;
ctx.players().opponents().all()
.filter(|p| p.tactical_positions.is_defender())
.map(|p| p.position.x)
.fold(if is_attacking_left { f32::MIN } else { f32::MAX },
|acc, x| if is_attacking_left { acc.max(x) } else { acc.min(x) })
}
fn would_be_offside_now(&self, ctx: &StateProcessingContext) -> bool {
self.would_be_offside(ctx, ctx.player.position)
}
fn is_in_dangerous_channel(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> bool {
let field_height = ctx.context.field_size.height as f32;
let channel_width = field_height / 5.0;
// Central channels are most dangerous
let center = field_height / 2.0;
let distance_from_center = (position.y - center).abs();
distance_from_center < channel_width * 1.5
}
fn is_behind_defensive_line(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> bool {
let attacking_direction = self.get_attacking_direction(ctx);
let is_attacking_left = attacking_direction.x > 0.0;
let avg_defender_x = ctx.players().opponents().all()
.filter(|p| p.tactical_positions.is_defender())
.map(|p| p.position.x)
.sum::<f32>() / 4.0; // Assume 4 defenders
if is_attacking_left {
position.x > avg_defender_x
} else {
position.x < avg_defender_x
}
}
fn calculate_local_congestion(&self, ctx: &StateProcessingContext) -> f32 {
self.calculate_position_congestion(ctx, ctx.player.position)
}
fn get_defensive_line_height(&self, ctx: &StateProcessingContext) -> f32 {
let field_width = ctx.context.field_size.width as f32;
let defenders: Vec<f32> = ctx.players().opponents().all()
.filter(|p| p.tactical_positions.is_defender())
.map(|p| p.position.x)
.collect();
if defenders.is_empty() {
return 0.5;
}
let avg_x = defenders.iter().sum::<f32>() / defenders.len() as f32;
avg_x / field_width
}
fn is_ball_in_wide_area(&self, ctx: &StateProcessingContext) -> bool {
let ball_y = ctx.tick_context.positions.ball.position.y;
let field_height = ctx.context.field_size.height as f32;
ball_y < field_height * 0.25 || ball_y > field_height * 0.75
}
fn are_defenders_compact(&self, ctx: &StateProcessingContext) -> bool {
let defenders: Vec<Vector3<f32>> = ctx.players().opponents().all()
.filter(|p| p.tactical_positions.is_defender())
.map(|p| p.position)
.collect();
if defenders.len() < 2 {
return false;
}
let max_distance = defenders.iter()
.flat_map(|d1| defenders.iter().map(move |d2| (d1 - d2).magnitude()))
.fold(0.0_f32, f32::max);
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | true |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/running_in_behind/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/running_in_behind/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardRunningInBehindState {}
impl StateProcessingHandler for ForwardRunningInBehindState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
let ball_ops = ctx.ball();
let player_ops = ctx.player();
if ctx.player.has_ball(ctx) {
// Transition to Dribbling or Shooting based on position
return if ball_ops.distance_to_opponent_goal() < 25.0 {
Some(StateChangeResult::with_forward_state(
ForwardState::Shooting,
))
} else {
Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
))
};
}
// Check if the player is offside
if !player_ops.on_own_side() {
// Transition to Standing state when offside
return Some(StateChangeResult::with_forward_state(
ForwardState::Standing,
));
}
// Check if the run is still viable
if !self.is_run_viable(ctx) {
// If the run is no longer viable, transition to Creating Space
return Some(StateChangeResult::with_forward_state(
ForwardState::CreatingSpace,
));
}
// Check if there's an opportunity to break the offside trap
if self.can_break_offside_trap(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::OffsideTrapBreaking,
));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
// Forward should sprint toward goal, behind the defensive line
let opponent_goal = ctx.ball().direction_to_opponent_goal();
let current_position = ctx.player.position;
// Calculate target position: run toward goal, slightly angled to stay in passing lane
let to_goal = (opponent_goal - current_position).normalize();
// Add slight lateral movement to avoid being directly behind defender
let lateral_offset = if current_position.y > 0.0 {
Vector3::new(0.0, -0.2, 0.0) // Drift slightly inward
} else {
Vector3::new(0.0, 0.2, 0.0)
};
let direction = (to_goal + lateral_offset).normalize();
// Sprint at maximum pace with acceleration bonus
let pace = ctx.player.skills.physical.pace;
let acceleration = ctx.player.skills.physical.acceleration / 20.0;
let sprint_speed = pace * (1.5 + acceleration * 0.5); // Fast sprint
Some(direction * sprint_speed)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Running in behind is very high intensity - explosive sprinting
ForwardCondition::with_velocity(ActivityIntensity::VeryHigh).process(ctx);
}
}
impl ForwardRunningInBehindState {
fn is_run_viable(&self, ctx: &StateProcessingContext) -> bool {
// Check if there's still space to run into
let space_ahead = self.space_ahead(ctx);
// Check if the player is still in a good position to receive a pass
let in_passing_lane = self.in_passing_lane(ctx);
// Check if the player has the stamina to continue the run
let has_stamina = !ctx.player().is_tired();
space_ahead && in_passing_lane && has_stamina
}
fn space_ahead(&self, ctx: &StateProcessingContext) -> bool {
let space_threshold = 10.0;
!ctx.players().opponents().exists(space_threshold)
}
fn in_passing_lane(&self, ctx: &StateProcessingContext) -> bool {
// Check if the player is in a good position to receive a pass
// This is a simplified version and may need to be more complex in practice
let teammate_with_ball = ctx
.tick_context
.positions
.players
.items
.iter()
.find(|p| {
p.side == ctx.player.side.unwrap() && ctx.ball().owner_id() == Some(p.player_id)
});
if let Some(teammate) = teammate_with_ball {
let direction_to_player = (ctx.player.position - teammate.position).normalize();
let direction_to_goal =
(ctx.ball().direction_to_own_goal() - teammate.position).normalize();
// Check if the player is running towards the goal
direction_to_player.dot(&direction_to_goal) > 0.7
} else {
false
}
}
fn can_break_offside_trap(&self, ctx: &StateProcessingContext) -> bool {
let player_ops = ctx.player();
let ball_ops = ctx.ball();
// Check if the player is currently offside
if player_ops.on_own_side() {
return false;
}
// Check if the ball is moving towards the player
if !ball_ops.is_towards_player() {
return false;
}
// Check if the player has enough space to run into
if !self.space_ahead(ctx) {
return false;
}
// Check if the player has the speed to break the offside trap
let player_speed = ctx.player.skills.physical.acceleration;
let speed_threshold = 80.0; // Adjust based on your game's balance
if player_speed < speed_threshold {
return false;
}
// Check if the player's team is losing
if !ctx.team().is_loosing() {
return false;
}
// If all conditions are met, the player can break the offside trap
true
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/running/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/running/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{
ConditionContext, MatchPlayerLite, PlayerDistanceFromStartPosition, PlayerSide,
StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior,
};
use crate::IntegerUtils;
use nalgebra::Vector3;
// Realistic shooting distances (field is 840 units)
const MAX_SHOOTING_DISTANCE: f32 = 120.0; // ~60m - absolute max for long shots
const MIN_SHOOTING_DISTANCE: f32 = 5.0;
const VERY_CLOSE_RANGE_DISTANCE: f32 = 40.0; // ~20m - anyone can shoot
const CLOSE_RANGE_DISTANCE: f32 = 60.0; // ~30m - close range shots
const OPTIMAL_SHOOTING_DISTANCE: f32 = 80.0; // ~40m - ideal shooting distance
const MEDIUM_RANGE_DISTANCE: f32 = 90.0; // ~45m - medium range shots
// Passing decision thresholds for forwards
const PASSING_DISABLED_DISTANCE: f32 = 100.0; // Within this distance, very restrictive passing
const SHOOTING_ZONE_DISTANCE: f32 = 150.0; // Enhanced shooting priority zone
const TEAMMATE_ADVANTAGE_STRICT_RATIO: f32 = 0.4; // Teammate must be 40% of distance closer
// Performance thresholds
const SPRINT_DURATION_THRESHOLD: u64 = 150; // Ticks before considering fatigue
#[derive(Default)]
pub struct ForwardRunningState {}
impl StateProcessingHandler for ForwardRunningState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// Handle cases when player has the ball
if ctx.player.has_ball(ctx) {
// Priority 0: Clear shooting opportunity
if ctx.player().shooting().has_excellent_opportunity() {
return Some(StateChangeResult::with_forward_state(
ForwardState::Shooting,
));
}
// Priority 1: Clear ball if congested anywhere (not just boundaries)
if ctx.player().movement().is_congested_near_boundary() || ctx.player().movement().is_congested() {
// Force a long clearance pass to any teammate
if let Some(_) = ctx.players().teammates().all().next() {
return Some(StateChangeResult::with_forward_state(ForwardState::Passing));
}
}
// Priority 2: In shooting range with good angle
if ctx.player().shooting().in_shooting_range() && ctx.player().shooting().has_good_angle() {
// Consider shooting vs passing based on situation
if ctx.player().shooting().should_shoot_over_pass() {
return Some(StateChangeResult::with_forward_state(
ForwardState::Shooting,
));
}
// In shooting range - don't pass backward
// Only consider passing forward to better positioned teammates
if self.should_pass_in_shooting_zone(ctx) {
return Some(StateChangeResult::with_forward_state(ForwardState::Passing));
}
// Stay with ball and keep running toward goal
return None;
}
// Priority 2b: In shooting range but wider angle - still shoot if good long shot ability
if ctx.player().shooting().in_shooting_range() {
let long_shots = ctx.player.skills.technical.long_shots / 20.0;
let finishing = ctx.player.skills.technical.finishing / 20.0;
let distance = ctx.ball().distance_to_opponent_goal();
// Allow shooting from wider angles if player has good long shot skills
if distance <= OPTIMAL_SHOOTING_DISTANCE
&& long_shots > 0.6
&& finishing > 0.5
&& ctx.player().has_clear_shot()
&& !ctx.players().opponents().exists(8.0) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Shooting,
));
}
}
// Priority 3: Under pressure - quick decision needed
if ctx.player().pressure().is_under_immediate_pressure() {
if self.should_pass_under_pressure(ctx) {
return Some(StateChangeResult::with_forward_state(ForwardState::Passing));
} else if self.can_dribble_out_of_pressure(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
));
}
}
// Priority 4: Evaluate best action based on game context
if self.should_pass(ctx) {
return Some(StateChangeResult::with_forward_state(ForwardState::Passing));
}
if self.should_dribble(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
));
}
// Continue running with ball if no better option
return None;
}
// Handle cases when player doesn't have the ball
else {
// Priority 0: Emergency - if ball is nearby, stopped, and unowned, go for it immediately
if ctx.ball().should_take_ball_immediately() {
return Some(StateChangeResult::with_forward_state(
ForwardState::TakeBall,
));
}
// Priority 1: Ball interception opportunity
if self.can_intercept_ball(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Intercepting,
));
}
// Priority 2: Pressing opportunity
if self.should_press(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Pressing,
));
}
// Priority 3: Create space when team has possession
if ctx.team().is_control_ball() {
if self.should_create_space(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::CreatingSpace,
));
}
// Make intelligent runs
if self.should_make_run_in_behind(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::RunningInBehind,
));
}
}
// Priority 4: Defensive duties when needed
if !ctx.team().is_control_ball() {
if self.should_return_to_position(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Returning,
));
}
if self.should_help_defend(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Pressing,
));
}
}
// Consider fatigue and state duration
if self.needs_recovery(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Standing,
));
}
// Prevent getting stuck in running state
if ctx.in_state_time > 300 {
return if ctx.team().is_control_ball() {
Some(StateChangeResult::with_forward_state(
ForwardState::CreatingSpace,
))
} else {
Some(StateChangeResult::with_forward_state(
ForwardState::Standing,
))
};
}
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
// Fatigue-aware velocity calculation
let fatigue_factor = self.calculate_fatigue_factor(ctx);
// If following waypoints (team tactical movement)
if ctx.player.should_follow_waypoints(ctx) && !ctx.player.has_ball(ctx) {
let waypoints = ctx.player.get_waypoints_as_vectors();
if !waypoints.is_empty() {
return Some(
SteeringBehavior::FollowPath {
waypoints,
current_waypoint: ctx.player.waypoint_manager.current_index,
path_offset: IntegerUtils::random(1, 10) as f32,
}
.calculate(ctx.player)
.velocity
* fatigue_factor
+ ctx.player().separation_velocity(),
);
}
}
// Movement with ball
if ctx.player.has_ball(ctx) {
Some(self.calculate_ball_carrying_movement(ctx) * fatigue_factor)
}
// Team has possession but this player doesn't have the ball
else if ctx.team().is_control_ball() {
Some(self.calculate_supporting_movement(ctx) * fatigue_factor)
}
// Team doesn't have possession
else {
Some(self.calculate_defensive_movement(ctx) * fatigue_factor)
}
}
fn process_conditions(&self, ctx: ConditionContext) {
// Forwards do a lot of intense running - high intensity with velocity
ForwardCondition::with_velocity(ActivityIntensity::High).process(ctx);
}
}
impl ForwardRunningState {
/// Special passing logic when in shooting zone - only forward passes to much better positioned players
fn should_pass_in_shooting_zone(&self, ctx: &StateProcessingContext) -> bool {
let distance = ctx.ball().distance_to_opponent_goal();
let player_pos = ctx.player.position;
let goal_pos = ctx.player().opponent_goal_position();
// Get teammates
let teammates: Vec<MatchPlayerLite> = ctx.players().teammates().nearby(200.0).collect();
if teammates.is_empty() {
return false;
}
// Only pass if there's a teammate in a MUCH better position
// AND the pass is forward (toward goal, not backward)
teammates.iter().any(|teammate| {
// Must be a forward pass (closer to goal direction)
let is_forward_pass = match ctx.player.side {
Some(PlayerSide::Left) => teammate.position.x > player_pos.x,
Some(PlayerSide::Right) => teammate.position.x < player_pos.x,
None => false,
};
if !is_forward_pass {
return false; // Never pass backward in shooting zone
}
// Teammate must be SIGNIFICANTLY closer to goal
let teammate_distance = (teammate.position - goal_pos).magnitude();
let is_much_closer = teammate_distance < distance * TEAMMATE_ADVANTAGE_STRICT_RATIO;
// Must have clear pass lane
let has_clear_pass = ctx.player().has_clear_pass(teammate.id);
// Teammate should be unmarked or lightly marked
let not_heavily_marked = ctx
.players()
.opponents()
.all()
.filter(|opp| (opp.position - teammate.position).magnitude() < 8.0)
.count() < 2;
is_much_closer && has_clear_pass && not_heavily_marked
})
}
/// Check if under immediate pressure
fn is_under_immediate_pressure(&self, ctx: &StateProcessingContext) -> bool {
let close_opponents = ctx.players().opponents().nearby(30.0).count();
close_opponents >= 1
}
/// Determine if should pass when under pressure
fn should_pass_under_pressure(&self, ctx: &StateProcessingContext) -> bool {
// Check for available passing options
let safe_pass_available = ctx
.players()
.teammates()
.nearby(200.0)
.any(|t| ctx.player().has_clear_pass(t.id));
let composure = ctx.player.skills.mental.composure / 20.0;
// Low composure players pass more under pressure
safe_pass_available
&& (composure < 0.7 || ctx.players().opponents().nearby(30.0).count() >= 1)
}
/// Check if can dribble out of pressure
fn can_dribble_out_of_pressure(&self, ctx: &StateProcessingContext) -> bool {
let dribbling = ctx.player.skills.technical.dribbling / 20.0;
let agility = ctx.player.skills.physical.agility / 20.0;
let composure = ctx.player.skills.mental.composure / 20.0;
let skill_factor = dribbling * 0.5 + agility * 0.3 + composure * 0.2;
// Check for escape route
let has_space = self.find_dribbling_space(ctx).is_some();
skill_factor > 0.5 && has_space
}
/// Find space to dribble into
fn find_dribbling_space(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
let player_pos = ctx.player.position;
let goal_direction = (ctx.player().opponent_goal_position() - player_pos).normalize();
// Check multiple angles for space
let angles = [-45.0f32, -30.0, 0.0, 30.0, 45.0];
for angle_deg in angles.iter() {
let angle_rad = angle_deg.to_radians();
let cos_a = angle_rad.cos();
let sin_a = angle_rad.sin();
// Rotate goal direction by angle
let check_direction = Vector3::new(
goal_direction.x * cos_a - goal_direction.y * sin_a,
goal_direction.x * sin_a + goal_direction.y * cos_a,
0.0,
);
let check_position = player_pos + check_direction * 15.0;
// Check if this direction is clear
let opponents_in_path = ctx
.players()
.opponents()
.all()
.filter(|opp| {
let to_opp = opp.position - player_pos;
let dist = to_opp.magnitude();
let dot = to_opp.normalize().dot(&check_direction);
dist < 20.0 && dot > 0.7
})
.count();
if opponents_in_path == 0 {
return Some(check_position);
}
}
None
}
/// Enhanced interception check
fn can_intercept_ball(&self, ctx: &StateProcessingContext) -> bool {
// Don't try to intercept if ball is already owned by teammate
if ctx.ball().is_owned() {
if let Some(owner_id) = ctx.ball().owner_id() {
if let Some(owner) = ctx.context.players.by_id(owner_id) {
if owner.team_id == ctx.player.team_id {
return false;
}
}
}
}
let ball_distance = ctx.ball().distance();
let ball_speed = ctx.ball().speed();
// Static or slow-moving ball nearby
if ball_distance < 30.0 && ball_speed < 2.0 {
return true;
}
// Ball moving toward player
if ball_distance < 150.0 && ctx.ball().is_towards_player_with_angle(0.8) {
// Calculate if player can reach interception point
let player_speed = ctx.player.skills.physical.pace / 20.0 * 10.0;
let time_to_reach = ball_distance / player_speed;
let ball_travel_distance = ball_speed * time_to_reach;
return ball_travel_distance < ball_distance * 1.5;
}
false
}
/// Improved pressing decision
fn should_press(&self, ctx: &StateProcessingContext) -> bool {
// Don't press if team has possession
if ctx.team().is_control_ball() {
return false;
}
let ball_distance = ctx.ball().distance();
let stamina_level = ctx.player.player_attributes.condition_percentage() as f32 / 100.0;
let work_rate = ctx.player.skills.mental.work_rate / 20.0;
// Adjust pressing distance based on stamina and work rate
let effective_press_distance = 150.0 * stamina_level * (0.5 + work_rate);
// Check tactical instruction (high press vs low block)
let high_press = ctx.team().tactics().is_high_pressing();
if high_press {
ball_distance < effective_press_distance * 1.3
} else {
// Only press in attacking third
ball_distance < effective_press_distance && !ctx.ball().on_own_third()
}
}
/// Determine if should create space
fn should_create_space(&self, ctx: &StateProcessingContext) -> bool {
// Don't create space if you're the ball carrier or very close to ball
let ball_distance = ctx.ball().distance();
if ball_distance < 5.0 {
return false;
}
// Check if another teammate has the ball - if so, we MUST create space
if let Some(owner_id) = ctx.ball().owner_id() {
if owner_id != ctx.player.id {
// Teammate has ball - check if they're on our team
if let Some(owner) = ctx.context.players.by_id(owner_id) {
if owner.team_id == ctx.player.team_id {
// Teammate has ball! We should create space to help them
// ALWAYS return true - forwards must support ball carrier
return true;
}
}
}
}
// No teammate has ball - still try to create space if we're not closest
let closest_to_ball = !ctx.players().teammates().all().any(|t| {
let t_dist = (t.position - ctx.tick_context.positions.ball.position).magnitude();
t_dist < ball_distance * 0.9
});
!closest_to_ball
}
/// Check if should make run in behind defense
fn should_make_run_in_behind(&self, ctx: &StateProcessingContext) -> bool {
// Don't make runs on own half
if ctx.player().on_own_side() {
return false;
}
// Check player attributes - relaxed requirements
let pace = ctx.player.skills.physical.pace / 20.0;
let off_ball = ctx.player.skills.mental.off_the_ball / 20.0;
let stamina = ctx.player.player_attributes.condition_percentage() as f32 / 100.0;
// Combined skill check - if player is good at any of these, allow the run
let skill_score = pace * 0.4 + off_ball * 0.4 + stamina * 0.2;
if skill_score < 0.4 {
return false;
}
// Check if there's space behind defense
let defensive_line = self.find_defensive_line(ctx);
let space_behind = self.check_space_behind_defense(ctx, defensive_line);
// Check if a teammate has the ball (any teammate, not just good passers)
let teammate_has_ball = ctx
.ball()
.owner_id()
.and_then(|id| ctx.context.players.by_id(id))
.map(|p| p.team_id == ctx.player.team_id)
.unwrap_or(false);
// More aggressive: make runs even if space is limited, as long as teammate has ball
// and we're in attacking third
let in_attacking_third = self.is_in_good_attacking_position(ctx);
(space_behind || in_attacking_third) && teammate_has_ball
}
/// Find opponent defensive line position
fn find_defensive_line(&self, ctx: &StateProcessingContext) -> f32 {
let defenders: Vec<f32> = ctx
.players()
.opponents()
.all()
.filter(|p| p.tactical_positions.is_defender())
.map(|p| match ctx.player.side {
Some(PlayerSide::Left) => p.position.x,
Some(PlayerSide::Right) => p.position.x,
None => p.position.x,
})
.collect();
if defenders.is_empty() {
ctx.context.field_size.width as f32 / 2.0
} else {
// Return the position of the last defender
match ctx.player.side {
Some(PlayerSide::Left) => defenders.iter().fold(f32::MIN, |a, &b| a.max(b)),
Some(PlayerSide::Right) => defenders.iter().fold(f32::MAX, |a, &b| a.min(b)),
None => defenders.iter().sum::<f32>() / defenders.len() as f32,
}
}
}
/// Check if there's exploitable space behind defense
fn check_space_behind_defense(
&self,
ctx: &StateProcessingContext,
defensive_line: f32,
) -> bool {
let player_x = ctx.player.position.x;
match ctx.player.side {
Some(PlayerSide::Left) => {
// Space exists if defensive line is high and there's room behind
defensive_line < ctx.context.field_size.width as f32 * 0.7
&& player_x < defensive_line + 20.0
}
Some(PlayerSide::Right) => {
defensive_line > ctx.context.field_size.width as f32 * 0.3
&& player_x > defensive_line - 20.0
}
None => false,
}
}
/// Determine if should return to defensive position
fn should_return_to_position(&self, ctx: &StateProcessingContext) -> bool {
ctx.player().position_to_distance() == PlayerDistanceFromStartPosition::Big
}
/// Check if forward should help defend
fn should_help_defend(&self, ctx: &StateProcessingContext) -> bool {
// Check game situation
let losing_badly = ctx.team().is_loosing() && ctx.context.time.is_running_out();
let work_rate = ctx.player.skills.mental.work_rate / 20.0;
// High work rate forwards help more
work_rate > 0.7 && losing_badly && ctx.ball().on_own_third()
}
/// Check if player needs recovery
fn needs_recovery(&self, ctx: &StateProcessingContext) -> bool {
let stamina = ctx.player.player_attributes.condition_percentage();
let has_been_sprinting = ctx.in_state_time > SPRINT_DURATION_THRESHOLD;
stamina < 60 && has_been_sprinting
}
/// Calculate fatigue factor for movement
fn calculate_fatigue_factor(&self, ctx: &StateProcessingContext) -> f32 {
let stamina = ctx.player.player_attributes.condition_percentage() as f32 / 100.0;
let time_in_state = ctx.in_state_time as f32;
// Gradual fatigue over time
let time_factor = (1.0 - (time_in_state / 500.0)).max(0.5);
stamina * time_factor
}
/// Calculate movement when carrying the ball
fn calculate_ball_carrying_movement(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
// First, look for optimal path to goal
if let Some(target_position) = self.find_optimal_attacking_path(ctx) {
SteeringBehavior::Arrive {
target: target_position,
slowing_distance: 20.0,
}
.calculate(ctx.player)
.velocity
+ ctx.player().separation_velocity()
} else {
// Default to moving toward goal
SteeringBehavior::Arrive {
target: ctx.player().opponent_goal_position(),
slowing_distance: 100.0,
}
.calculate(ctx.player)
.velocity
+ ctx.player().separation_velocity()
}
}
/// Find optimal path considering opponents and teammates
fn find_optimal_attacking_path(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
let player_pos = ctx.player.position;
let goal_pos = ctx.player().opponent_goal_position();
// Look for gaps in defense
if let Some(gap) = self.find_best_gap_in_defense(ctx) {
return Some(gap);
}
// Try to move toward goal while avoiding opponents
let to_goal = goal_pos - player_pos;
let goal_direction = to_goal.normalize();
// Check if direct path is clear
if !ctx.players().opponents().nearby(30.0).any(|opp| {
let to_opp = opp.position - player_pos;
let dot = to_opp.normalize().dot(&goal_direction);
dot > 0.8 && to_opp.magnitude() < 40.0
}) {
return Some(player_pos + goal_direction * 50.0);
}
None
}
/// Find the best gap in opponent defense
fn find_best_gap_in_defense(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
let player_pos = ctx.player.position;
let goal_pos = ctx.player().opponent_goal_position();
let opponents: Vec<MatchPlayerLite> = ctx
.players()
.opponents()
.nearby(100.0)
.filter(|opp| {
// Only consider opponents between player and goal
let to_goal = goal_pos - player_pos;
let to_opp = opp.position - player_pos;
to_goal.normalize().dot(&to_opp.normalize()) > 0.5
})
.collect();
if opponents.len() < 2 {
return None;
}
// Find largest gap
let mut best_gap = None;
let mut best_gap_size = 0.0;
for i in 0..opponents.len() {
for j in i + 1..opponents.len() {
let gap_center = (opponents[i].position + opponents[j].position) * 0.5;
let gap_size = (opponents[i].position - opponents[j].position).magnitude();
if gap_size > best_gap_size && gap_size > 20.0 {
best_gap_size = gap_size;
best_gap = Some(gap_center);
}
}
}
best_gap
}
/// Calculate supporting movement when team has ball
fn calculate_supporting_movement(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
// Find ball holder
let ball_holder = ctx
.ball()
.owner_id()
.and_then(|id| ctx.context.players.by_id(id))
.filter(|p| p.team_id == ctx.player.team_id);
if let Some(holder) = ball_holder {
let player_pos = ctx.player.position;
let holder_pos = holder.position;
let goal_pos = ctx.player().opponent_goal_position();
let field_width = ctx.context.field_size.width as f32;
let field_height = ctx.context.field_size.height as f32;
// Calculate direction toward goal
let attacking_direction = match ctx.player.side {
Some(PlayerSide::Left) => Vector3::new(1.0, 0.0, 0.0),
Some(PlayerSide::Right) => Vector3::new(-1.0, 0.0, 0.0),
None => (goal_pos - player_pos).normalize(),
};
// Determine if we're already ahead of the ball holder
let is_ahead_of_holder = match ctx.player.side {
Some(PlayerSide::Left) => player_pos.x > holder_pos.x,
Some(PlayerSide::Right) => player_pos.x < holder_pos.x,
None => false,
};
// Calculate target position based on role
let target_position = if is_ahead_of_holder {
// Already ahead - make run toward goal, creating passing option
let forward_run_distance = 60.0; // Run toward goal
let lateral_offset = if player_pos.y < field_height / 2.0 {
-20.0 // Stay on left side
} else {
20.0 // Stay on right side
};
Vector3::new(
(player_pos.x + attacking_direction.x * forward_run_distance)
.clamp(20.0, field_width - 20.0),
(player_pos.y + lateral_offset).clamp(30.0, field_height - 30.0),
0.0,
)
} else {
// Behind ball holder - get ahead of them toward goal
let overtake_distance = 80.0;
let lateral_spread = if player_pos.y < field_height / 2.0 {
-30.0 // Spread left
} else {
30.0 // Spread right
};
Vector3::new(
(holder_pos.x + attacking_direction.x * overtake_distance)
.clamp(20.0, field_width - 20.0),
(holder_pos.y + lateral_spread).clamp(30.0, field_height - 30.0),
0.0,
)
};
// Use Pursuit behavior for more aggressive movement toward target
SteeringBehavior::Pursuit {
target: target_position,
target_velocity: Vector3::zeros(),
}
.calculate(ctx.player)
.velocity
+ ctx.player().separation_velocity() * 2.0
} else {
// Move toward ball if no clear holder
SteeringBehavior::Arrive {
target: ctx.tick_context.positions.ball.position,
slowing_distance: 50.0,
}
.calculate(ctx.player)
.velocity
+ ctx.player().separation_velocity() * 2.5
}
}
/// Calculate intelligent support run position
fn calculate_support_run_position(
&self,
ctx: &StateProcessingContext,
holder_pos: Vector3<f32>,
) -> Vector3<f32> {
let player_pos = ctx.player.position;
let _field_width = ctx.context.field_size.width as f32;
let field_height = ctx.context.field_size.height as f32;
// Determine player's role based on position
let is_central = (player_pos.y - field_height / 2.0).abs() < field_height * 0.2;
let is_wide = !is_central;
if is_wide {
// Wide players make runs down the flanks
self.calculate_wide_support_position(ctx, holder_pos)
} else {
// Central players make runs through the middle
self.calculate_central_support_position(ctx, holder_pos)
}
}
/// Calculate wide support position
fn calculate_wide_support_position(
&self,
ctx: &StateProcessingContext,
holder_pos: Vector3<f32>,
) -> Vector3<f32> {
let player_pos = ctx.player.position;
let field_height = ctx.context.field_size.height as f32;
// Stay wide and ahead of ball
let target_y = if player_pos.y < field_height / 2.0 {
field_height * 0.1 // Left wing
} else {
field_height * 0.9 // Right wing
};
// Increased distance from ball carrier (40 → 80 units) to prevent clustering
let target_x = match ctx.player.side {
Some(PlayerSide::Left) => holder_pos.x + 80.0,
Some(PlayerSide::Right) => holder_pos.x - 80.0,
None => holder_pos.x,
};
Vector3::new(target_x, target_y, 0.0)
}
/// Calculate central support position
fn calculate_central_support_position(
&self,
ctx: &StateProcessingContext,
holder_pos: Vector3<f32>,
) -> Vector3<f32> {
let field_height = ctx.context.field_size.height as f32;
let player_pos = ctx.player.position;
// Move into space between defenders - increased distance (50 → 90 units)
let target_x = match ctx.player.side {
Some(PlayerSide::Left) => holder_pos.x + 90.0,
Some(PlayerSide::Right) => holder_pos.x - 90.0,
None => holder_pos.x,
};
// Use player's current Y position with slight adjustment toward center
// REMOVED oscillating sine wave that caused left-right cycling
let center_pull = (field_height / 2.0 - player_pos.y) * 0.2; // Gentle pull toward center
let target_y = player_pos.y + center_pull;
Vector3::new(target_x, target_y.clamp(field_height * 0.3, field_height * 0.7), 0.0)
}
/// Calculate defensive movement
fn calculate_defensive_movement(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let field_width = ctx.context.field_size.width as f32;
// Forwards maintain higher defensive line
let defensive_line = match ctx.player.side {
Some(PlayerSide::Left) => field_width * 0.55,
Some(PlayerSide::Right) => field_width * 0.45,
None => field_width * 0.5,
};
// Stay compact with midfield
let target_y = ctx.player.start_position.y;
let target_x = defensive_line;
SteeringBehavior::Arrive {
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | true |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/standing/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/standing/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior};
use nalgebra::Vector3;
const MAX_SHOOTING_DISTANCE: f32 = 30.0; // Maximum distance to attempt a shot
const MIN_SHOOTING_DISTANCE: f32 = 1.0; // Minimum distance to attempt a shot (very close to goal)
const PRESS_DISTANCE: f32 = 20.0; // Distance within which to press opponents
#[derive(Default)]
pub struct ForwardStandingState {}
impl StateProcessingHandler for ForwardStandingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// Check if the forward still has the ball
if ctx.player.has_ball(ctx) {
// CRITICAL: Add cooldown before allowing another shot to prevent rapid-fire goal spam
// Must wait at least 40 ticks (~0.7 seconds) after entering Standing before shooting again
const SHOOTING_COOLDOWN: u64 = 40;
// Decide next action based on game context
if self.is_in_shooting_range(ctx) && ctx.in_state_time > SHOOTING_COOLDOWN {
// Transition to Shooting state (only after cooldown)
return Some(StateChangeResult::with_forward_state(
ForwardState::Shooting,
));
}
if let Some(_) = self.find_best_teammate_to_pass(ctx) {
// Transition to Passing state
return Some(StateChangeResult::with_forward_state(ForwardState::Passing));
}
// If unable to shoot or pass, decide to dribble or hold position
if self.should_dribble(ctx) {
Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
))
} else {
None
// Hold possession
//return Some(StateChangeResult::with_forward_state(ForwardState::HoldingPossession));
}
} else {
// Emergency: if ball is nearby, slow-moving, and unowned, go for it immediately
// OR if player is notified to take the ball (no distance limit when notified)
let is_nearby = ctx.ball().distance() < 50.0;
let is_notified = ctx.ball().is_player_notified();
if (is_nearby || is_notified) && !ctx.ball().is_owned() {
let ball_velocity = ctx.tick_context.positions.ball.velocity.norm();
if ball_velocity < 3.0 { // Increased from 1.0 to catch slow rolling balls
// Ball is stopped or slow-moving - take it directly
return Some(StateChangeResult::with_forward_state(
ForwardState::TakeBall,
));
}
}
// If the forward doesn't have the ball, decide to move or press
if self.should_press(ctx) {
// Transition to Pressing state
Some(StateChangeResult::with_forward_state(
ForwardState::Pressing,
))
} else {
Some(StateChangeResult::with_forward_state(ForwardState::Running))
// Transition to Positioning state
//Some(StateChangeResult::with_forward_state(ForwardState::Positioning))
}
}
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// Implement neural network logic for advanced decision-making if necessary
// For example, adjust positioning based on opponent movement
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
// Check if player should follow waypoints even when standing
if ctx.player.should_follow_waypoints(ctx) {
let waypoints = ctx.player.get_waypoints_as_vectors();
if !waypoints.is_empty() {
return Some(
SteeringBehavior::FollowPath {
waypoints,
current_waypoint: ctx.player.waypoint_manager.current_index,
path_offset: 3.0,
}
.calculate(ctx.player)
.velocity * 0.5, // Slower speed when standing
);
}
}
Some(Vector3::new(0.0, 0.0, 0.0))
}
fn process_conditions(&self, ctx: ConditionContext) {
// Standing is recovery - minimal movement
ForwardCondition::new(ActivityIntensity::Recovery).process(ctx);
}
}
impl ForwardStandingState {
/// Determines if the forward is within shooting range of the opponent's goal.
fn is_in_shooting_range(&self, ctx: &StateProcessingContext) -> bool {
let distance_to_goal = self.distance_to_opponent_goal(ctx);
distance_to_goal <= MAX_SHOOTING_DISTANCE && distance_to_goal >= MIN_SHOOTING_DISTANCE
}
/// Finds the best teammate to pass to based on proximity and position.
fn find_best_teammate_to_pass<'a>(
&'a self,
ctx: &'a StateProcessingContext<'a>,
) -> Option<u32> {
if let Some((teammate_id, _)) = ctx.players().teammates().nearby_ids(100.0).next() {
return Some(teammate_id)
}
None
}
/// Decides whether the forward should dribble based on game context.
fn should_dribble(&self, ctx: &StateProcessingContext) -> bool {
// Example logic: dribble if no immediate threat and space is available
let safe_distance = 10.0;
!ctx.players().opponents().exists(safe_distance)
}
/// Decides whether the forward should press the opponent.
fn should_press(&self, ctx: &StateProcessingContext) -> bool {
// Only press if opponent has the ball AND is close
if let Some(opponent) = ctx.players().opponents().with_ball().next() {
opponent.distance(ctx) < PRESS_DISTANCE
} else {
false
}
}
/// Calculates the distance from the forward to the opponent's goal.
fn distance_to_opponent_goal(&self, ctx: &StateProcessingContext) -> f32 {
ctx.ball().distance_to_opponent_goal()
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/common/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/common/mod.rs | use crate::r#match::engine::player::strategies::common::{
ActivityIntensityConfig, ConditionProcessor,
LOW_CONDITION_THRESHOLD, FIELD_PLAYER_JADEDNESS_INTERVAL, JADEDNESS_INCREMENT,
};
/// Forward-specific activity intensity configuration
pub struct ForwardConfig;
impl ActivityIntensityConfig for ForwardConfig {
fn very_high_fatigue() -> f32 {
8.5 // Forwards: highest fatigue for explosive actions
}
fn high_fatigue() -> f32 {
5.5 // Slightly higher than midfielders
}
fn moderate_fatigue() -> f32 {
3.0
}
fn low_fatigue() -> f32 {
1.0
}
fn recovery_rate() -> f32 {
-3.0
}
fn sprint_multiplier() -> f32 {
1.6 // Forwards sprint more often than midfielders
}
fn jogging_multiplier() -> f32 {
0.6
}
fn walking_multiplier() -> f32 {
0.3
}
fn low_condition_threshold() -> i16 {
LOW_CONDITION_THRESHOLD
}
fn jadedness_interval() -> u64 {
FIELD_PLAYER_JADEDNESS_INTERVAL
}
fn jadedness_increment() -> i16 {
JADEDNESS_INCREMENT
}
}
/// Forward condition processor (type alias for clarity)
pub type ForwardCondition = ConditionProcessor<ForwardConfig>;
// Re-export for convenience
pub use crate::r#match::engine::player::strategies::common::ActivityIntensity;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/takeball/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/takeball/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler,
SteeringBehavior,
};
use nalgebra::Vector3;
// TakeBall timeout and distance constants
const MAX_TAKEBALL_DISTANCE: f32 = 500.0;
const OPPONENT_ADVANTAGE_THRESHOLD: f32 = 20.0; // Opponent must be this much closer to give up
const TEAMMATE_ADVANTAGE_THRESHOLD: f32 = 8.0; // Teammate must be this much closer to give up (reduced from 15.0)
#[derive(Default)]
pub struct ForwardTakeBallState {}
impl StateProcessingHandler for ForwardTakeBallState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// Check if ball is now owned by someone
if ctx.ball().is_owned() {
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
let ball_distance = ctx.ball().distance();
let ball_position = ctx.tick_context.positions.ball.landing_position;
// 1. Distance check - ball too far away
if ball_distance > MAX_TAKEBALL_DISTANCE {
return Some(StateChangeResult::with_forward_state(
ForwardState::Running,
));
}
// 2. Check if opponent will reach ball first
if let Some(closest_opponent) = ctx.players().opponents().all().min_by(|a, b| {
let dist_a = (a.position - ball_position).magnitude();
let dist_b = (b.position - ball_position).magnitude();
dist_a.partial_cmp(&dist_b).unwrap()
}) {
let opponent_distance = (closest_opponent.position - ball_position).magnitude();
// If opponent is significantly closer, give up and press
if opponent_distance < ball_distance - OPPONENT_ADVANTAGE_THRESHOLD {
return Some(StateChangeResult::with_forward_state(
ForwardState::Pressing,
));
}
}
// 3. Check if teammate is closer to the ball
if let Some(closest_teammate) = ctx.players().teammates().all().filter(|t| t.id != ctx.player.id).min_by(|a, b| {
let dist_a = (a.position - ball_position).magnitude();
let dist_b = (b.position - ball_position).magnitude();
dist_a.partial_cmp(&dist_b).unwrap()
}) {
let teammate_distance = (closest_teammate.position - ball_position).magnitude();
// If teammate is significantly closer, let them take it (stricter threshold)
if teammate_distance < ball_distance - TEAMMATE_ADVANTAGE_THRESHOLD {
return Some(StateChangeResult::with_forward_state(
ForwardState::CreatingSpace,
));
}
}
// Continue trying to take the ball
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
// If ball is aerial, target the landing position instead of current position
let target = ctx.tick_context.positions.ball.landing_position;
// Calculate base Arrive behavior
let mut arrive_velocity = SteeringBehavior::Arrive {
target,
slowing_distance: 15.0,
}
.calculate(ctx.player)
.velocity;
// Add separation force to prevent player stacking
// Reduce separation when approaching ball, but keep minimum to prevent clustering
const SEPARATION_RADIUS: f32 = 25.0;
const SEPARATION_WEIGHT: f32 = 0.5; // Increased from 0.4 for stronger separation
const BALL_CLAIM_DISTANCE: f32 = 15.0;
const BALL_PRIORITY_DISTANCE: f32 = 5.0;
const MIN_SEPARATION_FACTOR: f32 = 0.25; // Minimum 25% separation - allows closer approach with larger claiming radius
const MAX_SEPARATION_FACTOR: f32 = 1.0; // Maximum 100% separation when far
let distance_to_ball = (ctx.player.position - target).magnitude();
// Progressive separation reduction - minimum 25% to allow claiming with larger radius
let separation_factor = if distance_to_ball < BALL_PRIORITY_DISTANCE {
// Very close to ball - minimum separation (25%)
MIN_SEPARATION_FACTOR
} else if distance_to_ball < BALL_CLAIM_DISTANCE {
// Approaching ball - lerp from 25% to 60%
let ratio = (distance_to_ball - BALL_PRIORITY_DISTANCE) / (BALL_CLAIM_DISTANCE - BALL_PRIORITY_DISTANCE);
MIN_SEPARATION_FACTOR + (ratio * 0.35)
} else {
// Far from ball - full separation
MAX_SEPARATION_FACTOR
};
let mut separation_force = Vector3::zeros();
let mut neighbor_count = 0;
// Check all nearby players (teammates and opponents)
let all_players: Vec<_> = ctx.players().teammates().all()
.chain(ctx.players().opponents().all())
.filter(|p| p.id != ctx.player.id)
.collect();
for other_player in all_players {
let to_player = ctx.player.position - other_player.position;
let distance = to_player.magnitude();
if distance > 0.0 && distance < SEPARATION_RADIUS {
// Repulsive force inversely proportional to distance
let repulsion_strength = (SEPARATION_RADIUS - distance) / SEPARATION_RADIUS;
separation_force += to_player.normalize() * repulsion_strength;
neighbor_count += 1;
}
}
if neighbor_count > 0 {
// Average and scale the separation force
separation_force = separation_force / (neighbor_count as f32);
separation_force = separation_force * ctx.player.skills.max_speed_with_condition(
ctx.player.player_attributes.condition,
) * SEPARATION_WEIGHT * separation_factor;
// Blend arrive and separation velocities
arrive_velocity = arrive_velocity + separation_force;
// Limit to max speed
let magnitude = arrive_velocity.magnitude();
if magnitude > ctx.player.skills.max_speed_with_condition(
ctx.player.player_attributes.condition,
) {
arrive_velocity = arrive_velocity * (ctx.player.skills.max_speed_with_condition(
ctx.player.player_attributes.condition,
) / magnitude);
}
}
Some(arrive_velocity)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Taking ball is very high intensity - explosive action to claim possession
ForwardCondition::new(ActivityIntensity::VeryHigh).process(ctx);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/shooting/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/shooting/mod.rs | use crate::r#match::events::Event;
use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::player::events::{PlayerEvent, ShootingEventContext};
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler,
};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardShootingState {}
impl StateProcessingHandler for ForwardShootingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
Some(StateChangeResult::with_forward_state_and_event(
ForwardState::Standing,
Event::PlayerEvent(PlayerEvent::Shoot(
ShootingEventContext::new()
.with_player_id(ctx.player.id)
.with_target(ctx.player().shooting_direction())
.with_reason("FWD_SHOOTING")
.build(ctx)
)),
))
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
Some(Vector3::new(0.0, 0.0, 0.0))
}
fn process_conditions(&self, ctx: ConditionContext) {
// Shooting is very high intensity - explosive action
ForwardCondition::new(ActivityIntensity::VeryHigh).process(ctx);
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/assisting/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/assisting/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardAssistingState {}
impl StateProcessingHandler for ForwardAssistingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
if !ctx.team().is_control_ball(){
return Some(StateChangeResult::with_forward_state(
ForwardState::Running,
));
}
if ctx.ball().distance() < 200.0 && ctx.ball().is_towards_player_with_angle(0.9) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Intercepting
));
}
// Check if the player is on the opponent's side of the field
if ctx.team().is_control_ball() && !ctx.player().on_own_side() && ctx.players().opponents().exists(100.0){
// If not on the opponent's side, focus on creating space and moving forward
return Some(StateChangeResult::with_forward_state(
ForwardState::CreatingSpace,
));
}
// Check if there's an immediate threat from an opponent
if self.is_under_pressure(ctx) {
// If under high pressure, decide between quick pass or dribbling
if self.should_make_quick_pass(ctx) {
if let Some(_teammate_id) = self.find_best_teammate_to_assist(ctx) {
//result.events.add_player_event(PlayerEvent::Pass(ctx.player.player_id, teammate_id));
return Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
));
}
}
// If no good passing option, try to dribble
return Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
));
}
// If not under immediate pressure, look for assist opportunities
if let Some(_) = self.find_best_teammate_to_assist(ctx) {
return Some(StateChangeResult::with_forward_state(ForwardState::Passing));
}
if self.is_in_shooting_range(ctx) && ctx.player.has_ball(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Shooting,
));
} else if self.should_create_space(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::CreatingSpace,
));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
Some(
SteeringBehavior::Arrive {
target: ctx.player().opponent_goal_position(),
slowing_distance: 10.0,
}
.calculate(ctx.player)
.velocity,
)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Assisting is moderate intensity - supporting movement
ForwardCondition::with_velocity(ActivityIntensity::Moderate).process(ctx);
}
}
impl ForwardAssistingState {
fn is_under_pressure(&self, ctx: &StateProcessingContext) -> bool {
ctx.players().opponents().exists(30.0)
}
fn should_make_quick_pass(&self, ctx: &StateProcessingContext) -> bool {
// Decision based on player's skills and game situation
ctx.player.skills.technical.passing > 70.0 && ctx.player.skills.mental.decisions > 65.0
}
fn find_best_teammate_to_assist(&self, ctx: &StateProcessingContext) -> Option<u32> {
ctx.players()
.teammates()
.nearby_ids(200.0)
.filter(|(id, _)| self.is_in_good_scoring_position(ctx, *id))
.min_by(|(_, dist_a), (_, dist_b)| {
dist_a
.partial_cmp(dist_b)
.unwrap_or(std::cmp::Ordering::Equal)
})
.map(|(id, _)| id)
}
fn is_in_good_scoring_position(&self, ctx: &StateProcessingContext, _player_id: u32) -> bool {
// TODO
let distance_to_goal = ctx.ball().distance_to_opponent_goal();
distance_to_goal < 20.0
}
fn is_in_shooting_range(&self, ctx: &StateProcessingContext) -> bool {
let distance_to_goal = ctx.ball().distance_to_opponent_goal();
distance_to_goal < 25.0
}
fn should_create_space(&self, ctx: &StateProcessingContext) -> bool {
ctx.player.skills.mental.off_the_ball > 15.0
&& ctx.players().teammates().exists(100.0)
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/returning/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/returning/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler,
SteeringBehavior, MATCH_TIME_MS,
};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardReturningState {}
impl StateProcessingHandler for ForwardReturningState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
if ctx.player.has_ball(ctx) {
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
if ctx.team().is_control_ball(){
return Some(StateChangeResult::with_forward_state(
ForwardState::Running,
));
}
if !ctx.team().is_control_ball() && ctx.ball().distance() < 200.0 {
return Some(StateChangeResult::with_forward_state(
ForwardState::Intercepting,
));
}
if !ctx.team().is_control_ball() && ctx.ball().distance() < 100.0 {
return Some(StateChangeResult::with_forward_state(
ForwardState::Tackling,
));
}
// Stay in returning state until very close to start position
if ctx.player().distance_from_start_position() < 2.0 {
return Some(StateChangeResult::with_forward_state(
ForwardState::Standing,
));
}
// Intercept if ball coming towards player and is closer than before
if !ctx.team().is_control_ball() && ctx.ball().is_towards_player_with_angle(0.9) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Intercepting,
));
}
// Transition to Pressing late in the game only if ball is close as well
if ctx.team().is_loosing()
&& ctx.context.total_match_time > (MATCH_TIME_MS - 180)
&& ctx.ball().distance() < 30.0
{
return Some(StateChangeResult::with_forward_state(
ForwardState::Pressing,
));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
Some(
SteeringBehavior::Arrive {
target: ctx.player.start_position,
slowing_distance: 10.0,
}
.calculate(ctx.player)
.velocity,
)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Returning is moderate intensity - getting back to position
ForwardCondition::with_velocity(ActivityIntensity::Moderate).process(ctx);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/pressing/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/pressing/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler,
SteeringBehavior,
};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardPressingState {}
impl StateProcessingHandler for ForwardPressingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
if ctx.player.has_ball(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
));
}
if ctx.ball().distance() < 30.0 {
return Some(StateChangeResult::with_forward_state(
ForwardState::Tackling,
));
}
if ctx.team().is_control_ball() {
return Some(StateChangeResult::with_forward_state(
ForwardState::Assisting,
));
} else if ctx.ball().on_own_side() {
return Some(StateChangeResult::with_forward_state(
ForwardState::Standing,
));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
// Only pursue if opponent has the ball
if let Some(_opponent) = ctx.players().opponents().with_ball().next() {
// Pursue the ball (which is with the opponent)
Some(
SteeringBehavior::Pursuit {
target: ctx.tick_context.positions.ball.position,
target_velocity: ctx.tick_context.positions.ball.velocity,
}
.calculate(ctx.player)
.velocity + ctx.player().separation_velocity(),
)
} else {
// If no opponent has ball (teammate has it or it's loose), just maintain position
Some(Vector3::zeros())
}
}
fn process_conditions(&self, ctx: ConditionContext) {
// Pressing is high intensity - sustained running and pressure
ForwardCondition::with_velocity(ActivityIntensity::High).process(ctx);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/heading/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/heading/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::player::events::PlayerEvent;
use crate::r#match::result::VectorExtensions;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext,
StateProcessingHandler,
};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardHeadingState {}
impl StateProcessingHandler for ForwardHeadingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
let mut result = StateChangeResult::new();
// Check if the ball is within heading range
if !self.is_ball_within_heading_range(ctx) {
// Transition to Running state if the ball is not within heading range
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
// Calculate the heading direction
let heading_direction = self.calculate_heading_direction(ctx);
// Perform the heading action
result.events.add_player_event(PlayerEvent::RequestHeading(
ctx.player.id,
heading_direction,
));
// Transition to Running state after heading the ball
Some(StateChangeResult::with_forward_state(ForwardState::Running))
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
Some(Vector3::new(0.0, 0.0, 0.0))
}
fn process_conditions(&self, ctx: ConditionContext) {
// Heading is very high intensity - explosive jumping action
ForwardCondition::new(ActivityIntensity::VeryHigh).process(ctx);
}
}
impl ForwardHeadingState {
fn is_ball_within_heading_range(&self, ctx: &StateProcessingContext) -> bool {
let ball_position = ctx.tick_context.positions.ball.position;
let heading_range = 1.5; // Adjust based on your game's scale
ctx.player.position.distance_to(&ball_position) <= heading_range
}
fn calculate_heading_direction(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
let goal_position = ctx.player().opponent_goal_position();
let ball_position = ctx.tick_context.positions.ball.position;
(goal_position - ball_position).normalize()
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/passing/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/passing/mod.rs | use crate::r#match::events::Event;
use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::player::events::{PassingEventContext, PlayerEvent};
use crate::r#match::{
ConditionContext, MatchPlayerLite, PassEvaluator, StateChangeResult, StateProcessingContext,
StateProcessingHandler, SteeringBehavior,
};
use nalgebra::Vector3;
const MAX_PASS_DURATION: u64 = 30; // Ticks before trying alternative action (reduced for faster decision-making)
const MIN_POSITION_ADJUSTMENT_TIME: u64 = 5; // Minimum ticks before adjusting position (prevents immediate twitching)
const MAX_POSITION_ADJUSTMENT_TIME: u64 = 20; // Maximum ticks to spend adjusting position
#[derive(Default)]
pub struct ForwardPassingState {}
impl StateProcessingHandler for ForwardPassingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
// Check if the forward still has the ball
if !ctx.player.has_ball(ctx) {
// Lost possession, transition to Running state
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
// Determine the best teammate to pass to
if let Some(target_teammate) = self.find_best_pass_option(ctx) {
// Execute the pass
return Some(StateChangeResult::with_forward_state_and_event(
ForwardState::Running,
Event::PlayerEvent(PlayerEvent::PassTo(
PassingEventContext::new()
.with_from_player_id(ctx.player.id)
.with_to_player_id(target_teammate.id)
.with_reason("FWD_PASSING_STATE")
.build(ctx),
)),
));
}
// If no good passing option is found and we're close to goal, consid-er shooting
if ctx.ball().distance_to_opponent_goal() < 250.0 && self.should_shoot_instead_of_pass(ctx)
{
return Some(StateChangeResult::with_forward_state(
ForwardState::Shooting,
));
}
// If under excessive pressure, consider going back to dribbling
if self.is_under_heavy_pressure(ctx) {
if self.can_dribble_effectively(ctx) {
return Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
));
} else {
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
}
if ctx.in_state_time > MAX_PASS_DURATION {
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
// If the player should adjust position to find better passing angles
if self.should_adjust_position(ctx) {
// Look for space to move into
let steering_velocity = SteeringBehavior::Arrive {
target: self.calculate_better_passing_position(ctx),
slowing_distance: 30.0,
}
.calculate(ctx.player)
.velocity;
// Apply reduced separation to avoid interference with deliberate movement
let separation = ctx.player().separation_velocity() * 0.3;
return Some(steering_velocity + separation);
}
None
}
fn process_conditions(&self, ctx: ConditionContext) {
// Passing is low intensity - minimal fatigue
ForwardCondition::new(ActivityIntensity::Low).process(ctx);
}
}
impl ForwardPassingState {
fn find_best_pass_option<'a>(
&self,
ctx: &StateProcessingContext<'a>,
) -> Option<MatchPlayerLite> {
let teammates = ctx.players().teammates();
// Use player's vision skill to determine range
let vision_range = ctx.player.skills.mental.vision * 30.0;
let vision_range_min = 100.0;
// Get viable passing options within range
let pass_options: Vec<MatchPlayerLite> = teammates
.nearby_range(50.0, vision_range.max(vision_range_min))
.filter(|t| self.is_viable_pass_target(ctx, t))
.collect();
if pass_options.is_empty() {
return None;
}
// Evaluate each option - forwards prioritize different passes than other positions
pass_options
.into_iter()
.map(|teammate| {
let score = self.evaluate_forward_pass(ctx, &teammate);
(teammate, score)
})
.max_by(|(_, score_a), (_, score_b)| {
score_a
.partial_cmp(score_b)
.unwrap_or(std::cmp::Ordering::Equal)
})
.map(|(teammate, _)| teammate)
}
/// Forward-specific pass evaluation - prioritizing attacks and goal scoring opportunities
fn evaluate_forward_pass(
&self,
ctx: &StateProcessingContext,
teammate: &MatchPlayerLite,
) -> f32 {
// Start with the basic pass evaluator score
let base_score = PassEvaluator::evaluate_pass(ctx, ctx.player, teammate);
// Forward-specific factors - much more goal-oriented than midfielders
let mut score = base_score.expected_value;
// Goal distance factors - forwards prioritize passes that get closer to goal
let forward_to_goal_dist = ctx.ball().distance_to_opponent_goal();
let teammate_to_goal_dist =
(teammate.position - ctx.player().opponent_goal_position()).magnitude();
// Significantly boost passes that advance toward goal - key forward priority
if teammate_to_goal_dist < forward_to_goal_dist {
score += 30.0 * (1.0 - (teammate_to_goal_dist / forward_to_goal_dist));
}
// Boost for passes to other forwards (likely in better scoring positions)
if teammate.tactical_positions.is_forward() {
score += 20.0;
}
// Boost for passes that break defensive lines
if self.pass_breaks_defensive_line(ctx, teammate) {
score += 25.0;
}
// Heavy bonus for teammates who have a clear shot on goal - key forward priority
if self.teammate_has_clear_shot(ctx, teammate) {
score += 35.0;
}
// Small penalty for backwards passes unless under heavy pressure
if teammate.position.x < ctx.player.position.x && !self.is_under_heavy_pressure(ctx) {
score -= 15.0;
}
score
}
/// Check if a pass to this teammate would break through a defensive line
fn pass_breaks_defensive_line(
&self,
ctx: &StateProcessingContext,
teammate: &MatchPlayerLite,
) -> bool {
let player_pos = ctx.player.position;
let teammate_pos = teammate.position;
// Create a line between player and teammate
let pass_direction = (teammate_pos - player_pos).normalize();
let pass_distance = (teammate_pos - player_pos).magnitude();
// Look for opponents between the player and teammate
let opponents_in_line = ctx
.players()
.opponents()
.all()
.filter(|opponent| {
// Project opponent onto pass line
let to_opponent = opponent.position - player_pos;
let projection_distance = to_opponent.dot(&pass_direction);
// Check if opponent is between player and teammate
if projection_distance <= 0.0 || projection_distance >= pass_distance {
return false;
}
// Calculate perpendicular distance to pass line
let projected_point = player_pos + pass_direction * projection_distance;
let perp_distance = (opponent.position - projected_point).magnitude();
// Consider opponents close to passing lane
perp_distance < 3.0
})
.count();
// If there are opponents in the passing lane, this pass breaks a line
opponents_in_line > 0
}
/// Check if a teammate is viable for receiving a pass
fn is_viable_pass_target(
&self,
ctx: &StateProcessingContext,
teammate: &MatchPlayerLite,
) -> bool {
// Basic viability criteria
let has_clear_lane = ctx.player().has_clear_pass(teammate.id);
let not_heavily_marked = !self.is_heavily_marked(ctx, teammate);
// Forwards are more aggressive with passing - they care less about position
// and more about goal scoring opportunities
let creates_opportunity = self.pass_creates_opportunity(ctx, teammate);
has_clear_lane && not_heavily_marked && creates_opportunity
}
/// Check if a pass would create a good attacking opportunity
fn pass_creates_opportunity(
&self,
ctx: &StateProcessingContext,
teammate: &MatchPlayerLite,
) -> bool {
// Passing backwards is generally not a good option for forwards
// unless under heavy pressure
if teammate.position.x < ctx.player.position.x && !self.is_under_heavy_pressure(ctx) {
return false;
}
// Check if the teammate is in a good shooting position
let distance_to_goal =
(teammate.position - ctx.player().opponent_goal_position()).magnitude();
if distance_to_goal < 200.0 {
return true;
}
// Check if the teammate has space to advance
let space_around_teammate = self.calculate_space_around_player(ctx, teammate);
if space_around_teammate > 7.0 {
return true;
}
// Default - other passes may still be viable but lower priority
true
}
/// Check if a player is heavily marked by opponents
fn is_heavily_marked(&self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite) -> bool {
const MARKING_DISTANCE: f32 = 10.0;
const MAX_MARKERS: usize = 2;
let markers = ctx
.players()
.opponents()
.all()
.filter(|opponent| {
(opponent.position - teammate.position).magnitude() <= MARKING_DISTANCE
})
.count();
markers >= MAX_MARKERS
}
/// Determine if teammate has a clear shot on goal
fn teammate_has_clear_shot(
&self,
ctx: &StateProcessingContext,
teammate: &MatchPlayerLite,
) -> bool {
let teammate_pos = teammate.position;
let goal_pos = ctx.player().opponent_goal_position();
let shot_direction = (goal_pos - teammate_pos).normalize();
let shot_distance = (goal_pos - teammate_pos).magnitude();
let ray_cast_result =
ctx.tick_context
.space
.cast_ray(teammate_pos, shot_direction, shot_distance, false);
ray_cast_result.is_none() && shot_distance < 300.0
}
/// Calculate the amount of space around a player
fn calculate_space_around_player(
&self,
ctx: &StateProcessingContext,
player: &MatchPlayerLite,
) -> f32 {
let space_radius = 10.0;
let num_opponents_nearby = ctx
.players()
.opponents()
.all()
.filter(|opponent| {
let distance = (opponent.position - player.position).magnitude();
distance <= space_radius
})
.count();
space_radius - num_opponents_nearby as f32
}
/// Check if player should shoot instead of pass
fn should_shoot_instead_of_pass(&self, ctx: &StateProcessingContext) -> bool {
let distance_to_goal = ctx.ball().distance_to_opponent_goal();
let shooting_skill =
(ctx.player.skills.technical.finishing + ctx.player.skills.technical.technique) / 40.0;
// Forwards are more likely to shoot than midfielders
// They'll shoot from further out and with less clear sight of goal
let shooting_range = 250.0 * shooting_skill;
distance_to_goal < shooting_range && ctx.player().has_clear_shot()
}
/// Check if player is under heavy pressure from opponents
fn is_under_heavy_pressure(&self, ctx: &StateProcessingContext) -> bool {
const PRESSURE_DISTANCE: f32 = 20.0; // Forwards consider closer pressure
const PRESSURE_THRESHOLD: usize = 1; // Even one opponent is significant for forwards
let pressing_opponents = ctx.players().opponents().nearby(PRESSURE_DISTANCE).count();
pressing_opponents > PRESSURE_THRESHOLD
}
/// Determine if player can effectively dribble out of pressure
fn can_dribble_effectively(&self, ctx: &StateProcessingContext) -> bool {
// Forward players are generally better at dribbling under pressure
let dribbling_skill = ctx.player.skills.technical.dribbling / 20.0;
let agility = ctx.player.skills.physical.agility / 20.0;
// Calculate combined dribbling effectiveness
let dribbling_effectiveness = (dribbling_skill * 0.7) + (agility * 0.3);
// Check if there's space to dribble into
let has_space = !ctx.players().opponents().exists(15.0);
dribbling_effectiveness > 0.5 && has_space
}
/// Determine if player should adjust position to find better passing angles
fn should_adjust_position(&self, ctx: &StateProcessingContext) -> bool {
// Only adjust position within a specific time window to prevent endless twitching
let in_adjustment_window = ctx.in_state_time >= MIN_POSITION_ADJUSTMENT_TIME
&& ctx.in_state_time <= MAX_POSITION_ADJUSTMENT_TIME;
// If no good passing option and not under immediate pressure and within time window
in_adjustment_window
&& self.find_best_pass_option(ctx).is_none()
&& !self.is_under_heavy_pressure(ctx)
}
/// Calculate a better position for finding passing angles - forwards look for
/// spaces that open up shooting opportunities first, passing lanes second
fn calculate_better_passing_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> {
// Get positions
let player_pos = ctx.player.position;
let goal_pos = ctx.player().opponent_goal_position();
// First priority: move to a better shooting position if possible
if ctx.ball().distance_to_opponent_goal() < 250.0 {
// Look for space between defenders toward goal
if let Some(space) = self.find_space_between_opponents_toward_goal(ctx) {
return space;
}
}
// Second priority: find space for a better passing angle
let closest_teammate = ctx.players().teammates().nearby(150.0).next();
if let Some(teammate) = closest_teammate {
// Find a position that improves angle to this teammate
let to_teammate = teammate.position - player_pos;
let teammate_direction = to_teammate.normalize();
// Move slightly perpendicular to create a better angle
let perpendicular = Vector3::new(-teammate_direction.y, teammate_direction.x, 0.0);
let adjustment = perpendicular * 5.0; // Reduced from 8.0 to prevent excessive twitching
return player_pos + adjustment;
}
// Default to moving toward goal if no better option
let to_goal = goal_pos - player_pos;
let goal_direction = to_goal.normalize();
player_pos + goal_direction * 5.0 // Reduced from 10.0 to prevent excessive movement
}
/// Look for space between defenders toward the goal
fn find_space_between_opponents_toward_goal(
&self,
ctx: &StateProcessingContext,
) -> Option<Vector3<f32>> {
let player_pos = ctx.player.position;
let goal_pos = ctx.player().opponent_goal_position();
let to_goal_direction = (goal_pos - player_pos).normalize();
// Get opponents between player and goal
let opponents_between = ctx
.players()
.opponents()
.all()
.filter(|opp| {
let to_opp = opp.position - player_pos;
let projection = to_opp.dot(&to_goal_direction);
// Only consider opponents between player and goal
projection > 0.0 && projection < (goal_pos - player_pos).magnitude()
})
.collect::<Vec<_>>();
if opponents_between.len() < 2 {
return None; // Not enough opponents to find a gap
}
// Find the pair of opponents with the largest gap between them
let mut best_gap = None;
let mut max_gap_width = 0.0;
for i in 0..opponents_between.len() {
for j in i + 1..opponents_between.len() {
let opp1 = &opponents_between[i];
let opp2 = &opponents_between[j];
let midpoint = (opp1.position + opp2.position) * 0.5;
let gap_width = (opp1.position - opp2.position).magnitude();
// Check if midpoint is roughly toward goal
let to_midpoint = midpoint - player_pos;
let dot_product = to_midpoint.dot(&to_goal_direction);
if dot_product > 0.0 && gap_width > max_gap_width {
max_gap_width = gap_width;
best_gap = Some(midpoint);
}
}
}
// Return the midpoint of the largest gap
best_gap
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/walking/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/walking/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler,
SteeringBehavior,
};
use crate::IntegerUtils;
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardWalkingState {}
impl StateProcessingHandler for ForwardWalkingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
if ctx.ball().is_owned() {
if ctx.team().is_control_ball() {
return Some(StateChangeResult::with_forward_state(
ForwardState::CreatingSpace
));
} else {
return Some(StateChangeResult::with_forward_state(
ForwardState::Running
));
}
}
// Emergency: if ball is nearby, stopped, and unowned, go for it immediately
if ctx.ball().distance() < 50.0 && !ctx.ball().is_owned() {
let ball_velocity = ctx.tick_context.positions.ball.velocity.norm();
if ball_velocity < 1.0 {
// Ball is stopped or nearly stopped - take it directly
return Some(StateChangeResult::with_forward_state(
ForwardState::TakeBall,
));
}
}
None
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
if ctx.player.should_follow_waypoints(ctx) {
let waypoints = ctx.player.get_waypoints_as_vectors();
if !waypoints.is_empty() {
return Some(
SteeringBehavior::FollowPath {
waypoints,
current_waypoint: ctx.player.waypoint_manager.current_index,
path_offset: IntegerUtils::random(1, 10) as f32,
}
.calculate(ctx.player)
.velocity,
);
}
}
Some(
SteeringBehavior::Wander {
target: ctx.player.start_position,
radius: IntegerUtils::random(5, 15) as f32,
jitter: IntegerUtils::random(1, 5) as f32,
distance: IntegerUtils::random(10, 20) as f32,
angle: IntegerUtils::random(0, 360) as f32,
}
.calculate(ctx.player)
.velocity,
)
}
fn process_conditions(&self, ctx: ConditionContext) {
// Walking is low intensity - minimal fatigue
ForwardCondition::with_velocity(ActivityIntensity::Low).process(ctx);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/finishing/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/finishing/mod.rs | use crate::r#match::events::Event;
use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::player::events::PlayerEvent;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler,
};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardFinishingState {}
impl StateProcessingHandler for ForwardFinishingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
if !ctx.player.has_ball(ctx) {
// Transition to Running state if the player doesn't have the ball
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
// Check if the player is within shooting range
if !self.is_within_shooting_range(ctx) {
// Transition to Dribbling state if the player is not within shooting range
return Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
));
}
// Check if there's a clear shot on goal
if !ctx.player().has_clear_shot() {
// Transition to Passing state if there's no clear shot on goal
return Some(StateChangeResult::with_forward_state(ForwardState::Passing));
}
// Calculate the shooting direction and power
let (shooting_direction, _) = self.calculate_shooting_parameters(ctx);
// Transition to Running state after taking the shot
Some(StateChangeResult::with_forward_state_and_event(
ForwardState::Running,
Event::PlayerEvent(PlayerEvent::RequestShot(ctx.player.id, shooting_direction)),
))
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
Some(Vector3::new(0.0, 0.0, 0.0))
}
fn process_conditions(&self, ctx: ConditionContext) {
// Finishing is very high intensity - explosive action
ForwardCondition::new(ActivityIntensity::VeryHigh).process(ctx);
}
}
impl ForwardFinishingState {
fn is_within_shooting_range(&self, ctx: &StateProcessingContext) -> bool {
ctx.ball().distance_to_opponent_goal() <= 150.0
}
fn calculate_shooting_parameters(&self, ctx: &StateProcessingContext) -> (Vector3<f32>, f32) {
let goal_position = ctx.player().opponent_goal_position();
let shooting_direction = (goal_position - ctx.player.position).normalize();
let shooting_power = 1.0; // Adjust based on your game's mechanics
(shooting_direction, shooting_power)
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/forwarders/states/offside_trap_breaking/mod.rs | src/core/src/match/engine/player/strategies/forwarders/states/offside_trap_breaking/mod.rs | use crate::r#match::forwarders::states::common::{ActivityIntensity, ForwardCondition};
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::{
ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler,
};
use nalgebra::Vector3;
#[derive(Default)]
pub struct ForwardOffsideTrapBreakingState {}
impl StateProcessingHandler for ForwardOffsideTrapBreakingState {
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> {
let mut result = StateChangeResult::new();
let player_ops = ctx.player();
// Check if the player is onside
if player_ops.on_own_side() {
// Transition to Running state if the player is onside
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
// Check if the player has the ball
if ctx.player.has_ball(ctx) {
// Transition to Dribbling state if the player has the ball
return Some(StateChangeResult::with_forward_state(
ForwardState::Dribbling,
));
}
// Check if the offside trap is broken
if !self.is_offside_trap_active(ctx) {
// Transition to Running state if the offside trap is no longer active
return Some(StateChangeResult::with_forward_state(ForwardState::Running));
}
// Find the best position to break the offside trap
if let Some(target_position) = self.find_best_position(ctx) {
// Move towards the target position
let direction = (target_position - ctx.player.position).normalize();
result.velocity = Some(direction * ctx.player.skills.physical.acceleration);
}
Some(result)
}
fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> {
None
}
fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
Some(Vector3::new(0.0, 0.0, 0.0))
}
fn process_conditions(&self, ctx: ConditionContext) {
// Offside trap breaking is very high intensity - explosive sprint timing
ForwardCondition::with_velocity(ActivityIntensity::VeryHigh).process(ctx);
}
}
impl ForwardOffsideTrapBreakingState {
fn is_offside_trap_active(&self, ctx: &StateProcessingContext) -> bool {
let offside_line = ctx.players().opponents()
.all()
.map(|opponent| opponent.position.x)
.min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
.unwrap_or(0.0);
// Check if the player is beyond the offside line
ctx.player.position.x > offside_line
}
fn find_best_position(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> {
let ball_position = ctx.tick_context.positions.ball.position;
let offside_line = ctx.players().opponents()
.all()
.into_iter()
.map(|opponent| opponent.position.x)
.min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
.unwrap_or(0.0);
let target_x = offside_line - 1.0; // Adjust the target position to be just onside
let target_y = ball_position.y; // Maintain the same y-coordinate as the ball
Some(Vector3::new(target_x, target_y, 0.0))
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/squad/analyzer.rs | src/core/src/match/squad/analyzer.rs | use crate::club::{PlayerPositionType, Staff};
use crate::r#match::MatchResult;
use crate::{MatchTacticType, Player, TacticSelectionReason, TacticalStyle, Tactics, Team};
use log::info;
use std::collections::HashMap;
/// Enhanced tactical analysis for squad selection
pub struct TacticalSquadAnalyzer;
impl TacticalSquadAnalyzer {
/// Analyze team composition and suggest best formation
pub fn suggest_optimal_formation(team: &Team, staff: &Staff) -> Option<MatchTacticType> {
let available_players: Vec<&Player> = team
.players
.players()
.iter()
.filter(|&&p| !p.player_attributes.is_injured && !p.player_attributes.is_banned)
.map(|p| *p)
.collect();
if available_players.len() < 11 {
return None;
}
let composition = Self::analyze_squad_composition(&available_players);
let coach_preference = Self::analyze_coach_preferences(staff);
Self::determine_best_formation(composition, coach_preference)
}
/// Analyze the strengths and weaknesses of available players
fn analyze_squad_composition(players: &[&Player]) -> SquadComposition {
let mut composition = SquadComposition::new();
for &player in players {
// Analyze by position groups
for position in player.positions() {
let quality = Self::calculate_player_quality(player);
match position {
pos if pos.is_goalkeeper() => {
composition.goalkeeper_quality.push(quality);
}
pos if pos.is_defender() => {
composition.defender_quality.push(quality);
if matches!(pos, PlayerPositionType::DefenderLeft | PlayerPositionType::DefenderRight) {
composition.fullback_quality += quality;
}
}
pos if pos.is_midfielder() => {
composition.midfielder_quality.push(quality);
if matches!(pos, PlayerPositionType::DefensiveMidfielder) {
composition.defensive_mid_quality += quality;
}
if matches!(pos, PlayerPositionType::AttackingMidfielderCenter |
PlayerPositionType::AttackingMidfielderLeft |
PlayerPositionType::AttackingMidfielderRight) {
composition.attacking_mid_quality += quality;
}
}
pos if pos.is_forward() => {
composition.forward_quality.push(quality);
}
_ => {}
}
}
// Analyze specific attributes
composition.pace_merchants += if player.skills.physical.pace > 15.0 { 1 } else { 0 };
composition.technical_players += if player.skills.technical.technique > 15.0 { 1 } else { 0 };
composition.physical_players += if player.skills.physical.strength > 15.0 { 1 } else { 0 };
composition.creative_players += if player.skills.mental.vision > 15.0 { 1 } else { 0 };
}
composition.finalize_analysis();
composition
}
/// Analyze coach preferences and tactical knowledge
fn analyze_coach_preferences(staff: &Staff) -> CoachPreferences {
CoachPreferences {
tactical_knowledge: staff.staff_attributes.knowledge.tactical_knowledge,
attacking_preference: staff.staff_attributes.coaching.attacking,
defending_preference: staff.staff_attributes.coaching.defending,
prefers_youth: staff.staff_attributes.coaching.working_with_youngsters > 12,
conservative_approach: staff.behaviour.is_poor(),
}
}
/// Determine the best formation based on analysis
fn determine_best_formation(
composition: SquadComposition,
coach_prefs: CoachPreferences,
) -> Option<MatchTacticType> {
let mut formation_scores = HashMap::new();
// Score each formation based on squad composition
for formation in MatchTacticType::all() {
let score = Self::score_formation_fit(&formation, &composition, &coach_prefs);
formation_scores.insert(formation, score);
}
// Return the highest scoring formation
formation_scores
.into_iter()
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
.map(|(formation, _)| formation)
}
/// Score how well a formation fits the squad
fn score_formation_fit(
formation: &MatchTacticType,
composition: &SquadComposition,
coach_prefs: &CoachPreferences,
) -> f32 {
let tactics = Tactics::new(*formation);
let mut score = 0.0;
// Base fitness score (how well players fit positions)
score += tactics.calculate_formation_fitness(&composition.get_top_players()) * 0.4;
// Coach preference bonus
score += Self::coach_formation_preference_bonus(formation, coach_prefs) * 0.3;
// Tactical style bonuses based on squad strengths
match tactics.tactical_style() {
TacticalStyle::Attacking => {
score += composition.average_forward_quality() * 0.15;
score += composition.attacking_mid_quality * 0.1;
}
TacticalStyle::Defensive => {
score += composition.average_defender_quality() * 0.15;
score += composition.defensive_mid_quality * 0.1;
}
TacticalStyle::Possession => {
score += (composition.technical_players as f32 / 11.0) * 3.0;
score += (composition.creative_players as f32 / 11.0) * 2.0;
}
TacticalStyle::Counterattack => {
score += (composition.pace_merchants as f32 / 11.0) * 3.0;
score += composition.average_forward_quality() * 0.1;
}
TacticalStyle::WingPlay | TacticalStyle::WidePlay => {
score += composition.fullback_quality * 0.2;
score += (composition.pace_merchants as f32 / 11.0) * 2.0;
}
_ => {}
}
score
}
/// Calculate coach formation preference bonus
fn coach_formation_preference_bonus(
formation: &MatchTacticType,
coach_prefs: &CoachPreferences,
) -> f32 {
let mut bonus = 0.0;
// Tactical knowledge allows for more complex formations
let complexity_bonus = match formation {
MatchTacticType::T442 | MatchTacticType::T433 => {
// Simple formations - any coach can use
1.0
}
MatchTacticType::T4231 | MatchTacticType::T352 => {
// Moderate complexity
if coach_prefs.tactical_knowledge >= 12 { 1.2 } else { 0.8 }
}
MatchTacticType::T343 | MatchTacticType::T4312 => {
// High complexity
if coach_prefs.tactical_knowledge >= 15 { 1.5 } else { 0.6 }
}
_ => {
// Very complex formations
if coach_prefs.tactical_knowledge >= 18 { 2.0 } else { 0.4 }
}
};
bonus += complexity_bonus;
// Conservative coaches prefer proven formations
if coach_prefs.conservative_approach {
bonus += match formation {
MatchTacticType::T442 | MatchTacticType::T451 => 0.5,
_ => 0.0,
};
}
// Attacking/Defending preference
let attack_def_ratio = coach_prefs.attacking_preference as f32 / coach_prefs.defending_preference as f32;
if attack_def_ratio > 1.2 {
// Attacking coach
bonus += match formation {
MatchTacticType::T433 | MatchTacticType::T343 | MatchTacticType::T4231 => 0.3,
_ => 0.0,
};
} else if attack_def_ratio < 0.8 {
// Defensive coach
bonus += match formation {
MatchTacticType::T451 | MatchTacticType::T352 | MatchTacticType::T4141 => 0.3,
_ => 0.0,
};
}
bonus
}
/// Calculate overall player quality
fn calculate_player_quality(player: &Player) -> f32 {
let technical_avg = player.skills.technical.average();
let mental_avg = player.skills.mental.average();
let physical_avg = player.skills.physical.average();
let condition_factor = player.player_attributes.condition_percentage() as f32 / 100.0;
((technical_avg + mental_avg + physical_avg) / 3.0) * condition_factor
}
}
/// Analysis of squad composition
#[derive(Debug)]
pub struct SquadComposition {
pub goalkeeper_quality: Vec<f32>,
pub defender_quality: Vec<f32>,
pub midfielder_quality: Vec<f32>,
pub forward_quality: Vec<f32>,
pub fullback_quality: f32,
pub defensive_mid_quality: f32,
pub attacking_mid_quality: f32,
pub pace_merchants: u8,
pub technical_players: u8,
pub physical_players: u8,
pub creative_players: u8,
// Computed averages
avg_gk_quality: f32,
avg_def_quality: f32,
avg_mid_quality: f32,
avg_fwd_quality: f32,
}
impl SquadComposition {
fn new() -> Self {
SquadComposition {
goalkeeper_quality: Vec::new(),
defender_quality: Vec::new(),
midfielder_quality: Vec::new(),
forward_quality: Vec::new(),
fullback_quality: 0.0,
defensive_mid_quality: 0.0,
attacking_mid_quality: 0.0,
pace_merchants: 0,
technical_players: 0,
physical_players: 0,
creative_players: 0,
avg_gk_quality: 0.0,
avg_def_quality: 0.0,
avg_mid_quality: 0.0,
avg_fwd_quality: 0.0,
}
}
fn finalize_analysis(&mut self) {
self.avg_gk_quality = self.goalkeeper_quality.iter().sum::<f32>() / self.goalkeeper_quality.len().max(1) as f32;
self.avg_def_quality = self.defender_quality.iter().sum::<f32>() / self.defender_quality.len().max(1) as f32;
self.avg_mid_quality = self.midfielder_quality.iter().sum::<f32>() / self.midfielder_quality.len().max(1) as f32;
self.avg_fwd_quality = self.forward_quality.iter().sum::<f32>() / self.forward_quality.len().max(1) as f32;
}
pub fn average_goalkeeper_quality(&self) -> f32 { self.avg_gk_quality }
pub fn average_defender_quality(&self) -> f32 { self.avg_def_quality }
pub fn average_midfielder_quality(&self) -> f32 { self.avg_mid_quality }
pub fn average_forward_quality(&self) -> f32 { self.avg_fwd_quality }
/// Get a representative set of top players for formation fitness calculation
fn get_top_players(&self) -> Vec<&Player> {
// This would need to be implemented to return actual player references
// For now, return empty vec as this is used in a fitness calculation that
// we're approximating with the averages above
Vec::new()
}
}
/// Coach tactical preferences
#[derive(Debug)]
pub struct CoachPreferences {
pub tactical_knowledge: u8,
pub attacking_preference: u8,
pub defending_preference: u8,
pub prefers_youth: bool,
pub conservative_approach: bool,
}
/// Enhanced tactics selector that considers team dynamics
pub struct EnhancedTacticsSelector;
impl EnhancedTacticsSelector {
/// Select tactics considering recent performance and team mood
pub fn select_contextual_tactics(
team: &Team,
staff: &Staff,
recent_results: &[MatchResult],
team_morale: f32,
) -> Tactics {
let base_tactics = TacticalSquadAnalyzer::suggest_optimal_formation(team, staff)
.unwrap_or(MatchTacticType::T442);
let mut tactics = Tactics::new(base_tactics);
// Adjust based on recent performance
if let Some(adjusted) = Self::adjust_for_recent_form(&tactics, recent_results) {
tactics = adjusted;
}
// Adjust based on team morale
tactics = Self::adjust_for_morale(tactics, team_morale);
info!("Selected tactics: {} ({})",
tactics.formation_description(),
tactics.tactic_type.display_name());
tactics
}
/// Adjust tactics based on recent match results
fn adjust_for_recent_form(
current_tactics: &Tactics,
recent_results: &[MatchResult],
) -> Option<Tactics> {
if recent_results.len() < 3 {
return None;
}
let losses = recent_results.iter()
.take(5) // Last 5 games
.filter(|result| {
result.score.home_team.get() < result.score.away_team.get() ||
result.score.away_team.get() < result.score.home_team.get()
})
.count();
// If struggling, become more defensive
if losses >= 3 {
let defensive_formation = match current_tactics.tactic_type {
MatchTacticType::T433 => MatchTacticType::T451,
MatchTacticType::T4231 => MatchTacticType::T4141,
_ => return None,
};
Some(Tactics::with_reason(
defensive_formation,
TacticSelectionReason::GameSituation,
0.8,
))
} else {
None
}
}
/// Adjust tactics based on team morale
fn adjust_for_morale(mut tactics: Tactics, morale: f32) -> Tactics {
// High morale = more attacking
if morale > 0.7 {
tactics.formation_strength *= 1.1;
}
// Low morale = more conservative
else if morale < 0.3 {
tactics.formation_strength *= 0.9;
}
tactics
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/squad/mod.rs | src/core/src/match/squad/mod.rs | mod selector;
pub mod squad;
pub mod analyzer;
pub use analyzer::*;
pub use selector::*;
pub use squad::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/squad/selector.rs | src/core/src/match/squad/selector.rs | use crate::club::{PlayerPositionType, Staff};
use crate::r#match::player::MatchPlayer;
use crate::{Player, Tactics, Team};
use log::{debug, warn};
use std::borrow::Borrow;
pub struct SquadSelector;
const DEFAULT_SQUAD_SIZE: usize = 11;
const DEFAULT_BENCH_SIZE: usize = 7;
pub struct PlayerSelectionResult {
pub main_squad: Vec<MatchPlayer>,
pub substitutes: Vec<MatchPlayer>,
}
#[derive(Debug, Clone)]
struct PlayerRating {
player_id: u32,
rating: f32,
position_fitness: f32,
overall_ability: f32,
}
impl SquadSelector {
pub fn select(team: &Team, staff: &Staff) -> PlayerSelectionResult {
let current_tactics = team.tactics();
// Filter available players (not injured, not banned)
let available_players: Vec<&Player> = team
.players
.players()
.iter()
.filter(|&&p| !p.player_attributes.is_injured && !p.player_attributes.is_banned)
.map(|p| *p)
.collect();
debug!("Available players for selection: {}", available_players.len());
if available_players.len() < DEFAULT_SQUAD_SIZE {
warn!("Not enough available players for full squad: {}", available_players.len());
}
// Select main squad based on tactics
let main_squad = Self::select_main_squad_optimized(
team.id,
&available_players,
staff,
current_tactics.borrow(),
);
// Filter out selected main squad players for substitutes selection
let remaining_players: Vec<&Player> = available_players
.iter()
.filter(|&player| !main_squad.iter().any(|mp| mp.id == player.id))
.map(|&p| p)
.collect();
// Select substitutes
let substitutes = Self::select_substitutes_optimized(
team.id,
&remaining_players,
staff,
current_tactics.borrow(),
);
debug!("Selected squad - Main: {}, Subs: {}", main_squad.len(), substitutes.len());
PlayerSelectionResult {
main_squad,
substitutes,
}
}
/// Optimized main squad selection that properly uses tactics
fn select_main_squad_optimized(
team_id: u32,
available_players: &[&Player],
staff: &Staff,
tactics: &Tactics,
) -> Vec<MatchPlayer> {
let mut squad: Vec<MatchPlayer> = Vec::with_capacity(DEFAULT_SQUAD_SIZE);
let mut used_players: Vec<u32> = Vec::new();
// Get required positions from tactics
let required_positions = tactics.positions();
debug!("Formation: {} requires positions: {:?}",
tactics.formation_description(),
required_positions);
// For each required position, find the best available player
for (_, &required_position) in required_positions.iter().enumerate() {
if let Some(best_player) = Self::find_best_player_for_position(
available_players,
&used_players,
required_position,
staff,
tactics,
) {
squad.push(MatchPlayer::from_player(
team_id,
best_player,
required_position,
false,
));
used_players.push(best_player.id);
debug!("Selected {} for position {} ({})",
best_player.full_name,
required_position.get_short_name(),
Self::calculate_player_rating_for_position(best_player, staff, required_position, tactics));
} else {
warn!("No suitable player found for position: {}", required_position.get_short_name());
}
}
// Fill remaining spots if we don't have 11 players yet
while squad.len() < DEFAULT_SQUAD_SIZE && squad.len() < available_players.len() {
if let Some(best_remaining) = Self::find_best_remaining_player(
available_players,
&used_players,
staff,
tactics,
) {
// Assign them to their best position within the formation
let best_position = Self::find_best_position_for_player(best_remaining, tactics);
squad.push(MatchPlayer::from_player(
team_id,
best_remaining,
best_position,
false,
));
used_players.push(best_remaining.id);
} else {
break;
}
}
squad
}
/// Optimized substitute selection focusing on tactical flexibility
fn select_substitutes_optimized(
team_id: u32,
remaining_players: &[&Player],
staff: &Staff,
tactics: &Tactics,
) -> Vec<MatchPlayer> {
let mut substitutes: Vec<MatchPlayer> = Vec::with_capacity(DEFAULT_BENCH_SIZE);
let mut used_players: Vec<u32> = Vec::new();
// Prioritize substitute selection:
// 1. Backup goalkeeper (if not already selected)
if let Some(backup_gk) = remaining_players
.iter()
.filter(|p| p.positions.is_goalkeeper() && !used_players.contains(&p.id))
.max_by(|a, b| {
Self::calculate_player_rating_for_position(a, staff, PlayerPositionType::Goalkeeper, tactics)
.partial_cmp(&Self::calculate_player_rating_for_position(b, staff, PlayerPositionType::Goalkeeper, tactics))
.unwrap_or(std::cmp::Ordering::Equal)
}) {
substitutes.push(MatchPlayer::from_player(
team_id,
backup_gk,
PlayerPositionType::Goalkeeper,
false,
));
used_players.push(backup_gk.id);
}
// 2. Versatile players who can cover multiple positions
let mut versatile_players: Vec<(&Player, f32)> = remaining_players
.iter()
.filter(|p| !used_players.contains(&p.id))
.map(|&player| {
let versatility_score = Self::calculate_versatility_score(player, tactics);
(player, versatility_score)
})
.collect();
versatile_players.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
// 3. Add most versatile players to bench
for (player, _score) in versatile_players.iter().take(DEFAULT_BENCH_SIZE - substitutes.len()) {
if !used_players.contains(&player.id) {
let best_position = Self::find_best_position_for_player(player, tactics);
substitutes.push(MatchPlayer::from_player(
team_id,
player,
best_position,
false,
));
used_players.push(player.id);
}
}
// 4. Fill remaining spots with best available players
while substitutes.len() < DEFAULT_BENCH_SIZE && substitutes.len() + used_players.len() < remaining_players.len() {
if let Some(best_remaining) = Self::find_best_remaining_player(
remaining_players,
&used_players,
staff,
tactics,
) {
let best_position = Self::find_best_position_for_player(best_remaining, tactics);
substitutes.push(MatchPlayer::from_player(
team_id,
best_remaining,
best_position,
false,
));
used_players.push(best_remaining.id);
} else {
break;
}
}
substitutes
}
/// Find the best player for a specific position
fn find_best_player_for_position<'p>(
available_players: &'p [&Player],
used_players: &[u32],
position: PlayerPositionType,
staff: &Staff,
tactics: &Tactics,
) -> Option<&'p Player> {
available_players
.iter()
.filter(|p| !used_players.contains(&p.id))
.filter(|p| p.positions.has_position(position) || position == PlayerPositionType::Goalkeeper && p.positions.is_goalkeeper())
.max_by(|a, b| {
Self::calculate_player_rating_for_position(a, staff, position, tactics)
.partial_cmp(&Self::calculate_player_rating_for_position(b, staff, position, tactics))
.unwrap_or(std::cmp::Ordering::Equal)
})
.copied()
}
/// Find the best remaining player regardless of position
fn find_best_remaining_player<'p>(
available_players: &'p [&Player],
used_players: &[u32],
staff: &Staff,
tactics: &Tactics,
) -> Option<&'p Player> {
available_players
.iter()
.filter(|p| !used_players.contains(&p.id))
.max_by(|a, b| {
let rating_a = Self::calculate_overall_player_value(a, staff, tactics);
let rating_b = Self::calculate_overall_player_value(b, staff, tactics);
rating_a.partial_cmp(&rating_b).unwrap_or(std::cmp::Ordering::Equal)
})
.copied()
}
/// Find the best position for a player within the current tactics
fn find_best_position_for_player(player: &Player, tactics: &Tactics) -> PlayerPositionType {
let mut best_position = player.position(); // Default to primary position
let mut best_rating = 0.0;
for &position in tactics.positions() {
if player.positions.has_position(position) {
let position_level = player.positions.get_level(position) as f32;
if position_level > best_rating {
best_rating = position_level;
best_position = position;
}
}
}
best_position
}
/// Calculate player rating for a specific position considering tactics
pub fn calculate_player_rating_for_position(
player: &Player,
staff: &Staff,
position: PlayerPositionType,
tactics: &Tactics,
) -> f32 {
let mut rating = 0.0;
// Position proficiency (most important factor)
let position_level = player.positions.get_level(position) as f32;
rating += position_level * 0.4; // 40% weight
// Physical condition
rating += (player.player_attributes.condition as f32 / 10000.0) * 20.0 * 0.25; // 25% weight
// Overall ability
rating += player.player_attributes.current_ability as f32 / 200.0 * 20.0 * 0.2; // 20% weight
// Tactical fit for formation
rating += Self::calculate_tactical_fit(player, position, tactics) * 0.1; // 10% weight
// Staff relationship bonus
if staff.relations.is_favorite_player(player.id) {
rating += 2.0;
}
// Reputation bonus (small factor)
rating += (player.player_attributes.world_reputation as f32 / 10000.0) * 0.05; // 5% weight
rating
}
/// Calculate how well a player fits tactically in a position
fn calculate_tactical_fit(player: &Player, position: PlayerPositionType, tactics: &Tactics) -> f32 {
let mut fit_score = 10.0; // Base score
// Tactical style bonuses
match tactics.tactical_style() {
crate::TacticalStyle::Attacking => {
if position.is_forward() || position == PlayerPositionType::AttackingMidfielderCenter {
fit_score += player.skills.technical.finishing * 0.1;
fit_score += player.skills.mental.off_the_ball * 0.1;
}
}
crate::TacticalStyle::Defensive => {
if position.is_defender() || position == PlayerPositionType::DefensiveMidfielder {
fit_score += player.skills.technical.tackling * 0.1;
fit_score += player.skills.mental.positioning * 0.1;
}
}
crate::TacticalStyle::Possession => {
fit_score += player.skills.technical.passing * 0.08;
fit_score += player.skills.mental.vision * 0.08;
}
crate::TacticalStyle::Counterattack => {
if position.is_forward() || position.is_midfielder() {
fit_score += player.skills.physical.pace * 0.1;
fit_score += player.skills.mental.off_the_ball * 0.08;
}
}
crate::TacticalStyle::WingPlay | crate::TacticalStyle::WidePlay => {
if position == PlayerPositionType::WingbackLeft
|| position == PlayerPositionType::WingbackRight
|| position == PlayerPositionType::MidfielderLeft
|| position == PlayerPositionType::MidfielderRight {
fit_score += player.skills.technical.crossing * 0.1;
fit_score += player.skills.physical.pace * 0.08;
}
}
_ => {} // No specific bonuses for other styles
}
fit_score
}
/// Calculate overall player value considering multiple factors
fn calculate_overall_player_value(player: &Player, staff: &Staff, tactics: &Tactics) -> f32 {
let mut value = 0.0;
// Find best position for this player in current tactics
let best_position = Self::find_best_position_for_player(player, tactics);
value += Self::calculate_player_rating_for_position(player, staff, best_position, tactics);
// Add versatility bonus
value += Self::calculate_versatility_score(player, tactics) * 0.1;
value
}
/// Calculate how versatile a player is (can play multiple positions)
fn calculate_versatility_score(player: &Player, tactics: &Tactics) -> f32 {
let tactics_positions = tactics.positions();
let player_positions = player.positions();
let covered_positions = tactics_positions
.iter()
.filter(|&&pos| player_positions.contains(&pos))
.count();
// Score based on how many tactical positions they can cover
match covered_positions {
0 => 0.0,
1 => 1.0,
2 => 3.0,
3 => 6.0,
4 => 10.0,
_ => 15.0,
}
}
/// Legacy method for backward compatibility
pub fn select_main_squad(
team_id: u32,
players: &mut Vec<&Player>,
staff: &Staff,
tactics: &Tactics,
) -> Vec<MatchPlayer> {
Self::select_main_squad_optimized(team_id, players, staff, tactics)
}
/// Legacy method for backward compatibility
pub fn select_substitutes(
team_id: u32,
players: &mut Vec<&Player>,
staff: &Staff,
tactics: &Tactics,
) -> Vec<MatchPlayer> {
Self::select_substitutes_optimized(team_id, players, staff, tactics)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{IntegerUtils, MatchTacticType, PlayerCollection, PlayerGenerator, StaffCollection, TeamBuilder, TeamReputation, TeamType, TrainingSchedule};
use chrono::{NaiveTime, Utc};
#[test]
fn test_squad_selection_respects_formation() {
let team = generate_test_team();
let staff = generate_test_staff();
let result = SquadSelector::select(&team, &staff);
// Should select exactly 11 main squad players
assert_eq!(result.main_squad.len(), 11);
// Should have substitutes
assert!(!result.substitutes.is_empty());
assert!(result.substitutes.len() <= DEFAULT_BENCH_SIZE);
// All positions in formation should be covered
let tactics = team.tactics();
let formation_positions = tactics.positions();
assert_eq!(result.main_squad.len(), formation_positions.len());
}
#[test]
fn test_tactical_fit_calculation() {
let player = generate_attacking_player();
let tactics = crate::Tactics::new(MatchTacticType::T433); // More attacking formation
let fit = SquadSelector::calculate_tactical_fit(&player, PlayerPositionType::Striker, &tactics);
assert!(fit > 10.0); // Should be above base score due to attacking bonuses
}
// Helper functions for tests
fn generate_test_team() -> Team {
let mut team = TeamBuilder::new()
.id(1)
.league_id(1)
.club_id(1)
.name("Test Team".to_string())
.slug("test-team".to_string())
.team_type(TeamType::Main)
.training_schedule(TrainingSchedule::new(
NaiveTime::from_hms_opt(10, 0, 0).unwrap(),
NaiveTime::from_hms_opt(17, 0, 0).unwrap(),
))
.reputation(TeamReputation::new(100, 100, 100))
.players(PlayerCollection::new(generate_test_players()))
.staffs(StaffCollection::new(Vec::new()))
.tactics(Some(Tactics::new(MatchTacticType::T442)))
.build()
.expect("Failed to build test team");
team.tactics = Some(Tactics::new(MatchTacticType::T442));
team
}
fn generate_test_staff() -> Staff {
crate::StaffStub::default()
}
fn generate_test_players() -> Vec<Player> {
let mut players = Vec::new();
// Generate players for each position
for &position in &[
PlayerPositionType::Goalkeeper,
PlayerPositionType::DefenderLeft,
PlayerPositionType::DefenderCenter,
PlayerPositionType::DefenderRight,
PlayerPositionType::MidfielderLeft,
PlayerPositionType::MidfielderCenter,
PlayerPositionType::MidfielderRight,
PlayerPositionType::Striker,
] {
for _ in 0..3 { // 3 players per position
let level = IntegerUtils::random(15, 20) as u8;
let player = PlayerGenerator::generate(1, Utc::now().date_naive(), position, level);
players.push(player);
}
}
players
}
fn generate_versatile_player() -> crate::Player {
// Create a player that can play multiple positions
PlayerGenerator::generate(1, Utc::now().date_naive(), PlayerPositionType::MidfielderCenter, 18)
}
fn generate_attacking_player() -> crate::Player {
PlayerGenerator::generate(1, Utc::now().date_naive(), PlayerPositionType::Striker, 18)
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/squad/squad.rs | src/core/src/match/squad/squad.rs | use crate::r#match::MatchPlayer;
use crate::Tactics;
#[derive(Debug, Clone)]
pub struct MatchSquad {
pub team_id: u32,
pub team_name: String,
pub tactics: Tactics,
pub main_squad: Vec<MatchPlayer>,
pub substitutes: Vec<MatchPlayer>,
pub captain_id: Option<MatchPlayer>,
pub vice_captain_id: Option<MatchPlayer>,
pub penalty_taker_id: Option<MatchPlayer>,
pub free_kick_taker_id: Option<MatchPlayer>,
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/mood.rs | src/core/src/club/mood.rs | #[derive(Debug)]
pub struct ClubMood {
pub state: ClubMoodState,
}
impl ClubMood {
pub fn default() -> Self {
ClubMood {
state: ClubMoodState::Normal,
}
}
}
#[derive(Debug)]
pub enum ClubMoodState {
Poor,
Normal,
Good,
Excellent,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/status.rs | src/core/src/club/status.rs | #[derive(Debug)]
pub enum ClubStatus {
Amateur,
SemiProfessional,
Professional,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/club.rs | src/core/src/club/club.rs | use crate::club::academy::ClubAcademy;
use crate::club::board::ClubBoard;
use crate::club::status::ClubStatus;
use crate::club::{ClubFinances, ClubResult};
use crate::context::GlobalContext;
use crate::shared::Location;
use crate::TeamCollection;
#[derive(Debug)]
pub struct Club {
pub id: u32,
pub name: String,
pub location: Location,
pub board: ClubBoard,
pub finance: ClubFinances,
pub status: ClubStatus,
pub academy: ClubAcademy,
pub teams: TeamCollection,
}
impl Club {
pub fn new(
id: u32,
name: String,
location: Location,
finance: ClubFinances,
academy: ClubAcademy,
status: ClubStatus,
teams: TeamCollection,
) -> Self {
Club {
id,
name,
location,
finance,
status,
academy,
board: ClubBoard::new(),
teams,
}
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> ClubResult {
let result = ClubResult::new(
self.finance.simulate(ctx.with_finance()),
self.teams.simulate(ctx.with_club(self.id, &self.name)),
self.board.simulate(ctx.with_board()),
self.academy.simulate(ctx.clone()),
);
if ctx.simulation.is_week_beginning() {
self.process_salaries(ctx);
}
result
}
fn process_salaries(&mut self, ctx: GlobalContext<'_>) {
for team in &self.teams.teams {
let weekly_salary = team.get_week_salary();
self.finance.push_salary(
ctx.club.as_ref().expect("no club found").name,
weekly_salary as i32,
);
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/person.rs | src/core/src/club/person.rs | use crate::shared::FullName;
use crate::utils::DateUtils;
use crate::Relations;
use chrono::NaiveDate;
pub trait Person {
fn id(&self) -> u32;
fn fullname(&self) -> &FullName;
fn birthday(&self) -> NaiveDate;
fn age(&self, now: NaiveDate) -> u8 {
DateUtils::age(self.birthday(), now)
}
fn behaviour(&self) -> &PersonBehaviour;
fn attributes(&self) -> &PersonAttributes;
fn relations(&self) -> &Relations;
}
#[derive(Debug, Copy, Clone, Default)]
pub struct PersonAttributes {
pub adaptability: f32,
pub ambition: f32,
pub controversy: f32,
pub loyalty: f32,
pub pressure: f32,
pub professionalism: f32,
pub sportsmanship: f32,
pub temperament: f32,
}
#[derive(Debug, Default)]
pub struct PersonBehaviour {
pub state: PersonBehaviourState,
}
impl PersonBehaviour {
pub fn try_increase(&mut self) {
match self.state {
PersonBehaviourState::Poor => {
self.state = PersonBehaviourState::Normal;
}
PersonBehaviourState::Normal => {
self.state = PersonBehaviourState::Good;
}
_ => {}
}
}
pub fn is_poor(&self) -> bool {
self.state == PersonBehaviourState::Poor
}
pub fn as_str(&self) -> &'static str {
self.state.as_str()
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
#[derive(Default)]
pub enum PersonBehaviourState {
Poor,
#[default]
Normal,
Good,
}
impl PersonBehaviourState {
pub fn as_str(&self) -> &'static str {
match self {
PersonBehaviourState::Poor => "Poor",
PersonBehaviourState::Normal => "Normal",
PersonBehaviourState::Good => "Good",
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/result.rs | src/core/src/club/result.rs | use crate::club::academy::result::ClubAcademyResult;
use crate::club::{BoardResult, ClubFinanceResult};
use crate::simulator::SimulatorData;
use crate::{
PlayerContractProposal, PlayerMessage, PlayerMessageType, PlayerResult, SimulationResult,
TeamResult,
};
pub struct ClubResult {
pub finance: ClubFinanceResult,
pub teams: Vec<TeamResult>,
pub board: BoardResult,
pub academy: ClubAcademyResult,
}
impl ClubResult {
pub fn new(
finance: ClubFinanceResult,
teams: Vec<TeamResult>,
board: BoardResult,
academy: ClubAcademyResult,
) -> Self {
ClubResult {
finance,
teams,
board,
academy,
}
}
pub fn process(self, data: &mut SimulatorData, _result: &mut SimulationResult) {
self.finance.process(data);
for team_result in &self.teams {
for player_result in &team_result.players.players {
if player_result.has_contract_actions() {
Self::process_player_contract_interaction(player_result, data);
}
}
team_result.process(data);
}
self.board.process(data);
self.academy.process(data);
}
fn process_player_contract_interaction(result: &PlayerResult, data: &mut SimulatorData) {
if result.contract.no_contract || result.contract.want_improve_contract {
let player = data.player(result.player_id).expect(&format!("player {} not found", result.player_id));
let player_growth_potential = player.growth_potential(data.date.date());
player.mailbox.push(PlayerMessage {
message_type: PlayerMessageType::ContractProposal(PlayerContractProposal {
salary: get_contract_salary(player_growth_potential),
years: 3,
}),
})
}
fn get_contract_salary(player_growth_potential: u8) -> u32 {
match player_growth_potential as u32 {
0..=3 => 1000u32,
4 => 2000u32,
5 => 3000u32,
_ => 1000u32,
}
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/mod.rs | src/core/src/club/mod.rs | pub mod academy;
pub mod board;
pub mod club;
pub mod context;
pub mod finance;
pub mod mood;
pub mod person;
pub mod player;
pub mod relations;
pub mod result;
pub mod staff;
pub mod status;
pub mod team;
pub mod transfers;
// Re-export all simple modules
pub use board::*;
pub use club::*;
pub use context::*;
pub use mood::*;
pub use person::*;
pub use result::*;
pub use status::*;
// Finance exports
pub use finance::{
ClubFinances, ClubFinancialBalance, ClubFinancialBalanceHistory,
ClubSponsorship, ClubSponsorshipContract,
ClubFinanceContext, ClubFinanceResult,
};
// Relations exports
pub use relations::{
Relations, PlayerRelation, StaffRelation, ChemistryFactors,
ChangeType, MentorshipType, InfluenceLevel, ConflictType, ConflictSeverity,
RelationshipChange, ConflictInfo,
};
// Transfers exports
pub use transfers::{
ClubTransferStrategy,
};
// Player exports (except conflicting modules)
pub use player::{
Player, PlayerCollection, PlayerBuilder,
PlayerAttributes, PlayerContext,
PlayerPreferredFoot, PlayerPositionType, PlayerFieldPositionGroup, PlayerStatusType,
PlayerSkills, Technical, Mental, Physical,
PlayerPositions, PlayerPosition, PlayerStatus, StatusData,
PlayerStatistics, PlayerStatisticsHistory, PlayerStatisticsHistoryItem,
PlayerHappiness, PositiveHappiness, NegativeHappiness,
PlayerClubContract, ContractType, PlayerSquadStatus, PlayerTransferStatus,
ContractBonusType, ContractBonus, ContractClauseType, ContractClause,
PlayerMailbox, PlayerMessage, PlayerMessageType, PlayerContractProposal, PlayerMailboxResult,
PlayerTraining, PlayerTrainingHistory, TrainingRecord,
PlayerResult, PlayerCollectionResult, PlayerContractResult,
PlayerValueCalculator, PlayerGenerator, PlayerUtils,
CONDITION_MAX_VALUE,
};
// Also export the missing types
pub use player::training::result::PlayerTrainingResult;
pub use player::mailbox::handlers::{AcceptContractHandler, ProcessContractHandler};
// Also export context module for those who want to import from it
pub use player::context as player_context;
// Also keep module aliases for those who want to import from the module
pub use player::attributes as player_attributes_mod;
pub use player::contract as player_contract_mod;
pub use player::builder as player_builder_mod;
pub use player::mailbox::handlers;
// Staff exports (except conflicting modules)
pub use staff::{
Staff, StaffCollection, StaffStub,
StaffAttributes, StaffContext,
StaffCoaching, StaffGoalkeeperCoaching, StaffMental,
StaffKnowledge, StaffDataAnalysis, StaffMedical,
StaffClubContract, StaffPosition, StaffStatus,
CoachFocus, TechnicalFocusType, MentalFocusType, PhysicalFocusType,
StaffResponsibility, BoardResponsibility, RecruitmentResponsibility,
IncomingTransfersResponsibility, OutgoingTransfersResponsibility,
ContractRenewalResponsibility, ScoutingResponsibility, TrainingResponsibility,
StaffPerformance, CoachingStyle,
StaffResult, StaffCollectionResult, StaffContractResult, StaffTrainingResult,
StaffWarning, StaffMoraleEvent, ResignationReason, HealthIssue,
RelationshipEvent, StaffLicenseType, StaffTrainingSession,
};
// Also export context module for those who want to import from it
pub use staff::context as staff_context;
pub use staff::focus;
pub use staff::responsibility;
pub use staff::staff_stub;
// Also keep module aliases for those who want to import from the module
pub use staff::attributes as staff_attributes_mod;
pub use staff::contract as staff_contract_mod;
// Team exports (except conflicting modules)
pub use team::{
Team, TeamCollection, TeamType, TeamBuilder, TeamContext,
TeamResult,
TeamBehaviour, TeamBehaviourResult, PlayerBehaviourResult, PlayerRelationshipChangeResult,
Tactics, TacticalStyle, MatchTacticType, TacticSelectionReason, TacticsSelector,
TacticalDecisionEngine, TacticalDecisionResult, FormationChange, SquadAnalysis,
TacticalRecommendation, RecommendationPriority, RecommendationCategory,
TeamTraining, TeamTrainingResult, TrainingSchedule, TrainingType,
TrainingSession, TrainingIntensity, WeeklyTrainingPlan, PeriodizationPhase,
TrainingEffects, PhysicalGains, TechnicalGains, MentalGains,
IndividualTrainingPlan, TrainingFocus, SkillType, SpecialInstruction,
CoachingPhilosophy, TacticalFocus, TrainingIntensityPreference, RotationPreference,
TrainingFacilities, FacilityQuality, TrainingLoadManager, PlayerTrainingLoad,
Transfers, TransferItem,
MatchHistory, MatchHistoryItem,
TeamReputation, ReputationLevel, ReputationTrend, Achievement, AchievementType,
MatchResultInfo, MatchOutcome, ReputationRequirements,
TACTICS_POSITIONS,
};
// Also export context module for those who want to import from it
pub use team::context as team_context;
pub use team::behaviour;
pub use team::collection;
pub use team::matches;
pub use team::reputation;
pub use team::tactics;
pub use team::training as team_training_mod;
pub use team::transfers as team_transfers_mod;
// Also keep module aliases for those who want to import from the module
pub use team::builder as team_builder_mod;
// Note: team's CompetitionType is exported but will conflict in lib.rs
pub use team::reputation::CompetitionType as TeamCompetitionType;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/relations.rs | src/core/src/club/relations.rs | use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};
/// Enhanced Relations system with complex relationship dynamics
#[derive(Debug, Clone)]
pub struct Relations {
/// Player relationships
players: RelationStore<PlayerRelation>,
/// Staff relationships
staffs: RelationStore<StaffRelation>,
/// Group dynamics and cliques
groups: GroupDynamics,
/// Relationship events history
history: RelationshipHistory,
/// Global mood and chemistry
chemistry: TeamChemistry,
}
impl Default for Relations {
fn default() -> Self {
Self::new()
}
}
impl Relations {
pub fn new() -> Self {
Relations {
players: RelationStore::new(),
staffs: RelationStore::new(),
groups: GroupDynamics::new(),
history: RelationshipHistory::new(),
chemistry: TeamChemistry::new(),
}
}
/// Simple update method for backward compatibility
/// Updates a player relationship by a simple increment value
pub fn update(&mut self, player_id: u32, increment: f32) {
// Create a relationship change based on the increment
let change = if increment >= 0.0 {
RelationshipChange::positive(
ChangeType::NaturalProgression,
increment.abs(),
)
} else {
RelationshipChange::negative(
ChangeType::NaturalProgression,
increment.abs(),
)
};
// Use the current date (you might want to pass this as a parameter)
let date = chrono::Local::now().date_naive();
// Update using the existing method
self.update_player_relationship(player_id, change, date);
}
/// Alternative: Direct level update without full change tracking
pub fn update_simple(&mut self, player_id: u32, increment: f32) {
let relation = self.players.get_or_create(player_id);
relation.level = (relation.level + increment).clamp(-100.0, 100.0);
// Update momentum based on the change
relation.momentum = (relation.momentum + increment.signum() * 0.1).clamp(-1.0, 1.0);
// Update interaction frequency
relation.interaction_frequency = (relation.interaction_frequency + 0.1).min(1.0);
// Recalculate chemistry if significant change
if increment.abs() > 0.1 {
self.chemistry.recalculate(&self.players, &self.staffs);
}
}
// ========== Player Relations ==========
/// Get relationship with a specific player
pub fn get_player(&self, id: u32) -> Option<&PlayerRelation> {
self.players.get(id)
}
/// Update player relationship with detailed context
pub fn update_player_relationship(
&mut self,
player_id: u32,
change: RelationshipChange,
date: NaiveDate,
) {
// Store values we need before taking mutable borrows
let (old_level, new_level, should_recalculate) = {
// Create a scope for the mutable borrow
let relation = self.players.get_or_create(player_id);
// Store the old level
let old_level = relation.level;
// Apply the change
relation.apply_change(&change);
// Store the new level
let new_level = relation.level;
// Determine if we should recalculate chemistry
let should_recalculate = (new_level - old_level).abs() > 0.1;
// Return the values we need (this ends the mutable borrow)
(old_level, new_level, should_recalculate)
}; // Mutable borrow of self.players ends here
// Record the event (no borrow conflicts)
self.history.record_event(RelationshipEvent {
date,
subject_id: player_id,
subject_type: SubjectType::Player,
change_type: change.change_type.clone(),
old_value: old_level,
new_value: new_level,
});
// Update chemistry if significant change (can now borrow immutably)
if should_recalculate {
self.chemistry.recalculate(&self.players, &self.staffs);
}
// Check for group formation/dissolution (uses new_level instead of relation.level)
self.groups.update_from_relationship(player_id, new_level);
}
/// Get all favorite players
pub fn get_favorite_players(&self) -> Vec<u32> {
self.players.get_favorites()
}
/// Get all disliked players
pub fn get_disliked_players(&self) -> Vec<u32> {
self.players.get_disliked()
}
/// Check if player is a favorite
pub fn is_favorite_player(&self, player_id: u32) -> bool {
self.players.get(player_id)
.map(|r| r.is_favorite())
.unwrap_or(false)
}
// ========== Staff Relations ==========
/// Get relationship with a specific staff member
pub fn get_staff(&self, id: u32) -> Option<&StaffRelation> {
self.staffs.get(id)
}
/// Update staff relationship
pub fn update_staff_relationship(
&mut self,
staff_id: u32,
change: RelationshipChange,
date: NaiveDate,
) {
let relation = self.staffs.get_or_create(staff_id);
let old_level = relation.level;
relation.apply_change(&change);
self.history.record_event(RelationshipEvent {
date,
subject_id: staff_id,
subject_type: SubjectType::Staff,
change_type: change.change_type.clone(),
old_value: old_level,
new_value: relation.level,
});
self.chemistry.recalculate(&self.players, &self.staffs);
}
/// Get coaching receptiveness (how well player responds to coaching)
pub fn get_coaching_receptiveness(&self, coach_id: u32) -> f32 {
self.staffs.get(coach_id)
.map(|r| r.calculate_coaching_multiplier())
.unwrap_or(1.0)
}
// ========== Group Dynamics ==========
/// Get all cliques/groups this entity belongs to
pub fn get_groups(&self, entity_id: u32) -> Vec<GroupId> {
self.groups.get_entity_groups(entity_id)
}
/// Get influence level in the dressing room
pub fn get_influence_level(&self, player_id: u32) -> InfluenceLevel {
let base_influence = self.players.get(player_id)
.map(|r| r.influence)
.unwrap_or(0.0);
let group_bonus = self.groups.get_leadership_bonus(player_id);
InfluenceLevel::from_value(base_influence + group_bonus)
}
/// Check for potential conflicts
pub fn get_potential_conflicts(&self) -> Vec<ConflictInfo> {
let mut conflicts = Vec::new();
// Check for rivalries
for (id1, rel1) in self.players.iter() {
for (id2, rel2) in self.players.iter() {
if id1 < id2 && rel1.rivalry_with.contains(&id2) {
conflicts.push(ConflictInfo {
party_a: *id1,
party_b: *id2,
conflict_type: ConflictType::PersonalRivalry,
severity: ConflictSeverity::from_relationship_levels(rel1.level, rel2.level),
});
}
}
}
// Check for group conflicts
conflicts.extend(self.groups.get_group_conflicts());
conflicts
}
// ========== Chemistry & Morale ==========
/// Get overall team chemistry
pub fn get_team_chemistry(&self) -> f32 {
self.chemistry.overall
}
/// Get chemistry breakdown
pub fn get_chemistry_factors(&self) -> &ChemistryFactors {
&self.chemistry.factors
}
/// Process weekly relationship decay and evolution
pub fn process_weekly_update(&mut self, date: NaiveDate) {
// Natural relationship evolution
self.players.apply_natural_decay();
self.staffs.apply_natural_decay();
// Update groups
self.groups.weekly_update();
// Clean old history
self.history.cleanup_old_events(date);
// Recalculate chemistry
self.chemistry.recalculate(&self.players, &self.staffs);
}
/// Simulate relationship interactions during training
pub fn simulate_training_interactions(
&mut self,
participants: &[u32],
training_quality: f32,
date: NaiveDate,
) {
// Players training together build relationships
for i in 0..participants.len() {
for j in i + 1..participants.len() {
let change = if training_quality > 0.7 {
RelationshipChange::positive(
ChangeType::TrainingBonding,
0.02 * training_quality,
)
} else if training_quality < 0.3 {
RelationshipChange::negative(
ChangeType::TrainingFriction,
0.01,
)
} else {
continue;
};
self.update_player_relationship(participants[j], change, date);
}
}
}
}
/// Store for relationships of a specific type
#[derive(Debug, Clone)]
struct RelationStore<T: Relationship> {
relations: HashMap<u32, T>,
}
impl<T: Relationship> RelationStore<T> {
fn new() -> Self {
RelationStore {
relations: HashMap::new(),
}
}
fn get(&self, id: u32) -> Option<&T> {
self.relations.get(&id)
}
fn get_or_create(&mut self, id: u32) -> &mut T {
self.relations.entry(id).or_insert_with(T::new_neutral)
}
fn get_favorites(&self) -> Vec<u32> {
self.relations.iter()
.filter(|(_, r)| r.is_favorite())
.map(|(id, _)| *id)
.collect()
}
fn get_disliked(&self) -> Vec<u32> {
self.relations.iter()
.filter(|(_, r)| r.is_disliked())
.map(|(id, _)| *id)
.collect()
}
fn apply_natural_decay(&mut self) {
for relation in self.relations.values_mut() {
relation.apply_decay();
}
}
fn iter(&self) -> impl Iterator<Item=(&u32, &T)> {
self.relations.iter()
}
}
/// Trait for relationship types
trait Relationship {
fn new_neutral() -> Self;
fn is_favorite(&self) -> bool;
fn is_disliked(&self) -> bool;
fn apply_decay(&mut self);
fn apply_change(&mut self, change: &RelationshipChange);
}
/// Player relationship details
#[derive(Debug, Clone)]
pub struct PlayerRelation {
/// Relationship level (-100 to 100)
pub level: f32,
/// Trust level (0 to 100)
pub trust: f32,
/// Respect level (0 to 100)
pub respect: f32,
/// Friendship level (0 to 100)
pub friendship: f32,
/// Professional respect (0 to 100)
pub professional_respect: f32,
/// Influence this player has
pub influence: f32,
/// Mentorship relationship
pub mentorship: Option<MentorshipType>,
/// Rivalry information
pub rivalry_with: HashSet<u32>,
/// Interaction frequency
pub interaction_frequency: f32,
/// Relationship momentum
momentum: f32,
}
impl Relationship for PlayerRelation {
fn new_neutral() -> Self {
PlayerRelation {
level: 0.0,
trust: 50.0,
respect: 50.0,
friendship: 30.0,
professional_respect: 50.0,
influence: 0.0,
mentorship: None,
rivalry_with: HashSet::new(),
interaction_frequency: 0.0,
momentum: 0.0,
}
}
fn is_favorite(&self) -> bool {
self.level >= 70.0 && self.trust >= 70.0
}
fn is_disliked(&self) -> bool {
self.level <= -50.0 || self.trust <= 20.0
}
fn apply_decay(&mut self) {
// Relationships naturally decay toward neutral
if self.interaction_frequency < 0.3 {
self.level *= 0.98;
self.trust *= 0.99;
self.friendship *= 0.97;
}
// Reset interaction frequency
self.interaction_frequency *= 0.9;
// Momentum decays
self.momentum *= 0.95;
}
fn apply_change(&mut self, change: &RelationshipChange) {
let magnitude = change.magnitude * (1.0 + self.momentum * 0.5);
match change.change_type {
ChangeType::MatchCooperation => {
self.level += magnitude * 2.0;
self.trust += magnitude * 1.5;
self.professional_respect += magnitude * 3.0;
}
ChangeType::TrainingBonding => {
self.friendship += magnitude * 2.0;
self.level += magnitude;
}
ChangeType::ConflictResolution => {
self.trust += magnitude * 3.0;
self.respect += magnitude * 2.0;
self.level += magnitude * 2.0;
}
ChangeType::PersonalSupport => {
self.friendship += magnitude * 4.0;
self.trust += magnitude * 3.0;
self.level += magnitude * 2.0;
}
ChangeType::CompetitionRivalry => {
self.level -= magnitude * 2.0;
self.professional_respect -= magnitude;
self.rivalry_with.insert(0); // Add to rivalry set
}
ChangeType::TrainingFriction => {
self.level -= magnitude;
self.trust -= magnitude * 0.5;
}
ChangeType::PersonalConflict => {
self.level -= magnitude * 3.0;
self.trust -= magnitude * 2.0;
self.friendship -= magnitude * 3.0;
}
_ => {
self.level += magnitude;
}
}
// Update momentum
self.momentum = (self.momentum + magnitude.signum() * 0.1).clamp(-1.0, 1.0);
// Update interaction frequency
self.interaction_frequency = (self.interaction_frequency + 0.1).min(1.0);
// Clamp values
self.level = self.level.clamp(-100.0, 100.0);
self.trust = self.trust.clamp(0.0, 100.0);
self.respect = self.respect.clamp(0.0, 100.0);
self.friendship = self.friendship.clamp(0.0, 100.0);
self.professional_respect = self.professional_respect.clamp(0.0, 100.0);
}
}
/// Staff relationship details
#[derive(Debug, Clone)]
pub struct StaffRelation {
/// Relationship level (-100 to 100)
pub level: f32,
/// Authority respect (0 to 100)
pub authority_respect: f32,
/// Trust in abilities (0 to 100)
pub trust_in_abilities: f32,
/// Personal bond (0 to 100)
pub personal_bond: f32,
/// Coaching receptiveness
pub receptiveness: f32,
/// Loyalty to staff member
pub loyalty: f32,
}
impl StaffRelation {
pub fn calculate_coaching_multiplier(&self) -> f32 {
let base = 1.0;
let respect_bonus = (self.authority_respect / 100.0) * 0.3;
let trust_bonus = (self.trust_in_abilities / 100.0) * 0.2;
let receptiveness_bonus = (self.receptiveness / 100.0) * 0.3;
base + respect_bonus + trust_bonus + receptiveness_bonus
}
}
impl Relationship for StaffRelation {
fn new_neutral() -> Self {
StaffRelation {
level: 0.0,
authority_respect: 50.0,
trust_in_abilities: 50.0,
personal_bond: 30.0,
receptiveness: 50.0,
loyalty: 30.0,
}
}
fn is_favorite(&self) -> bool {
self.level >= 70.0 && self.loyalty >= 70.0
}
fn is_disliked(&self) -> bool {
self.level <= -50.0 || self.authority_respect <= 20.0
}
fn apply_decay(&mut self) {
// Authority respect decays if not reinforced
self.authority_respect *= 0.99;
// Personal bonds decay without interaction
self.personal_bond *= 0.98;
// Level trends toward neutral
self.level *= 0.99;
}
fn apply_change(&mut self, change: &RelationshipChange) {
let magnitude = change.magnitude;
match change.change_type {
ChangeType::CoachingSuccess => {
self.trust_in_abilities += magnitude * 3.0;
self.receptiveness += magnitude * 2.0;
self.level += magnitude * 2.0;
}
ChangeType::TacticalDisagreement => {
self.authority_respect -= magnitude * 2.0;
self.receptiveness -= magnitude * 3.0;
self.level -= magnitude;
}
ChangeType::PersonalSupport => {
self.personal_bond += magnitude * 4.0;
self.loyalty += magnitude * 3.0;
self.level += magnitude * 2.0;
}
ChangeType::DisciplinaryAction => {
self.authority_respect += magnitude; // Can increase if fair
self.personal_bond -= magnitude * 2.0;
self.level -= magnitude;
}
_ => {
self.level += magnitude;
}
}
// Clamp values
self.level = self.level.clamp(-100.0, 100.0);
self.authority_respect = self.authority_respect.clamp(0.0, 100.0);
self.trust_in_abilities = self.trust_in_abilities.clamp(0.0, 100.0);
self.personal_bond = self.personal_bond.clamp(0.0, 100.0);
self.receptiveness = self.receptiveness.clamp(0.0, 100.0);
self.loyalty = self.loyalty.clamp(0.0, 100.0);
}
}
/// Group dynamics and cliques
#[derive(Debug, Clone)]
struct GroupDynamics {
groups: HashMap<GroupId, Group>,
entity_groups: HashMap<u32, HashSet<GroupId>>,
next_group_id: GroupId,
}
impl GroupDynamics {
fn new() -> Self {
GroupDynamics {
groups: HashMap::new(),
entity_groups: HashMap::new(),
next_group_id: 0,
}
}
fn update_from_relationship(&mut self, _entity_id: u32, _relationship_level: f32) {
// Logic to form/update groups based on relationships
// Simplified for brevity
}
fn get_entity_groups(&self, entity_id: u32) -> Vec<GroupId> {
self.entity_groups.get(&entity_id)
.map(|groups| groups.iter().copied().collect())
.unwrap_or_default()
}
fn get_leadership_bonus(&self, entity_id: u32) -> f32 {
self.entity_groups.get(&entity_id)
.map(|groups| {
groups.iter()
.filter_map(|gid| self.groups.get(gid))
.filter(|g| g.leader_id == Some(entity_id))
.map(|g| 0.2 * g.cohesion)
.sum()
})
.unwrap_or(0.0)
}
fn get_group_conflicts(&self) -> Vec<ConflictInfo> {
let mut conflicts = Vec::new();
for group in self.groups.values() {
if let Some(rival_group) = group.rival_group {
if let Some(rival) = self.groups.get(&rival_group) {
conflicts.push(ConflictInfo {
party_a: group.id,
party_b: rival.id,
conflict_type: ConflictType::GroupRivalry,
severity: ConflictSeverity::Medium,
});
}
}
}
conflicts
}
fn weekly_update(&mut self) {
// Update group cohesion and dynamics
for group in self.groups.values_mut() {
group.weekly_update();
}
// Remove dissolved groups
self.groups.retain(|_, g| g.cohesion > 0.1);
}
}
#[derive(Debug, Clone)]
struct Group {
id: GroupId,
members: HashSet<u32>,
leader_id: Option<u32>,
cohesion: f32,
group_type: GroupType,
rival_group: Option<GroupId>,
}
impl Group {
fn weekly_update(&mut self) {
// Natural cohesion decay
self.cohesion *= 0.98;
}
}
type GroupId = u32;
#[derive(Debug, Clone)]
enum GroupType {
Nationality,
AgeGroup,
PlayingPosition,
Social,
Professional,
}
/// Team chemistry calculator
#[derive(Debug, Clone)]
struct TeamChemistry {
overall: f32,
factors: ChemistryFactors,
}
impl TeamChemistry {
fn new() -> Self {
TeamChemistry {
overall: 50.0,
factors: ChemistryFactors::default(),
}
}
fn recalculate<T: Relationship, S: Relationship>(
&mut self,
players: &RelationStore<T>,
staffs: &RelationStore<S>,
) {
// Calculate various chemistry factors
let player_harmony = self.calculate_player_harmony(players);
let leadership_quality = self.calculate_leadership_quality(players);
let coach_relationship = self.calculate_coach_relationship(staffs);
self.factors = ChemistryFactors {
player_harmony,
leadership_quality,
coach_relationship,
group_cohesion: 50.0, // Simplified
conflict_level: 10.0, // Simplified
};
// Calculate overall chemistry
self.overall = (
player_harmony * 0.4 +
leadership_quality * 0.2 +
coach_relationship * 0.3 +
self.factors.group_cohesion * 0.1
) * (1.0 - self.factors.conflict_level / 100.0);
}
fn calculate_player_harmony<T: Relationship>(&self, players: &RelationStore<T>) -> f32 {
if players.relations.is_empty() {
return 50.0;
}
let avg_positive = players.relations.values()
.filter(|r| !r.is_disliked())
.count() as f32;
(avg_positive / players.relations.len() as f32) * 100.0
}
fn calculate_leadership_quality<T: Relationship>(&self, _players: &RelationStore<T>) -> f32 {
// Simplified - would check actual leader relationships
60.0
}
fn calculate_coach_relationship<S: Relationship>(&self, staffs: &RelationStore<S>) -> f32 {
if staffs.relations.is_empty() {
return 50.0;
}
let avg_positive = staffs.relations.values()
.filter(|r| !r.is_disliked())
.count() as f32;
(avg_positive / staffs.relations.len() as f32) * 100.0
}
}
#[derive(Debug, Clone, Default)]
pub struct ChemistryFactors {
pub player_harmony: f32,
pub leadership_quality: f32,
pub coach_relationship: f32,
pub group_cohesion: f32,
pub conflict_level: f32,
}
/// Relationship history tracking
#[derive(Debug, Clone)]
struct RelationshipHistory {
events: VecDeque<RelationshipEvent>,
max_events: usize,
}
impl RelationshipHistory {
fn new() -> Self {
RelationshipHistory {
events: VecDeque::with_capacity(100),
max_events: 100,
}
}
fn record_event(&mut self, event: RelationshipEvent) {
self.events.push_back(event);
if self.events.len() > self.max_events {
self.events.pop_front();
}
}
fn cleanup_old_events(&mut self, current_date: NaiveDate) {
let cutoff = current_date - chrono::Duration::days(365);
self.events.retain(|e| e.date > cutoff);
}
}
#[derive(Debug, Clone)]
struct RelationshipEvent {
date: NaiveDate,
subject_id: u32,
subject_type: SubjectType,
change_type: ChangeType,
old_value: f32,
new_value: f32,
}
#[derive(Debug, Clone)]
enum SubjectType {
Player,
Staff,
}
/// Types of relationship changes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ChangeType {
// Positive
MatchCooperation,
TrainingBonding,
ConflictResolution,
PersonalSupport,
CoachingSuccess,
TeamSuccess,
MentorshipBond,
// Negative
CompetitionRivalry,
TrainingFriction,
PersonalConflict,
TacticalDisagreement,
DisciplinaryAction,
TeamFailure,
// Neutral
NaturalProgression,
}
/// Relationship change event
#[derive(Debug, Clone)]
pub struct RelationshipChange {
pub change_type: ChangeType,
pub magnitude: f32,
pub is_positive: bool,
}
impl RelationshipChange {
pub fn positive(change_type: ChangeType, magnitude: f32) -> Self {
RelationshipChange {
change_type,
magnitude: magnitude.abs(),
is_positive: true,
}
}
pub fn negative(change_type: ChangeType, magnitude: f32) -> Self {
RelationshipChange {
change_type,
magnitude: -magnitude.abs(),
is_positive: false,
}
}
}
/// Mentorship types
#[derive(Debug, Clone)]
pub enum MentorshipType {
Mentor,
Mentee,
}
/// Influence levels in the dressing room
#[derive(Debug, Clone, PartialEq)]
pub enum InfluenceLevel {
KeyPlayer,
Influential,
Regular,
Peripheral,
}
impl InfluenceLevel {
fn from_value(value: f32) -> Self {
match value {
v if v >= 80.0 => InfluenceLevel::KeyPlayer,
v if v >= 60.0 => InfluenceLevel::Influential,
v if v >= 30.0 => InfluenceLevel::Regular,
_ => InfluenceLevel::Peripheral,
}
}
}
/// Conflict information
#[derive(Debug, Clone)]
pub struct ConflictInfo {
pub party_a: u32,
pub party_b: u32,
pub conflict_type: ConflictType,
pub severity: ConflictSeverity,
}
#[derive(Debug, Clone)]
pub enum ConflictType {
PersonalRivalry,
GroupRivalry,
AuthorityChallenge,
PlayingTimeDispute,
}
#[derive(Debug, Clone)]
pub enum ConflictSeverity {
Minor,
Medium,
Serious,
Critical,
}
impl ConflictSeverity {
fn from_relationship_levels(level_a: f32, level_b: f32) -> Self {
let avg = (level_a + level_b) / 2.0;
match avg {
v if v <= -75.0 => ConflictSeverity::Critical,
v if v <= -50.0 => ConflictSeverity::Serious,
v if v <= -25.0 => ConflictSeverity::Medium,
_ => ConflictSeverity::Minor,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_player_relationship_updates() {
let mut relations = Relations::new();
let change = RelationshipChange::positive(
ChangeType::TrainingBonding,
0.5,
);
relations.update_player_relationship(
1,
change,
NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
);
let rel = relations.get_player(1).unwrap();
assert!(rel.friendship > 30.0);
}
#[test]
fn test_coaching_receptiveness() {
let mut relations = Relations::new();
let change = RelationshipChange::positive(
ChangeType::CoachingSuccess,
0.8,
);
relations.update_staff_relationship(
1,
change,
NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
);
let receptiveness = relations.get_coaching_receptiveness(1);
assert!(receptiveness > 1.0);
}
#[test]
fn test_team_chemistry_calculation() {
let mut relations = Relations::new();
// Add some positive relationships
for i in 1..5 {
let change = RelationshipChange::positive(
ChangeType::TeamSuccess,
0.5,
);
relations.update_player_relationship(
i,
change,
NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
);
}
let chemistry = relations.get_team_chemistry();
assert!(chemistry > 50.0);
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/context.rs | src/core/src/club/context.rs | #[derive(Clone)]
pub struct ClubContext<'c> {
pub id: u32,
pub name: &'c str,
}
impl<'c> ClubContext<'c> {
pub fn new(id: u32, name: &'c str) -> Self {
ClubContext { id, name }
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/staff/focus.rs | src/core/src/club/staff/focus.rs | #[derive(Debug)]
pub struct CoachFocus {
pub technical_focus: Vec<TechnicalFocusType>,
pub mental_focus: Vec<MentalFocusType>,
pub physical_focus: Vec<PhysicalFocusType>,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum TechnicalFocusType {
Corners,
Crossing,
Dribbling,
Finishing,
FirstTouch,
FreeKicks,
Heading,
LongShots,
LongThrows,
Marking,
Passing,
PenaltyTaking,
Tackling,
Technique,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum MentalFocusType {
Aggression,
Anticipation,
Bravery,
Composure,
Concentration,
Decisions,
Determination,
Flair,
Leadership,
OffTheBall,
Positioning,
Teamwork,
Vision,
WorkRate,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum PhysicalFocusType {
Acceleration,
Agility,
Balance,
Jumping,
NaturalFitness,
Pace,
Stamina,
Strength,
MatchReadiness,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/staff/contract.rs | src/core/src/club/staff/contract.rs | use crate::context::SimulationContext;
pub use chrono::prelude::{DateTime, Datelike, NaiveDate, Utc};
#[derive(Debug, PartialEq)]
pub enum StaffPosition {
Free,
Coach,
Chairman,
Director,
ManagingDirector,
DirectorOfFootball,
Physio,
Scout,
Manager,
AssistantManager,
MediaPundit,
GeneralManager,
FitnessCoach,
GoalkeeperCoach,
U21Manager,
ChiefScout,
YouthCoach,
HeadOfPhysio,
U19Manager,
FirstTeamCoach,
HeadOfYouthDevelopment,
CaretakerManager,
}
#[derive(Debug, PartialEq)]
pub enum StaffStatus {
Active,
ExpiredContract,
}
#[derive(Debug)]
pub struct StaffClubContract {
pub expired: NaiveDate,
pub salary: u32,
pub position: StaffPosition,
pub status: StaffStatus,
}
impl StaffClubContract {
pub fn new(
salary: u32,
expired: NaiveDate,
position: StaffPosition,
status: StaffStatus,
) -> Self {
StaffClubContract {
salary,
expired,
position,
status,
}
}
pub fn is_expired(&self, context: &SimulationContext) -> bool {
self.expired >= context.date.date()
}
pub fn simulate(&mut self, context: &SimulationContext) {
if context.check_contract_expiration() && self.is_expired(context) {
self.status = StaffStatus::ExpiredContract;
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/staff/staff.rs | src/core/src/club/staff/staff.rs | // Assuming rand is available
extern crate rand;
use crate::club::{
PersonBehaviour, StaffClubContract, StaffPosition, StaffStatus
};
use crate::context::GlobalContext;
use crate::shared::fullname::FullName;
use crate::utils::DateUtils;
use crate::{CoachFocus, Logging, PersonAttributes, PersonBehaviourState, Relations, StaffAttributes, StaffCollectionResult, StaffResponsibility, StaffResult, StaffStub, TeamType, TrainingIntensity, TrainingType};
use chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike};
#[derive(Debug)]
pub struct Staff {
pub id: u32,
pub full_name: FullName,
pub country_id: u32,
pub birth_date: NaiveDate,
pub attributes: PersonAttributes,
pub behaviour: PersonBehaviour,
pub staff_attributes: StaffAttributes,
pub contract: Option<StaffClubContract>,
pub relations: Relations,
pub license: StaffLicenseType,
pub focus: Option<CoachFocus>,
// New fields for enhanced simulation
pub fatigue: f32, // 0-100, affects performance
pub job_satisfaction: f32, // 0-100, affects retention
pub recent_performance: StaffPerformance,
pub coaching_style: CoachingStyle,
pub training_schedule: Vec<StaffTrainingSession>,
}
#[derive(Debug)]
pub struct StaffCollection {
pub staffs: Vec<Staff>,
pub responsibility: StaffResponsibility,
stub: Staff,
}
impl StaffCollection {
pub fn new(staffs: Vec<Staff>) -> Self {
StaffCollection {
staffs,
responsibility: StaffResponsibility::default(),
stub: StaffStub::default(),
}
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> StaffCollectionResult {
let staff_results = self
.staffs
.iter_mut()
.map(|staff| {
let message = &format!("simulate staff: id: {}", &staff.id);
Logging::estimate_result(|| staff.simulate(ctx.with_staff(Some(staff.id))), message)
})
.collect();
StaffCollectionResult::new(staff_results)
}
pub fn training_coach(&self, team_type: &TeamType) -> &Staff {
let responsibility_coach = match team_type {
TeamType::Main => self.responsibility.training.training_first_team,
_ => self.responsibility.training.training_youth_team,
};
match responsibility_coach {
Some(_) => self.get_by_id(responsibility_coach.unwrap()),
None => self.get_by_position(StaffPosition::Coach),
}
}
fn manager(&self) -> Option<&Staff> {
let manager = self
.staffs
.iter()
.filter(|staff| staff.contract.is_some())
.find(|staff| {
staff
.contract
.as_ref()
.expect("no staff contract found")
.position
== StaffPosition::Manager
});
match manager {
Some(_) => manager,
None => None,
}
}
pub fn head_coach(&self) -> &Staff {
match self.manager() {
Some(ref head_coach) => head_coach,
None => self.get_by_position(StaffPosition::AssistantManager),
}
}
pub fn contract_resolver(&self, team_type: TeamType) -> &Staff {
let staff_id = match team_type {
TeamType::Main => {
self.responsibility
.contract_renewal
.handle_first_team_contracts
}
TeamType::B => {
self.responsibility
.contract_renewal
.handle_other_staff_contracts
}
_ => {
self.responsibility
.contract_renewal
.handle_youth_team_contracts
}
};
self.get_by_id(staff_id.unwrap())
}
fn get_by_position(&self, position: StaffPosition) -> &Staff {
let staffs: Vec<&Staff> = self
.staffs
.iter()
.filter(|staff| {
staff.contract.is_some() && staff.contract.as_ref().unwrap().position == position
})
.collect();
if staffs.is_empty() {
return &self.stub;
}
//TODO most relevant
staffs.first().unwrap()
}
fn get_by_id(&self, id: u32) -> &Staff {
self.staffs.iter().find(|staff| staff.id == id).unwrap()
}
}
#[derive(Debug, Clone)]
pub struct StaffPerformance {
pub training_effectiveness: f32, // 0-1 multiplier
pub player_development_rate: f32, // 0-1 multiplier
pub injury_prevention_rate: f32, // 0-1 multiplier
pub tactical_implementation: f32, // 0-1 multiplier
pub last_evaluation_date: Option<NaiveDate>,
}
#[derive(Debug, Clone)]
pub enum CoachingStyle {
Authoritarian, // Strict discipline, high demands
Democratic, // Collaborative, player input
LaissezFaire, // Hands-off, player autonomy
Transformational, // Inspirational, vision-focused
Tactical, // Detail-oriented, system-focused
}
impl Staff {
pub fn new(
id: u32,
full_name: FullName,
country_id: u32,
birth_date: NaiveDate,
staff_attributes: StaffAttributes,
contract: Option<StaffClubContract>,
attributes: PersonAttributes,
license: StaffLicenseType,
focus: Option<CoachFocus>,
) -> Self {
Staff {
id,
full_name,
country_id,
birth_date,
staff_attributes,
contract,
behaviour: PersonBehaviour::default(),
relations: Relations::new(),
attributes,
license,
focus,
fatigue: 0.0,
job_satisfaction: 50.0,
recent_performance: StaffPerformance::default(),
coaching_style: CoachingStyle::default(),
training_schedule: Vec::new(),
}
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> StaffResult {
let now = ctx.simulation.date;
let mut result = StaffResult::new();
// Birthday handling - improves mood
if DateUtils::is_birthday(self.birth_date, now.date()) {
self.behaviour.try_increase();
self.job_satisfaction = (self.job_satisfaction + 5.0).min(100.0);
result.add_event(StaffMoraleEvent::Birthday);
}
// Process contract status and negotiations
self.process_contract(&mut result, now);
// Update fatigue based on workload
self.update_fatigue(&ctx, &mut result);
// Process training responsibilities
self.process_training_duties(&ctx, &mut result);
// Update job satisfaction
self.update_job_satisfaction(&ctx, &mut result);
// Check for burnout or resignation triggers
self.check_resignation_triggers(&mut result);
// Process relationships with players and other staff
self.process_relationships(&ctx, &mut result);
// Handle performance evaluation
if self.should_evaluate_performance(now.date()) {
self.evaluate_performance(&ctx, &mut result);
}
// Process professional development
self.process_professional_development(&ctx, &mut result);
result
}
fn process_contract(&mut self, result: &mut StaffResult, now: NaiveDateTime) {
if let Some(ref mut contract) = self.contract {
const THREE_MONTHS_DAYS: i64 = 90;
const SIX_MONTHS_DAYS: i64 = 180;
let days_remaining = contract.days_to_expiration(now);
// Check if contract expired
if days_remaining <= 0 {
contract.status = StaffStatus::ExpiredContract;
result.contract.expired = true;
// Decide if staff wants to renew
if self.wants_renewal() {
result.contract.wants_renewal = true;
result.contract.requested_salary = self.calculate_desired_salary();
} else {
result.contract.leaving = true;
}
}
// Contract expiring soon - start negotiations
else if days_remaining < SIX_MONTHS_DAYS {
if days_remaining < THREE_MONTHS_DAYS && !result.contract.negotiating {
// Urgent renewal needed
result.contract.negotiating = true;
result.contract.urgent = true;
if self.job_satisfaction < 40.0 {
// Unhappy - likely to leave
result.contract.likely_to_leave = true;
}
}
// Staff member initiates renewal discussion
if self.attributes.ambition > 15.0 && self.recent_performance.training_effectiveness > 0.7 {
result.contract.wants_improved_terms = true;
result.contract.requested_salary = contract.salary as f32 * 1.3;
}
}
} else {
// No contract - staff is likely temporary or consultant
result.contract.no_contract = true;
if self.recent_performance.training_effectiveness > 0.8 {
// Performing well, should offer contract
result.contract.deserves_contract = true;
}
}
}
fn update_fatigue(&mut self, ctx: &GlobalContext<'_>, result: &mut StaffResult) {
// Calculate workload based on responsibilities
let workload = self.calculate_workload(ctx);
// Increase fatigue based on workload
self.fatigue += workload * 2.0;
// Recovery on weekends
if ctx.simulation.date.weekday() == chrono::Weekday::Sun {
self.fatigue = (self.fatigue - 15.0).max(0.0);
}
// Vacation periods provide significant recovery
if self.is_on_vacation(ctx.simulation.date.date()) {
self.fatigue = (self.fatigue - 30.0).max(0.0);
}
// Cap fatigue at 100
self.fatigue = self.fatigue.min(100.0);
// High fatigue affects performance and morale
if self.fatigue > 80.0 {
result.add_warning(StaffWarning::HighFatigue);
self.recent_performance.training_effectiveness *= 0.8;
self.job_satisfaction -= 2.0;
}
// Extreme fatigue can lead to health issues
if self.fatigue > 95.0 {
result.add_warning(StaffWarning::BurnoutRisk);
if rand::random::<f32>() < 0.05 {
result.health_issue = Some(HealthIssue::StressRelated);
}
}
}
fn process_training_duties(&mut self, ctx: &GlobalContext<'_>, result: &mut StaffResult) {
// Only process if staff has coaching responsibilities
if !self.has_coaching_duties() {
return;
}
// Plan training sessions for the week
if ctx.simulation.is_week_beginning() {
self.training_schedule = self.plan_weekly_training(ctx);
result.training.sessions_planned = self.training_schedule.len() as u8;
}
// Execute today's training if scheduled
if let Some(session) = self.get_todays_training(ctx.simulation.date) {
// Training effectiveness based on various factors
let effectiveness = self.calculate_training_effectiveness();
result.training.session_conducted = true;
result.training.effectiveness = effectiveness;
result.training.session_type = session.session_type.clone();
// Track which players attended
if let Some(team_id) = ctx.team.as_ref().map(|t| t.id) {
result.training.team_id = Some(team_id);
}
// Fatigue from conducting training
self.fatigue += match session.intensity {
TrainingIntensity::VeryLight => 1.0,
TrainingIntensity::Light => 2.0,
TrainingIntensity::Moderate => 3.0,
TrainingIntensity::High => 4.0,
TrainingIntensity::VeryHigh => 5.0,
};
}
}
fn update_job_satisfaction(&mut self, ctx: &GlobalContext<'_>, result: &mut StaffResult) {
let mut satisfaction_change = 0.0;
// Positive factors
if self.recent_performance.training_effectiveness > 0.75 {
satisfaction_change += 1.0; // Good performance
}
if self.behaviour.state == PersonBehaviourState::Good {
satisfaction_change += 0.5; // Good relationships
}
// Check team performance if applicable
if let Some(_club) = ctx.club.as_ref() {
// Would need team performance metrics
// satisfaction_change += team_performance_factor;
}
// Negative factors
if self.fatigue > 70.0 {
satisfaction_change -= 2.0; // Overworked
}
if let Some(contract) = &self.contract {
if self.is_underpaid(contract.salary) {
satisfaction_change -= 1.5; // Salary dissatisfaction
}
}
// Apply change with dampening
self.job_satisfaction = (self.job_satisfaction + satisfaction_change * 0.5)
.clamp(0.0, 100.0);
// Report significant satisfaction issues
if self.job_satisfaction < 30.0 {
result.add_warning(StaffWarning::LowMorale);
} else if self.job_satisfaction > 80.0 {
result.add_event(StaffMoraleEvent::HighSatisfaction);
}
}
fn check_resignation_triggers(&self, result: &mut StaffResult) {
// Multiple factors can trigger resignation consideration
let resignation_probability = self.calculate_resignation_probability();
if resignation_probability > 0.0 {
if rand::random::<f32>() < resignation_probability {
result.resignation_risk = true;
if resignation_probability > 0.5 {
// Actually submit resignation
result.resigned = true;
result.resignation_reason = Some(self.determine_resignation_reason());
}
}
}
}
fn process_relationships(&mut self, ctx: &GlobalContext<'_>, result: &mut StaffResult) {
// Daily relationship updates are minimal
// Major updates happen during training and matches
if ctx.simulation.date.hour() == 12 { // Midday check
// Small random relationship events
if rand::random::<f32>() < 0.1 {
// Positive interaction with random player
result.relationship_event = Some(RelationshipEvent::PositiveInteraction);
// This would update the actual relations
// self.relations.update_simple(player_id, 0.5);
}
if rand::random::<f32>() < 0.05 && self.job_satisfaction < 40.0 {
// Conflict when satisfaction is low
result.relationship_event = Some(RelationshipEvent::Conflict);
}
}
}
fn evaluate_performance(&mut self, ctx: &GlobalContext<'_>, result: &mut StaffResult) {
// Monthly performance evaluation
let prev_effectiveness = self.recent_performance.training_effectiveness;
// Calculate new performance metrics
self.recent_performance = self.calculate_performance_metrics(ctx);
self.recent_performance.last_evaluation_date = Some(ctx.simulation.date.date());
// Report performance change
if self.recent_performance.training_effectiveness > prev_effectiveness + 0.1 {
result.performance_improved = true;
} else if self.recent_performance.training_effectiveness < prev_effectiveness - 0.1 {
result.performance_declined = true;
}
// Board/management reaction to performance
if self.recent_performance.training_effectiveness < 0.4 {
result.add_warning(StaffWarning::PoorPerformance);
} else if self.recent_performance.training_effectiveness > 0.8 {
result.add_event(StaffMoraleEvent::ExcellentPerformance);
self.job_satisfaction += 5.0;
}
}
fn process_professional_development(&mut self, ctx: &GlobalContext<'_>, result: &mut StaffResult) {
// Check for license upgrade opportunities
if self.should_upgrade_license() {
if rand::random::<f32>() < 0.01 { // Small daily chance
result.license_upgrade_available = true;
if self.attributes.ambition > 15.0 {
result.wants_license_upgrade = true;
}
}
}
// Learning from experience
if ctx.simulation.is_month_beginning() {
self.improve_attributes_from_experience();
}
// Attending courses or conferences
if self.is_on_course(ctx.simulation.date.date()) {
result.on_professional_development = true;
self.fatigue = (self.fatigue - 5.0).max(0.0); // Courses are refreshing
}
}
// Helper methods
fn wants_renewal(&self) -> bool {
self.job_satisfaction > 40.0 &&
self.behaviour.state != PersonBehaviourState::Poor
}
fn calculate_desired_salary(&self) -> f32 {
let base = self.contract.as_ref().map(|c| c.salary).unwrap_or(50000) as f32;
let performance_multiplier = 1.0 + (self.recent_performance.training_effectiveness - 0.5);
let ambition_multiplier = 1.0 + (self.attributes.ambition / 20.0) * 0.3;
base * performance_multiplier * ambition_multiplier
}
fn calculate_workload(&self, _ctx: &GlobalContext<'_>) -> f32 {
// Base workload from position
let position_load = match self.contract.as_ref().map(|c| &c.position) {
Some(StaffPosition::Manager) => 8.0,
Some(StaffPosition::AssistantManager) => 6.0,
Some(StaffPosition::Coach) => 5.0,
Some(StaffPosition::FitnessCoach) => 4.0,
Some(StaffPosition::GoalkeeperCoach) => 3.0,
Some(StaffPosition::Scout) => 4.0,
Some(StaffPosition::Physio) => 5.0,
_ => 3.0,
};
// Additional load from training sessions
let training_load = self.training_schedule.len() as f32 * 0.5;
position_load + training_load
}
fn is_on_vacation(&self, date: NaiveDate) -> bool {
// Summer break (simplified)
date.month() == 7 && date.day() <= 14
}
fn has_coaching_duties(&self) -> bool {
matches!(
self.contract.as_ref().map(|c| &c.position),
Some(StaffPosition::Manager) |
Some(StaffPosition::AssistantManager) |
Some(StaffPosition::Coach) |
Some(StaffPosition::FitnessCoach) |
Some(StaffPosition::GoalkeeperCoach) |
Some(StaffPosition::FirstTeamCoach) |
Some(StaffPosition::YouthCoach)
)
}
fn plan_weekly_training(&self, _ctx: &GlobalContext<'_>) -> Vec<StaffTrainingSession> {
let mut sessions = Vec::new();
// Simplified training plan
// Monday - Recovery
sessions.push(StaffTrainingSession {
session_type: TrainingType::Recovery,
intensity: TrainingIntensity::Light,
duration_minutes: 60,
});
// Tuesday - Technical
sessions.push(StaffTrainingSession {
session_type: TrainingType::BallControl,
intensity: TrainingIntensity::Moderate,
duration_minutes: 90,
});
// Wednesday - Tactical
sessions.push(StaffTrainingSession {
session_type: TrainingType::TeamShape,
intensity: TrainingIntensity::Moderate,
duration_minutes: 90,
});
// Thursday - Physical
sessions.push(StaffTrainingSession {
session_type: TrainingType::Endurance,
intensity: TrainingIntensity::High,
duration_minutes: 75,
});
// Friday - Match preparation
sessions.push(StaffTrainingSession {
session_type: TrainingType::Positioning,
intensity: TrainingIntensity::Light,
duration_minutes: 60,
});
sessions
}
fn get_todays_training(&self, date: NaiveDateTime) -> Option<&StaffTrainingSession> {
// Map weekday to training session
let weekday = date.weekday();
let index = match weekday {
chrono::Weekday::Mon => 0,
chrono::Weekday::Tue => 1,
chrono::Weekday::Wed => 2,
chrono::Weekday::Thu => 3,
chrono::Weekday::Fri => 4,
_ => return None, // No training on weekends
};
self.training_schedule.get(index)
}
fn calculate_training_effectiveness(&self) -> f32 {
let base = (self.staff_attributes.coaching.technical as f32 +
self.staff_attributes.coaching.tactical as f32 +
self.staff_attributes.coaching.fitness as f32 +
self.staff_attributes.coaching.mental as f32) / 80.0;
let fatigue_penalty = if self.fatigue > 50.0 {
1.0 - ((self.fatigue - 50.0) / 100.0)
} else {
1.0
};
let morale_bonus = self.job_satisfaction / 100.0;
(base * fatigue_penalty * morale_bonus).clamp(0.1, 1.0)
}
fn is_underpaid(&self, salary: u32) -> bool {
// Compare to market rate based on attributes and performance
let expected_salary = self.calculate_market_value();
salary < (expected_salary as u32)
}
fn calculate_market_value(&self) -> f32 {
// Base salary by position and license
let base = match self.license {
StaffLicenseType::ContinentalPro => 100000.0,
StaffLicenseType::ContinentalA => 70000.0,
StaffLicenseType::ContinentalB => 50000.0,
StaffLicenseType::ContinentalC => 35000.0,
StaffLicenseType::NationalA => 30000.0,
StaffLicenseType::NationalB => 25000.0,
StaffLicenseType::NationalC => 20000.0,
};
let skill_multiplier = (self.staff_attributes.coaching.tactical as f32 +
self.staff_attributes.coaching.technical as f32) / 40.0 + 0.5;
base * skill_multiplier * self.recent_performance.training_effectiveness
}
fn calculate_resignation_probability(&self) -> f32 {
let mut prob: f32 = 0.0;
// Job satisfaction is primary factor
if self.job_satisfaction < 20.0 {
prob += 0.3;
} else if self.job_satisfaction < 35.0 {
prob += 0.1;
}
// Extreme fatigue
if self.fatigue > 90.0 {
prob += 0.2;
}
// Poor relationships
if self.behaviour.state == PersonBehaviourState::Poor {
prob += 0.15;
}
// Contract issues
if self.contract.is_none() {
prob += 0.1;
} else if let Some(contract) = &self.contract {
if self.is_underpaid(contract.salary) {
prob += 0.1;
}
}
prob.min(0.9) // Cap at 90% chance
}
fn determine_resignation_reason(&self) -> ResignationReason {
if self.job_satisfaction < 30.0 {
ResignationReason::LowSatisfaction
} else if self.fatigue > 85.0 {
ResignationReason::Burnout
} else if self.behaviour.state == PersonBehaviourState::Poor {
ResignationReason::PersonalReasons
} else {
ResignationReason::BetterOpportunity
}
}
fn should_evaluate_performance(&self, date: NaiveDate) -> bool {
// Monthly evaluation
if let Some(last_eval) = self.recent_performance.last_evaluation_date {
(date - last_eval).num_days() >= 30
} else {
true // First evaluation
}
}
fn calculate_performance_metrics(&self, ctx: &GlobalContext<'_>) -> StaffPerformance {
// Simplified calculation - would need actual team/player data
StaffPerformance {
training_effectiveness: self.calculate_training_effectiveness(),
player_development_rate: (self.staff_attributes.coaching.working_with_youngsters as f32 / 20.0),
injury_prevention_rate: (self.staff_attributes.medical.sports_science as f32 / 20.0),
tactical_implementation: (self.staff_attributes.coaching.tactical as f32 / 20.0),
last_evaluation_date: Some(ctx.simulation.date.date()),
}
}
fn should_upgrade_license(&self) -> bool {
// Check if eligible for license upgrade
match self.license {
StaffLicenseType::NationalC => {
self.staff_attributes.coaching.tactical > 10
},
StaffLicenseType::NationalB => {
self.staff_attributes.coaching.tactical > 12 &&
self.staff_attributes.coaching.technical > 12
},
StaffLicenseType::NationalA => {
self.staff_attributes.coaching.tactical > 14 &&
self.staff_attributes.coaching.technical > 14
},
_ => false, // Continental licenses need special conditions
}
}
fn improve_attributes_from_experience(&mut self) {
// Slow improvement over time
if rand::random::<f32>() < 0.3 {
// Small chance of improvement each month
let improvement = 1;
// Improve a random coaching attribute
match rand::random::<u8>() % 6 {
0 => self.staff_attributes.coaching.attacking =
(self.staff_attributes.coaching.attacking + improvement).min(20),
1 => self.staff_attributes.coaching.defending =
(self.staff_attributes.coaching.defending + improvement).min(20),
2 => self.staff_attributes.coaching.tactical =
(self.staff_attributes.coaching.tactical + improvement).min(20),
3 => self.staff_attributes.coaching.technical =
(self.staff_attributes.coaching.technical + improvement).min(20),
4 => self.staff_attributes.coaching.fitness =
(self.staff_attributes.coaching.fitness + improvement).min(20),
_ => self.staff_attributes.coaching.mental =
(self.staff_attributes.coaching.mental + improvement).min(20),
}
}
}
fn is_on_course(&self, date: NaiveDate) -> bool {
// Simplified - courses in January
date.month() == 1 && date.day() >= 15 && date.day() <= 20
}
}
#[derive(Debug, Default)]
pub struct StaffContractResult {
pub expired: bool,
pub no_contract: bool,
pub negotiating: bool,
pub urgent: bool,
pub wants_renewal: bool,
pub wants_improved_terms: bool,
pub likely_to_leave: bool,
pub leaving: bool,
pub deserves_contract: bool,
pub requested_salary: f32,
}
#[derive(Debug, Default)]
pub struct StaffTrainingResult {
pub sessions_planned: u8,
pub session_conducted: bool,
pub effectiveness: f32,
pub session_type: TrainingType,
pub team_id: Option<u32>,
}
#[derive(Debug)]
pub enum StaffWarning {
HighFatigue,
BurnoutRisk,
LowMorale,
PoorPerformance,
}
#[derive(Debug)]
pub enum StaffMoraleEvent {
Birthday,
HighSatisfaction,
ExcellentPerformance,
}
#[derive(Debug)]
pub enum ResignationReason {
LowSatisfaction,
Burnout,
PersonalReasons,
BetterOpportunity,
Retirement,
}
#[derive(Debug)]
pub enum HealthIssue {
StressRelated,
PhysicalInjury,
Illness,
}
#[derive(Debug)]
pub enum RelationshipEvent {
PositiveInteraction,
Conflict,
MentorshipStarted,
TrustBuilt,
}
#[derive(Debug)]
pub enum StaffLicenseType {
ContinentalPro,
ContinentalA,
ContinentalB,
ContinentalC,
NationalA,
NationalB,
NationalC
}
// Default implementations
impl Default for StaffPerformance {
fn default() -> Self {
StaffPerformance {
training_effectiveness: 0.5,
player_development_rate: 0.5,
injury_prevention_rate: 0.5,
tactical_implementation: 0.5,
last_evaluation_date: None,
}
}
}
impl Default for CoachingStyle {
fn default() -> Self {
CoachingStyle::Democratic
}
}
#[derive(Debug, Clone)]
pub struct StaffTrainingSession {
pub session_type: TrainingType,
pub intensity: TrainingIntensity,
pub duration_minutes: u16,
}
// Additional helper trait implementations
impl StaffClubContract {
pub fn days_to_expiration(&self, now: NaiveDateTime) -> i64 {
(self.expired - now.date()).num_days()
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/staff/responsibility.rs | src/core/src/club/staff/responsibility.rs | #[derive(Debug, Default)]
pub struct StaffResponsibility {
pub board: BoardResponsibility,
pub recruitment: RecruitmentResponsibility,
pub incoming_transfers: IncomingTransfersResponsibility,
pub outgoing_transfers: OutgoingTransfersResponsibility,
pub contract_renewal: ContractRenewalResponsibility,
pub scouting: ScoutingResponsibility,
pub training: TrainingResponsibility,
}
#[derive(Debug, Default)]
pub struct BoardResponsibility {
pub hire_fire_director: Option<u32>,
}
#[derive(Debug, Default)]
pub struct RecruitmentResponsibility {
pub hire_fire_head_of_youth_development: Option<u32>,
pub hire_fire_chief_scout: Option<u32>,
pub hire_fire_other_staff: Option<u32>,
}
#[derive(Debug, Default)]
pub struct IncomingTransfersResponsibility {
pub find_and_make_offers_first_team: Option<u32>,
pub finalize_first_team_signings: Option<u32>,
pub find_and_make_offers_youth_team: Option<u32>,
pub finalize_youth_team_signings: Option<u32>,
}
#[derive(Debug, Default)]
pub struct OutgoingTransfersResponsibility {
pub find_clubs_for_transfers_and_loans_listed_first_team: Option<u32>,
pub find_clubs_for_transfers_and_loans_listed_youth_team: Option<u32>,
}
#[derive(Debug, Default)]
pub struct ContractRenewalResponsibility {
pub handle_first_team_contracts: Option<u32>,
pub handle_youth_team_contracts: Option<u32>,
pub handle_director_of_football_contract: Option<u32>,
pub handle_other_staff_contracts: Option<u32>,
}
#[derive(Debug, Default)]
pub struct ScoutingResponsibility {
pub handle_scouting_tasks: Option<u32>,
pub updates_you_on_players_found: Option<u32>,
}
#[derive(Debug, Default)]
pub struct TrainingResponsibility {
pub training_first_team: Option<u32>,
pub training_youth_team: Option<u32>,
pub individual_training_first_team: Option<u32>,
pub individual_training_youth_team: Option<u32>,
pub match_training_first_team: Option<u32>,
pub match_training_reserve_team: Option<u32>,
pub match_training_youth_team: Option<u32>,
pub youth_development: Option<u32>,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/staff/result.rs | src/core/src/club/staff/result.rs | use crate::simulator::SimulatorData;
use crate::{HealthIssue, RelationshipEvent, ResignationReason, StaffContractResult, StaffMoraleEvent, StaffTrainingResult, StaffWarning};
pub struct StaffCollectionResult {
pub staff: Vec<StaffResult>,
}
impl StaffCollectionResult {
pub fn new(staff: Vec<StaffResult>) -> Self {
StaffCollectionResult { staff }
}
pub fn process(&self, _: &mut SimulatorData) {}
}
// Enhanced StaffResult with new fields
pub struct StaffResult {
pub transfer_requests: Vec<u32>,
pub contract: StaffContractResult,
pub training: StaffTrainingResult,
pub resigned: bool,
pub resignation_reason: Option<ResignationReason>,
pub resignation_risk: bool,
pub performance_improved: bool,
pub performance_declined: bool,
pub license_upgrade_available: bool,
pub wants_license_upgrade: bool,
pub on_professional_development: bool,
pub health_issue: Option<HealthIssue>,
pub relationship_event: Option<RelationshipEvent>,
pub warnings: Vec<StaffWarning>,
pub events: Vec<StaffMoraleEvent>,
}
impl StaffResult {
pub fn new() -> Self {
StaffResult {
transfer_requests: Vec::new(),
contract: StaffContractResult::default(),
training: StaffTrainingResult::default(),
resigned: false,
resignation_reason: None,
resignation_risk: false,
performance_improved: false,
performance_declined: false,
license_upgrade_available: false,
wants_license_upgrade: false,
on_professional_development: false,
health_issue: None,
relationship_event: None,
warnings: Vec::new(),
events: Vec::new(),
}
}
pub fn request_transfer(&mut self, player_id: u32) {
self.transfer_requests.push(player_id);
}
pub fn add_warning(&mut self, warning: StaffWarning) {
self.warnings.push(warning);
}
pub fn add_event(&mut self, event: StaffMoraleEvent) {
self.events.push(event);
}
pub fn process(&self, _data: &mut SimulatorData) {
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/staff/mod.rs | src/core/src/club/staff/mod.rs | pub mod attributes;
pub mod context;
pub mod contract;
pub mod focus;
pub mod responsibility;
pub mod result;
pub mod staff;
pub mod staff_stub;
pub use attributes::*;
pub use context::*;
pub use contract::*;
pub use focus::*;
pub use responsibility::*;
pub use result::*;
pub use staff::*;
pub use staff_stub::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/staff/staff_stub.rs | src/core/src/club/staff/staff_stub.rs | use crate::club::PersonBehaviour;
use crate::shared::fullname::FullName;
use crate::{
CoachFocus, MentalFocusType, PersonAttributes, PhysicalFocusType, Relations, Staff,
StaffAttributes, StaffCoaching, StaffDataAnalysis, StaffGoalkeeperCoaching, StaffKnowledge,
StaffLicenseType, StaffMedical, StaffMental, TechnicalFocusType,
};
use chrono::NaiveDate;
#[derive(Debug)]
pub struct StaffStub;
impl StaffStub {
pub fn default() -> Staff {
let staff = Staff {
id: 0,
full_name: FullName::with_full(
"stub".to_string(),
"stub".to_string(),
"stub".to_string(),
),
contract: None,
country_id: 0,
behaviour: PersonBehaviour::default(),
birth_date: NaiveDate::from_ymd_opt(2019, 1, 1).unwrap(),
relations: Relations::new(),
license: StaffLicenseType::NationalC,
attributes: PersonAttributes {
adaptability: 1.0f32,
ambition: 1.0f32,
controversy: 1.0f32,
loyalty: 1.0f32,
pressure: 1.0f32,
professionalism: 1.0f32,
sportsmanship: 1.0f32,
temperament: 1.0f32,
},
staff_attributes: StaffAttributes {
coaching: StaffCoaching {
attacking: 1,
defending: 1,
fitness: 1,
mental: 1,
tactical: 1,
technical: 1,
working_with_youngsters: 1,
},
goalkeeping: StaffGoalkeeperCoaching {
distribution: 1,
handling: 1,
shot_stopping: 1,
},
mental: StaffMental {
adaptability: 1,
determination: 1,
discipline: 1,
man_management: 1,
motivating: 1,
},
knowledge: StaffKnowledge {
judging_player_ability: 1,
judging_player_potential: 1,
tactical_knowledge: 1,
},
data_analysis: StaffDataAnalysis {
judging_player_data: 1,
judging_team_data: 1,
presenting_data: 1,
},
medical: StaffMedical {
physiotherapy: 1,
sports_science: 1,
non_player_tendencies: 1,
},
},
focus: Some(CoachFocus {
technical_focus: vec![
TechnicalFocusType::FreeKicks,
TechnicalFocusType::LongThrows,
],
mental_focus: vec![MentalFocusType::OffTheBall, MentalFocusType::Teamwork],
physical_focus: vec![PhysicalFocusType::NaturalFitness],
}),
fatigue: 0.0,
job_satisfaction: 0.0,
recent_performance: Default::default(),
coaching_style: Default::default(),
training_schedule: vec![],
};
staff
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/staff/attributes.rs | src/core/src/club/staff/attributes.rs | #[derive(Debug)]
pub struct StaffAttributes {
pub coaching: StaffCoaching,
pub goalkeeping: StaffGoalkeeperCoaching,
pub mental: StaffMental,
pub knowledge: StaffKnowledge,
pub data_analysis: StaffDataAnalysis,
pub medical: StaffMedical,
}
#[derive(Debug)]
pub struct StaffCoaching {
pub attacking: u8,
pub defending: u8,
pub fitness: u8,
pub mental: u8,
pub tactical: u8,
pub technical: u8,
pub working_with_youngsters: u8,
}
#[derive(Debug)]
pub struct StaffGoalkeeperCoaching {
pub distribution: u8,
pub handling: u8,
pub shot_stopping: u8,
}
#[derive(Debug)]
pub struct StaffMental {
pub adaptability: u8,
pub determination: u8,
pub discipline: u8,
pub man_management: u8,
pub motivating: u8,
}
#[derive(Debug)]
pub struct StaffKnowledge {
pub judging_player_ability: u8,
pub judging_player_potential: u8,
pub tactical_knowledge: u8,
}
#[derive(Debug)]
pub struct StaffDataAnalysis {
pub judging_player_data: u8,
pub judging_team_data: u8,
pub presenting_data: u8,
}
#[derive(Debug)]
pub struct StaffMedical {
pub physiotherapy: u8,
pub sports_science: u8,
pub non_player_tendencies: u8,
}
impl StaffAttributes {}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/staff/context.rs | src/core/src/club/staff/context.rs | #[derive(Clone)]
pub struct StaffContext {
pub id: Option<u32>,
}
impl StaffContext {
pub fn new(id: Option<u32>) -> Self {
StaffContext { id }
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/finance/sponsorship.rs | src/core/src/club/finance/sponsorship.rs | use chrono::NaiveDate;
#[derive(Debug)]
pub struct ClubSponsorship {
pub sponsorship_contracts: Vec<ClubSponsorshipContract>,
}
impl ClubSponsorship {
pub fn new(contracts: Vec<ClubSponsorshipContract>) -> Self {
ClubSponsorship {
sponsorship_contracts: contracts,
}
}
fn remove_expired_contracts(&mut self, date: NaiveDate) {
self.sponsorship_contracts
.retain(|contract| !contract.is_expired(date))
}
pub fn get_sponsorship_incomes<'s>(&mut self, date: NaiveDate) -> &[ClubSponsorshipContract] {
self.remove_expired_contracts(date);
&self.sponsorship_contracts
}
}
#[derive(Debug)]
pub struct ClubSponsorshipContract {
pub sponsor_name: String,
pub wage: i32,
expiration: NaiveDate,
}
impl ClubSponsorshipContract {
pub fn new(sponsor_name: String, wage: i32, expiration: NaiveDate) -> Self {
ClubSponsorshipContract {
sponsor_name,
wage,
expiration,
}
}
pub fn is_expired(&self, date: NaiveDate) -> bool {
self.expiration >= date
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/finance/result.rs | src/core/src/club/finance/result.rs | use crate::simulator::SimulatorData;
pub struct ClubFinanceResult {}
impl ClubFinanceResult {
pub fn new() -> Self {
ClubFinanceResult {}
}
pub fn process(&self, _: &mut SimulatorData) {}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/finance/history.rs | src/core/src/club/finance/history.rs | use crate::club::ClubFinancialBalance;
use chrono::NaiveDate;
use std::collections::LinkedList;
#[derive(Debug)]
pub struct ClubFinancialBalanceHistory {
history: LinkedList<(NaiveDate, ClubFinancialBalance)>,
}
impl ClubFinancialBalanceHistory {
pub fn new() -> Self {
ClubFinancialBalanceHistory {
history: LinkedList::new(),
}
}
pub fn get(&self, date: NaiveDate) -> Option<&ClubFinancialBalance> {
for (history_date, item) in self.history.iter() {
if *history_date == date {
return Some(item);
}
}
None
}
pub fn add(&mut self, date: NaiveDate, balance: ClubFinancialBalance) {
self.history.push_front((date, balance))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_date_not_found_none() {
let history = ClubFinancialBalanceHistory::new();
let date = NaiveDate::from_ymd_opt(2020, 2, 1).unwrap();
let result = history.get(date);
assert!(result.is_none());
}
#[test]
fn get_date_exist_return_balance() {
let mut history = ClubFinancialBalanceHistory::new();
let balance = ClubFinancialBalance::new(123);
let date = NaiveDate::from_ymd_opt(2020, 2, 1).unwrap();
history.add(date, balance);
let result = history.get(date);
assert!(result.is_some());
assert_eq!(123, result.unwrap().balance);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/finance/mod.rs | src/core/src/club/finance/mod.rs | mod balance;
mod context;
mod history;
mod result;
mod sponsorship;
pub use balance::*;
pub use context::*;
pub use history::*;
pub use result::*;
pub use sponsorship::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/finance/context.rs | src/core/src/club/finance/context.rs | #[derive(Clone)]
pub struct ClubFinanceContext {}
impl ClubFinanceContext {
pub fn new() -> Self {
ClubFinanceContext {}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/finance/balance.rs | src/core/src/club/finance/balance.rs | use crate::context::GlobalContext;
use crate::shared::CurrencyValue;
use crate::{ClubFinanceResult, ClubFinancialBalanceHistory, ClubSponsorship, ClubSponsorshipContract};
use chrono::NaiveDate;
use log::debug;
#[derive(Debug)]
pub struct ClubFinances {
pub balance: ClubFinancialBalance,
pub history: ClubFinancialBalanceHistory,
pub sponsorship: ClubSponsorship,
pub transfer_budget: Option<CurrencyValue>, // NEW FIELD
pub wage_budget: Option<CurrencyValue>, // NEW FIELD
}
impl ClubFinances {
pub fn new(amount: i32, sponsorship_contract: Vec<ClubSponsorshipContract>) -> Self {
ClubFinances {
balance: ClubFinancialBalance::new(amount),
history: ClubFinancialBalanceHistory::new(),
sponsorship: ClubSponsorship::new(sponsorship_contract),
transfer_budget: None,
wage_budget: None,
}
}
// New constructor with budgets
pub fn with_budgets(
amount: i32,
sponsorship_contract: Vec<ClubSponsorshipContract>,
transfer_budget: Option<CurrencyValue>,
wage_budget: Option<CurrencyValue>,
) -> Self {
ClubFinances {
balance: ClubFinancialBalance::new(amount),
history: ClubFinancialBalanceHistory::new(),
sponsorship: ClubSponsorship::new(sponsorship_contract),
transfer_budget,
wage_budget,
}
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> ClubFinanceResult {
let result = ClubFinanceResult::new();
let club_name = ctx.club.as_ref().expect("no club found").name;
if ctx.simulation.is_month_beginning() {
debug!("club: {}, finance: start new month", club_name);
self.start_new_month(club_name, ctx.simulation.date.date());
// Update budgets at month beginning
self.update_budgets();
}
if ctx.simulation.is_year_beginning() {
// ... sponsorship income code ...
// Reset budgets for new year
self.reset_annual_budgets();
}
result
}
fn start_new_month(&mut self, club_name: &str, date: NaiveDate) {
debug!(
"club: {}, finance: add history, date = {}, balance = {}, income={}, outcome={}",
club_name, date, self.balance.balance, self.balance.income, self.balance.outcome
);
self.history.add(date, self.balance.clone());
self.balance.clear();
}
pub fn push_salary(&mut self, club_name: &str, amount: i32) {
debug!(
"club: {}, finance: push salary, amount = {}",
club_name, amount
);
self.balance.push_outcome(amount);
}
fn update_budgets(&mut self) {
// Update transfer and wage budgets based on current financial situation
let available_funds = self.balance.balance as f64;
// Allocate 30% of available funds to transfers if positive balance
if available_funds > 0.0 {
self.transfer_budget = Some(CurrencyValue {
amount: available_funds * 0.3,
currency: crate::shared::Currency::Usd,
});
}
}
fn reset_annual_budgets(&mut self) {
// Reset budgets based on overall financial health
let available_funds = self.balance.balance as f64;
if available_funds > 0.0 {
// Set annual transfer budget (40% of available funds)
self.transfer_budget = Some(CurrencyValue {
amount: available_funds * 0.4,
currency: crate::shared::Currency::Usd,
});
// Set annual wage budget (50% of available funds)
self.wage_budget = Some(CurrencyValue {
amount: available_funds * 0.5,
currency: crate::shared::Currency::Usd,
});
} else {
// No budget if in debt
self.transfer_budget = None;
self.wage_budget = None;
}
}
// Helper method to spend from transfer budget
pub fn spend_from_transfer_budget(&mut self, amount: f64) -> bool {
if let Some(ref mut budget) = self.transfer_budget {
if budget.amount >= amount {
budget.amount -= amount;
self.balance.push_outcome(amount as i32);
return true;
}
}
false
}
// Helper method to add transfer income
pub fn add_transfer_income(&mut self, amount: f64) {
self.balance.push_income(amount as i32);
// Add 50% of transfer income to transfer budget
if let Some(ref mut budget) = self.transfer_budget {
budget.amount += amount * 0.5;
} else {
self.transfer_budget = Some(CurrencyValue {
amount: amount * 0.5,
currency: crate::shared::Currency::Usd,
});
}
}
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct ClubFinancialBalance {
pub balance: i32,
pub income: i32,
pub outcome: i32,
highest_wage_paid: i32,
latest_season_tickets: i32,
remaining_budget: i32,
season_transfer_funds: i32,
transfer_income_percentage: i32,
weekly_wage_budget: i32,
highest_wage: i32,
youth_grant_income: i32,
}
impl ClubFinancialBalance {
pub fn new(balance: i32) -> Self {
ClubFinancialBalance {
balance,
income: 0,
outcome: 0,
highest_wage_paid: 0,
latest_season_tickets: 0,
remaining_budget: 0,
season_transfer_funds: 0,
transfer_income_percentage: 0,
weekly_wage_budget: 0,
highest_wage: 0,
youth_grant_income: 0,
}
}
pub fn push_income(&mut self, wage: i32) {
self.balance = self.balance + wage;
self.income = self.income + wage;
}
pub fn push_outcome(&mut self, wage: i32) {
self.balance = self.balance - wage;
self.outcome = self.outcome + wage;
}
pub fn clear(&mut self) {
self.income = 0;
self.outcome = 0;
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/team.rs | src/core/src/club/team/team.rs | use crate::club::team::behaviour::TeamBehaviour;
use crate::context::GlobalContext;
use crate::r#match::{
EnhancedTacticsSelector, MatchPlayer, MatchSquad, SquadSelector,
};
use crate::shared::CurrencyValue;
use crate::{MatchHistory, MatchTacticType, Player, PlayerCollection, RecommendationPriority, StaffCollection, Tactics, TacticsSelector, TeamReputation, TeamResult, TeamTraining, TrainingSchedule, TransferItem, Transfers};
use log::{debug, info};
use std::borrow::Cow;
use std::str::FromStr;
use crate::club::team::builder::TeamBuilder;
#[derive(Debug, PartialEq)]
pub enum TeamType {
Main = 0,
B = 1,
U18 = 2,
U19 = 3,
U21 = 4,
U23 = 5,
}
#[derive(Debug)]
pub struct Team {
pub id: u32,
pub league_id: u32,
pub club_id: u32,
pub name: String,
pub slug: String,
pub team_type: TeamType,
pub tactics: Option<Tactics>,
pub players: PlayerCollection,
pub staffs: StaffCollection,
pub behaviour: TeamBehaviour,
pub reputation: TeamReputation,
pub training_schedule: TrainingSchedule,
pub transfer_list: Transfers,
pub match_history: MatchHistory,
}
impl Team {
pub fn builder() -> TeamBuilder {
TeamBuilder::new()
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> TeamResult {
let result = TeamResult::new(
self.id,
self.players.simulate(ctx.with_player(None)),
self.staffs.simulate(ctx.with_staff(None)),
self.behaviour
.simulate(&mut self.players, &mut self.staffs, ctx.with_team(self.id)),
TeamTraining::train(self, ctx.simulation.date),
);
if self.tactics.is_none() {
self.tactics = Some(TacticsSelector::select(self, self.staffs.head_coach()));
};
if self.training_schedule.is_default {
//let coach = self.staffs.head_coach();
}
result
}
pub fn players(&self) -> Vec<&Player> {
self.players.players()
}
pub fn add_player_to_transfer_list(&mut self, player_id: u32, value: CurrencyValue) {
self.transfer_list.add(TransferItem {
player_id,
amount: value,
})
}
pub fn get_week_salary(&self) -> u32 {
self.players
.players
.iter()
.filter_map(|p| p.contract.as_ref())
.map(|c| c.salary)
.chain(
self.staffs
.staffs
.iter()
.filter_map(|p| p.contract.as_ref())
.map(|c| c.salary),
)
.sum()
}
/// Enhanced get_match_squad that uses improved tactical analysis
pub fn get_enhanced_match_squad(&self) -> MatchSquad {
let head_coach = self.staffs.head_coach();
// Step 2: Use enhanced squad selection
let squad_result = SquadSelector::select(self, head_coach);
// Step 3: Create match squad with selected tactics
let final_tactics = self
.tactics
.as_ref()
.cloned()
.unwrap_or_else(|| TacticsSelector::select(self, head_coach));
// Step 5: Validate squad selection
self.validate_squad_selection(&squad_result, &final_tactics);
MatchSquad {
team_id: self.id,
team_name: self.name.clone(),
tactics: final_tactics,
main_squad: squad_result.main_squad,
substitutes: squad_result.substitutes,
captain_id: self.select_captain(),
vice_captain_id: self.select_vice_captain(),
penalty_taker_id: self.select_penalty_taker(),
free_kick_taker_id: self.select_free_kick_taker(),
}
}
fn validate_squad_selection(
&self,
squad_result: &crate::r#match::squad::PlayerSelectionResult,
tactics: &Tactics,
) {
let formation_positions = tactics.positions();
if squad_result.main_squad.len() != formation_positions.len() {
log::warn!(
"Squad size mismatch: got {} players for {} positions",
squad_result.main_squad.len(),
formation_positions.len()
);
}
let mut position_coverage = std::collections::HashMap::new();
for match_player in &squad_result.main_squad {
let pos = match_player.tactical_position.current_position;
*position_coverage.entry(pos).or_insert(0) += 1;
}
for &required_pos in formation_positions {
if !position_coverage.contains_key(&required_pos) {
log::warn!(
"No player selected for required position: {}",
required_pos.get_short_name()
);
}
}
}
/// Select team captain based on leadership and experience
fn select_captain(&self) -> Option<MatchPlayer> {
self.players
.players()
.iter()
.filter(|p| !p.player_attributes.is_injured && !p.player_attributes.is_banned)
.max_by(|a, b| {
let leadership_a = a.skills.mental.leadership;
let leadership_b = b.skills.mental.leadership;
let experience_a = a.player_attributes.international_apps;
let experience_b = b.player_attributes.international_apps;
(leadership_a + experience_a as f32 / 10.0)
.partial_cmp(&(leadership_b + experience_b as f32 / 10.0))
.unwrap_or(std::cmp::Ordering::Equal)
})
.map(|p| MatchPlayer::from_player(self.id, p, p.position(), false))
}
/// Select vice captain
fn select_vice_captain(&self) -> Option<MatchPlayer> {
// Similar logic to captain but exclude current captain
// Implementation would be similar to select_captain
None
}
/// Select penalty taker based on penalty taking skill and composure
fn select_penalty_taker(&self) -> Option<MatchPlayer> {
self.players
.players()
.iter()
.filter(|p| !p.player_attributes.is_injured && !p.player_attributes.is_banned)
.max_by(|a, b| {
let penalty_skill_a = a.skills.technical.penalty_taking + a.skills.mental.composure;
let penalty_skill_b = b.skills.technical.penalty_taking + b.skills.mental.composure;
penalty_skill_a
.partial_cmp(&penalty_skill_b)
.unwrap_or(std::cmp::Ordering::Equal)
})
.map(|p| MatchPlayer::from_player(self.id, p, p.position(), false))
}
/// Select free kick taker based on free kick skill and technique
fn select_free_kick_taker(&self) -> Option<MatchPlayer> {
self.players
.players()
.iter()
.filter(|p| !p.player_attributes.is_injured && !p.player_attributes.is_banned)
.max_by(|a, b| {
let fk_skill_a = a.skills.technical.free_kicks + a.skills.technical.technique;
let fk_skill_b = b.skills.technical.free_kicks + b.skills.technical.technique;
fk_skill_a
.partial_cmp(&fk_skill_b)
.unwrap_or(std::cmp::Ordering::Equal)
})
.map(|p| MatchPlayer::from_player(self.id, p, p.position(), false))
}
/// Adaptive tactics during a match based on game state
pub fn adapt_tactics_during_match_enhanced(
&mut self,
score_difference: i8,
minutes_played: u8,
is_home: bool,
team_morale: f32,
) -> Option<Tactics> {
let current_tactic = &self.tactics().tactic_type;
let available_players: Vec<&crate::Player> = self
.players
.players()
.into_iter()
.filter(|p| p.is_ready_for_match())
.collect();
// Use enhanced contextual selection
let staff = self.staffs.head_coach();
let recent_results = vec![]; // This would come from match history
let suggested_tactics = EnhancedTacticsSelector::select_contextual_tactics(
self,
staff,
&recent_results,
team_morale,
);
// Override with situational tactics if needed
if let Some(situational_tactics) = TacticsSelector::select_situational_tactic(
current_tactic,
is_home,
score_difference,
minutes_played,
&available_players,
) {
info!(
"Adapting tactics due to match situation: {} -> {}",
current_tactic.display_name(),
situational_tactics.tactic_type.display_name()
);
return Some(situational_tactics);
}
// Check if suggested tactics are significantly different
if suggested_tactics.tactic_type != *current_tactic {
let fitness_current = self
.tactics()
.calculate_formation_fitness(&available_players);
let fitness_suggested =
suggested_tactics.calculate_formation_fitness(&available_players);
if fitness_suggested > fitness_current + 0.1 {
// Significant improvement threshold
info!(
"Switching tactics for better formation fitness: {:.2} -> {:.2}",
fitness_current, fitness_suggested
);
return Some(suggested_tactics);
}
}
None
}
/// Run comprehensive tactical analysis during team simulation
pub fn run_tactical_analysis(
&mut self,
) -> crate::club::team::tactics::decision::TacticalDecisionResult {
let decisions =
crate::club::team::tactics::decision::TacticalDecisionEngine::make_tactical_decisions(
self,
);
// Apply formation change if recommended with high confidence
if let Some(ref change) = decisions.formation_change {
if change.confidence > 0.75 {
info!(
"Implementing formation change: {} -> {} ({})",
change.from.map(|f| f.display_name()).unwrap_or("None"),
change.to.display_name(),
change.reason
);
self.tactics = Some(Tactics::with_reason(
change.to,
crate::TacticSelectionReason::TeamComposition,
change.confidence,
));
}
}
// Log important recommendations
for rec in &decisions.recommendations {
match rec.priority {
RecommendationPriority::High | RecommendationPriority::Critical => {
log::warn!(
"[{}] {}: {}",
if rec.priority == RecommendationPriority::Critical {
"CRITICAL"
} else {
"HIGH"
},
format!("{:?}", rec.category),
rec.description
);
}
_ => {
debug!(
"[{:?}] {}: {}",
rec.priority,
format!("{:?}", rec.category),
rec.description
);
}
}
}
decisions
}
pub fn tactics(&self) -> Cow<'_, Tactics> {
if let Some(tactics) = &self.tactics {
Cow::Borrowed(tactics)
} else {
Cow::Owned(Tactics::new(MatchTacticType::T442))
}
}
/// Method to adapt tactics during a match
pub fn adapt_tactics_during_match(
&mut self,
score_difference: i8,
minutes_played: u8,
is_home: bool,
) -> Option<Tactics> {
let current_tactic = &self.tactics().tactic_type;
let available_players: Vec<&Player> = self
.players
.players()
.into_iter()
.filter(|p| p.is_ready_for_match())
.collect();
TacticsSelector::select_situational_tactic(
current_tactic,
is_home,
score_difference,
minutes_played,
&available_players,
)
}
}
impl FromStr for TeamType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Main" => Ok(TeamType::Main),
"B" => Ok(TeamType::B),
"U18" => Ok(TeamType::U18),
"U19" => Ok(TeamType::U19),
"U21" => Ok(TeamType::U21),
"U23" => Ok(TeamType::U23),
_ => Err(format!("'{}' is not a valid value for WSType", s)),
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/builder.rs | src/core/src/club/team/builder.rs | use crate::club::team::behaviour::TeamBehaviour;
use crate::{MatchHistory, PlayerCollection, StaffCollection, Tactics, Team, TeamReputation, TeamType, TrainingSchedule, Transfers};
#[derive(Default)]
pub struct TeamBuilder {
id: Option<u32>,
league_id: Option<u32>,
club_id: Option<u32>,
name: Option<String>,
slug: Option<String>,
team_type: Option<TeamType>,
tactics: Option<Option<Tactics>>,
players: Option<PlayerCollection>,
staffs: Option<StaffCollection>,
behaviour: Option<TeamBehaviour>,
reputation: Option<TeamReputation>,
training_schedule: Option<TrainingSchedule>,
transfer_list: Option<Transfers>,
match_history: Option<MatchHistory>,
}
impl TeamBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
pub fn league_id(mut self, league_id: u32) -> Self {
self.league_id = Some(league_id);
self
}
pub fn club_id(mut self, club_id: u32) -> Self {
self.club_id = Some(club_id);
self
}
pub fn name(mut self, name: String) -> Self {
self.name = Some(name);
self
}
pub fn slug(mut self, slug: String) -> Self {
self.slug = Some(slug);
self
}
pub fn team_type(mut self, team_type: TeamType) -> Self {
self.team_type = Some(team_type);
self
}
pub fn tactics(mut self, tactics: Option<Tactics>) -> Self {
self.tactics = Some(tactics);
self
}
pub fn players(mut self, players: PlayerCollection) -> Self {
self.players = Some(players);
self
}
pub fn staffs(mut self, staffs: StaffCollection) -> Self {
self.staffs = Some(staffs);
self
}
pub fn behaviour(mut self, behaviour: TeamBehaviour) -> Self {
self.behaviour = Some(behaviour);
self
}
pub fn reputation(mut self, reputation: TeamReputation) -> Self {
self.reputation = Some(reputation);
self
}
pub fn training_schedule(mut self, training_schedule: TrainingSchedule) -> Self {
self.training_schedule = Some(training_schedule);
self
}
pub fn transfer_list(mut self, transfer_list: Transfers) -> Self {
self.transfer_list = Some(transfer_list);
self
}
pub fn match_history(mut self, match_history: MatchHistory) -> Self {
self.match_history = Some(match_history);
self
}
pub fn build(self) -> Result<Team, String> {
Ok(Team {
id: self.id.ok_or("id is required")?,
league_id: self.league_id.ok_or("league_id is required")?,
club_id: self.club_id.ok_or("club_id is required")?,
name: self.name.ok_or("name is required")?,
slug: self.slug.ok_or("slug is required")?,
team_type: self.team_type.ok_or("team_type is required")?,
tactics: self.tactics.unwrap_or(None),
players: self.players.ok_or("players is required")?,
staffs: self.staffs.ok_or("staffs is required")?,
behaviour: self.behaviour.unwrap_or_else(TeamBehaviour::new),
reputation: self.reputation.ok_or("reputation is required")?,
training_schedule: self.training_schedule.ok_or("training_schedule is required")?,
transfer_list: self.transfer_list.unwrap_or_else(Transfers::new),
match_history: self.match_history.unwrap_or_else(MatchHistory::new),
})
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/result.rs | src/core/src/club/team/result.rs | use crate::club::team::behaviour::TeamBehaviourResult;
use crate::club::PlayerCollectionResult;
use crate::shared::{Currency, CurrencyValue};
use crate::simulator::SimulatorData;
use crate::{StaffCollectionResult, TeamTrainingResult};
pub struct TeamResult {
pub team_id: u32,
pub players: PlayerCollectionResult,
pub staffs: StaffCollectionResult,
pub behaviour: TeamBehaviourResult,
pub training: TeamTrainingResult,
}
impl TeamResult {
pub fn new(
team_id: u32,
players: PlayerCollectionResult,
staffs: StaffCollectionResult,
behaviour: TeamBehaviourResult,
training: TeamTrainingResult,
) -> Self {
TeamResult {
team_id,
players,
staffs,
behaviour,
training,
}
}
pub fn process(&self, data: &mut SimulatorData) {
let team = data.team_mut(self.team_id).unwrap();
for player_result in &self.players.players {
team.add_player_to_transfer_list(
player_result.player_id,
CurrencyValue {
amount: 100000 as f64,
currency: Currency::Usd,
},
)
}
self.players.process(data);
self.staffs.process(data);
self.training.process(data);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/mod.rs | src/core/src/club/team/mod.rs | pub mod behaviour;
pub mod builder;
pub mod collection;
pub mod context;
pub mod matches;
pub mod reputation;
pub mod result;
pub mod tactics;
pub mod team;
pub mod training;
pub mod transfers;
pub use behaviour::*;
pub use builder::*;
pub use collection::*;
pub use context::*;
pub use matches::*;
pub use reputation::*;
pub use result::*;
pub use tactics::*;
pub use team::*;
pub use training::*;
pub use transfers::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/reputation.rs | src/core/src/club/team/reputation.rs | use chrono::NaiveDate;
use std::collections::VecDeque;
/// Enhanced TeamReputation with dynamic updates and history tracking
#[derive(Debug, Clone)]
pub struct TeamReputation {
/// Local/regional reputation (0-1000)
pub home: u16,
/// National reputation (0-1000)
pub national: u16,
/// International reputation (0-1000)
pub world: u16,
/// Momentum - how fast reputation is changing
momentum: ReputationMomentum,
/// Historical tracking
history: ReputationHistory,
/// Factors affecting reputation
factors: ReputationFactors,
}
impl TeamReputation {
/// Create a new TeamReputation with initial values
pub fn new(home: u16, national: u16, world: u16) -> Self {
TeamReputation {
home: home.min(1000),
national: national.min(1000),
world: world.min(1000),
momentum: ReputationMomentum::default(),
history: ReputationHistory::new(),
factors: ReputationFactors::default(),
}
}
/// Get the overall reputation score (weighted average)
pub fn overall_score(&self) -> f32 {
(self.home as f32 * 0.2 + self.national as f32 * 0.3 + self.world as f32 * 0.5) / 1000.0
}
/// Get reputation level category
pub fn level(&self) -> ReputationLevel {
match self.overall_score() {
s if s >= 0.9 => ReputationLevel::Elite,
s if s >= 0.75 => ReputationLevel::Continental,
s if s >= 0.6 => ReputationLevel::National,
s if s >= 0.4 => ReputationLevel::Regional,
s if s >= 0.2 => ReputationLevel::Local,
_ => ReputationLevel::Amateur,
}
}
/// Process weekly reputation update based on recent performance
pub fn process_weekly_update(
&mut self,
match_results: &[MatchResultInfo],
league_position: u8,
total_teams: u8,
date: NaiveDate,
) {
// Calculate performance factors
let match_factor = self.calculate_match_factor(match_results);
let position_factor = self.calculate_position_factor(league_position, total_teams);
// Update momentum based on recent results
self.momentum.update(match_factor + position_factor);
// Apply reputation changes
self.apply_reputation_changes(match_factor, position_factor);
// Record in history
self.history.record_snapshot(
date,
ReputationSnapshot {
home: self.home,
national: self.national,
world: self.world,
overall: self.overall_score(),
}
);
// Decay old factors
self.factors.decay();
}
/// Process a major achievement (trophy, promotion, etc.)
pub fn process_achievement(&mut self, achievement: Achievement) {
let boost = achievement.reputation_boost();
match achievement.scope() {
AchievementScope::Local => {
self.home = (self.home + boost.0).min(1000);
self.national = (self.national + boost.1 / 2).min(1000);
}
AchievementScope::National => {
self.home = (self.home + boost.0).min(1000);
self.national = (self.national + boost.1).min(1000);
self.world = (self.world + boost.2 / 2).min(1000);
}
AchievementScope::Continental => {
self.national = (self.national + boost.1).min(1000);
self.world = (self.world + boost.2).min(1000);
}
AchievementScope::Global => {
self.world = (self.world + boost.2).min(1000);
self.national = (self.national + boost.1).min(1000);
}
}
self.factors.achievements.push(achievement);
self.momentum.boost(0.2);
}
/// Process a player signing that affects reputation
pub fn process_player_signing(&mut self, player_reputation: u16, is_star_player: bool) {
if is_star_player && player_reputation > self.world {
// Signing a star player boosts reputation
let boost = ((player_reputation - self.world) / 10) as u16;
self.world = (self.world + boost).min(1000);
self.national = (self.national + boost / 2).min(1000);
self.factors.star_players_signed += 1;
self.momentum.boost(0.05);
}
}
/// Process manager change
pub fn process_manager_change(&mut self, manager_reputation: u16) {
if manager_reputation > self.national {
let boost = ((manager_reputation - self.national) / 8) as u16;
self.national = (self.national + boost).min(1000);
self.world = (self.world + boost / 2).min(1000);
self.momentum.boost(0.1);
}
}
/// Apply gradual reputation decay (called monthly)
pub fn apply_monthly_decay(&mut self) {
// Reputation slowly decays without achievements
let decay_rate = match self.level() {
ReputationLevel::Elite => 0.995, // Slower decay for elite teams
ReputationLevel::Continental => 0.993,
ReputationLevel::National => 0.990,
_ => 0.988, // Faster decay for lower reputation
};
if self.momentum.current < 0.0 {
// Accelerated decay if momentum is negative
let adjusted_decay = decay_rate - (self.momentum.current.abs() * 0.01);
self.apply_decay(adjusted_decay.max(0.95));
} else if self.momentum.current < 0.1 {
// Normal decay if momentum is low
self.apply_decay(decay_rate);
}
// No decay if momentum is high (team is performing well)
}
/// Calculate reputation factor from match results
fn calculate_match_factor(&self, results: &[MatchResultInfo]) -> f32 {
if results.is_empty() {
return 0.0;
}
let mut factor = 0.0;
for result in results {
let result_value = match result.outcome {
MatchOutcome::Win => {
let opponent_factor = result.opponent_reputation as f32 / self.overall_score().max(100.0);
0.03 * opponent_factor
}
MatchOutcome::Draw => {
let opponent_factor = result.opponent_reputation as f32 / self.overall_score().max(100.0);
0.01 * opponent_factor - 0.005
}
MatchOutcome::Loss => {
let opponent_factor = self.overall_score() / result.opponent_reputation as f32;
-0.02 * opponent_factor
}
};
// Competition importance multiplier
let competition_mult = match result.competition_type {
CompetitionType::League => 1.0,
CompetitionType::DomesticCup => 1.2,
CompetitionType::ContinentalCup => 1.5,
CompetitionType::WorldCup => 2.0,
};
factor += result_value * competition_mult;
}
factor / results.len() as f32
}
/// Calculate reputation factor from league position
fn calculate_position_factor(&self, position: u8, total_teams: u8) -> f32 {
let relative_position = position as f32 / total_teams as f32;
match relative_position {
p if p <= 0.1 => 0.03, // Top 10%
p if p <= 0.25 => 0.01, // Top 25%
p if p <= 0.5 => 0.0, // Top 50%
p if p <= 0.75 => -0.01, // Bottom 50%
_ => -0.02, // Bottom 25%
}
}
/// Apply calculated reputation changes
fn apply_reputation_changes(&mut self, match_factor: f32, position_factor: f32) {
let total_factor = (match_factor + position_factor) * (1.0 + self.momentum.current);
// Different scopes affected differently
let home_change = (total_factor * 20.0) as i16;
let national_change = (total_factor * 15.0) as i16;
let world_change = (total_factor * 10.0) as i16;
self.home = ((self.home as i16 + home_change).max(0) as u16).min(1000);
self.national = ((self.national as i16 + national_change).max(0) as u16).min(1000);
self.world = ((self.world as i16 + world_change).max(0) as u16).min(1000);
// Ensure logical ordering (world <= national <= home)
if self.world > self.national {
self.national = self.world;
}
if self.national > self.home {
self.home = self.national;
}
}
/// Apply decay to all reputation values
fn apply_decay(&mut self, rate: f32) {
self.home = (self.home as f32 * rate) as u16;
self.national = (self.national as f32 * rate) as u16;
self.world = (self.world as f32 * rate) as u16;
}
/// Get recent trend
pub fn get_trend(&self) -> ReputationTrend {
self.history.calculate_trend()
}
/// Check if reputation meets requirements
pub fn meets_requirements(&self, requirements: &ReputationRequirements) -> bool {
self.home >= requirements.min_home &&
self.national >= requirements.min_national &&
self.world >= requirements.min_world
}
/// Get attractiveness factor for transfers/signings
pub fn attractiveness_factor(&self) -> f32 {
let base = self.overall_score();
let momentum_bonus = self.momentum.current.max(0.0) * 0.2;
let achievement_bonus = (self.factors.achievements.len() as f32 * 0.02).min(0.2);
(base + momentum_bonus + achievement_bonus).min(1.0)
}
}
/// Reputation momentum tracking
#[derive(Debug, Clone)]
struct ReputationMomentum {
current: f32,
history: VecDeque<f32>,
}
impl Default for ReputationMomentum {
fn default() -> Self {
ReputationMomentum {
current: 0.0,
history: VecDeque::with_capacity(10),
}
}
}
impl ReputationMomentum {
fn update(&mut self, change: f32) {
self.history.push_back(change);
if self.history.len() > 10 {
self.history.pop_front();
}
// Calculate weighted average (recent changes matter more)
let mut weighted_sum = 0.0;
let mut weight_total = 0.0;
for (i, &value) in self.history.iter().enumerate() {
let weight = (i + 1) as f32;
weighted_sum += value * weight;
weight_total += weight;
}
self.current = if weight_total > 0.0 {
(weighted_sum / weight_total).clamp(-0.5, 0.5)
} else {
0.0
};
}
fn boost(&mut self, amount: f32) {
self.current = (self.current + amount).min(0.5);
}
}
/// Historical reputation tracking
#[derive(Debug, Clone)]
struct ReputationHistory {
snapshots: VecDeque<(NaiveDate, ReputationSnapshot)>,
max_snapshots: usize,
}
impl ReputationHistory {
fn new() -> Self {
ReputationHistory {
snapshots: VecDeque::with_capacity(52), // Store ~1 year of weekly snapshots
max_snapshots: 52,
}
}
fn record_snapshot(&mut self, date: NaiveDate, snapshot: ReputationSnapshot) {
self.snapshots.push_back((date, snapshot));
if self.snapshots.len() > self.max_snapshots {
self.snapshots.pop_front();
}
}
fn calculate_trend(&self) -> ReputationTrend {
if self.snapshots.len() < 4 {
return ReputationTrend::Stable;
}
let recent_avg = self.snapshots.iter()
.rev()
.take(4)
.map(|(_, s)| s.overall)
.sum::<f32>() / 4.0;
let older_avg = self.snapshots.iter()
.rev()
.skip(4)
.take(4)
.map(|(_, s)| s.overall)
.sum::<f32>() / 4.0;
let change = recent_avg - older_avg;
match change {
c if c > 0.05 => ReputationTrend::Rising,
c if c < -0.05 => ReputationTrend::Falling,
_ => ReputationTrend::Stable,
}
}
}
#[derive(Debug, Clone)]
struct ReputationSnapshot {
home: u16,
national: u16,
world: u16,
overall: f32,
}
/// Factors affecting reputation
#[derive(Debug, Clone, Default)]
struct ReputationFactors {
achievements: Vec<Achievement>,
star_players_signed: u8,
recent_investment: f64,
stadium_upgrade: bool,
youth_development: u8,
}
impl ReputationFactors {
fn decay(&mut self) {
// Remove old achievements
self.achievements.retain(|a| !a.is_expired());
// Decay other factors
if self.star_players_signed > 0 {
self.star_players_signed -= 1;
}
self.recent_investment *= 0.95;
}
}
/// Reputation level categories
#[derive(Debug, Clone, PartialEq)]
pub enum ReputationLevel {
Amateur,
Local,
Regional,
National,
Continental,
Elite,
}
/// Reputation trend
#[derive(Debug, Clone, PartialEq)]
pub enum ReputationTrend {
Rising,
Stable,
Falling,
}
/// Achievement that affects reputation
#[derive(Debug, Clone)]
pub struct Achievement {
achievement_type: AchievementType,
date: NaiveDate,
importance: u8, // 1-10 scale
}
impl Achievement {
pub fn new(achievement_type: AchievementType, date: NaiveDate, importance: u8) -> Self {
Achievement {
achievement_type,
date,
importance: importance.min(10),
}
}
fn reputation_boost(&self) -> (u16, u16, u16) {
match self.achievement_type {
AchievementType::LeagueTitle => (50, 100, 80),
AchievementType::CupWin => (40, 60, 40),
AchievementType::Promotion => (60, 40, 20),
AchievementType::ContinentalQualification => (30, 50, 60),
AchievementType::ContinentalTrophy => (40, 80, 150),
AchievementType::RecordBreaking => (20, 30, 40),
}
}
fn scope(&self) -> AchievementScope {
match self.achievement_type {
AchievementType::Promotion | AchievementType::RecordBreaking => AchievementScope::Local,
AchievementType::LeagueTitle | AchievementType::CupWin => AchievementScope::National,
AchievementType::ContinentalQualification => AchievementScope::Continental,
AchievementType::ContinentalTrophy => AchievementScope::Global,
}
}
fn is_expired(&self) -> bool {
// Achievements expire after 2 years
let today = chrono::Local::now().date_naive();
(today - self.date).num_days() > 730
}
}
#[derive(Debug, Clone)]
pub enum AchievementType {
LeagueTitle,
CupWin,
Promotion,
ContinentalQualification,
ContinentalTrophy,
RecordBreaking,
}
#[derive(Debug, Clone)]
enum AchievementScope {
Local,
National,
Continental,
Global,
}
/// Match result information for reputation calculation
#[derive(Debug, Clone)]
pub struct MatchResultInfo {
pub outcome: MatchOutcome,
pub opponent_reputation: u16,
pub competition_type: CompetitionType,
}
#[derive(Debug, Clone)]
pub enum MatchOutcome {
Win,
Draw,
Loss,
}
#[derive(Debug, Clone)]
pub enum CompetitionType {
League,
DomesticCup,
ContinentalCup,
WorldCup,
}
/// Requirements for reputation-gated content
#[derive(Debug, Clone)]
pub struct ReputationRequirements {
pub min_home: u16,
pub min_national: u16,
pub min_world: u16,
}
impl ReputationRequirements {
pub fn new(home: u16, national: u16, world: u16) -> Self {
ReputationRequirements {
min_home: home,
min_national: national,
min_world: world,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_reputation_levels() {
let mut rep = TeamReputation::new(100, 100, 100);
assert_eq!(rep.level(), ReputationLevel::Amateur);
rep = TeamReputation::new(500, 500, 500);
assert_eq!(rep.level(), ReputationLevel::Regional);
rep = TeamReputation::new(900, 900, 900);
assert_eq!(rep.level(), ReputationLevel::Elite);
}
#[test]
fn test_achievement_processing() {
let mut rep = TeamReputation::new(400, 400, 400);
let initial_world = rep.world;
let achievement = Achievement::new(
AchievementType::LeagueTitle,
NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
8
);
rep.process_achievement(achievement);
assert!(rep.national > 400);
assert!(rep.world > initial_world);
}
#[test]
fn test_match_results_processing() {
let mut rep = TeamReputation::new(500, 500, 500);
let results = vec![
MatchResultInfo {
outcome: MatchOutcome::Win,
opponent_reputation: 600,
competition_type: CompetitionType::League,
},
MatchResultInfo {
outcome: MatchOutcome::Win,
opponent_reputation: 700,
competition_type: CompetitionType::DomesticCup,
},
];
rep.process_weekly_update(&results, 3, 20, NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());
assert!(rep.momentum.current > 0.0);
}
#[test]
fn test_attractiveness_factor() {
let mut rep = TeamReputation::new(800, 800, 800);
let base_attractiveness = rep.attractiveness_factor();
// Add achievement
rep.process_achievement(Achievement::new(
AchievementType::ContinentalTrophy,
NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
10
));
let new_attractiveness = rep.attractiveness_factor();
assert!(new_attractiveness > base_attractiveness);
}
#[test]
fn test_reputation_decay() {
let mut rep = TeamReputation::new(500, 500, 500);
let initial_home = rep.home;
rep.apply_monthly_decay();
assert!(rep.home < initial_home);
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/context.rs | src/core/src/club/team/context.rs | #[derive(Clone)]
pub struct TeamContext {
pub id: u32,
}
impl TeamContext {
pub fn new(id: u32) -> Self {
TeamContext { id }
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/collection.rs | src/core/src/club/team/collection.rs | use crate::context::GlobalContext;
use crate::utils::Logging;
use crate::{Team, TeamResult, TeamType};
#[derive(Debug)]
pub struct TeamCollection {
pub teams: Vec<Team>,
}
impl TeamCollection {
pub fn new(teams: Vec<Team>) -> Self {
TeamCollection { teams }
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> Vec<TeamResult> {
self.teams
.iter_mut()
.map(|team| {
let message = &format!("simulate team: {}", &team.name);
Logging::estimate_result(|| team.simulate(ctx.with_team(team.id)), message)
})
.collect()
}
pub fn by_id(&self, id: u32) -> &Team {
self.teams
.iter()
.find(|t| t.id == id)
.expect(format!("no team with id = {}", id).as_str())
}
pub fn main_team_id(&self) -> Option<u32> {
self.teams
.iter()
.find(|t| t.team_type == TeamType::Main)
.map(|t| t.id)
}
pub fn with_league(&self, league_id: u32) -> Vec<u32> {
self.teams
.iter()
.filter(|t| t.league_id == league_id)
.map(|t| t.id)
.collect()
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/tactics/decision.rs | src/core/src/club/team/tactics/decision.rs | use crate::r#match::{SquadSelector, TacticalSquadAnalyzer};
use crate::{Player, Team};
pub struct TacticalDecisionEngine;
impl TacticalDecisionEngine {
/// Make comprehensive tactical decisions for a team
pub fn make_tactical_decisions(team: &mut Team) -> TacticalDecisionResult {
let head_coach = team.staffs.head_coach();
let mut decisions = TacticalDecisionResult::new();
// 1. Formation Analysis
if let Some(optimal_formation) = TacticalSquadAnalyzer::suggest_optimal_formation(team, head_coach) {
let current_formation = team.tactics.as_ref().map(|t| t.tactic_type);
if current_formation != Some(optimal_formation) {
decisions.formation_change = Some(FormationChange {
from: current_formation,
to: optimal_formation,
reason: "Squad composition analysis".to_string(),
confidence: 0.8,
});
}
}
// 2. Squad Selection Analysis
let squad_result = SquadSelector::select(team, head_coach);
decisions.squad_analysis = Self::analyze_squad_selection(&squad_result, team);
// 3. Tactical Recommendations
decisions.recommendations = Self::generate_tactical_recommendations(team, head_coach);
decisions
}
/// Analyze the quality of squad selection
fn analyze_squad_selection(
squad_result: &crate::r#match::squad::PlayerSelectionResult,
team: &Team,
) -> SquadAnalysis {
let tactics = team.tactics();
let mut analysis = SquadAnalysis::new();
// Calculate average ratings for main squad
let mut total_rating = 0.0;
let mut position_mismatches = 0;
for match_player in &squad_result.main_squad {
let players = team.players.players();
let player = players
.iter()
.find(|p| p.id == match_player.id)
.unwrap();
let position = match_player.tactical_position.current_position;
let rating = SquadSelector::calculate_player_rating_for_position(
player,
team.staffs.head_coach(),
position,
&tactics
);
total_rating += rating;
// Check for position mismatches
if !player.positions.has_position(position) {
position_mismatches += 1;
analysis.warnings.push(format!(
"{} playing out of position at {}",
player.full_name,
position.get_short_name()
));
}
}
analysis.average_rating = total_rating / squad_result.main_squad.len() as f32;
analysis.position_mismatches = position_mismatches;
analysis.formation_fitness = tactics.calculate_formation_fitness(&team.players.players());
// Analyze bench strength
analysis.bench_quality = Self::calculate_bench_quality(&squad_result.substitutes, team);
analysis
}
/// Calculate the quality of substitutes
fn calculate_bench_quality(
substitutes: &[crate::r#match::MatchPlayer],
team: &Team,
) -> f32 {
if substitutes.is_empty() {
return 0.0;
}
let mut total_quality = 0.0;
for sub in substitutes {
if let Some(player) = team.players.players().iter().find(|p| p.id == sub.id) {
let quality = (player.skills.technical.average() +
player.skills.mental.average() +
player.skills.physical.average()) / 3.0;
total_quality += quality;
}
}
total_quality / substitutes.len() as f32
}
/// Generate tactical recommendations for the team
fn generate_tactical_recommendations(team: &Team, staff: &crate::Staff) -> Vec<TacticalRecommendation> {
let mut recommendations = Vec::new();
// Check if coach tactical knowledge matches formation complexity
let current_tactics = team.tactics();
let coach_knowledge = staff.staff_attributes.knowledge.tactical_knowledge;
match current_tactics.tactic_type {
crate::MatchTacticType::T4312 | crate::MatchTacticType::T343 if coach_knowledge < 15 => {
recommendations.push(TacticalRecommendation {
priority: RecommendationPriority::High,
category: RecommendationCategory::Formation,
description: "Current formation may be too complex for coach's tactical knowledge. Consider simpler formation like 4-4-2 or 4-3-3.".to_string(),
suggested_action: Some("Change to 4-4-2".to_string()),
});
}
_ => {}
}
// Check for player-position mismatches
let available_players: Vec<&Player> = team.players.players()
.iter()
.filter(|p| !p.player_attributes.is_injured && !p.player_attributes.is_banned)
.map(|p| *p)
.collect();
let formation_fitness = current_tactics.calculate_formation_fitness(&available_players);
if formation_fitness < 0.6 {
recommendations.push(TacticalRecommendation {
priority: RecommendationPriority::Medium,
category: RecommendationCategory::SquadSelection,
description: format!("Formation fitness is low ({:.2}). Consider formation change or player acquisitions.", formation_fitness),
suggested_action: Some("Analyze alternative formations".to_string()),
});
}
// Check bench depth
let bench_players = available_players.len() - 11;
if bench_players < 7 {
recommendations.push(TacticalRecommendation {
priority: RecommendationPriority::Medium,
category: RecommendationCategory::SquadDepth,
description: format!("Limited bench options ({} substitutes available). Squad depth may be insufficient.", bench_players),
suggested_action: Some("Consider loan or transfer signings".to_string()),
});
}
recommendations
}
}
/// Result of tactical decision analysis
#[derive(Debug)]
pub struct TacticalDecisionResult {
pub formation_change: Option<FormationChange>,
pub squad_analysis: SquadAnalysis,
pub recommendations: Vec<TacticalRecommendation>,
}
impl TacticalDecisionResult {
fn new() -> Self {
TacticalDecisionResult {
formation_change: None,
squad_analysis: SquadAnalysis::new(),
recommendations: Vec::new(),
}
}
}
/// Suggested formation change
#[derive(Debug)]
pub struct FormationChange {
pub from: Option<crate::MatchTacticType>,
pub to: crate::MatchTacticType,
pub reason: String,
pub confidence: f32,
}
/// Analysis of squad selection quality
#[derive(Debug)]
pub struct SquadAnalysis {
pub average_rating: f32,
pub formation_fitness: f32,
pub position_mismatches: u8,
pub bench_quality: f32,
pub warnings: Vec<String>,
}
impl SquadAnalysis {
fn new() -> Self {
SquadAnalysis {
average_rating: 0.0,
formation_fitness: 0.0,
position_mismatches: 0,
bench_quality: 0.0,
warnings: Vec::new(),
}
}
}
/// Tactical recommendation for team improvement
#[derive(Debug)]
pub struct TacticalRecommendation {
pub priority: RecommendationPriority,
pub category: RecommendationCategory,
pub description: String,
pub suggested_action: Option<String>,
}
#[derive(Debug, PartialEq)]
pub enum RecommendationPriority {
Low,
Medium,
High,
Critical,
}
#[derive(Debug)]
pub enum RecommendationCategory {
Formation,
SquadSelection,
SquadDepth,
TacticalStyle,
PlayerDevelopment,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/tactics/tactics.rs | src/core/src/club/team/tactics/tactics.rs | use crate::club::{PersonBehaviourState, Player, PlayerPositionType, Staff};
use crate::Team;
#[derive(Debug, Clone)]
pub struct Tactics {
pub tactic_type: MatchTacticType,
pub selected_reason: TacticSelectionReason,
pub formation_strength: f32, // 0.0 to 1.0 indicating how well this formation suits the team
}
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum TacticSelectionReason {
CoachPreference,
TeamComposition,
OpponentCounter,
GameSituation,
Default,
}
impl Tactics {
pub fn new(tactic_type: MatchTacticType) -> Self {
Tactics {
tactic_type,
selected_reason: TacticSelectionReason::Default,
formation_strength: 0.5,
}
}
pub fn with_reason(
tactic_type: MatchTacticType,
reason: TacticSelectionReason,
strength: f32,
) -> Self {
Tactics {
tactic_type,
selected_reason: reason,
formation_strength: strength.clamp(0.0, 1.0),
}
}
pub fn positions(&self) -> &[PlayerPositionType; 11] {
let (_, positions) = TACTICS_POSITIONS
.iter()
.find(|(positioning, _)| *positioning == self.tactic_type)
.unwrap_or(&TACTICS_POSITIONS[0]);
positions
}
pub fn defender_count(&self) -> usize {
self.positions()
.iter()
.filter(|pos| pos.is_defender())
.count()
}
pub fn midfielder_count(&self) -> usize {
self.positions()
.iter()
.filter(|pos| pos.is_midfielder())
.count()
}
pub fn forward_count(&self) -> usize {
self.positions()
.iter()
.filter(|pos| pos.is_forward())
.count()
}
pub fn formation_description(&self) -> String {
format!(
"{}-{}-{}",
self.defender_count(),
self.midfielder_count(),
self.forward_count()
)
}
pub fn is_attacking(&self) -> bool {
self.forward_count() >= 3 || (self.forward_count() == 2 && self.midfielder_count() <= 3)
}
pub fn is_defensive(&self) -> bool {
self.defender_count() >= 5 || (self.defender_count() == 4 && self.midfielder_count() >= 5)
}
pub fn is_high_pressing(&self) -> bool {
true
}
pub fn tactical_style(&self) -> TacticalStyle {
match self.tactic_type {
MatchTacticType::T442
| MatchTacticType::T442Diamond
| MatchTacticType::T442DiamondWide => TacticalStyle::Balanced,
MatchTacticType::T433 | MatchTacticType::T343 => TacticalStyle::Attacking,
MatchTacticType::T451 | MatchTacticType::T4141 => TacticalStyle::Defensive,
MatchTacticType::T352 => TacticalStyle::WingPlay,
MatchTacticType::T4231 | MatchTacticType::T4312 => TacticalStyle::Possession,
MatchTacticType::T442Narrow => TacticalStyle::Compact,
MatchTacticType::T4411 => TacticalStyle::Counterattack,
MatchTacticType::T1333 => TacticalStyle::Experimental,
MatchTacticType::T4222 => TacticalStyle::WidePlay,
}
}
/// Calculate how well this tactic suits the available players
pub fn calculate_formation_fitness(&self, players: &[&Player]) -> f32 {
let required_positions = self.positions();
let mut fitness_score = 0.0;
let mut total_positions = 0.0;
for required_pos in required_positions.iter() {
let best_player_fitness = players
.iter()
.filter(|p| p.positions().contains(required_pos))
.map(|p| self.calculate_player_position_fitness(p, required_pos))
.fold(0.0f32, |acc, x| acc.max(x));
fitness_score += best_player_fitness;
total_positions += 1.0;
}
if total_positions > 0.0 {
fitness_score / total_positions
} else {
0.0
}
}
fn calculate_player_position_fitness(
&self,
player: &Player,
position: &PlayerPositionType,
) -> f32 {
let position_level = player.positions.get_level(*position) as f32 / 20.0; // Normalize to 0-1
let overall_ability = player.player_attributes.current_ability as f32 / 200.0; // Normalize to 0-1
let match_readiness = player.skills.physical.match_readiness / 20.0; // Normalize to 0-1
// Weight the factors
(position_level * 0.5) + (overall_ability * 0.3) + (match_readiness * 0.2)
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum TacticalStyle {
Attacking,
Defensive,
Balanced,
Possession,
Counterattack,
WingPlay,
WidePlay,
Compact,
Experimental,
}
// Include the TACTICS_POSITIONS array from the previous implementation
pub const TACTICS_POSITIONS: &[(MatchTacticType, [PlayerPositionType; 11])] = &[
(
MatchTacticType::T442,
[
PlayerPositionType::Goalkeeper,
PlayerPositionType::DefenderLeft,
PlayerPositionType::DefenderCenterLeft,
PlayerPositionType::DefenderCenterRight,
PlayerPositionType::DefenderRight,
PlayerPositionType::MidfielderLeft,
PlayerPositionType::MidfielderCenterLeft,
PlayerPositionType::MidfielderCenterRight,
PlayerPositionType::MidfielderRight,
PlayerPositionType::ForwardLeft,
PlayerPositionType::ForwardRight,
],
),
(
MatchTacticType::T433,
[
PlayerPositionType::Goalkeeper,
PlayerPositionType::DefenderLeft,
PlayerPositionType::DefenderCenterLeft,
PlayerPositionType::DefenderCenterRight,
PlayerPositionType::DefenderRight,
PlayerPositionType::MidfielderCenterLeft,
PlayerPositionType::MidfielderCenter,
PlayerPositionType::MidfielderCenterRight,
PlayerPositionType::ForwardLeft,
PlayerPositionType::ForwardCenter,
PlayerPositionType::ForwardRight,
],
),
(
MatchTacticType::T451,
[
PlayerPositionType::Goalkeeper,
PlayerPositionType::DefenderLeft,
PlayerPositionType::DefenderCenterLeft,
PlayerPositionType::DefenderCenterRight,
PlayerPositionType::DefenderRight,
PlayerPositionType::MidfielderLeft,
PlayerPositionType::MidfielderCenterLeft,
PlayerPositionType::MidfielderCenter,
PlayerPositionType::MidfielderCenterRight,
PlayerPositionType::MidfielderRight,
PlayerPositionType::Striker,
],
),
(
MatchTacticType::T4231,
[
PlayerPositionType::Goalkeeper,
PlayerPositionType::DefenderLeft,
PlayerPositionType::DefenderCenterLeft,
PlayerPositionType::DefenderCenterRight,
PlayerPositionType::DefenderRight,
PlayerPositionType::DefensiveMidfielder,
PlayerPositionType::MidfielderCenter,
PlayerPositionType::AttackingMidfielderLeft,
PlayerPositionType::AttackingMidfielderCenter,
PlayerPositionType::AttackingMidfielderRight,
PlayerPositionType::Striker,
],
),
(
MatchTacticType::T352,
[
PlayerPositionType::Goalkeeper,
PlayerPositionType::DefenderCenterLeft,
PlayerPositionType::DefenderCenter,
PlayerPositionType::DefenderCenterRight,
PlayerPositionType::WingbackLeft,
PlayerPositionType::MidfielderCenterLeft,
PlayerPositionType::MidfielderCenter,
PlayerPositionType::MidfielderCenterRight,
PlayerPositionType::WingbackRight,
PlayerPositionType::ForwardLeft,
PlayerPositionType::ForwardRight,
],
),
// Add more formations as needed...
];
#[derive(Copy, Debug, Eq, PartialEq, PartialOrd, Clone, Hash)]
pub enum MatchTacticType {
T442,
T433,
T451,
T4231,
T352,
T442Diamond,
T442DiamondWide,
T442Narrow,
T4141,
T4411,
T343,
T1333,
T4312,
T4222,
}
impl MatchTacticType {
pub fn all() -> Vec<MatchTacticType> {
vec![
MatchTacticType::T442,
MatchTacticType::T433,
MatchTacticType::T451,
MatchTacticType::T4231,
MatchTacticType::T352,
MatchTacticType::T442Diamond,
MatchTacticType::T442DiamondWide,
MatchTacticType::T442Narrow,
MatchTacticType::T4141,
MatchTacticType::T4411,
MatchTacticType::T343,
MatchTacticType::T1333,
MatchTacticType::T4312,
MatchTacticType::T4222,
]
}
pub fn display_name(&self) -> &'static str {
match self {
MatchTacticType::T442 => "4-4-2",
MatchTacticType::T433 => "4-3-3",
MatchTacticType::T451 => "4-5-1",
MatchTacticType::T4231 => "4-2-3-1",
MatchTacticType::T352 => "3-5-2",
MatchTacticType::T442Diamond => "4-4-2 Diamond",
MatchTacticType::T442DiamondWide => "4-4-2 Diamond Wide",
MatchTacticType::T442Narrow => "4-4-2 Narrow",
MatchTacticType::T4141 => "4-1-4-1",
MatchTacticType::T4411 => "4-4-1-1",
MatchTacticType::T343 => "3-4-3",
MatchTacticType::T1333 => "1-3-3-3",
MatchTacticType::T4312 => "4-3-1-2",
MatchTacticType::T4222 => "4-2-2-2",
}
}
}
pub struct TacticsSelector;
impl TacticsSelector {
/// Main method to select the best tactic for a team
pub fn select(team: &Team, coach: &Staff) -> Tactics {
let available_players: Vec<&Player> = team
.players
.players()
.into_iter()
.filter(|p| p.is_ready_for_match())
.collect();
if available_players.len() < 11 {
// Emergency: not enough players, use simple formation
return Tactics::with_reason(
MatchTacticType::T442,
TacticSelectionReason::Default,
0.3,
);
}
// Evaluate multiple selection strategies
let strategies = vec![
Self::select_by_coach_preference(coach, &available_players),
Self::select_by_team_composition(&available_players),
Self::select_by_player_quality(&available_players),
];
// Choose the best strategy result
strategies
.into_iter()
.max_by(|a, b| {
a.formation_strength
.partial_cmp(&b.formation_strength)
.unwrap_or(std::cmp::Ordering::Equal)
})
.unwrap_or_else(|| {
Tactics::with_reason(MatchTacticType::T442, TacticSelectionReason::Default, 0.5)
})
}
/// Select tactic based on coach attributes and behavior
fn select_by_coach_preference(coach: &Staff, players: &[&Player]) -> Tactics {
let tactical_knowledge = coach.staff_attributes.knowledge.tactical_knowledge;
let attacking_coaching = coach.staff_attributes.coaching.attacking;
let defending_coaching = coach.staff_attributes.coaching.defending;
let preferred_tactic = match coach.behaviour.state {
PersonBehaviourState::Poor => {
// Conservative, simple formation
if tactical_knowledge < 10 {
MatchTacticType::T442
} else {
MatchTacticType::T451
}
}
PersonBehaviourState::Normal => Self::select_balanced_by_coaching_style(
attacking_coaching,
defending_coaching,
tactical_knowledge,
),
PersonBehaviourState::Good => Self::select_advanced_by_coaching_expertise(
attacking_coaching,
defending_coaching,
tactical_knowledge,
),
};
let tactic = Tactics::new(preferred_tactic);
let strength =
tactic.calculate_formation_fitness(players) * Self::coach_confidence_multiplier(coach);
Tactics::with_reason(
preferred_tactic,
TacticSelectionReason::CoachPreference,
strength,
)
}
fn select_balanced_by_coaching_style(
attacking: u8,
defending: u8,
tactical: u8,
) -> MatchTacticType {
let attack_def_diff = attacking as i16 - defending as i16;
match (attack_def_diff, tactical) {
(diff, tact) if diff > 5 && tact >= 12 => MatchTacticType::T433,
(diff, tact) if diff < -5 && tact >= 12 => MatchTacticType::T451,
(_, tact) if tact >= 15 => MatchTacticType::T4231,
(_, tact) if tact >= 10 => MatchTacticType::T442,
_ => MatchTacticType::T442,
}
}
fn select_advanced_by_coaching_expertise(
attacking: u8,
defending: u8,
tactical: u8,
) -> MatchTacticType {
if tactical >= 18 {
// Master tactician - can use complex formations
if attacking >= 16 {
MatchTacticType::T343
} else if defending >= 16 {
MatchTacticType::T352
} else {
MatchTacticType::T4312
}
} else if tactical >= 15 {
// Experienced - advanced but proven formations
if attacking > defending + 3 {
MatchTacticType::T433
} else if defending > attacking + 3 {
MatchTacticType::T4141
} else {
MatchTacticType::T4231
}
} else {
// Good but not exceptional
MatchTacticType::T442Diamond
}
}
/// Select tactic based on available player composition
fn select_by_team_composition(players: &[&Player]) -> Tactics {
let position_analysis = Self::analyze_team_composition(players);
let selected_tactic = Self::match_formation_to_composition(&position_analysis);
let tactic = Tactics::new(selected_tactic);
let strength = tactic.calculate_formation_fitness(players);
Tactics::with_reason(
selected_tactic,
TacticSelectionReason::TeamComposition,
strength,
)
}
fn analyze_team_composition(players: &[&Player]) -> TeamCompositionAnalysis {
let mut analysis = TeamCompositionAnalysis::new();
for player in players {
for position in player.positions() {
let quality = player.player_attributes.current_ability as f32 / 200.0;
match position {
pos if pos.is_defender() => {
analysis.defender_quality += quality;
analysis.defender_count += 1;
}
pos if pos.is_midfielder() => {
analysis.midfielder_quality += quality;
analysis.midfielder_count += 1;
}
pos if pos.is_forward() => {
analysis.forward_quality += quality;
analysis.forward_count += 1;
}
PlayerPositionType::Goalkeeper => {
analysis.goalkeeper_quality += quality;
analysis.goalkeeper_count += 1;
}
_ => {}
}
}
}
// Calculate averages
if analysis.defender_count > 0 {
analysis.defender_quality /= analysis.defender_count as f32;
}
if analysis.midfielder_count > 0 {
analysis.midfielder_quality /= analysis.midfielder_count as f32;
}
if analysis.forward_count > 0 {
analysis.forward_quality /= analysis.forward_count as f32;
}
analysis
}
fn match_formation_to_composition(analysis: &TeamCompositionAnalysis) -> MatchTacticType {
// Determine strongest area
let def_strength =
analysis.defender_quality * (analysis.defender_count as f32 / 6.0).min(1.0);
let mid_strength =
analysis.midfielder_quality * (analysis.midfielder_count as f32 / 6.0).min(1.0);
let att_strength =
analysis.forward_quality * (analysis.forward_count as f32 / 4.0).min(1.0);
if att_strength > def_strength + 0.15 && att_strength > mid_strength + 0.1 {
// Strong attack
if analysis.forward_count >= 4 {
MatchTacticType::T433
} else {
MatchTacticType::T4231
}
} else if def_strength > att_strength + 0.15 && def_strength > mid_strength + 0.1 {
// Strong defense
if analysis.defender_count >= 6 {
MatchTacticType::T352
} else {
MatchTacticType::T451
}
} else if mid_strength > 0.7 {
// Strong midfield
MatchTacticType::T4312
} else {
// Balanced
MatchTacticType::T442
}
}
/// Select tactic based on individual player quality and fitness
fn select_by_player_quality(players: &[&Player]) -> Tactics {
// Test multiple formations and pick the one with best player fit
let candidate_tactics = vec![
MatchTacticType::T442,
MatchTacticType::T433,
MatchTacticType::T451,
MatchTacticType::T4231,
MatchTacticType::T352,
];
let mut best_tactic = MatchTacticType::T442;
let mut best_strength = 0.0;
for tactic_type in candidate_tactics {
let tactic = Tactics::new(tactic_type);
let strength = tactic.calculate_formation_fitness(players);
if strength > best_strength {
best_strength = strength;
best_tactic = tactic_type;
}
}
Tactics::with_reason(
best_tactic,
TacticSelectionReason::TeamComposition,
best_strength,
)
}
/// Select counter tactic against specific opponent formation
pub fn select_counter_tactic(
opponent_tactic: &MatchTacticType,
our_players: &[&Player],
) -> Tactics {
let counter_tactic = match opponent_tactic {
// Counter attacking formations with defensive setups
MatchTacticType::T433 | MatchTacticType::T343 => MatchTacticType::T451,
// Counter defensive formations with attacking ones
MatchTacticType::T451 | MatchTacticType::T4141 => MatchTacticType::T433,
// Counter possession-based with pressing
MatchTacticType::T4231 | MatchTacticType::T4312 => MatchTacticType::T442Diamond,
// Counter narrow with wide
MatchTacticType::T442Narrow => MatchTacticType::T442DiamondWide,
// Counter wide with compact
MatchTacticType::T442DiamondWide => MatchTacticType::T442Narrow,
// Default counter
_ => MatchTacticType::T442,
};
let tactic = Tactics::new(counter_tactic);
let strength = tactic.calculate_formation_fitness(our_players) * 0.9; // Slight penalty for reactive approach
Tactics::with_reason(
counter_tactic,
TacticSelectionReason::OpponentCounter,
strength,
)
}
/// Select tactics based on game situation
pub fn select_situational_tactic(
current_tactic: &MatchTacticType,
is_home: bool,
score_difference: i8,
minutes_played: u8,
players: &[&Player],
) -> Option<Tactics> {
let new_tactic = match (score_difference, minutes_played) {
// Desperately need goals
(diff, min) if diff < -1 && min > 75 => Some(MatchTacticType::T343),
(diff, min) if diff < 0 && min > 70 => Some(MatchTacticType::T433),
// Protecting a lead
(diff, min) if diff > 1 && min > 80 => Some(MatchTacticType::T451),
(diff, min) if diff > 0 && min > 75 => Some(MatchTacticType::T4141),
// First half adjustments
(diff, min) if diff < -1 && min < 30 && is_home => Some(MatchTacticType::T4231),
_ => None,
};
if let Some(tactic_type) = new_tactic {
if tactic_type != *current_tactic {
let tactic = Tactics::new(tactic_type);
let strength = tactic.calculate_formation_fitness(players) * 0.8; // Penalty for mid-game change
return Some(Tactics::with_reason(
tactic_type,
TacticSelectionReason::GameSituation,
strength,
));
}
}
None
}
fn coach_confidence_multiplier(coach: &Staff) -> f32 {
let base_confidence = match coach.behaviour.state {
PersonBehaviourState::Poor => 0.7,
PersonBehaviourState::Normal => 1.0,
PersonBehaviourState::Good => 1.2,
};
let tactical_bonus =
(coach.staff_attributes.knowledge.tactical_knowledge as f32 / 20.0) * 0.3;
let experience_bonus = (coach.staff_attributes.mental.determination as f32 / 20.0) * 0.2;
(base_confidence + tactical_bonus + experience_bonus).clamp(0.5, 1.5)
}
}
#[derive(Debug)]
struct TeamCompositionAnalysis {
goalkeeper_count: u8,
goalkeeper_quality: f32,
defender_count: u8,
defender_quality: f32,
midfielder_count: u8,
midfielder_quality: f32,
forward_count: u8,
forward_quality: f32,
}
impl TeamCompositionAnalysis {
fn new() -> Self {
Self {
goalkeeper_count: 0,
goalkeeper_quality: 0.0,
defender_count: 0,
defender_quality: 0.0,
midfielder_count: 0,
midfielder_quality: 0.0,
forward_count: 0,
forward_quality: 0.0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::shared::fullname::FullName;
use crate::PersonAttributes;
use crate::club::player::builder::PlayerBuilder;
fn create_test_player(id: u32, position: PlayerPositionType, ability: u8) -> Player {
use crate::club::player::*;
PlayerBuilder::new()
.id(id)
.full_name(FullName::new("Test".to_string(), "Player".to_string()))
.birth_date(NaiveDate::from_ymd_opt(1995, 1, 1).unwrap())
.country_id(1)
.skills(PlayerSkills::default())
.attributes(PersonAttributes::default())
.player_attributes(PlayerAttributes {
current_ability: ability,
potential_ability: ability + 10,
condition: 10000,
..Default::default()
})
.contract(None)
.positions(PlayerPositions {
positions: vec![PlayerPosition {
position,
level: 18,
}],
})
.build()
.expect("Failed to build test player")
}
#[test]
fn test_formation_fitness_calculation() {
let players = vec![
create_test_player(1, PlayerPositionType::Goalkeeper, 150),
create_test_player(2, PlayerPositionType::DefenderLeft, 140),
create_test_player(3, PlayerPositionType::MidfielderCenter, 160),
create_test_player(4, PlayerPositionType::ForwardCenter, 170),
];
let player_refs: Vec<&Player> = players.iter().collect();
let tactic = Tactics::new(MatchTacticType::T442);
let fitness = tactic.calculate_formation_fitness(&player_refs);
assert!(fitness > 0.0 && fitness <= 1.0);
}
#[test]
fn test_tactical_selection_by_composition() {
// Create a team with strong attackers
let players = vec![
create_test_player(1, PlayerPositionType::ForwardCenter, 180),
create_test_player(2, PlayerPositionType::ForwardLeft, 175),
create_test_player(3, PlayerPositionType::ForwardRight, 170),
create_test_player(4, PlayerPositionType::MidfielderCenter, 140),
];
let player_refs: Vec<&Player> = players.iter().collect();
let result = TacticsSelector::select_by_team_composition(&player_refs);
// Should prefer attacking formation for strong forwards
assert!(result.is_attacking() || matches!(result.tactic_type, MatchTacticType::T4231));
}
#[test]
fn test_counter_tactic_selection() {
let players = vec![create_test_player(1, PlayerPositionType::Goalkeeper, 150)];
let player_refs: Vec<&Player> = players.iter().collect();
let counter = TacticsSelector::select_counter_tactic(&MatchTacticType::T433, &player_refs);
assert_eq!(counter.tactic_type, MatchTacticType::T451);
assert_eq!(
counter.selected_reason,
TacticSelectionReason::OpponentCounter
);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/tactics/mod.rs | src/core/src/club/team/tactics/mod.rs | pub mod tactics;
pub mod decision;
pub use decision::*;
pub use tactics::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/matches/history.rs | src/core/src/club/team/matches/history.rs | use crate::r#match::TeamScore;
use chrono::NaiveDateTime;
const DEFAULT_MATCH_LIST_SIZE: usize = 10;
#[derive(Debug)]
pub struct MatchHistory {
items: Vec<MatchHistoryItem>,
}
impl Default for MatchHistory {
fn default() -> Self {
Self::new()
}
}
impl MatchHistory {
pub fn new() -> Self {
MatchHistory {
items: Vec::with_capacity(DEFAULT_MATCH_LIST_SIZE),
}
}
pub fn add(&mut self, item: MatchHistoryItem) {
self.items.push(item);
}
}
#[derive(Debug)]
#[allow(dead_code)]
pub struct MatchHistoryItem {
date: NaiveDateTime,
rival_team_id: u32,
score: (TeamScore, TeamScore),
}
impl MatchHistoryItem {
pub fn new(date: NaiveDateTime, rival_team_id: u32, score: (TeamScore, TeamScore)) -> Self {
MatchHistoryItem {
date,
rival_team_id,
score,
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/matches/mod.rs | src/core/src/club/team/matches/mod.rs | mod history;
pub use history::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/training/schedule.rs | src/core/src/club/team/training/schedule.rs | use chrono::{NaiveDateTime, NaiveTime};
#[derive(Debug)]
pub struct TrainingSchedule {
pub morning_time: NaiveTime,
pub evening_time: NaiveTime,
pub is_default: bool,
}
impl TrainingSchedule {
pub fn new(morning_time: NaiveTime, evening_time: NaiveTime) -> Self {
TrainingSchedule {
morning_time,
evening_time,
is_default: true,
}
}
pub fn is_time(&self, date: NaiveDateTime) -> bool {
self.morning_time == date.time() || self.evening_time == date.time()
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/training/training.rs | src/core/src/club/team/training/training.rs | use crate::club::player::training::result::PlayerTrainingResult;
use crate::{Player, PlayerPositionType, PlayerTraining, Staff, Team, TeamTrainingResult};
use chrono::{Datelike, NaiveDateTime, Weekday};
use std::collections::HashMap;
#[derive(Debug)]
pub struct TeamTraining;
impl TeamTraining {
pub fn train(team: &mut Team, date: NaiveDateTime) -> TeamTrainingResult {
let mut result = TeamTrainingResult::new();
// Check if it's training time
if !team.training_schedule.is_time(date) {
return result;
}
// Get the current training plan
let current_weekday = date.weekday();
let coach = team.staffs.training_coach(&team.team_type);
// Determine periodization phase based on season progress
let phase = Self::determine_phase(date);
// Get or generate weekly plan
let weekly_plan = WeeklyTrainingPlan::generate_weekly_plan(
Self::get_next_match_day(team, date),
Self::get_previous_match_day(team, date),
phase,
&Self::get_coach_philosophy(coach),
);
// Execute today's training sessions
if let Some(sessions) = weekly_plan.sessions.get(¤t_weekday) {
for session in sessions {
let session_results = Self::execute_training_session(
team,
coach,
session,
date,
);
result.player_results.extend(session_results);
}
}
// Apply team cohesion effects
Self::apply_team_cohesion_effects(team, &result);
result
}
fn execute_training_session(
team: &Team,
coach: &Staff,
session: &TrainingSession,
date: NaiveDateTime,
) -> Vec<PlayerTrainingResult> {
let participants = Self::select_participants(team, session);
let mut results = Vec::with_capacity(participants.len());
for player in participants {
results.push(PlayerTraining::train(
player,
coach,
session,
date,
));
}
results
}
fn select_participants<'a>(team: &'a Team, session: &TrainingSession) -> Vec<&'a Player> {
let mut participants = Vec::new();
// If specific participants are listed, use those
if !session.participants.is_empty() {
for player_id in &session.participants {
if let Some(player) = team.players.players.iter().find(|p| p.id == *player_id) {
if Self::can_participate(player) {
participants.push(player);
}
}
}
} else if !session.focus_positions.is_empty() {
// Select players based on focus positions
for player in &team.players.players {
if Self::can_participate(player) {
for position in &session.focus_positions {
if player.positions.has_position(*position) {
participants.push(player);
break;
}
}
}
}
} else {
// All available players participate
for player in &team.players.players {
if Self::can_participate(player) {
participants.push(player);
}
}
}
participants
}
fn can_participate(player: &Player) -> bool {
!player.player_attributes.is_injured &&
!player.player_attributes.is_banned &&
player.player_attributes.condition_percentage() > 30
}
fn apply_team_cohesion_effects(team: &mut Team, training_results: &TeamTrainingResult) {
// Players training together build relationships
let participant_ids: Vec<u32> = training_results.player_results
.iter()
.map(|r| r.player_id)
.collect();
// Small relationship improvements between training partners
for i in 0..participant_ids.len() {
for j in i + 1..participant_ids.len() {
if let Some(player_i) = team.players.players.iter_mut().find(|p| p.id == participant_ids[i]) {
player_i.relations.update(participant_ids[j], 0.01);
}
if let Some(player_j) = team.players.players.iter_mut().find(|p| p.id == participant_ids[j]) {
player_j.relations.update(participant_ids[i], 0.01);
}
}
}
}
fn determine_phase(date: NaiveDateTime) -> PeriodizationPhase {
let month = date.month();
match month {
6 | 7 => PeriodizationPhase::PreSeason,
8 | 9 => PeriodizationPhase::EarlySeason,
10 | 11 | 12 | 1 | 2 => PeriodizationPhase::MidSeason,
3 | 4 => PeriodizationPhase::LateSeason,
5 => PeriodizationPhase::OffSeason,
_ => PeriodizationPhase::MidSeason,
}
}
fn get_next_match_day(_team: &Team, _date: NaiveDateTime) -> Option<Weekday> {
// This would check the actual match schedule
// For now, assume Saturday matches
Some(Weekday::Sat)
}
fn get_previous_match_day(_team: &Team, _date: NaiveDateTime) -> Option<Weekday> {
// This would check the actual match history
// For now, return None
None
}
fn get_coach_philosophy(coach: &Staff) -> CoachingPhilosophy {
// Determine coach philosophy based on attributes
let tactical_focus = if coach.staff_attributes.coaching.attacking > coach.staff_attributes.coaching.defending {
if coach.staff_attributes.coaching.attacking > 15 {
TacticalFocus::Attacking
} else {
TacticalFocus::Possession
}
} else if coach.staff_attributes.coaching.defending > 15 {
TacticalFocus::Defensive
} else {
TacticalFocus::Balanced
};
let training_intensity = if coach.staff_attributes.coaching.fitness > 15 {
TrainingIntensityPreference::High
} else if coach.staff_attributes.coaching.fitness < 10 {
TrainingIntensityPreference::Low
} else {
TrainingIntensityPreference::Medium
};
CoachingPhilosophy {
tactical_focus,
training_intensity,
youth_focus: coach.staff_attributes.coaching.working_with_youngsters > 12,
rotation_preference: RotationPreference::Moderate,
}
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub enum TrainingType {
// Physical Training
#[default]
Endurance,
Strength,
Speed,
Agility,
Recovery,
// Technical Training
BallControl,
Passing,
Shooting,
Crossing,
SetPieces,
// Tactical Training
Positioning,
TeamShape,
PressingDrills,
TransitionPlay,
SetPiecesDefensive,
// Mental Training
Concentration,
DecisionMaking,
Leadership,
// Match Preparation
MatchPreparation,
VideoAnalysis,
OpponentSpecific,
// Recovery
RestDay,
LightRecovery,
Rehabilitation,
}
#[derive(Debug, Clone)]
pub struct TrainingSession {
pub session_type: TrainingType,
pub intensity: TrainingIntensity,
pub duration_minutes: u16,
pub focus_positions: Vec<PlayerPositionType>,
pub participants: Vec<u32>, // Player IDs
}
#[derive(Debug, Clone, PartialEq)]
pub enum TrainingIntensity {
VeryLight, // 20-40% max effort - recovery sessions
Light, // 40-60% max effort - technical work
Moderate, // 60-75% max effort - standard training
High, // 75-90% max effort - intense sessions
VeryHigh, // 90-100% max effort - match simulation
}
// ============== Weekly Training Schedule ==============
#[derive(Debug, Clone)]
pub struct WeeklyTrainingPlan {
pub sessions: HashMap<Weekday, Vec<TrainingSession>>,
pub match_days: Vec<Weekday>,
pub periodization_phase: PeriodizationPhase,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PeriodizationPhase {
PreSeason, // High volume, building fitness
EarlySeason, // Balancing fitness and tactics
MidSeason, // Maintenance and tactical focus
LateSeason, // Managing fatigue, focus on recovery
OffSeason, // Rest and light maintenance
}
impl WeeklyTrainingPlan {
/// Generate a realistic weekly training plan based on match schedule
pub fn generate_weekly_plan(
next_match_day: Option<Weekday>,
previous_match_day: Option<Weekday>,
phase: PeriodizationPhase,
coach_philosophy: &CoachingPhilosophy,
) -> Self {
let mut sessions = HashMap::new();
let match_days = vec![next_match_day, previous_match_day]
.into_iter()
.flatten()
.collect();
// Monday - Recovery or moderate training
sessions.insert(Weekday::Mon, Self::monday_sessions(previous_match_day, phase));
// Tuesday - Main training day
sessions.insert(Weekday::Tue, Self::tuesday_sessions(phase, coach_philosophy));
// Wednesday - Tactical/Technical focus
sessions.insert(Weekday::Wed, Self::wednesday_sessions(phase));
// Thursday - High intensity or recovery based on fixture
sessions.insert(Weekday::Thu, Self::thursday_sessions(next_match_day, phase));
// Friday - Match preparation or main training
sessions.insert(Weekday::Fri, Self::friday_sessions(next_match_day, phase));
// Saturday - Match day or training
sessions.insert(Weekday::Sat, Self::saturday_sessions(next_match_day));
// Sunday - Match day or rest
sessions.insert(Weekday::Sun, Self::sunday_sessions(next_match_day));
WeeklyTrainingPlan {
sessions,
match_days,
periodization_phase: phase,
}
}
fn monday_sessions(previous_match: Option<Weekday>, _phase: PeriodizationPhase) -> Vec<TrainingSession> {
if previous_match == Some(Weekday::Sun) || previous_match == Some(Weekday::Sat) {
// Recovery after weekend match
vec![
TrainingSession {
session_type: TrainingType::Recovery,
intensity: TrainingIntensity::VeryLight,
duration_minutes: 45,
focus_positions: vec![],
participants: vec![],
},
TrainingSession {
session_type: TrainingType::VideoAnalysis,
intensity: TrainingIntensity::VeryLight,
duration_minutes: 30,
focus_positions: vec![],
participants: vec![],
}
]
} else {
// Normal training
vec![
TrainingSession {
session_type: TrainingType::Endurance,
intensity: TrainingIntensity::Moderate,
duration_minutes: 60,
focus_positions: vec![],
participants: vec![],
},
TrainingSession {
session_type: TrainingType::Passing,
intensity: TrainingIntensity::Moderate,
duration_minutes: 45,
focus_positions: vec![],
participants: vec![],
}
]
}
}
fn tuesday_sessions(phase: PeriodizationPhase, philosophy: &CoachingPhilosophy) -> Vec<TrainingSession> {
let base_intensity = match phase {
PeriodizationPhase::PreSeason => TrainingIntensity::High,
PeriodizationPhase::MidSeason => TrainingIntensity::Moderate,
PeriodizationPhase::LateSeason => TrainingIntensity::Light,
_ => TrainingIntensity::Moderate,
};
vec![
TrainingSession {
session_type: match philosophy.tactical_focus {
TacticalFocus::Possession => TrainingType::Passing,
TacticalFocus::Pressing => TrainingType::PressingDrills,
TacticalFocus::Counter => TrainingType::TransitionPlay,
_ => TrainingType::TeamShape,
},
intensity: base_intensity.clone(),
duration_minutes: 90,
focus_positions: vec![],
participants: vec![],
},
TrainingSession {
session_type: TrainingType::SetPieces,
intensity: TrainingIntensity::Light,
duration_minutes: 30,
focus_positions: vec![],
participants: vec![],
}
]
}
fn wednesday_sessions(_phase: PeriodizationPhase) -> Vec<TrainingSession> {
vec![
TrainingSession {
session_type: TrainingType::Positioning,
intensity: TrainingIntensity::Moderate,
duration_minutes: 75,
focus_positions: vec![],
participants: vec![],
},
TrainingSession {
session_type: TrainingType::Shooting,
intensity: TrainingIntensity::Moderate,
duration_minutes: 45,
focus_positions: vec![PlayerPositionType::Striker, PlayerPositionType::ForwardCenter],
participants: vec![],
}
]
}
fn thursday_sessions(next_match: Option<Weekday>, _phase: PeriodizationPhase) -> Vec<TrainingSession> {
if next_match == Some(Weekday::Sat) {
// Light preparation for Saturday match
vec![
TrainingSession {
session_type: TrainingType::MatchPreparation,
intensity: TrainingIntensity::Light,
duration_minutes: 60,
focus_positions: vec![],
participants: vec![],
}
]
} else {
// Full training session
vec![
TrainingSession {
session_type: TrainingType::Speed,
intensity: TrainingIntensity::High,
duration_minutes: 45,
focus_positions: vec![],
participants: vec![],
},
TrainingSession {
session_type: TrainingType::TeamShape,
intensity: TrainingIntensity::Moderate,
duration_minutes: 60,
focus_positions: vec![],
participants: vec![],
}
]
}
}
fn friday_sessions(next_match: Option<Weekday>, _phase: PeriodizationPhase) -> Vec<TrainingSession> {
if next_match == Some(Weekday::Sat) {
// Final preparation
vec![
TrainingSession {
session_type: TrainingType::SetPieces,
intensity: TrainingIntensity::Light,
duration_minutes: 30,
focus_positions: vec![],
participants: vec![],
},
TrainingSession {
session_type: TrainingType::OpponentSpecific,
intensity: TrainingIntensity::VeryLight,
duration_minutes: 45,
focus_positions: vec![],
participants: vec![],
}
]
} else {
// Normal training
vec![
TrainingSession {
session_type: TrainingType::BallControl,
intensity: TrainingIntensity::Moderate,
duration_minutes: 60,
focus_positions: vec![],
participants: vec![],
},
TrainingSession {
session_type: TrainingType::TransitionPlay,
intensity: TrainingIntensity::High,
duration_minutes: 45,
focus_positions: vec![],
participants: vec![],
}
]
}
}
fn saturday_sessions(next_match: Option<Weekday>) -> Vec<TrainingSession> {
if next_match == Some(Weekday::Sat) {
vec![] // Match day
} else {
vec![
TrainingSession {
session_type: TrainingType::MatchPreparation,
intensity: TrainingIntensity::High,
duration_minutes: 90,
focus_positions: vec![],
participants: vec![],
}
]
}
}
fn sunday_sessions(next_match: Option<Weekday>) -> Vec<TrainingSession> {
if next_match == Some(Weekday::Sun) {
vec![] // Match day
} else {
vec![
TrainingSession {
session_type: TrainingType::RestDay,
intensity: TrainingIntensity::VeryLight,
duration_minutes: 0,
focus_positions: vec![],
participants: vec![],
}
]
}
}
}
// ============== Training Effects System ==============
#[derive(Debug)]
pub struct TrainingEffects {
pub physical_gains: PhysicalGains,
pub technical_gains: TechnicalGains,
pub mental_gains: MentalGains,
pub fatigue_change: f32,
pub injury_risk: f32,
pub morale_change: f32,
}
#[derive(Debug, Default)]
pub struct PhysicalGains {
pub stamina: f32,
pub strength: f32,
pub pace: f32,
pub agility: f32,
pub balance: f32,
pub jumping: f32,
pub natural_fitness: f32,
}
#[derive(Debug, Default)]
pub struct TechnicalGains {
pub first_touch: f32,
pub passing: f32,
pub crossing: f32,
pub dribbling: f32,
pub finishing: f32,
pub heading: f32,
pub tackling: f32,
pub technique: f32,
}
#[derive(Debug, Default)]
pub struct MentalGains {
pub concentration: f32,
pub decisions: f32,
pub positioning: f32,
pub teamwork: f32,
pub vision: f32,
pub work_rate: f32,
pub leadership: f32,
}
// ============== Individual Player Training Plans ==============
#[derive(Debug)]
pub struct IndividualTrainingPlan {
pub player_id: u32,
pub focus_areas: Vec<TrainingFocus>,
pub intensity_modifier: f32, // 0.5 to 1.5
pub special_instructions: Vec<SpecialInstruction>,
}
#[derive(Debug, Clone)]
pub enum TrainingFocus {
WeakFootImprovement,
PositionRetraining(PlayerPositionType),
SpecificSkill(SkillType),
InjuryRecovery,
FitnessBuilding,
MentalDevelopment,
}
#[derive(Debug, Clone)]
pub enum SkillType {
FreeKicks,
Penalties,
LongShots,
Heading,
Tackling,
Crossing,
Dribbling,
}
#[derive(Debug, Clone)]
pub enum SpecialInstruction {
ExtraGymWork,
DietProgram,
MentalCoaching,
MediaTraining,
LeadershipDevelopment,
RestMoreOften,
}
// ============== Coaching Philosophy ==============
#[derive(Debug, Clone)]
pub struct CoachingPhilosophy {
pub tactical_focus: TacticalFocus,
pub training_intensity: TrainingIntensityPreference,
pub youth_focus: bool,
pub rotation_preference: RotationPreference,
}
#[derive(Debug, Clone, PartialEq)]
pub enum TacticalFocus {
Possession,
Counter,
Pressing,
Attacking,
Defensive,
Balanced,
}
#[derive(Debug, Clone, PartialEq)]
pub enum TrainingIntensityPreference {
Low, // Focus on technical, less physical
Medium, // Balanced approach
High, // Heavy physical training
}
#[derive(Debug, Clone, PartialEq)]
pub enum RotationPreference {
Minimal, // Same XI mostly
Moderate, // Some rotation
Heavy, // Lots of rotation
}
// ============== Training Ground Facilities ==============
#[derive(Debug)]
pub struct TrainingFacilities {
pub quality: FacilityQuality,
pub gym_quality: FacilityQuality,
pub medical_facilities: FacilityQuality,
pub recovery_facilities: FacilityQuality,
pub pitches_count: u8,
pub has_swimming_pool: bool,
pub has_sports_science: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum FacilityQuality {
Poor,
Basic,
Good,
Excellent,
WorldClass,
}
impl TrainingFacilities {
pub fn get_training_modifier(&self) -> f32 {
let base = match self.quality {
FacilityQuality::Poor => 0.7,
FacilityQuality::Basic => 0.85,
FacilityQuality::Good => 1.0,
FacilityQuality::Excellent => 1.15,
FacilityQuality::WorldClass => 1.3,
};
let gym_bonus = match self.gym_quality {
FacilityQuality::Poor => -0.05,
FacilityQuality::Basic => 0.0,
FacilityQuality::Good => 0.05,
FacilityQuality::Excellent => 0.1,
FacilityQuality::WorldClass => 0.15,
};
base + gym_bonus
}
pub fn get_injury_risk_modifier(&self) -> f32 {
let base = match self.quality {
FacilityQuality::Poor => 1.3,
FacilityQuality::Basic => 1.15,
FacilityQuality::Good => 1.0,
FacilityQuality::Excellent => 0.9,
FacilityQuality::WorldClass => 0.8,
};
let medical_modifier = match self.medical_facilities {
FacilityQuality::Poor => 1.2,
FacilityQuality::Basic => 1.1,
FacilityQuality::Good => 1.0,
FacilityQuality::Excellent => 0.9,
FacilityQuality::WorldClass => 0.8,
};
base * medical_modifier
}
pub fn get_recovery_modifier(&self) -> f32 {
let base = match self.recovery_facilities {
FacilityQuality::Poor => 0.7,
FacilityQuality::Basic => 0.85,
FacilityQuality::Good => 1.0,
FacilityQuality::Excellent => 1.2,
FacilityQuality::WorldClass => 1.4,
};
let pool_bonus = if self.has_swimming_pool { 0.1 } else { 0.0 };
let sports_science_bonus = if self.has_sports_science { 0.15 } else { 0.0 };
base + pool_bonus + sports_science_bonus
}
}
// ============== Training Load Management ==============
#[derive(Debug)]
pub struct TrainingLoadManager {
pub player_loads: HashMap<u32, PlayerTrainingLoad>,
}
#[derive(Debug)]
pub struct PlayerTrainingLoad {
pub acute_load: f32, // Last 7 days
pub chronic_load: f32, // Last 28 days
pub load_ratio: f32, // Acute/Chronic ratio
pub cumulative_fatigue: f32,
pub last_high_intensity: Option<NaiveDateTime>,
pub sessions_this_week: u8,
}
impl PlayerTrainingLoad {
pub fn new() -> Self {
PlayerTrainingLoad {
acute_load: 0.0,
chronic_load: 0.0,
load_ratio: 1.0,
cumulative_fatigue: 0.0,
last_high_intensity: None,
sessions_this_week: 0,
}
}
pub fn update_load(&mut self, session_load: f32, intensity: &TrainingIntensity, date: NaiveDateTime) {
// Update acute load (exponentially weighted)
self.acute_load = self.acute_load * 0.9 + session_load * 0.1;
// Update chronic load (slower adaptation)
self.chronic_load = self.chronic_load * 0.97 + session_load * 0.03;
// Calculate load ratio
self.load_ratio = if self.chronic_load > 0.0 {
self.acute_load / self.chronic_load
} else {
1.0
};
// Update fatigue
self.cumulative_fatigue = (self.cumulative_fatigue + session_load * 0.2).min(100.0);
// Track high intensity sessions
if matches!(intensity, TrainingIntensity::High | TrainingIntensity::VeryHigh) {
self.last_high_intensity = Some(date);
}
self.sessions_this_week += 1;
}
pub fn get_injury_risk_factor(&self) -> f32 {
// High acute:chronic ratios increase injury risk
if self.load_ratio > 1.5 {
1.5
} else if self.load_ratio > 1.3 {
1.2
} else if self.load_ratio < 0.8 {
1.1 // Too little load can also increase injury risk
} else {
1.0
}
}
pub fn needs_rest(&self) -> bool {
self.cumulative_fatigue > 75.0 ||
self.load_ratio > 1.5 ||
self.sessions_this_week >= 6
}
pub fn weekly_reset(&mut self) {
self.sessions_this_week = 0;
self.cumulative_fatigue *= 0.7; // Partial recovery
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/training/result.rs | src/core/src/club/team/training/result.rs | use crate::club::player::training::result::PlayerTrainingResult;
use crate::SimulatorData;
pub struct TeamTrainingResult {
pub player_results: Vec<PlayerTrainingResult>,
}
impl TeamTrainingResult {
pub fn new() -> Self {
TeamTrainingResult {
player_results: Vec::new(),
}
}
pub fn empty() -> Self {
TeamTrainingResult {
player_results: Vec::new(),
}
}
pub fn process(&self, data: &mut SimulatorData) {
for player_result in &self.player_results {
player_result.process(data);
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/training/mod.rs | src/core/src/club/team/training/mod.rs | mod result;
mod schedule;
mod training;
pub use result::*;
pub use schedule::*;
pub use training::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/transfers/transfer.rs | src/core/src/club/team/transfers/transfer.rs | use crate::shared::CurrencyValue;
const DEFAULT_TRANSFER_LIST_SIZE: usize = 10;
#[derive(Debug)]
pub struct Transfers {
items: Vec<TransferItem>,
}
impl Transfers {
pub fn new() -> Self {
Transfers {
items: Vec::with_capacity(DEFAULT_TRANSFER_LIST_SIZE),
}
}
pub fn add(&mut self, item: TransferItem) {
self.items.push(item);
}
}
#[derive(Debug)]
pub struct TransferItem {
pub player_id: u32,
pub amount: CurrencyValue,
}
impl TransferItem {
pub fn new(player_id: u32, amount: CurrencyValue) -> TransferItem {
TransferItem { player_id, amount }
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/transfers/mod.rs | src/core/src/club/team/transfers/mod.rs | pub mod transfer;
pub use transfer::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/behaviour/behaviour.rs | src/core/src/club/team/behaviour/behaviour.rs | use crate::club::team::behaviour::{PlayerRelationshipChangeResult, TeamBehaviourResult};
use crate::context::GlobalContext;
use crate::utils::FloatUtils;
use crate::{Person, PersonBehaviourState, Player, PlayerCollection, PlayerPositionType, PlayerRelation, StaffCollection};
use chrono::{Datelike, NaiveDateTime};
use log::{debug, info};
#[derive(Debug)]
pub struct TeamBehaviour {
last_full_update: Option<NaiveDateTime>,
last_minor_update: Option<NaiveDateTime>,
}
impl Default for TeamBehaviour {
fn default() -> Self {
Self::new()
}
}
impl TeamBehaviour {
pub fn new() -> Self {
TeamBehaviour {
last_full_update: None,
last_minor_update: None,
}
}
/// Main simulate function that decides what type of update to run
pub fn simulate(
&mut self,
players: &mut PlayerCollection,
staffs: &mut StaffCollection,
ctx: GlobalContext<'_>,
) -> TeamBehaviourResult {
let current_time = ctx.simulation.date;
// Determine update frequency based on simulation settings
let should_run_full = self.should_run_full_update(current_time);
let should_run_minor = self.should_run_minor_update(current_time);
if should_run_full {
info!("🏟️ Running FULL team behaviour update at {}", current_time);
self.last_full_update = Some(current_time);
self.run_full_behaviour_simulation(players, staffs, ctx)
} else if should_run_minor {
debug!("⚽ Running minor team behaviour update at {}", current_time);
self.last_minor_update = Some(current_time);
self.run_minor_behaviour_simulation(players, staffs, ctx)
} else {
debug!("⏸️ Skipping team behaviour update at {}", current_time);
TeamBehaviourResult::new()
}
}
/// Determine if we should run a full behaviour update
fn should_run_full_update(&self, current_time: NaiveDateTime) -> bool {
match self.last_full_update {
None => true, // First run
Some(last) => {
let days_since = current_time.signed_duration_since(last).num_days();
// Run full update every week (7 days)
days_since >= 7 ||
// Or if it's a match day (more interactions)
current_time.weekday() == chrono::Weekday::Sat ||
current_time.weekday() == chrono::Weekday::Sun ||
// Or beginning of month (team meetings, etc.)
current_time.day() == 1
}
}
}
fn should_run_minor_update(&self, current_time: NaiveDateTime) -> bool {
match self.last_minor_update {
None => true, // First run
Some(last) => {
let days_since = current_time.signed_duration_since(last).num_days();
// Run minor updates every 2-3 days
days_since >= 2 ||
// Or during training intensive periods (Tuesday to Thursday)
matches!(current_time.weekday(),
chrono::Weekday::Tue | chrono::Weekday::Wed | chrono::Weekday::Thu)
}
}
}
/// Full comprehensive behaviour simulation
fn run_full_behaviour_simulation(
&self,
players: &mut PlayerCollection,
_staffs: &mut StaffCollection,
ctx: GlobalContext<'_>,
) -> TeamBehaviourResult {
info!("🔄 Processing comprehensive team dynamics...");
let mut result = TeamBehaviourResult::new();
// Log team state before processing
Self::log_team_state(players, "BEFORE full update");
// Process all interaction types
Self::process_position_group_dynamics(players, &mut result);
Self::process_age_group_dynamics(players, &mut result);
Self::process_performance_based_relationships(players, &mut result);
Self::process_personality_conflicts(players, &mut result);
Self::process_leadership_influence(players, &mut result);
Self::process_playing_time_jealousy(players, &mut result);
// Additional full-update only processes
Self::process_contract_satisfaction(players, &mut result, &ctx);
Self::process_injury_sympathy(players, &mut result, &ctx);
Self::process_international_duty_bonds(players, &mut result, &ctx);
info!(
"✅ Full team behaviour update complete - {} relationship changes",
result.players.relationship_result.len()
);
result
}
/// Lighter, more frequent behaviour updates
fn run_minor_behaviour_simulation(
&self,
players: &mut PlayerCollection,
_staffs: &mut StaffCollection,
ctx: GlobalContext<'_>,
) -> TeamBehaviourResult {
debug!("🔄 Processing minor team dynamics...");
let mut result = TeamBehaviourResult::new();
// Only process most dynamic relationships for minor updates
Self::process_daily_interactions(players, &mut result, &ctx);
Self::process_mood_changes(players, &mut result, &ctx);
Self::process_recent_performance_reactions(players, &mut result);
// Log results if there are changes
if !result.players.relationship_result.is_empty() {
debug!(
"✅ Minor team behaviour update complete - {} relationship changes",
result.players.relationship_result.len()
);
}
result
}
/// Log current team relationship state
fn log_team_state(players: &PlayerCollection, context: &str) {
debug!(
"📊 Team State {}: {} players",
context,
players.players.len()
);
let mut happy_players = 0;
let mut unhappy_players = 0;
let mut neutral_players = 0;
for player in &players.players {
let happiness = Self::calculate_player_happiness(player);
if happiness > 0.2 {
happy_players += 1;
} else if happiness < -0.2 {
unhappy_players += 1;
} else {
neutral_players += 1;
}
}
info!(
"😊 Happy: {} | 😐 Neutral: {} | 😠 Unhappy: {}",
happy_players, neutral_players, unhappy_players
);
}
fn process_daily_interactions(
players: &PlayerCollection,
result: &mut TeamBehaviourResult,
ctx: &GlobalContext<'_>,
) {
debug!("🗣️ Processing daily player interactions...");
// Random small interactions between players who already know each other
for i in 0..players.players.len().min(10) {
// Limit for performance
for j in i + 1..players.players.len().min(10) {
let player_i = &players.players[i];
let player_j = &players.players[j];
// Check if they already have a relationship
if let Some(existing_relationship) = player_i.relations.get_player(player_j.id) {
// Small random fluctuations in existing relationships
let daily_change = Self::calculate_daily_interaction_change(
player_i,
player_j,
existing_relationship,
ctx,
);
if daily_change.abs() > 0.005 {
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_i.id,
to_player_id: player_j.id,
relationship_change: daily_change,
});
}
}
}
}
}
/// Process mood-based relationship changes
fn process_mood_changes(
players: &PlayerCollection,
result: &mut TeamBehaviourResult,
_ctx: &GlobalContext<'_>,
) {
debug!("😔 Processing player mood changes...");
for player in &players.players {
let current_happiness = Self::calculate_player_happiness(player);
// Very unhappy players affect team morale
if current_happiness < -0.5 {
for other_player in &players.players {
if player.id != other_player.id {
let mood_impact =
Self::calculate_mood_spread(player, other_player, current_happiness);
if mood_impact.abs() > 0.01 {
result.players.relationship_result.push(
PlayerRelationshipChangeResult {
from_player_id: other_player.id,
to_player_id: player.id,
relationship_change: mood_impact,
},
);
}
}
}
}
}
}
/// Process reactions to recent match performances
fn process_recent_performance_reactions(
players: &PlayerCollection,
result: &mut TeamBehaviourResult,
) {
debug!("⚽ Processing recent performance reactions...");
// This would ideally check recent match results, but for now simulate
// reactions to recent stat changes
for player in &players.players {
// Players who scored recently get temporary popularity boost
if player.statistics.goals > 0 && player.position().is_forward() {
let popularity_boost = 0.05;
for other_player in &players.players {
if player.id != other_player.id {
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: other_player.id,
to_player_id: player.id,
relationship_change: popularity_boost,
});
}
}
}
}
}
// ========== ADDITIONAL FULL UPDATE PROCESSES ==========
/// Process contract satisfaction effects on relationships
fn process_contract_satisfaction(
players: &PlayerCollection,
result: &mut TeamBehaviourResult,
_ctx: &GlobalContext<'_>,
) {
debug!("💰 Processing contract satisfaction effects...");
for i in 0..players.players.len() {
for j in i + 1..players.players.len() {
let player_i = &players.players[i];
let player_j = &players.players[j];
let contract_jealousy = Self::calculate_contract_jealousy(player_i, player_j);
if contract_jealousy.abs() > 0.02 {
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_i.id,
to_player_id: player_j.id,
relationship_change: contract_jealousy,
});
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_j.id,
to_player_id: player_i.id,
relationship_change: contract_jealousy,
});
}
}
}
}
/// Process injury sympathy and support
fn process_injury_sympathy(
players: &PlayerCollection,
result: &mut TeamBehaviourResult,
_ctx: &GlobalContext<'_>,
) {
debug!("🏥 Processing injury sympathy...");
for injured_player in players
.players
.iter()
.filter(|p| p.player_attributes.is_injured)
{
for other_player in &players.players {
if injured_player.id != other_player.id {
let sympathy = Self::calculate_injury_sympathy(injured_player, other_player);
if sympathy > 0.01 {
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: other_player.id,
to_player_id: injured_player.id,
relationship_change: sympathy,
});
}
}
}
}
}
/// Process international duty bonding
fn process_international_duty_bonds(
players: &PlayerCollection,
result: &mut TeamBehaviourResult,
_ctx: &GlobalContext<'_>,
) {
debug!("🌍 Processing international duty bonds...");
// Group players by country
use std::collections::HashMap;
let mut country_groups: HashMap<u32, Vec<&Player>> = HashMap::new();
for player in &players.players {
country_groups
.entry(player.country_id)
.or_default()
.push(player);
}
// Players from same country bond
for (_, country_players) in country_groups {
if country_players.len() > 1 {
for i in 0..country_players.len() {
for j in i + 1..country_players.len() {
let bond_strength = Self::calculate_national_team_bond(
country_players[i],
country_players[j],
);
if bond_strength > 0.01 {
result.players.relationship_result.push(
PlayerRelationshipChangeResult {
from_player_id: country_players[i].id,
to_player_id: country_players[j].id,
relationship_change: bond_strength,
},
);
result.players.relationship_result.push(
PlayerRelationshipChangeResult {
from_player_id: country_players[j].id,
to_player_id: country_players[i].id,
relationship_change: bond_strength,
},
);
}
}
}
}
}
}
// ========== CALCULATION HELPER FUNCTIONS ==========
fn calculate_daily_interaction_change(
player_a: &Player,
player_b: &Player,
existing_relationship: &PlayerRelation, // Changed from f32 to &PlayerRelation
_ctx: &GlobalContext<'_>,
) -> f32 {
// Extract the relationship level from the PlayerRelation struct
let relationship_level = existing_relationship.level;
// Small random fluctuations based on personalities
let temperament_factor =
(player_a.attributes.temperament + player_b.attributes.temperament) / 40.0;
let base_change = FloatUtils::random(-0.02, 0.02) * temperament_factor;
// Additional factors from the enhanced relationship data
let trust_factor = existing_relationship.trust / 100.0;
let friendship_factor = existing_relationship.friendship / 100.0;
// Relationship decay/improvement tendency
if relationship_level > 50.0 {
// Very good relationships tend to stay stable but can still improve slightly
// Trust and friendship help maintain good relationships
let stability_bonus = (trust_factor * 0.3 + friendship_factor * 0.2) * base_change;
base_change * 0.5 + stability_bonus
} else if relationship_level < -50.0 {
// Very bad relationships might improve over time
// Low trust makes improvement harder
let improvement_chance = base_change + 0.01 * (1.0 - trust_factor);
improvement_chance
} else {
// Neutral relationships are more volatile
// Professional respect can stabilize neutral relationships
let professional_factor = existing_relationship.professional_respect / 100.0;
base_change * (1.0 - professional_factor * 0.3)
}
}
fn calculate_daily_interaction_change_simple(
player_a: &Player,
player_b: &Player,
existing_relationship_level: f32, // Just the level value
_ctx: &GlobalContext<'_>,
) -> f32 {
// Small random fluctuations based on personalities
let temperament_factor =
(player_a.attributes.temperament + player_b.attributes.temperament) / 40.0;
let base_change = FloatUtils::random(-0.02, 0.02) * temperament_factor;
// Relationship decay/improvement tendency
if existing_relationship_level > 50.0 {
// Very good relationships tend to stay stable
base_change * 0.5
} else if existing_relationship_level < -50.0 {
// Very bad relationships might improve over time
base_change + 0.01
} else {
base_change
}
}
fn calculate_mood_spread(
unhappy_player: &Player,
other_player: &Player,
happiness: f32,
) -> f32 {
// Unhappy players with high leadership spread negativity more
let influence = (unhappy_player.skills.mental.leadership / 20.0) * happiness.abs() * 0.1;
// Players with high professionalism resist negative influence
let resistance = other_player.attributes.professionalism / 20.0;
influence * (1.0 - resistance).max(0.0)
}
fn calculate_contract_jealousy(player_a: &Player, player_b: &Player) -> f32 {
let salary_a = player_a.contract.as_ref().map(|c| c.salary).unwrap_or(0);
let salary_b = player_b.contract.as_ref().map(|c| c.salary).unwrap_or(0);
if salary_a == 0 || salary_b == 0 {
return 0.0; // Can't compare without contracts
}
let salary_ratio = salary_a as f32 / salary_b as f32;
if salary_ratio > 2.0 || salary_ratio < 0.5 {
// Large salary differences create jealousy
let jealousy_factor =
(player_a.attributes.ambition + player_b.attributes.ambition) / 40.0;
-0.1 * jealousy_factor
} else {
0.0
}
}
fn calculate_injury_sympathy(_injured_player: &Player, other_player: &Player) -> f32 {
// More empathetic players show more sympathy
let empathy = other_player.attributes.sportsmanship / 20.0;
// Team players show more concern
let team_spirit = other_player.skills.mental.teamwork / 20.0;
(empathy + team_spirit) * 0.1
}
fn calculate_national_team_bond(player_a: &Player, player_b: &Player) -> f32 {
// International experience creates stronger bonds
let int_experience_a =
(player_a.player_attributes.international_apps as f32 / 50.0).min(1.0);
let int_experience_b =
(player_b.player_attributes.international_apps as f32 / 50.0).min(1.0);
(int_experience_a + int_experience_b) * 0.05
}
// Include all the previous helper functions from the earlier implementation
// (calculate_competition_factor, calculate_synergy_factor, etc.)
// ... [Previous helper functions would go here] ...
fn calculate_player_happiness(player: &Player) -> f32 {
let mut happiness = 0.0;
// Contract satisfaction
happiness += player
.contract
.as_ref()
.map(|c| (c.salary as f32 / 10000.0).min(1.0))
.unwrap_or(-0.5);
// Playing time satisfaction
if player.statistics.played > 20 {
happiness += 0.3;
} else if player.statistics.played > 10 {
happiness += 0.1;
} else {
happiness -= 0.2;
}
// Performance satisfaction
let goals_ratio = player.statistics.goals as f32 / player.statistics.played.max(1) as f32;
if player.position().is_forward() && goals_ratio > 0.5 {
happiness += 0.2;
} else if !player.position().is_forward() && goals_ratio > 0.3 {
happiness += 0.15;
}
// Personality factors
happiness += (player.attributes.professionalism - 10.0) / 100.0;
happiness -= (player.attributes.controversy - 10.0) / 50.0;
// Behavior state affects happiness
match player.behaviour.state {
PersonBehaviourState::Good => happiness += 0.2,
PersonBehaviourState::Poor => happiness -= 0.3,
PersonBehaviourState::Normal => {}
}
happiness.clamp(-1.0, 1.0)
}
// pub fn simulate(
// players: &mut PlayerCollection,
// _staffs: &mut StaffCollection,
// ) -> TeamBehaviourResult {
// let mut result = TeamBehaviourResult::new();
//
// // Process different types of interactions
// Self::process_position_group_dynamics(players, &mut result);
// Self::process_age_group_dynamics(players, &mut result);
// Self::process_performance_based_relationships(players, &mut result);
// Self::process_personality_conflicts(players, &mut result);
// Self::process_leadership_influence(players, &mut result);
// Self::process_playing_time_jealousy(players, &mut result);
//
// result
// }
/// Players in similar positions tend to have more complex relationships
/// due to competition for spots
fn process_position_group_dynamics(
players: &PlayerCollection,
result: &mut TeamBehaviourResult,
) {
for i in 0..players.players.len() {
for j in i + 1..players.players.len() {
let player_i = &players.players[i];
let player_j = &players.players[j];
let position_i = player_i.position();
let position_j = player_j.position();
// Same position = competition (negative relationship)
if position_i == position_j {
let competition_factor = Self::calculate_competition_factor(player_i, player_j);
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_i.id,
to_player_id: player_j.id,
relationship_change: -competition_factor,
});
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_j.id,
to_player_id: player_i.id,
relationship_change: -competition_factor,
});
}
// Complementary positions (e.g., defender + midfielder) = positive
else if Self::are_complementary_positions(&position_i, &position_j) {
let synergy_factor = Self::calculate_synergy_factor(player_i, player_j);
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_i.id,
to_player_id: player_j.id,
relationship_change: synergy_factor,
});
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_j.id,
to_player_id: player_i.id,
relationship_change: synergy_factor,
});
}
}
}
}
/// Age groups naturally form bonds - young players stick together,
/// veterans mentor youth, but sometimes clash with middle-aged players
fn process_age_group_dynamics(players: &PlayerCollection, result: &mut TeamBehaviourResult) {
for i in 0..players.players.len() {
for j in i + 1..players.players.len() {
let player_i = &players.players[i];
let player_j = &players.players[j];
// Calculate ages (using a fixed date for consistency)
let current_date = chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
let age_i = player_i.age(current_date);
let age_j = player_j.age(current_date);
let age_diff = (age_i as i32 - age_j as i32).abs();
let relationship_change =
Self::calculate_age_relationship_factor(age_i, age_j, age_diff);
if relationship_change.abs() > 0.01 {
// Only process significant changes
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_i.id,
to_player_id: player_j.id,
relationship_change,
});
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_j.id,
to_player_id: player_i.id,
relationship_change,
});
}
}
}
}
/// Players with similar performance levels respect each other,
/// while big performance gaps can create tension
fn process_performance_based_relationships(
players: &PlayerCollection,
result: &mut TeamBehaviourResult,
) {
for i in 0..players.players.len() {
for j in i + 1..players.players.len() {
let player_i = &players.players[i];
let player_j = &players.players[j];
let performance_i = Self::calculate_player_performance_rating(player_i);
let performance_j = Self::calculate_player_performance_rating(player_j);
let performance_diff = (performance_i - performance_j).abs();
let relationship_change = Self::calculate_performance_relationship_factor(
performance_i,
performance_j,
performance_diff,
);
if relationship_change.abs() > 0.01 {
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_i.id,
to_player_id: player_j.id,
relationship_change,
});
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_j.id,
to_player_id: player_i.id,
relationship_change,
});
}
}
}
}
/// Some personality combinations just don't work well together
fn process_personality_conflicts(players: &PlayerCollection, result: &mut TeamBehaviourResult) {
for i in 0..players.players.len() {
for j in i + 1..players.players.len() {
let player_i = &players.players[i];
let player_j = &players.players[j];
let conflict_factor = Self::calculate_personality_conflict(player_i, player_j);
if conflict_factor.abs() > 0.02 {
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_i.id,
to_player_id: player_j.id,
relationship_change: conflict_factor,
});
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_j.id,
to_player_id: player_i.id,
relationship_change: conflict_factor,
});
}
}
}
}
/// High leadership players influence team morale and relationships
fn process_leadership_influence(players: &PlayerCollection, result: &mut TeamBehaviourResult) {
// Find leaders (high leadership skill)
let leaders: Vec<&Player> = players
.players
.iter()
.filter(|p| p.skills.mental.leadership > 15.0)
.collect();
for leader in leaders {
for player in &players.players {
if leader.id == player.id {
continue;
}
let influence = Self::calculate_leadership_influence(leader, player);
if influence.abs() > 0.01 {
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player.id,
to_player_id: leader.id,
relationship_change: influence,
});
}
}
}
}
/// Players with similar playing time are more likely to bond,
/// while those with very different playing time might be jealous
fn process_playing_time_jealousy(players: &PlayerCollection, result: &mut TeamBehaviourResult) {
for i in 0..players.players.len() {
for j in i + 1..players.players.len() {
let player_i = &players.players[i];
let player_j = &players.players[j];
let playing_time_i = player_i.statistics.played;
let playing_time_j = player_j.statistics.played;
let jealousy_factor = Self::calculate_playing_time_jealousy(
playing_time_i,
playing_time_j,
player_i,
player_j,
);
if jealousy_factor.abs() > 0.01 {
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_i.id,
to_player_id: player_j.id,
relationship_change: jealousy_factor,
});
result
.players
.relationship_result
.push(PlayerRelationshipChangeResult {
from_player_id: player_j.id,
to_player_id: player_i.id,
relationship_change: jealousy_factor,
});
}
}
}
}
// Helper functions for calculations
fn calculate_competition_factor(player_a: &Player, player_b: &Player) -> f32 {
let ability_diff = (player_a.player_attributes.current_ability as f32
- player_b.player_attributes.current_ability as f32)
.abs();
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | true |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/behaviour/result.rs | src/core/src/club/team/behaviour/result.rs | use crate::SimulatorData;
pub struct TeamBehaviourResult {
pub players: PlayerBehaviourResult,
}
impl Default for TeamBehaviourResult {
fn default() -> Self {
Self::new()
}
}
impl TeamBehaviourResult {
pub fn new() -> Self {
TeamBehaviourResult {
players: PlayerBehaviourResult::new(),
}
}
pub fn process(&self, data: &mut SimulatorData) {
self.players.process(data);
}
}
pub struct PlayerBehaviourResult {
pub relationship_result: Vec<PlayerRelationshipChangeResult>,
}
impl Default for PlayerBehaviourResult {
fn default() -> Self {
Self::new()
}
}
impl PlayerBehaviourResult {
pub fn new() -> Self {
PlayerBehaviourResult {
relationship_result: Vec::new(),
}
}
pub fn process(&self, data: &mut SimulatorData) {
for relationship_result in &self.relationship_result {
let player_to_modify = data.player_mut(relationship_result.from_player_id).unwrap();
player_to_modify.relations.update(
relationship_result.to_player_id,
relationship_result.relationship_change,
);
}
}
}
pub struct PlayerRelationshipChangeResult {
pub from_player_id: u32,
pub to_player_id: u32,
pub relationship_change: f32,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/team/behaviour/mod.rs | src/core/src/club/team/behaviour/mod.rs | mod behaviour;
mod result;
pub use behaviour::*;
pub use result::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/board/mood.rs | src/core/src/club/board/mood.rs | #[derive(Debug)]
pub struct BoardMood {
pub state: BoardMoodState,
}
impl BoardMood {
pub fn default() -> Self {
BoardMood {
state: BoardMoodState::Normal,
}
}
}
#[derive(Debug)]
pub enum BoardMoodState {
Poor,
Normal,
Good,
Excellent,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/board/board.rs | src/core/src/club/board/board.rs | use crate::club::{BoardMood, BoardResult, StaffClubContract};
use crate::context::{GlobalContext, SimulationContext};
#[derive(Debug)]
pub struct ClubBoard {
pub mood: BoardMood,
pub director: Option<StaffClubContract>,
pub sport_director: Option<StaffClubContract>,
}
impl ClubBoard {
pub fn new() -> Self {
ClubBoard {
mood: BoardMood::default(),
director: None,
sport_director: None,
}
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> BoardResult {
let result = BoardResult::new();
if self.director.is_none() {
self.run_director_election(&ctx.simulation);
}
if self.sport_director.is_none() {
self.run_sport_director_election(&ctx.simulation);
}
if ctx.simulation.check_contract_expiration() {
if self.is_director_contract_expiring(&ctx.simulation) {}
if self.is_sport_director_contract_expiring(&ctx.simulation) {}
}
result
}
fn is_director_contract_expiring(&self, simulation_ctx: &SimulationContext) -> bool {
match &self.director {
Some(d) => d.is_expired(simulation_ctx),
None => false,
}
}
fn run_director_election(&mut self, _: &SimulationContext) {}
fn is_sport_director_contract_expiring(&self, simulation_ctx: &SimulationContext) -> bool {
match &self.director {
Some(d) => d.is_expired(simulation_ctx),
None => false,
}
}
fn run_sport_director_election(&mut self, _: &SimulationContext) {}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/board/result.rs | src/core/src/club/board/result.rs | use crate::simulator::SimulatorData;
pub struct BoardResult {}
impl BoardResult {
pub fn new() -> Self {
BoardResult {}
}
pub fn process(&self, _: &mut SimulatorData) {}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/board/mod.rs | src/core/src/club/board/mod.rs | pub mod board;
pub mod context;
mod mood;
mod result;
pub use board::*;
pub use context::*;
pub use mood::*;
pub use result::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/board/context.rs | src/core/src/club/board/context.rs | #[derive(Clone)]
pub struct BoardContext {}
impl BoardContext {
pub fn new() -> Self {
BoardContext {}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/transfers/mod.rs | src/core/src/club/transfers/mod.rs | pub mod strategy;
pub use strategy::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/transfers/strategy.rs | src/core/src/club/transfers/strategy.rs | use crate::shared::CurrencyValue;
use crate::transfers::offer::{TransferClause, TransferOffer};
use crate::transfers::window::PlayerValuationCalculator;
use crate::{Person, Player, PlayerPositionType};
use chrono::NaiveDate;
pub struct ClubTransferStrategy {
pub club_id: u32,
pub budget: Option<CurrencyValue>,
pub selling_willingness: f32, // 0.0-1.0
pub buying_aggressiveness: f32, // 0.0-1.0
pub target_positions: Vec<PlayerPositionType>,
pub reputation_level: u16,
}
impl ClubTransferStrategy {
pub fn new(club_id: u32) -> Self {
ClubTransferStrategy {
club_id,
budget: None,
selling_willingness: 0.5,
buying_aggressiveness: 0.5,
target_positions: Vec::new(),
reputation_level: 50,
}
}
pub fn decide_player_interest(&self, player: &Player) -> bool {
// Decide if the club should be interested in this player
// Position need
let position_needed = self.target_positions.contains(&player.position());
if !position_needed && self.target_positions.len() > 0 {
return false;
}
// Age policy
let age = player.age(chrono::Local::now().naive_local().date());
if self.reputation_level > 80 && age > 30 {
// Top clubs rarely sign older players
return false;
}
// Quality check
let player_ability = player.player_attributes.current_ability as u16;
// Is player good enough for the club?
if player_ability < self.reputation_level / 2 {
return false;
}
// Is player too good for the club?
if player_ability > self.reputation_level * 2 {
// Only aggressive buyers go for much better players
return self.buying_aggressiveness > 0.8;
}
true
}
pub fn calculate_initial_offer(
&self,
player: &Player,
asking_price: &CurrencyValue,
current_date: NaiveDate
) -> TransferOffer {
// Club budget check
let max_budget = match &self.budget {
Some(budget) => budget.amount,
None => f64::MAX, // No budget constraint
};
// Calculate base valuation
let player_value = PlayerValuationCalculator::calculate_value(player, current_date);
// Adjust based on asking price
let mut offer_amount = if asking_price.amount > 0.0 {
// Start with 60-90% of asking price depending on aggressiveness
asking_price.amount * (0.6 + (self.buying_aggressiveness as f64 * 0.3))
} else {
// No asking price - use our valuation but discount it
player_value.amount * (0.7 + (self.buying_aggressiveness as f64 * 0.2f64))
};
// Cap by budget - never offer more than 80% of available budget
let budget_cap = max_budget * 0.8;
if offer_amount > budget_cap {
offer_amount = budget_cap;
}
// Create the base offer
let mut offer = TransferOffer::new(
CurrencyValue {
amount: offer_amount,
currency: crate::shared::Currency::Usd,
},
self.club_id,
current_date,
);
// Add clauses based on player profile and club strategy
// 1. Add sell-on clause for young players with potential
let age = player.age(current_date);
let potential_gap = player.player_attributes.potential_ability as i16 -
player.player_attributes.current_ability as i16;
if age < 23 && potential_gap > 10 {
// Add sell-on clause for promising youngsters
let sell_on_percentage = 0.1 + (potential_gap as f32 / 100.0).min(0.1);
offer = offer.with_clause(TransferClause::SellOnClause(sell_on_percentage));
}
// 2. Add appearance bonuses for older players to reduce risk
if age > 28 {
let appearance_amount = offer_amount * 0.1; // 10% of transfer fee
offer = offer.with_clause(TransferClause::AppearanceFee(
CurrencyValue {
amount: appearance_amount,
currency: crate::shared::Currency::Usd,
},
20 // After 20 appearances
));
}
// 3. Add goal bonus for attackers
if player.position().is_forward() && player.statistics.goals > 5 {
let goals_bonus = offer_amount * 0.15; // 15% of transfer fee
offer = offer.with_clause(TransferClause::GoalBonus(
CurrencyValue {
amount: goals_bonus,
currency: crate::shared::Currency::Usd,
},
15 // After 15 goals
));
}
// 4. Add promotion bonus for lower reputation clubs
if self.reputation_level < 60 {
let promotion_bonus = offer_amount * 0.2; // 20% of transfer fee
offer = offer.with_clause(TransferClause::PromotionBonus(
CurrencyValue {
amount: promotion_bonus,
currency: crate::shared::Currency::Usd,
}
));
}
// Set contract length based on player age
let contract_years = if age < 24 {
5 // Long contract for young players
} else if age < 28 {
4 // Standard length for prime players
} else if age < 32 {
2 // Shorter for older players
} else {
1 // One year for veterans
};
offer.with_contract_length(contract_years)
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/academy/settings.rs | src/core/src/club/academy/settings.rs | use std::ops::Range;
#[derive(Debug)]
pub struct AcademySettings {
pub players_count_range: Range<u8>,
}
impl AcademySettings {
pub fn default() -> Self {
AcademySettings {
players_count_range: 30..50,
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/academy/result.rs | src/core/src/club/academy/result.rs | use crate::{Player, PlayerCollectionResult, SimulatorData};
pub struct ClubAcademyResult {
pub players: PlayerCollectionResult
}
impl ClubAcademyResult {
pub fn new(players: PlayerCollectionResult) -> Self {
ClubAcademyResult {
players
}
}
pub fn process(&self, _: &mut SimulatorData) {}
}
pub struct ProduceYouthPlayersResult {
pub players: Vec<Player>,
}
impl ProduceYouthPlayersResult {
pub fn new(players: Vec<Player>) -> Self {
ProduceYouthPlayersResult { players }
}
pub fn process(&self, _: &mut SimulatorData) {}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/academy/academy.rs | src/core/src/club/academy/academy.rs | use crate::academy::result::ProduceYouthPlayersResult;
use crate::club::academy::result::ClubAcademyResult;
use crate::club::academy::settings::AcademySettings;
use crate::context::GlobalContext;
use crate::utils::IntegerUtils;
use crate::{Person, Player, PlayerCollection, PlayerGenerator, PlayerPositionType, StaffCollection};
use chrono::Datelike;
use log::debug;
#[derive(Debug)]
pub struct ClubAcademy {
settings: AcademySettings,
players: PlayerCollection,
_staff: StaffCollection,
level: u8,
last_production_year: Option<i32>,
}
impl ClubAcademy {
pub fn new(level: u8) -> Self {
ClubAcademy {
settings: AcademySettings::default(),
players: PlayerCollection::new(Vec::new()),
_staff: StaffCollection::new(Vec::new()),
level,
last_production_year: None,
}
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> ClubAcademyResult {
// Simulate existing academy players
let players_result = self.players.simulate(ctx.with_player(None));
// Produce new youth players
let produce_result = self.produce_youth_players(ctx);
// Add newly produced players to the academy
for player in produce_result.players {
debug!("🎓 academy: adding new youth player: {}", player.fullname());
self.players.add(player);
}
ClubAcademyResult::new(players_result)
}
fn produce_youth_players(&mut self, ctx: GlobalContext<'_>) -> ProduceYouthPlayersResult {
let current_year = ctx.simulation.date.year();
let current_month = ctx.simulation.date.month();
// Check if we should produce players this year
if !self.should_produce_players(current_year, current_month) {
return ProduceYouthPlayersResult::new(Vec::new());
}
let club_name = ctx.club.as_ref()
.map(|c| c.name)
.unwrap_or("Unknown Club");
debug!("🎓 academy: {} starting yearly youth intake", club_name);
// Determine how many players to produce based on academy level and current squad size
let current_size = self.players.players.len();
let min_required = self.settings.players_count_range.start as usize;
let max_allowed = self.settings.players_count_range.end as usize;
let mut players_to_produce = 0;
// Always produce some players if below minimum
if current_size < min_required {
players_to_produce = min_required - current_size;
debug!("⚠️ academy: {} below minimum capacity ({}/{}), producing {} players",
club_name, current_size, min_required, players_to_produce);
}
// Annual intake based on academy level (even if at capacity)
let annual_intake = self.calculate_annual_intake();
// Only add annual intake if we won't exceed maximum
if current_size + players_to_produce + annual_intake <= max_allowed {
players_to_produce += annual_intake;
debug!("📊 academy: {} annual intake of {} players (level {})",
club_name, annual_intake, self.level);
} else {
let space_available = max_allowed.saturating_sub(current_size);
players_to_produce = space_available.min(players_to_produce + annual_intake);
debug!("⚠️ academy: {} limited to {} new players due to capacity ({}/{})",
club_name, players_to_produce, current_size, max_allowed);
}
if players_to_produce == 0 {
debug!("ℹ️ academy: {} at full capacity, no new players produced", club_name);
return ProduceYouthPlayersResult::new(Vec::new());
}
// Generate the youth players
let mut generated_players = Vec::with_capacity(players_to_produce);
// Get country_id from club context if available
let country_id = ctx.country.as_ref()
.map(|c| c.id)
.unwrap_or(1); // Default to 1 if not available
for i in 0..players_to_produce {
let position = self.select_position_for_youth_player(i, players_to_produce);
let generated_player = PlayerGenerator::generate(
country_id,
ctx.simulation.date.date(),
position,
self.level, // Pass academy level to influence player quality
);
debug!("👤 academy: {} generated youth player: {} ({}, age {})",
club_name,
generated_player.full_name,
position.get_short_name(),
generated_player.age(ctx.simulation.date.date()));
generated_players.push(generated_player);
}
// Update last production year
self.last_production_year = Some(current_year);
debug!("✅ academy: {} completed youth intake with {} new players",
club_name, generated_players.len());
ProduceYouthPlayersResult::new(generated_players)
}
fn should_produce_players(&self, current_year: i32, current_month: u32) -> bool {
// Produce players once per year, typically in July (pre-season)
const YOUTH_INTAKE_MONTH: u32 = 7;
if current_month != YOUTH_INTAKE_MONTH {
return false;
}
// Check if we've already produced players this year
match self.last_production_year {
Some(last_year) if last_year >= current_year => false,
_ => true,
}
}
fn calculate_annual_intake(&self) -> usize {
// Academy level determines quality and quantity of youth intake
// Level 1-3: Poor academy (2-4 players)
// Level 4-6: Average academy (3-6 players)
// Level 7-9: Good academy (4-8 players)
// Level 10: Excellent academy (5-10 players)
let (min_intake, max_intake) = match self.level {
1..=3 => (2, 4),
4..=6 => (3, 6),
7..=9 => (4, 8),
10 => (5, 10),
_ => (2, 4), // Default for unexpected values
};
IntegerUtils::random(min_intake, max_intake) as usize
}
fn select_position_for_youth_player(&self, index: usize, total_players: usize) -> PlayerPositionType {
// Distribute positions somewhat realistically
// Ensure at least 1 GK if producing 4+ players
// Otherwise random distribution favoring outfield players
if total_players >= 4 && index == 0 {
// First player is goalkeeper when producing 4+ players
PlayerPositionType::Goalkeeper
} else {
// Random distribution for other positions
let position_roll = IntegerUtils::random(0, 100);
match position_roll {
0..=5 => PlayerPositionType::Goalkeeper, // 5% chance
6..=20 => {
// Defenders 15% chance
match IntegerUtils::random(0, 5) {
0 => PlayerPositionType::DefenderLeft,
1 => PlayerPositionType::DefenderRight,
2 => PlayerPositionType::DefenderCenter,
3 => PlayerPositionType::DefenderCenterLeft,
4 => PlayerPositionType::DefenderCenterRight,
_ => PlayerPositionType::DefenderCenter,
}
},
21..=50 => {
// Midfielders 30% chance
match IntegerUtils::random(0, 6) {
0 => PlayerPositionType::DefensiveMidfielder,
1 => PlayerPositionType::MidfielderLeft,
2 => PlayerPositionType::MidfielderRight,
3 => PlayerPositionType::MidfielderCenter,
4 => PlayerPositionType::MidfielderCenterLeft,
5 => PlayerPositionType::MidfielderCenterRight,
_ => PlayerPositionType::MidfielderCenter,
}
},
51..=75 => {
// Attacking midfielders/wingers 25% chance
match IntegerUtils::random(0, 4) {
0 => PlayerPositionType::AttackingMidfielderLeft,
1 => PlayerPositionType::AttackingMidfielderRight,
2 => PlayerPositionType::AttackingMidfielderCenter,
3 => PlayerPositionType::WingbackLeft,
_ => PlayerPositionType::WingbackRight,
}
},
_ => {
// Forwards 25% chance
match IntegerUtils::random(0, 3) {
0 => PlayerPositionType::Striker,
1 => PlayerPositionType::ForwardLeft,
2 => PlayerPositionType::ForwardRight,
_ => PlayerPositionType::ForwardCenter,
}
}
}
}
}
pub fn graduate_player(&mut self, player_id: u32) -> Option<Player> {
// Remove a player from academy (e.g., promoted to first team)
self.players.take_player(&player_id)
}
pub fn release_player(&mut self, player_id: u32) -> Option<Player> {
// Release a player from academy
let player = self.players.take_player(&player_id);
if let Some(ref p) = player {
debug!("👋 academy: releasing player {}", p.full_name);
}
player
}
pub fn get_capacity_status(&self) -> (usize, usize, usize) {
let current = self.players.players.len();
let min = self.settings.players_count_range.start as usize;
let max = self.settings.players_count_range.end as usize;
(current, min, max)
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/academy/mod.rs | src/core/src/club/academy/mod.rs | pub mod academy;
pub mod result;
mod settings;
pub use academy::*;
pub use result::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/player.rs | src/core/src/club/player/player.rs | use crate::club::player::utils::PlayerUtils;
use crate::club::{
PersonBehaviour, PlayerAttributes, PlayerClubContract, PlayerCollectionResult, PlayerMailbox,
PlayerResult, PlayerSkills, PlayerTraining,
};
use crate::context::GlobalContext;
use crate::shared::fullname::FullName;
use crate::utils::{DateUtils, Logging};
use crate::{
Person, PersonAttributes, PlayerHappiness, PlayerPositionType, PlayerPositions,
PlayerStatistics, PlayerStatisticsHistory, PlayerStatus, PlayerTrainingHistory,
PlayerValueCalculator, Relations,
};
use chrono::{NaiveDate, NaiveDateTime};
use std::fmt::{Display, Formatter, Result};
use std::ops::Index;
use crate::club::player::builder::PlayerBuilder;
#[derive(Debug)]
pub struct Player {
//person data
pub id: u32,
pub full_name: FullName,
pub birth_date: NaiveDate,
pub country_id: u32,
pub behaviour: PersonBehaviour,
pub attributes: PersonAttributes,
//player data
pub happiness: PlayerHappiness,
pub statuses: PlayerStatus,
pub skills: PlayerSkills,
pub contract: Option<PlayerClubContract>,
pub positions: PlayerPositions,
pub preferred_foot: PlayerPreferredFoot,
pub player_attributes: PlayerAttributes,
pub mailbox: PlayerMailbox,
pub training: PlayerTraining,
pub training_history: PlayerTrainingHistory,
pub relations: Relations,
pub statistics: PlayerStatistics,
pub statistics_history: PlayerStatisticsHistory,
}
impl Player {
pub fn builder() -> PlayerBuilder {
PlayerBuilder::new()
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> PlayerResult {
let now = ctx.simulation.date;
let mut result = PlayerResult::new(self.id);
if DateUtils::is_birthday(self.birth_date, now.date()) {
self.behaviour.try_increase();
}
self.process_contract(&mut result, now);
self.process_mailbox(&mut result, now.date());
if self.behaviour.is_poor() {
result.request_transfer(self.id);
}
result
}
fn process_contract(&mut self, result: &mut PlayerResult, now: NaiveDateTime) {
if let Some(ref mut contract) = self.contract {
const HALF_YEAR_DAYS: i64 = 30 * 6;
if contract.days_to_expiration(now) < HALF_YEAR_DAYS {
result.contract.want_extend_contract = true;
}
} else {
result.contract.no_contract = true;
}
}
fn process_mailbox(&mut self, result: &mut PlayerResult, now: NaiveDate) {
PlayerMailbox::process(self, result, now);
}
pub fn shirt_number(&self) -> u8 {
if let Some(contract) = &self.contract {
return contract.shirt_number.unwrap_or(0);
}
0
}
pub fn value(&self, date: NaiveDate) -> f64 {
PlayerValueCalculator::calculate(self, date)
}
#[inline]
pub fn positions(&self) -> Vec<PlayerPositionType> {
self.positions.positions()
}
#[inline]
pub fn position(&self) -> PlayerPositionType {
*self
.positions
.positions()
.first()
.expect("no position found")
}
pub fn preferred_foot_str(&self) -> &'static str {
match self.preferred_foot {
PlayerPreferredFoot::Left => "Left",
PlayerPreferredFoot::Right => "Right",
PlayerPreferredFoot::Both => "Both",
}
}
pub fn is_ready_for_match(&self) -> bool {
match self.skills.physical.match_readiness.floor() as u32 {
0..=10 => false,
11..=20 => true,
_ => false,
}
}
pub fn growth_potential(&self, now: NaiveDate) -> u8 {
PlayerUtils::growth_potential(self, now)
}
}
impl Person for Player {
fn id(&self) -> u32 {
self.id
}
fn fullname(&self) -> &FullName {
&self.full_name
}
fn birthday(&self) -> NaiveDate {
self.birth_date
}
fn behaviour(&self) -> &PersonBehaviour {
&self.behaviour
}
fn attributes(&self) -> &PersonAttributes {
&self.attributes
}
fn relations(&self) -> &Relations {
&self.relations
}
}
#[derive(Debug)]
pub enum PlayerPreferredFoot {
Left,
Right,
Both,
}
//DISPLAY
impl Display for Player {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "{}, {}", self.full_name, self.birth_date)
}
}
const DEFAULT_PLAYER_TRANSFER_BUFFER_SIZE: usize = 10;
#[derive(Debug)]
pub struct PlayerCollection {
pub players: Vec<Player>,
}
impl PlayerCollection {
pub fn new(players: Vec<Player>) -> Self {
PlayerCollection { players }
}
pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> PlayerCollectionResult {
let player_results: Vec<PlayerResult> = self
.players
.iter_mut()
.map(|player| {
let message = &format!("simulate player: id: {}", player.id);
Logging::estimate_result(
|| player.simulate(ctx.with_player(Some(player.id))),
message,
)
})
.collect();
let mut outgoing_players = Vec::with_capacity(DEFAULT_PLAYER_TRANSFER_BUFFER_SIZE);
for transfer_request_player_id in player_results.iter().flat_map(|p| &p.transfer_requests) {
if let Some(player) = self.take_player(transfer_request_player_id) {
outgoing_players.push(player)
}
}
PlayerCollectionResult::new(player_results, outgoing_players)
}
pub fn by_position(&self, position: &PlayerPositionType) -> Vec<&Player> {
self.players
.iter()
.filter(|p| p.positions().contains(position))
.collect()
}
pub fn add(&mut self, player: Player) {
self.players.push(player);
}
pub fn add_range(&mut self, players: Vec<Player>) {
for player in players {
self.players.push(player);
}
}
pub fn get_week_salary(&self) -> u32 {
self.players
.iter()
.filter_map(|p| p.contract.as_ref())
.map(|c| c.salary)
.sum::<u32>()
}
pub fn players(&self) -> Vec<&Player> {
self.players.iter().map(|player| player).collect()
}
pub fn take_player(&mut self, player_id: &u32) -> Option<Player> {
let player_idx = self.players.iter().position(|p| p.id == *player_id);
match player_idx {
Some(idx) => Some(self.players.remove(idx)),
None => None,
}
}
pub fn contains(&self, player_id: u32) -> bool {
self.players.iter().any(|p| p.id == player_id)
}
}
impl Index<u32> for PlayerCollection {
type Output = Player;
fn index(&self, player_id: u32) -> &Self::Output {
self
.players
.iter()
.find(|p| p.id == player_id)
.expect(&format!("no player with id = {}", player_id))
}
}
impl PartialEq for Player {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
#[cfg(test)]
mod tests {
#[test]
fn player_is_correct() {
assert_eq!(10, 10);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/builder.rs | src/core/src/club/player/builder.rs | use crate::club::{
PersonBehaviour, PlayerAttributes, PlayerClubContract, PlayerMailbox,
PlayerSkills, PlayerTraining,
};
use crate::shared::fullname::FullName;
use crate::{PersonAttributes, Player, PlayerHappiness, PlayerPositions, PlayerPreferredFoot, PlayerStatistics, PlayerStatisticsHistory, PlayerStatus, PlayerTrainingHistory, Relations};
use chrono::NaiveDate;
// Builder for Player
#[derive(Default)]
pub struct PlayerBuilder {
id: Option<u32>,
full_name: Option<FullName>,
birth_date: Option<NaiveDate>,
country_id: Option<u32>,
behaviour: Option<PersonBehaviour>,
attributes: Option<PersonAttributes>,
happiness: Option<PlayerHappiness>,
statuses: Option<PlayerStatus>,
skills: Option<PlayerSkills>,
contract: Option<Option<PlayerClubContract>>,
positions: Option<PlayerPositions>,
preferred_foot: Option<PlayerPreferredFoot>,
player_attributes: Option<PlayerAttributes>,
mailbox: Option<PlayerMailbox>,
training: Option<PlayerTraining>,
training_history: Option<PlayerTrainingHistory>,
relations: Option<Relations>,
statistics: Option<PlayerStatistics>,
statistics_history: Option<PlayerStatisticsHistory>,
}
impl PlayerBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
pub fn full_name(mut self, full_name: FullName) -> Self {
self.full_name = Some(full_name);
self
}
pub fn birth_date(mut self, birth_date: NaiveDate) -> Self {
self.birth_date = Some(birth_date);
self
}
pub fn country_id(mut self, country_id: u32) -> Self {
self.country_id = Some(country_id);
self
}
pub fn behaviour(mut self, behaviour: PersonBehaviour) -> Self {
self.behaviour = Some(behaviour);
self
}
pub fn attributes(mut self, attributes: PersonAttributes) -> Self {
self.attributes = Some(attributes);
self
}
pub fn happiness(mut self, happiness: PlayerHappiness) -> Self {
self.happiness = Some(happiness);
self
}
pub fn statuses(mut self, statuses: PlayerStatus) -> Self {
self.statuses = Some(statuses);
self
}
pub fn skills(mut self, skills: PlayerSkills) -> Self {
self.skills = Some(skills);
self
}
pub fn contract(mut self, contract: Option<PlayerClubContract>) -> Self {
self.contract = Some(contract);
self
}
pub fn positions(mut self, positions: PlayerPositions) -> Self {
self.positions = Some(positions);
self
}
pub fn preferred_foot(mut self, preferred_foot: PlayerPreferredFoot) -> Self {
self.preferred_foot = Some(preferred_foot);
self
}
pub fn player_attributes(mut self, player_attributes: PlayerAttributes) -> Self {
self.player_attributes = Some(player_attributes);
self
}
pub fn mailbox(mut self, mailbox: PlayerMailbox) -> Self {
self.mailbox = Some(mailbox);
self
}
pub fn training(mut self, training: PlayerTraining) -> Self {
self.training = Some(training);
self
}
pub fn training_history(mut self, training_history: PlayerTrainingHistory) -> Self {
self.training_history = Some(training_history);
self
}
pub fn relations(mut self, relations: Relations) -> Self {
self.relations = Some(relations);
self
}
pub fn statistics(mut self, statistics: PlayerStatistics) -> Self {
self.statistics = Some(statistics);
self
}
pub fn statistics_history(mut self, statistics_history: PlayerStatisticsHistory) -> Self {
self.statistics_history = Some(statistics_history);
self
}
pub fn build(self) -> Result<Player, String> {
Ok(Player {
id: self.id.ok_or("id is required")?,
full_name: self.full_name.ok_or("full_name is required")?,
birth_date: self.birth_date.ok_or("birth_date is required")?,
country_id: self.country_id.ok_or("country_id is required")?,
behaviour: self.behaviour.unwrap_or_default(),
attributes: self.attributes.ok_or("attributes is required")?,
happiness: self.happiness.unwrap_or_else(PlayerHappiness::new),
statuses: self.statuses.unwrap_or_else(PlayerStatus::new),
skills: self.skills.ok_or("skills is required")?,
contract: self.contract.unwrap_or(None),
positions: self.positions.ok_or("positions is required")?,
preferred_foot: self.preferred_foot.unwrap_or(PlayerPreferredFoot::Right),
player_attributes: self.player_attributes.ok_or("player_attributes is required")?,
mailbox: self.mailbox.unwrap_or_else(PlayerMailbox::new),
training: self.training.unwrap_or_else(PlayerTraining::new),
training_history: self.training_history.unwrap_or_else(PlayerTrainingHistory::new),
relations: self.relations.unwrap_or_else(Relations::new),
statistics: self.statistics.unwrap_or_default(),
statistics_history: self.statistics_history.unwrap_or_else(PlayerStatisticsHistory::new),
})
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/status.rs | src/core/src/club/player/status.rs | use chrono::NaiveDate;
use serde::Serialize;
#[derive(Debug)]
pub struct StatusData {
pub start_date: NaiveDate,
pub status: PlayerStatusType,
}
impl StatusData {
pub fn new(start_date: NaiveDate, status: PlayerStatusType) -> Self {
StatusData { start_date, status }
}
}
#[derive(Debug)]
pub struct PlayerStatus {
pub statuses: Vec<StatusData>,
}
impl PlayerStatus {
pub fn new() -> Self {
PlayerStatus {
statuses: Vec::new(),
}
}
pub fn add(&mut self, start_date: NaiveDate, status: PlayerStatusType) {
self.statuses.push(StatusData::new(start_date, status));
}
pub fn remove(&mut self, status: PlayerStatusType) {
if let Some(idx) = self.statuses.iter().position(|s| s.status == status) {
self.statuses.remove(idx);
}
}
pub fn get(&self) -> Vec<PlayerStatusType> {
self.statuses.iter().map(|s| s.status).collect()
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize)]
pub enum PlayerStatusType {
//When a player is absent from the club without permission
Abs,
//The player has had a bid from another club accepted
Bid,
//An out-of-contract player still with a club
Ctr,
//The player is cup-tied, having played in the same competition in a previous round but for another club
Cup,
//The player is on an MLS developmental contract
Dev,
//The player has been selected in the MLS Draft
Dft,
//Another club has made a transfer enquiry about the player
Enq,
//A player who counts as a foreign player in a competition
Fgn,
//A player who wants to leave the club on a free transfer at the end of the season
Frt,
//The player is concerned about his future at the club
Fut,
//The player counts towards the Home Grown quota necessary for a competition
HG,
//A player currently on holiday
Hol,
//Ineligible for the next match.
Ine,
//When it has a red background, this means a player is injured and cannot be selected. If the background is orange, he has resumed light training, but he may not be fully fit. Check his condition indicator
Inj,
//The player is away on international duty
Int,
//When a player is short on match fitness (perhaps after a long spell on the sidelines), and needs perhaps to play with the reserves in order to regain full fitness
Lmp,
//Player is available for loan
Loa,
//The player is learning from a team-mate (see Tut below).
Lrn,
//The player is transfer listed
Lst,
//The player has reacted to a media comment made by you
PR,
//The player has requested to leave the club
Req,
//The player is retiring at the end of the season
Ret,
//The player is jaded and in need of a rest
Rst,
//The player is being scouted by your scouts
Sct,
//The player is an MLS Senior International - a non domestic player aged 25+
SI,
//The player has some slight concerns
Slt,
//The player is suspended
Sus,
//The player has agreed a transfer with another club and will go there when the transfer window opens.
Trn,
//The player is travelling to/from international duty with his squad
Trv,
//The player is tutoring a team-mate
Tut,
//The player is unfit, and shouldn't be selected unless in case of an emergency
Unf,
//A player is unhappy with his role or an event/action
Unh,
//The player is unregistered for a competition
Unr,
//The player has been withdrawn from international duty by his club manager
Wdn,
//The player is wanted by another club
Wnt,
//The player has no work permit and is unable to play
Wp,
//The player is one yellow card away from a suspension
Yel,
//The player is an MLS Youth International - a non domestic player aged 24 or under.
YI,
//The player is on a youth contract and is not yet on professional terms
Yth,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/result.rs | src/core/src/club/player/result.rs | use crate::club::Player;
use crate::simulator::SimulatorData;
pub struct PlayerCollectionResult {
pub players: Vec<PlayerResult>,
pub outgoing_players: Vec<Player>,
}
impl PlayerCollectionResult {
pub fn new(players: Vec<PlayerResult>, outgoing_players: Vec<Player>) -> Self {
PlayerCollectionResult {
players,
outgoing_players,
}
}
pub fn process(&self, data: &mut SimulatorData) {
for player in &self.players {
player.process(data);
}
}
}
pub struct PlayerResult {
pub player_id: u32,
pub contract: PlayerContractResult,
pub is_transfer_requested: bool,
pub transfer_requests: Vec<u32>,
}
pub struct PlayerContractResult {
pub no_contract: bool,
pub contract_rejected: bool,
pub want_improve_contract: bool,
pub want_extend_contract: bool,
}
impl PlayerResult {
pub fn new(player_id: u32) -> Self {
PlayerResult {
player_id,
contract: PlayerContractResult {
no_contract: false,
contract_rejected: false,
want_improve_contract: false,
want_extend_contract: false,
},
is_transfer_requested: false,
transfer_requests: Vec::new(),
}
}
pub fn process(&self, _: &mut SimulatorData) {}
pub fn request_transfer(&mut self, player_id: u32) {
self.transfer_requests.push(player_id);
}
pub fn has_contract_actions(&self) -> bool {
self.contract.no_contract
|| self.contract.contract_rejected
|| self.contract.want_extend_contract
|| self.contract.want_improve_contract
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/utils.rs | src/core/src/club/player/utils.rs | use crate::{Person, Player};
use chrono::NaiveDate;
pub struct PlayerUtils;
impl PlayerUtils {
#[inline]
pub fn growth_potential(player: &Player, now: NaiveDate) -> u8 {
let age = player.age(now);
let age_factor = Self::age_factor(age);
let determination = player.skills.mental.determination as f32 / 20.0;
let ambition = player.attributes.ambition as f32 / 20.0;
let professionalism = player.attributes.professionalism as f32 / 20.0;
let base_factor = determination + ambition + professionalism;
let current_ability = player.player_attributes.current_ability as f32;
let potential_ability = player.player_attributes.potential_ability as f32;
let ability_factor = (potential_ability - current_ability) / 20.0;
let condition = player.player_attributes.condition as f32 / 100.0;
let fitness = player.player_attributes.fitness as f32 / 20.0;
let jadedness = player.player_attributes.jadedness as f32 / 100.0;
let physical_factor = (condition + fitness - jadedness) / 3.0;
let reputation = player.player_attributes.current_reputation as f32 / 100.0;
let international_factor = player.player_attributes.international_apps as f32 / 100.0;
let total_factor = age_factor
* base_factor
* ability_factor
* physical_factor
* reputation
* international_factor;
let growth_potential = (total_factor * 5.0).round() as u8;
growth_potential
}
pub fn age_factor(age: u8) -> f32 {
1.0 / (1.0 + (-0.1 * age as f32).exp())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_age_factor_under_18() {
let age_factor = PlayerUtils::age_factor(18);
assert!(age_factor > 0.0);
assert!(age_factor < 1.0);
}
#[test]
fn test_age_factor_under_30() {
let age_factor = PlayerUtils::age_factor(30);
assert!(age_factor > 0.0);
assert!(age_factor < 1.0);
}
#[test]
fn test_age_factor_under_40() {
let age_factor = PlayerUtils::age_factor(40);
assert!(age_factor > 0.0);
assert!(age_factor < 1.0);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/happiness.rs | src/core/src/club/player/happiness.rs | #[derive(Debug)]
pub struct PlayerHappiness {
positive: Vec<PositiveHappiness>,
negative: Vec<NegativeHappiness>,
}
impl PlayerHappiness {
pub fn new() -> Self {
PlayerHappiness {
positive: Vec::new(),
negative: Vec::new(),
}
}
pub fn is_happy(&self) -> bool {
self.positive.len() > self.negative.len()
}
}
#[derive(Debug)]
pub struct PositiveHappiness {
pub description: String,
}
#[derive(Debug)]
pub struct NegativeHappiness {
pub description: String,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/mod.rs | src/core/src/club/player/mod.rs | pub mod attributes;
pub mod calculators;
pub mod context;
pub mod contract;
pub mod generators;
pub mod happiness;
pub mod mailbox;
pub mod player;
pub mod position;
pub mod result;
pub mod skills;
pub mod statistics;
pub mod status;
pub mod training;
pub mod utils;
pub mod builder;
pub use attributes::*;
pub use builder::*;
pub use calculators::*;
pub use context::*;
pub use contract::*;
pub use generators::*;
pub use happiness::*;
pub use mailbox::*;
pub use player::*;
pub use position::*;
pub use result::*;
pub use skills::*;
pub use statistics::*;
pub use status::*;
pub use training::*;
pub use utils::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/attributes.rs | src/core/src/club/player/attributes.rs | pub const CONDITION_MAX_VALUE: i16 = 10000;
#[derive(Debug, Clone, Copy, Default)]
pub struct PlayerAttributes {
pub is_banned: bool,
pub is_injured: bool,
pub condition: i16,
pub fitness: i16,
pub jadedness: i16,
pub weight: u8,
pub height: u8,
pub value: u32,
//reputation
pub current_reputation: i16,
pub home_reputation: i16,
pub world_reputation: i16,
//ability
pub current_ability: u8,
pub potential_ability: u8,
//international expirience
pub international_apps: u16,
pub international_goals: u16,
pub under_21_international_apps: u16,
pub under_21_international_goals: u16,
}
impl PlayerAttributes {
pub fn rest(&mut self, val: u16) {
self.condition += val as i16;
if self.condition > CONDITION_MAX_VALUE {
self.condition = CONDITION_MAX_VALUE;
}
}
pub fn condition_percentage(&self) -> u32 {
(self.condition as f32 * 100.0 / CONDITION_MAX_VALUE as f32).floor() as u32
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rest_increases_condition() {
let mut player_attributes = PlayerAttributes {
is_banned: false,
is_injured: false,
condition: 5000,
fitness: 8000,
jadedness: 2000,
weight: 75,
height: 180,
value: 1000000,
current_reputation: 50,
home_reputation: 60,
world_reputation: 70,
current_ability: 80,
potential_ability: 90,
international_apps: 10,
international_goals: 5,
under_21_international_apps: 15,
under_21_international_goals: 7,
};
player_attributes.rest(1000);
assert_eq!(player_attributes.condition, 6000);
}
#[test]
fn test_rest_does_not_exceed_max_condition() {
let mut player_attributes = PlayerAttributes {
is_banned: false,
is_injured: false,
condition: 9500,
fitness: 8000,
jadedness: 2000,
weight: 75,
height: 180,
value: 1000000,
current_reputation: 50,
home_reputation: 60,
world_reputation: 70,
current_ability: 80,
potential_ability: 90,
international_apps: 10,
international_goals: 5,
under_21_international_apps: 15,
under_21_international_goals: 7,
};
player_attributes.rest(1000);
assert_eq!(player_attributes.condition, CONDITION_MAX_VALUE);
}
#[test]
fn test_condition_percentage() {
let player_attributes = PlayerAttributes {
is_banned: false,
is_injured: false,
condition: 7500,
fitness: 8000,
jadedness: 2000,
weight: 75,
height: 180,
value: 1000000,
current_reputation: 50,
home_reputation: 60,
world_reputation: 70,
current_ability: 80,
potential_ability: 90,
international_apps: 10,
international_goals: 5,
under_21_international_apps: 15,
under_21_international_goals: 7,
};
let condition_percentage = player_attributes.condition_percentage();
assert_eq!(condition_percentage, 75);
}
#[test]
fn test_condition_percentage_rounding() {
let player_attributes = PlayerAttributes {
is_banned: false,
is_injured: false,
condition: 7499,
fitness: 8000,
jadedness: 2000,
weight: 75,
height: 180,
value: 1000000,
current_reputation: 50,
home_reputation: 60,
world_reputation: 70,
current_ability: 80,
potential_ability: 90,
international_apps: 10,
international_goals: 5,
under_21_international_apps: 15,
under_21_international_goals: 7,
};
let condition_percentage = player_attributes.condition_percentage();
assert_eq!(condition_percentage, 74);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/position.rs | src/core/src/club/player/position.rs | use serde::Serialize;
use std::fmt::{Display, Formatter, Result};
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, PartialOrd, Serialize)]
pub enum PlayerPositionType {
Goalkeeper,
Sweeper,
DefenderLeft,
DefenderCenterLeft,
DefenderCenter,
DefenderCenterRight,
DefenderRight,
DefensiveMidfielder,
MidfielderLeft,
MidfielderCenterLeft,
MidfielderCenter,
MidfielderCenterRight,
MidfielderRight,
AttackingMidfielderLeft,
AttackingMidfielderCenter,
AttackingMidfielderRight,
WingbackLeft,
WingbackRight,
Striker,
ForwardLeft,
ForwardCenter,
ForwardRight,
}
impl Display for PlayerPositionType {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{:?}", self)
}
}
impl PlayerPositionType {
#[inline]
pub fn get_short_name(&self) -> &'static str {
match *self {
PlayerPositionType::Goalkeeper => "GK",
PlayerPositionType::Sweeper => "SW",
PlayerPositionType::DefenderLeft => "DL",
PlayerPositionType::DefenderCenterLeft => "DCL",
PlayerPositionType::DefenderCenter => "DC",
PlayerPositionType::DefenderCenterRight => "DCR",
PlayerPositionType::DefenderRight => "DR",
PlayerPositionType::DefensiveMidfielder => "DM",
PlayerPositionType::MidfielderLeft => "ML",
PlayerPositionType::MidfielderCenterLeft => "MCL",
PlayerPositionType::MidfielderCenter => "MC",
PlayerPositionType::MidfielderCenterRight => "MCR",
PlayerPositionType::MidfielderRight => "MR",
PlayerPositionType::AttackingMidfielderLeft => "AML",
PlayerPositionType::AttackingMidfielderCenter => "AMC",
PlayerPositionType::AttackingMidfielderRight => "AMR",
PlayerPositionType::WingbackLeft => "WL",
PlayerPositionType::WingbackRight => "WR",
PlayerPositionType::ForwardLeft => "FL",
PlayerPositionType::ForwardCenter => "FC",
PlayerPositionType::ForwardRight => "FR",
PlayerPositionType::Striker => "ST",
}
}
#[inline]
pub fn is_goalkeeper(&self) -> bool {
self.position_group() == PlayerFieldPositionGroup::Goalkeeper
}
#[inline]
pub fn is_defender(&self) -> bool {
self.position_group() == PlayerFieldPositionGroup::Defender
}
#[inline]
pub fn is_midfielder(&self) -> bool {
self.position_group() == PlayerFieldPositionGroup::Midfielder
}
#[inline]
pub fn is_forward(&self) -> bool {
self.position_group() == PlayerFieldPositionGroup::Forward
}
#[inline]
pub fn position_group(&self) -> PlayerFieldPositionGroup {
match *self {
PlayerPositionType::Goalkeeper => PlayerFieldPositionGroup::Goalkeeper,
PlayerPositionType::Sweeper |
PlayerPositionType::DefenderLeft |
PlayerPositionType::DefenderCenterLeft |
PlayerPositionType::DefenderCenter |
PlayerPositionType::DefenderCenterRight |
PlayerPositionType::DefenderRight |
PlayerPositionType::DefensiveMidfielder => PlayerFieldPositionGroup::Defender,
PlayerPositionType::MidfielderLeft |
PlayerPositionType::MidfielderCenterLeft |
PlayerPositionType::MidfielderCenter |
PlayerPositionType::MidfielderCenterRight |
PlayerPositionType::MidfielderRight |
PlayerPositionType::AttackingMidfielderLeft |
PlayerPositionType::AttackingMidfielderCenter |
PlayerPositionType::AttackingMidfielderRight |
PlayerPositionType::WingbackLeft |
PlayerPositionType::WingbackRight => PlayerFieldPositionGroup::Midfielder,
PlayerPositionType::ForwardLeft |
PlayerPositionType::ForwardCenter |
PlayerPositionType::ForwardRight |
PlayerPositionType::Striker => PlayerFieldPositionGroup::Forward,
}
}
}
#[derive(Debug)]
pub struct PlayerPositions {
pub positions: Vec<PlayerPosition>,
}
const REQUIRED_POSITION_LEVEL: u8 = 15;
impl PlayerPositions {
pub fn positions(&self) -> Vec<PlayerPositionType> {
self.positions
.iter()
.filter(|p| p.level >= REQUIRED_POSITION_LEVEL)
.map(|p| p.position)
.collect()
}
pub fn display_positions(&self) -> Vec<&str> {
self.positions()
.iter()
.map(|p| p.get_short_name())
.collect()
}
pub fn has_position(&self, position: PlayerPositionType) -> bool {
self.positions().contains(&position)
}
pub fn is_goalkeeper(&self) -> bool {
self.positions().contains(&PlayerPositionType::Goalkeeper)
}
pub fn get_level(&self, position: PlayerPositionType) -> u8 {
match self.positions.iter().find(|p| p.position == position) {
Some(p) => p.level,
None => 0,
}
}
}
#[derive(Debug)]
pub struct PlayerPosition {
pub position: PlayerPositionType,
pub level: u8,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_position_names_is_correct() {
assert_eq!("GK", PlayerPositionType::Goalkeeper.get_short_name());
assert_eq!("SW", PlayerPositionType::Sweeper.get_short_name());
assert_eq!("DL", PlayerPositionType::DefenderLeft.get_short_name());
assert_eq!("DC", PlayerPositionType::DefenderCenter.get_short_name());
assert_eq!("DR", PlayerPositionType::DefenderRight.get_short_name());
assert_eq!(
"DM",
PlayerPositionType::DefensiveMidfielder.get_short_name()
);
assert_eq!("ML", PlayerPositionType::MidfielderLeft.get_short_name());
assert_eq!("MC", PlayerPositionType::MidfielderCenter.get_short_name());
assert_eq!("MR", PlayerPositionType::MidfielderRight.get_short_name());
assert_eq!(
"AML",
PlayerPositionType::AttackingMidfielderLeft.get_short_name()
);
assert_eq!(
"AMC",
PlayerPositionType::AttackingMidfielderCenter.get_short_name()
);
assert_eq!(
"AMR",
PlayerPositionType::AttackingMidfielderRight.get_short_name()
);
assert_eq!("ST", PlayerPositionType::Striker.get_short_name());
assert_eq!("WL", PlayerPositionType::WingbackLeft.get_short_name());
assert_eq!("WR", PlayerPositionType::WingbackRight.get_short_name());
}
#[test]
fn display_positions_return_with_over_15_level() {
let positions = PlayerPositions {
positions: vec![
PlayerPosition {
position: PlayerPositionType::Goalkeeper,
level: 1,
},
PlayerPosition {
position: PlayerPositionType::Sweeper,
level: 10,
},
PlayerPosition {
position: PlayerPositionType::Striker,
level: 14,
},
PlayerPosition {
position: PlayerPositionType::WingbackLeft,
level: 15,
},
PlayerPosition {
position: PlayerPositionType::WingbackRight,
level: 20,
},
],
};
let display_positions = positions.display_positions().join(",");
assert_eq!("WL,WR", display_positions);
}
}
#[derive(PartialEq, Debug)]
pub enum PlayerFieldPositionGroup {
Goalkeeper,
Defender,
Midfielder,
Forward,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/context.rs | src/core/src/club/player/context.rs | #[derive(Clone)]
pub struct PlayerContext {
pub id: Option<u32>,
}
impl PlayerContext {
pub fn new(id: Option<u32>) -> Self {
PlayerContext { id }
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/skills.rs | src/core/src/club/player/skills.rs | #[derive(Debug, Copy, Clone, Default)]
pub struct PlayerSkills {
pub technical: Technical,
pub mental: Mental,
pub physical: Physical,
}
impl PlayerSkills {
/// Calculate maximum speed without condition factor (raw speed based on skills only)
pub fn max_speed(&self) -> f32 {
let pace_factor = (self.physical.pace as f32 - 1.0) / 19.0;
let acceleration_factor = (self.physical.acceleration as f32 - 1.0) / 19.0;
let agility_factor = (self.physical.agility as f32 - 1.0) / 19.0;
let balance_factor = (self.physical.balance as f32 - 1.0) / 19.0;
let base_speed = 1.1; // Increased by 2x from 1.3 to 2.6 for faster gameplay
let max_speed = base_speed
* (0.6 * pace_factor
+ 0.2 * acceleration_factor
+ 0.1 * agility_factor
+ 0.1 * balance_factor);
max_speed
}
/// Calculate maximum speed with condition factor (real-time performance)
/// This is what should be used during match for actual speed calculation
/// Speed depends primarily (90%) on condition, with minimal stamina influence (10%)
pub fn max_speed_with_condition(&self, condition: i16) -> f32 {
let base_max_speed = self.max_speed();
// Condition is the primary factor (0-10000 scale)
let condition_percentage = (condition as f32 / 10000.0).clamp(0.0, 1.0);
// Stamina provides minimal resistance to fatigue (0-10% boost when tired)
// High stamina players maintain 90-100% speed at low condition
// Low stamina players drop to 80-100% speed at low condition
let stamina_normalized = (self.physical.stamina / 20.0).clamp(0.0, 1.0);
let stamina_protection = stamina_normalized * 0.10; // Max 10% protection
// Simple linear condition curve with stamina protection
// At 100% condition: 100% speed (regardless of stamina)
// At 50% condition: 50-60% speed (depending on stamina)
// At 0% condition: 10-20% speed (minimum + stamina protection)
let condition_factor = (condition_percentage * (1.0 - stamina_protection) + stamina_protection)
.clamp(0.10, 1.0);
base_max_speed * condition_factor
}
}
#[derive(Debug, Copy, Clone, Default)]
pub struct Technical {
pub corners: f32,
pub crossing: f32,
pub dribbling: f32,
pub finishing: f32,
pub first_touch: f32,
pub free_kicks: f32,
pub heading: f32,
pub long_shots: f32,
pub long_throws: f32,
pub marking: f32,
pub passing: f32,
pub penalty_taking: f32,
pub tackling: f32,
pub technique: f32,
}
impl Technical {
pub fn average(&self) -> f32 {
(self.corners
+ self.crossing
+ self.dribbling
+ self.finishing
+ self.first_touch
+ self.free_kicks
+ self.heading
+ self.long_shots
+ self.long_throws
+ self.marking
+ self.passing
+ self.penalty_taking
+ self.tackling
+ self.technique)
/ 14.0
}
pub fn rest(&mut self) {}
}
#[derive(Debug, Copy, Clone, Default)]
pub struct Mental {
pub aggression: f32,
pub anticipation: f32,
pub bravery: f32,
pub composure: f32,
pub concentration: f32,
pub decisions: f32,
pub determination: f32,
pub flair: f32,
pub leadership: f32,
pub off_the_ball: f32,
pub positioning: f32,
pub teamwork: f32,
pub vision: f32,
pub work_rate: f32,
}
impl Mental {
pub fn average(&self) -> f32 {
(self.aggression
+ self.anticipation
+ self.bravery
+ self.composure
+ self.concentration
+ self.decisions
+ self.determination
+ self.flair
+ self.leadership
+ self.off_the_ball
+ self.positioning
+ self.teamwork
+ self.vision
+ self.work_rate)
/ 14.0
}
pub fn rest(&mut self) {}
}
#[derive(Debug, Copy, Clone, Default)]
pub struct Physical {
pub acceleration: f32,
pub agility: f32,
pub balance: f32,
pub jumping: f32,
pub natural_fitness: f32,
pub pace: f32,
pub stamina: f32,
pub strength: f32,
pub match_readiness: f32,
}
impl Physical {
pub fn average(&self) -> f32 {
(self.acceleration
+ self.agility
+ self.balance
+ self.jumping
+ self.natural_fitness
+ self.pace
+ self.stamina
+ self.strength)
/ 8.0
}
pub fn rest(&mut self) {}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_technical_average() {
let technical = Technical {
corners: 10.0,
crossing: 20.0,
dribbling: 30.0,
finishing: 40.0,
first_touch: 50.0,
free_kicks: 60.0,
heading: 70.0,
long_shots: 80.0,
long_throws: 90.0,
marking: 100.0,
passing: 110.0,
penalty_taking: 120.0,
tackling: 130.0,
technique: 140.0,
};
assert_eq!(technical.average(), 75.0); // (10 + 20 + 30 + 40 + 50 + 60 + 70 + 80 + 90 + 100 + 110 + 120 + 130 + 140) / 14
}
#[test]
fn test_technical_rest() {
let mut technical = Technical {
corners: 10.0,
crossing: 20.0,
dribbling: 30.0,
finishing: 40.0,
first_touch: 50.0,
free_kicks: 60.0,
heading: 70.0,
long_shots: 80.0,
long_throws: 90.0,
marking: 100.0,
passing: 110.0,
penalty_taking: 120.0,
tackling: 130.0,
technique: 140.0,
};
technical.rest();
// Since the rest method doesn't modify any fields, we'll just assert true to indicate it ran successfully
assert!(true);
}
#[test]
fn test_mental_average() {
let mental = Mental {
aggression: 10.0,
anticipation: 20.0,
bravery: 30.0,
composure: 40.0,
concentration: 50.0,
decisions: 60.0,
determination: 70.0,
flair: 80.0,
leadership: 90.0,
off_the_ball: 100.0,
positioning: 110.0,
teamwork: 120.0,
vision: 130.0,
work_rate: 140.0,
};
assert_eq!(mental.average(), 75.0); // (10 + 20 + 30 + 40 + 50 + 60 + 70 + 80 + 90 + 100 + 110 + 120 + 130 + 140) / 14
}
#[test]
fn test_mental_rest() {
let mut mental = Mental {
aggression: 10.0,
anticipation: 20.0,
bravery: 30.0,
composure: 40.0,
concentration: 50.0,
decisions: 60.0,
determination: 70.0,
flair: 80.0,
leadership: 90.0,
off_the_ball: 100.0,
positioning: 110.0,
teamwork: 120.0,
vision: 130.0,
work_rate: 140.0,
};
mental.rest();
// Since the rest method doesn't modify any fields, we'll just assert true to indicate it ran successfully
assert!(true);
}
#[test]
fn test_physical_average() {
let physical = Physical {
acceleration: 10.0,
agility: 20.0,
balance: 30.0,
jumping: 40.0,
natural_fitness: 50.0,
pace: 60.0,
stamina: 70.0,
strength: 80.0,
match_readiness: 90.0,
};
assert_eq!(physical.average(), 45.0); // (10 + 20 + 30 + 40 + 50 + 60 + 70 + 80) / 8
}
#[test]
fn test_physical_rest() {
let mut physical = Physical {
acceleration: 10.0,
agility: 20.0,
balance: 30.0,
jumping: 40.0,
natural_fitness: 50.0,
pace: 60.0,
stamina: 70.0,
strength: 80.0,
match_readiness: 90.0,
};
physical.rest();
// Since the rest method doesn't modify any fields, we'll just assert true to indicate it ran successfully
assert!(true);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/statistics.rs | src/core/src/club/player/statistics.rs | use crate::league::Season;
#[derive(Debug, Default)]
pub struct PlayerStatistics {
pub played: u16,
pub played_subs: u16,
pub goals: u16,
pub assists: u16,
pub penalties: u16,
pub player_of_the_match: u8,
pub yellow_cards: u8,
pub red_cards: u8,
pub shots_on_target: f32,
pub tackling: f32,
pub passes: u8,
pub average_rating: f32,
}
#[derive(Debug)]
pub struct PlayerStatisticsHistory {
pub items: Vec<PlayerStatisticsHistoryItem>,
}
#[derive(Debug)]
pub struct PlayerStatisticsHistoryItem {
pub season: Season,
pub statistics: PlayerStatistics,
}
impl Default for PlayerStatisticsHistory {
fn default() -> Self {
Self::new()
}
}
impl PlayerStatisticsHistory {
pub fn new() -> Self {
PlayerStatisticsHistory { items: Vec::new() }
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/generators/generator.rs | src/core/src/club/player/generators/generator.rs | use crate::shared::FullName;
use crate::utils::IntegerUtils;
use crate::{
Mental, PersonAttributes, PersonBehaviour, PersonBehaviourState, Physical, Player,
PlayerAttributes, PlayerHappiness, PlayerMailbox, PlayerPosition, PlayerPositionType,
PlayerPositions, PlayerPreferredFoot, PlayerSkills, PlayerStatistics, PlayerStatisticsHistory,
PlayerStatus, PlayerTraining, PlayerTrainingHistory, Relations, Technical,
};
use chrono::{Datelike, NaiveDate};
pub struct PlayerGenerator;
impl PlayerGenerator {
pub fn generate(
country_id: u32,
now: NaiveDate,
position: PlayerPositionType,
level: u8,
) -> Player {
let year = IntegerUtils::random(now.year() - 14, now.year() - 16) as u32;
let month = IntegerUtils::random(1, 12) as u32;
let day = IntegerUtils::random(1, 29) as u32;
let positions = PlayerPositions {
positions: vec![PlayerPosition { position, level }],
};
Player {
id: IntegerUtils::random(0, 100000) as u32,
full_name: FullName::with_full("".to_string(), "".to_string(), "".to_string()),
birth_date: NaiveDate::from_ymd_opt(year as i32, month, day).unwrap(),
country_id,
behaviour: PersonBehaviour {
state: PersonBehaviourState::Poor,
},
attributes: PersonAttributes {
adaptability: 10.0,
ambition: 10.0,
controversy: 10.0,
loyalty: 10.0,
pressure: 10.0,
professionalism: 10.0,
sportsmanship: 10.0,
temperament: 10.0,
},
happiness: PlayerHappiness::new(),
statuses: PlayerStatus { statuses: vec![] },
skills: PlayerSkills {
technical: Technical {
corners: 10.0,
crossing: 10.0,
dribbling: 10.0,
finishing: 10.0,
first_touch: 10.0,
free_kicks: 10.0,
heading: 10.0,
long_shots: 10.0,
long_throws: 10.0,
marking: 10.0,
passing: 10.0,
penalty_taking: 10.0,
tackling: 10.0,
technique: 10.0,
},
mental: Mental {
aggression: 10.0,
anticipation: 10.0,
bravery: 10.0,
composure: 10.0,
concentration: 10.0,
decisions: 10.0,
determination: 10.0,
flair: 10.0,
leadership: 10.0,
off_the_ball: 10.0,
positioning: 10.0,
teamwork: 10.0,
vision: 10.0,
work_rate: 10.0,
},
physical: Physical {
acceleration: 10.0,
agility: 10.0,
balance: 10.0,
jumping: 10.0,
natural_fitness: 10.0,
pace: 10.0,
stamina: 10.0,
strength: 10.0,
match_readiness: 10.0,
},
},
contract: Option::None,
positions,
preferred_foot: PlayerPreferredFoot::Left,
player_attributes: PlayerAttributes {
is_banned: false,
is_injured: false,
condition: 10000,
fitness: 0,
jadedness: 0,
weight: 0,
height: 0,
value: 0,
current_reputation: 0,
home_reputation: 1000,
world_reputation: 1000,
current_ability: 0,
potential_ability: 0,
international_apps: 0,
international_goals: 0,
under_21_international_apps: 0,
under_21_international_goals: 0,
},
mailbox: PlayerMailbox::new(),
training: PlayerTraining::new(),
training_history: PlayerTrainingHistory::new(),
relations: Relations::new(),
statistics: PlayerStatistics::default(),
statistics_history: PlayerStatisticsHistory::new(),
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/generators/mod.rs | src/core/src/club/player/generators/mod.rs | mod generator;
pub use generator::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/training/training.rs | src/core/src/club/player/training/training.rs | use crate::club::player::training::result::PlayerTrainingResult;
use crate::{MentalGains, Person, PhysicalGains, Player, Staff, TechnicalGains, TrainingEffects, TrainingIntensity, TrainingSession, TrainingType};
use chrono::NaiveDateTime;
#[derive(Debug)]
pub struct PlayerTraining {}
impl Default for PlayerTraining {
fn default() -> Self {
Self::new()
}
}
impl PlayerTraining {
pub fn new() -> Self {
PlayerTraining {}
}
pub fn train(
player: &Player,
coach: &Staff,
session: &TrainingSession,
date: NaiveDateTime,
) -> PlayerTrainingResult {
let mut effects = TrainingEffects {
physical_gains: PhysicalGains::default(),
technical_gains: TechnicalGains::default(),
mental_gains: MentalGains::default(),
fatigue_change: 0.0,
injury_risk: 0.0,
morale_change: 0.0,
};
// Base effectiveness factors
let coach_quality = Self::calculate_coach_effectiveness(coach, &session.session_type);
let player_receptiveness = Self::calculate_player_receptiveness(player, coach);
let age_factor = Self::calculate_age_training_factor(player.age(date.date()));
// Intensity multipliers
let intensity_multiplier = match session.intensity {
TrainingIntensity::VeryLight => 0.3,
TrainingIntensity::Light => 0.5,
TrainingIntensity::Moderate => 1.0,
TrainingIntensity::High => 1.5,
TrainingIntensity::VeryHigh => 2.0,
};
// Calculate gains based on training type
match session.session_type {
TrainingType::Endurance => {
effects.physical_gains.stamina = 0.05 * coach_quality * player_receptiveness * age_factor;
effects.physical_gains.natural_fitness = 0.03 * coach_quality * player_receptiveness * age_factor;
effects.fatigue_change = 15.0 * intensity_multiplier;
effects.injury_risk = 0.02 * intensity_multiplier;
}
TrainingType::Strength => {
effects.physical_gains.strength = 0.04 * coach_quality * player_receptiveness * age_factor;
effects.physical_gains.jumping = 0.02 * coach_quality * player_receptiveness * age_factor;
effects.fatigue_change = 20.0 * intensity_multiplier;
effects.injury_risk = 0.03 * intensity_multiplier;
}
TrainingType::Speed => {
effects.physical_gains.pace = 0.03 * coach_quality * player_receptiveness * age_factor;
effects.physical_gains.agility = 0.04 * coach_quality * player_receptiveness * age_factor;
effects.fatigue_change = 25.0 * intensity_multiplier;
effects.injury_risk = 0.04 * intensity_multiplier;
}
TrainingType::BallControl => {
effects.technical_gains.first_touch = 0.05 * coach_quality * player_receptiveness;
effects.technical_gains.technique = 0.04 * coach_quality * player_receptiveness;
effects.technical_gains.dribbling = 0.03 * coach_quality * player_receptiveness;
effects.fatigue_change = 10.0 * intensity_multiplier;
effects.injury_risk = 0.01 * intensity_multiplier;
}
TrainingType::Passing => {
effects.technical_gains.passing = 0.06 * coach_quality * player_receptiveness;
effects.mental_gains.vision = 0.02 * coach_quality * player_receptiveness;
effects.fatigue_change = 8.0 * intensity_multiplier;
effects.injury_risk = 0.01 * intensity_multiplier;
}
TrainingType::Shooting => {
effects.technical_gains.finishing = 0.05 * coach_quality * player_receptiveness;
effects.technical_gains.technique = 0.02 * coach_quality * player_receptiveness;
effects.mental_gains.decisions = 0.01 * coach_quality * player_receptiveness;
effects.fatigue_change = 12.0 * intensity_multiplier;
effects.injury_risk = 0.02 * intensity_multiplier;
}
TrainingType::Positioning => {
effects.mental_gains.positioning = 0.06 * coach_quality * player_receptiveness;
effects.mental_gains.concentration = 0.03 * coach_quality * player_receptiveness;
effects.mental_gains.decisions = 0.02 * coach_quality * player_receptiveness;
effects.fatigue_change = 5.0 * intensity_multiplier;
effects.injury_risk = 0.005 * intensity_multiplier;
}
TrainingType::TeamShape => {
effects.mental_gains.teamwork = 0.05 * coach_quality * player_receptiveness;
effects.mental_gains.positioning = 0.04 * coach_quality * player_receptiveness;
effects.mental_gains.work_rate = 0.02 * coach_quality * player_receptiveness;
effects.fatigue_change = 10.0 * intensity_multiplier;
effects.injury_risk = 0.01 * intensity_multiplier;
effects.morale_change = 0.1; // Team activities boost morale
}
TrainingType::Recovery => {
effects.fatigue_change = -30.0; // Negative means recovery
effects.injury_risk = -0.02; // Reduces injury risk
effects.morale_change = 0.05;
}
TrainingType::VideoAnalysis => {
effects.mental_gains.decisions = 0.03 * coach_quality;
effects.mental_gains.positioning = 0.02 * coach_quality;
effects.mental_gains.vision = 0.02 * coach_quality;
effects.fatigue_change = 0.0;
effects.injury_risk = 0.0;
}
_ => {
// Default minimal gains for unspecified training types
effects.fatigue_change = 10.0 * intensity_multiplier;
effects.injury_risk = 0.01 * intensity_multiplier;
}
}
// Apply player condition modifiers
let condition_factor = player.player_attributes.condition_percentage() as f32 / 100.0;
if condition_factor < 0.7 {
effects.injury_risk *= 1.5; // Higher injury risk when tired
effects.fatigue_change *= 1.2; // Get tired faster when already fatigued
}
// Apply professionalism bonus to gains
let professionalism_bonus = player.attributes.professionalism / 20.0;
effects.physical_gains = Self::apply_bonus_to_physical(effects.physical_gains, professionalism_bonus);
effects.technical_gains = Self::apply_bonus_to_technical(effects.technical_gains, professionalism_bonus);
effects.mental_gains = Self::apply_bonus_to_mental(effects.mental_gains, professionalism_bonus);
PlayerTrainingResult::new(player.id, effects)
}
fn apply_bonus_to_physical(mut gains: PhysicalGains, bonus: f32) -> PhysicalGains {
gains.stamina *= 1.0 + bonus;
gains.strength *= 1.0 + bonus;
gains.pace *= 1.0 + bonus;
gains.agility *= 1.0 + bonus;
gains.balance *= 1.0 + bonus;
gains.jumping *= 1.0 + bonus;
gains.natural_fitness *= 1.0 + bonus;
gains
}
fn apply_bonus_to_technical(mut gains: TechnicalGains, bonus: f32) -> TechnicalGains {
gains.first_touch *= 1.0 + bonus;
gains.passing *= 1.0 + bonus;
gains.crossing *= 1.0 + bonus;
gains.dribbling *= 1.0 + bonus;
gains.finishing *= 1.0 + bonus;
gains.heading *= 1.0 + bonus;
gains.tackling *= 1.0 + bonus;
gains.technique *= 1.0 + bonus;
gains
}
fn apply_bonus_to_mental(mut gains: MentalGains, bonus: f32) -> MentalGains {
gains.concentration *= 1.0 + bonus;
gains.decisions *= 1.0 + bonus;
gains.positioning *= 1.0 + bonus;
gains.teamwork *= 1.0 + bonus;
gains.vision *= 1.0 + bonus;
gains.work_rate *= 1.0 + bonus;
gains.leadership *= 1.0 + bonus;
gains
}
fn calculate_coach_effectiveness(coach: &Staff, training_type: &TrainingType) -> f32 {
let base_effectiveness = match training_type {
TrainingType::Endurance | TrainingType::Strength | TrainingType::Speed => {
coach.staff_attributes.coaching.fitness as f32 / 20.0
}
TrainingType::BallControl | TrainingType::Passing | TrainingType::Shooting => {
coach.staff_attributes.coaching.technical as f32 / 20.0
}
TrainingType::Positioning | TrainingType::TeamShape => {
coach.staff_attributes.coaching.tactical as f32 / 20.0
}
TrainingType::Concentration | TrainingType::DecisionMaking => {
coach.staff_attributes.coaching.mental as f32 / 20.0
}
_ => {
// Average of all coaching attributes
(coach.staff_attributes.coaching.attacking +
coach.staff_attributes.coaching.defending +
coach.staff_attributes.coaching.tactical +
coach.staff_attributes.coaching.technical) as f32 / 80.0
}
};
// Add determination factor
let determination_factor = coach.staff_attributes.mental.determination as f32 / 20.0;
(base_effectiveness * 0.7 + determination_factor * 0.3).min(1.0)
}
fn calculate_player_receptiveness(player: &Player, coach: &Staff) -> f32 {
// Base receptiveness from player attributes
let base = (player.attributes.professionalism + player.attributes.ambition) / 40.0;
// Relationship with coach affects receptiveness
let relationship_bonus = if coach.relations.is_favorite_player(player.id) {
0.2
} else if coach.relations.get_player(player.id).map_or(false, |r| r.level < -50.0) {
-0.2
} else {
0.0
};
// Age affects receptiveness (younger players learn faster)
let age_bonus = match player.age(chrono::Local::now().date_naive()) {
16..=20 => 0.3,
21..=24 => 0.2,
25..=28 => 0.1,
29..=32 => 0.0,
_ => -0.1,
};
(base + relationship_bonus + age_bonus).clamp(0.1, 1.5)
}
fn calculate_age_training_factor(age: u8) -> f32 {
match age {
16..=18 => 1.5, // Youth develop quickly
19..=21 => 1.3,
22..=24 => 1.1,
25..=27 => 1.0,
28..=30 => 0.8,
31..=33 => 0.5,
34..=36 => 0.3,
_ => 0.1, // Very old players barely improve
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/training/result.rs | src/core/src/club/player/training/result.rs | use crate::{MentalGains, PhysicalGains, SimulatorData, TechnicalGains, TrainingEffects};
pub struct PlayerTrainingResult {
pub player_id: u32,
pub effects: TrainingEffects,
}
impl PlayerTrainingResult {
pub fn new(player_id: u32, effects: TrainingEffects) -> Self {
PlayerTrainingResult {
player_id,
effects,
}
}
pub fn empty(player_id: u32) -> Self {
PlayerTrainingResult {
player_id,
effects: TrainingEffects {
physical_gains: PhysicalGains::default(),
technical_gains: TechnicalGains::default(),
mental_gains: MentalGains::default(),
fatigue_change: 0.0,
injury_risk: 0.0,
morale_change: 0.0,
},
}
}
/// Apply the training effects to the player
/// This is where the actual skill updates happen with mutable references
pub fn process(&self, data: &mut SimulatorData) {
// Get mutable reference to the player
if let Some(player) = data.player_mut(self.player_id) {
// Apply physical gains
player.skills.physical.stamina = (player.skills.physical.stamina + self.effects.physical_gains.stamina).min(20.0);
player.skills.physical.strength = (player.skills.physical.strength + self.effects.physical_gains.strength).min(20.0);
player.skills.physical.pace = (player.skills.physical.pace + self.effects.physical_gains.pace).min(20.0);
player.skills.physical.agility = (player.skills.physical.agility + self.effects.physical_gains.agility).min(20.0);
player.skills.physical.balance = (player.skills.physical.balance + self.effects.physical_gains.balance).min(20.0);
player.skills.physical.jumping = (player.skills.physical.jumping + self.effects.physical_gains.jumping).min(20.0);
player.skills.physical.natural_fitness = (player.skills.physical.natural_fitness + self.effects.physical_gains.natural_fitness).min(20.0);
// Apply technical gains
player.skills.technical.first_touch = (player.skills.technical.first_touch + self.effects.technical_gains.first_touch).min(20.0);
player.skills.technical.passing = (player.skills.technical.passing + self.effects.technical_gains.passing).min(20.0);
player.skills.technical.crossing = (player.skills.technical.crossing + self.effects.technical_gains.crossing).min(20.0);
player.skills.technical.dribbling = (player.skills.technical.dribbling + self.effects.technical_gains.dribbling).min(20.0);
player.skills.technical.finishing = (player.skills.technical.finishing + self.effects.technical_gains.finishing).min(20.0);
player.skills.technical.heading = (player.skills.technical.heading + self.effects.technical_gains.heading).min(20.0);
player.skills.technical.tackling = (player.skills.technical.tackling + self.effects.technical_gains.tackling).min(20.0);
player.skills.technical.technique = (player.skills.technical.technique + self.effects.technical_gains.technique).min(20.0);
// Apply mental gains
player.skills.mental.concentration = (player.skills.mental.concentration + self.effects.mental_gains.concentration).min(20.0);
player.skills.mental.decisions = (player.skills.mental.decisions + self.effects.mental_gains.decisions).min(20.0);
player.skills.mental.positioning = (player.skills.mental.positioning + self.effects.mental_gains.positioning).min(20.0);
player.skills.mental.teamwork = (player.skills.mental.teamwork + self.effects.mental_gains.teamwork).min(20.0);
player.skills.mental.vision = (player.skills.mental.vision + self.effects.mental_gains.vision).min(20.0);
player.skills.mental.work_rate = (player.skills.mental.work_rate + self.effects.mental_gains.work_rate).min(20.0);
player.skills.mental.leadership = (player.skills.mental.leadership + self.effects.mental_gains.leadership).min(20.0);
// Apply fatigue changes
let new_condition = player.player_attributes.condition as f32 - self.effects.fatigue_change;
player.player_attributes.condition = new_condition.clamp(0.0, 10000.0) as i16;
// Apply injury risk (simplified)
if rand::random::<f32>() < self.effects.injury_risk {
player.player_attributes.is_injured = true;
// You might want to add more injury details here
}
// Update match readiness based on training
if self.effects.fatigue_change < 0.0 {
// Recovery training improves match readiness
player.skills.physical.match_readiness = (player.skills.physical.match_readiness + 2.0).min(20.0);
} else if self.effects.fatigue_change > 20.0 {
// Intense training reduces match readiness
player.skills.physical.match_readiness = (player.skills.physical.match_readiness - 1.0).max(0.0);
}
// Apply morale changes to happiness (simplified)
// You might want to integrate this with your happiness system
if self.effects.morale_change > 0.0 {
// Positive morale change could improve behavior
if rand::random::<f32>() < self.effects.morale_change {
player.behaviour.try_increase();
}
}
// Record training in history (if you implement this)
// player.training_history.add_record(TrainingRecord {
// date: data.date,
// skills: player.skills.clone(),
// });
}
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/training/history.rs | src/core/src/club/player/training/history.rs | use crate::PlayerSkills;
use chrono::{NaiveDate, NaiveDateTime};
#[derive(Debug)]
pub struct PlayerTrainingHistory {
records: Vec<TrainingRecord>,
}
impl PlayerTrainingHistory {
pub fn new() -> Self {
PlayerTrainingHistory {
records: Vec::new(),
}
}
pub fn add_record(&mut self, record: TrainingRecord) {
self.records.push(record);
}
pub fn get_latest_record(&self) -> Option<&TrainingRecord> {
self.records.last()
}
pub fn weeks_since_last_training(&self, now: NaiveDate) -> u32 {
let mut weeks_since_last_training: u32 = 0;
if let Some(last_training_record) = self.records.last() {
let duration = now.signed_duration_since(last_training_record.date.date());
weeks_since_last_training = duration.num_weeks() as u32;
}
weeks_since_last_training
}
}
#[derive(Debug)]
pub struct TrainingRecord {
date: NaiveDateTime,
_skills: PlayerSkills,
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.