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/midfielders/states/intercepting/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/intercepting/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::{ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior}; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderInterceptingState {} impl StateProcessingHandler for MidfielderInterceptingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } if ctx.team().is_control_ball() { if ctx.ball().distance() > 150.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )); } } else { if ctx.ball().distance() < 30.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Tackling, )); } if !self.can_reach_before_opponent(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::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 high intensity - sustained running to catch the ball MidfielderCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl MidfielderInterceptingState { 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/midfielders/states/attack_supporting/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/attack_supporting/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::{ ConditionContext, MatchPlayerLite, PlayerDistanceFromStartPosition, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; const TACKLE_RANGE: f32 = 30.0; const PRESS_RANGE: f32 = 100.0; const ATTACK_SUPPORT_TIME_LIMIT: u64 = 300; const CHANNEL_WIDTH: f32 = 15.0; // Width of vertical channels for runs #[derive(Default)] pub struct MidfielderAttackSupportingState {} impl StateProcessingHandler for MidfielderAttackSupportingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // If player has the ball, transition to running with ball if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } // If team loses possession, switch to defensive duties if !ctx.team().is_control_ball() { if ctx.ball().distance() < TACKLE_RANGE { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Tackling, )); } if ctx.ball().distance() < PRESS_RANGE && ctx.ball().is_towards_player_with_angle(0.8) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } return Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )); } // Team has possession - continue supporting if ctx.ball().is_towards_player_with_angle(0.8) && ctx.ball().distance() < 100.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Intercepting, )); } // Check if we should make a late run into the box if self.should_make_late_box_run(ctx) { // Continue in this state but with more aggressive positioning return None; } // If ball is too far, actively create space if ctx.ball().distance() > 300.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::CreatingSpace, )); } // Timeout check if ctx.in_state_time > ATTACK_SUPPORT_TIME_LIMIT { if ctx.player().position_to_distance() == PlayerDistanceFromStartPosition::Big { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )); } return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { let ball_position = ctx.tick_context.positions.ball.position; let ball_distance = ctx.ball().distance(); // Check if we have the ball - if so, drive forward if ctx.player.has_ball(ctx) { return Some(self.calculate_ball_carrying_velocity(ctx)); } // Key change: Don't run to the ball if a teammate has it if let Some(ball_owner_id) = ctx.ball().owner_id() { if let Some(ball_owner) = ctx.context.players.by_id(ball_owner_id) { if ball_owner.team_id == ctx.player.team_id { // Teammate has ball - make attacking run instead of clustering let target_position = self.calculate_attacking_run_position(ctx); // Vary speed based on situation let urgency_factor = self.calculate_urgency_factor(ctx); let slowing_distance = 20.0 * (1.0 - urgency_factor * 0.3); return Some( SteeringBehavior::Arrive { target: target_position, slowing_distance, } .calculate(ctx.player) .velocity + ctx.player().separation_velocity() * 1.5, // Increase separation ); } } } // Ball is loose or opponent has it - only pursue if we're closest if !ctx.team().is_control_ball() || !ctx.ball().is_owned() { if ctx.team().is_best_player_to_chase_ball() && ball_distance < 100.0 { // We're best positioned - go get the ball return Some( SteeringBehavior::Pursuit { target: ball_position, target_velocity: ctx.tick_context.positions.ball.velocity, } .calculate(ctx.player) .velocity, ); } } // Default: Make intelligent supporting run let target_position = self.calculate_optimal_support_position(ctx); // Adjust speed based on urgency let urgency_factor = self.calculate_urgency_factor(ctx); let slowing_distance = 30.0 * (1.0 - urgency_factor * 0.5); Some( SteeringBehavior::Arrive { target: target_position, slowing_distance, } .calculate(ctx.player) .velocity + ctx.player().separation_velocity(), ) } fn process_conditions(&self, ctx: ConditionContext) { // Attack supporting is high intensity - sustained running to support attacks MidfielderCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl MidfielderAttackSupportingState { // Add new helper method for attacking runs when teammate has ball fn calculate_attacking_run_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_position = ctx.tick_context.positions.ball.position; let player_position = ctx.player.position; let goal_position = 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; // Determine attacking direction let attacking_direction = match ctx.player.side { Some(PlayerSide::Left) => 1.0, Some(PlayerSide::Right) => -1.0, None => 0.0, }; let distance_to_goal = (ball_position - goal_position).magnitude(); // Different run types based on position and situation let run_type = self.determine_run_type(ctx, distance_to_goal); match run_type { AttackingRunType::ThroughBall => { // Run beyond the defensive line toward goal let advanced_position = Vector3::new( goal_position.x - (attacking_direction * 120.0), player_position.y + self.calculate_lateral_run_adjustment(ctx), 0.0, ); // Check offside risk and adjust if self.is_offside_risk(ctx, advanced_position) { Vector3::new( advanced_position.x - (attacking_direction * 20.0), advanced_position.y, 0.0, ).clamp_to_field(field_width, field_height) } else { advanced_position.clamp_to_field(field_width, field_height) } } AttackingRunType::OverlapRun => { // Wide overlapping run let side_adjustment = if player_position.y < field_height / 2.0 { -field_height * 0.35 // Go to left flank } else { field_height * 0.35 // Go to right flank }; Vector3::new( ball_position.x + (attacking_direction * 60.0), field_height / 2.0 + side_adjustment, 0.0, ).clamp_to_field(field_width, field_height) } AttackingRunType::LateBoxRun => { // Late run into the box let box_entry_point = self.find_box_entry_point(ctx, goal_position); box_entry_point.clamp_to_field(field_width, field_height) } AttackingRunType::SupportRun => { // Supporting run to create passing option let support_angle = if player_position.y < ball_position.y { -30.0_f32.to_radians() } else { 30.0_f32.to_radians() }; let support_distance = 40.0; let support_offset = Vector3::new( support_distance * support_angle.cos() * attacking_direction, support_distance * support_angle.sin(), 0.0, ); (ball_position + support_offset).clamp_to_field(field_width, field_height) } AttackingRunType::DiagonalRun => { // Diagonal run to exploit space between defenders let diagonal_target = Vector3::new( ball_position.x + (attacking_direction * 70.0), player_position.y + if player_position.y < field_height / 2.0 { 40.0 } else { -40.0 }, 0.0, ); diagonal_target.clamp_to_field(field_width, field_height) } } } // Add new helper to determine run type fn determine_run_type(&self, ctx: &StateProcessingContext, distance_to_goal: f32) -> AttackingRunType { let field_width = ctx.context.field_size.width as f32; let player_skills = &ctx.player.skills; // Player attributes affect run selection let pace = player_skills.physical.pace; let off_the_ball = player_skills.mental.off_the_ball; let anticipation = player_skills.mental.anticipation; // Close to goal - make decisive runs if distance_to_goal < field_width * 0.25 { if off_the_ball > 14.0 && pace > 14.0 { AttackingRunType::ThroughBall } else if anticipation > 13.0 { AttackingRunType::LateBoxRun } else { AttackingRunType::SupportRun } } // Middle third - varied runs else if distance_to_goal < field_width * 0.5 { let has_space_wide = self.check_wide_space(ctx); if has_space_wide && pace > 13.0 { AttackingRunType::OverlapRun } else if off_the_ball > 12.0 { AttackingRunType::DiagonalRun } else { AttackingRunType::SupportRun } } // Build-up phase - support play else { AttackingRunType::SupportRun } } // Add helper to calculate lateral adjustment for runs fn calculate_lateral_run_adjustment(&self, ctx: &StateProcessingContext) -> f32 { let field_height = ctx.context.field_size.height as f32; let player_y = ctx.player.position.y; // Check defender positioning let defenders_central = ctx.players().opponents().all() .filter(|opp| { opp.tactical_positions.is_defender() && (opp.position.y - field_height / 2.0).abs() < field_height * 0.2 }) .count(); // If defenders are concentrated centrally, make wider runs if defenders_central >= 2 { if player_y < field_height / 2.0 { -30.0 // Go wider left } else { 30.0 // Go wider right } } else { // Make central runs if space exists if (player_y - field_height / 2.0).abs() > field_height * 0.25 { if player_y < field_height / 2.0 { 20.0 // Come inside from left } else { -20.0 // Come inside from right } } else { 0.0 } } } // Add helper to find best box entry point fn find_box_entry_point(&self, ctx: &StateProcessingContext, goal_position: Vector3<f32>) -> Vector3<f32> { let field_height = ctx.context.field_size.height as f32; // Identify gaps in the box let box_defenders = ctx.players().opponents().all() .filter(|opp| { let dist_to_goal = (opp.position - goal_position).magnitude(); dist_to_goal < 200.0 && opp.tactical_positions.is_defender() }) .collect::<Vec<_>>(); // Find best entry point based on defender positions if box_defenders.is_empty() { // No defenders - go straight to goal Vector3::new( goal_position.x - 100.0, goal_position.y, 0.0, ) } else { // Find gap between defenders let mut best_gap_y = goal_position.y; let mut max_gap_size = 0.0; for window in box_defenders.windows(2) { let gap_y = (window[0].position.y + window[1].position.y) / 2.0; let gap_size = (window[1].position.y - window[0].position.y).abs(); if gap_size > max_gap_size { max_gap_size = gap_size; best_gap_y = gap_y; } } // Also check edges let edge_gap_top = field_height * 0.35 - box_defenders.first().map(|d| d.position.y).unwrap_or(0.0); let edge_gap_bottom = field_height * 0.65 - box_defenders.last().map(|d| d.position.y).unwrap_or(field_height); if edge_gap_top > max_gap_size { best_gap_y = goal_position.y - 80.0; } else if edge_gap_bottom > max_gap_size { best_gap_y = goal_position.y + 80.0; } Vector3::new( goal_position.x - 150.0, best_gap_y, 0.0, ) } } // Add helper to check wide space availability fn check_wide_space(&self, ctx: &StateProcessingContext) -> bool { let field_height = ctx.context.field_size.height as f32; let player_y = ctx.player.position.y; // Determine which flank to check let flank_y = if player_y < field_height / 2.0 { field_height * 0.15 // Left flank } else { field_height * 0.85 // Right flank }; // Count opponents in wide area let opponents_wide = ctx.players().opponents().all() .filter(|opp| (opp.position.y - flank_y).abs() < 30.0) .count(); opponents_wide < 2 } // Add method for ball carrying when midfielder has possession fn calculate_ball_carrying_velocity(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let goal_position = ctx.player().opponent_goal_position(); let player_position = ctx.player.position; let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; // Check pressure let under_pressure = ctx.players().opponents().exists(15.0); if under_pressure { // Under pressure - make quick decision if ctx.player().has_clear_shot() && ctx.ball().distance_to_opponent_goal() < 250.0 { // Face goal for shot let to_goal = (goal_position - player_position).normalize(); return to_goal * 2.0; } // Look for outlet pass by turning away from pressure let nearest_opponent = ctx.players().opponents().nearby(15.0).next(); if let Some(opponent) = nearest_opponent { let away_from_pressure = (player_position - opponent.position).normalize(); return away_from_pressure * 3.0; } } // Not under immediate pressure - drive forward intelligently let attacking_direction = match ctx.player.side { Some(PlayerSide::Left) => 1.0, Some(PlayerSide::Right) => -1.0, None => 0.0, }; // Find space to drive into let forward_space = Vector3::new( player_position.x + (attacking_direction * 40.0), player_position.y, 0.0, ); // Check if forward space is clear let forward_clear = !ctx.players().opponents().all() .any(|opp| (opp.position - forward_space).magnitude() < 20.0); if forward_clear { // Drive forward with pace let drive_speed = ctx.player.skills.physical.pace * 0.35; SteeringBehavior::Seek { target: goal_position, } .calculate(ctx.player) .velocity * (drive_speed / ctx.player.skills.max_speed_with_condition( ctx.player.player_attributes.condition, )) } else { // Space blocked - move laterally to find space let lateral_target = Vector3::new( player_position.x + (attacking_direction * 20.0), if player_position.y < field_height / 2.0 { player_position.y + 30.0 } else { player_position.y - 30.0 }, 0.0, ).clamp_to_field(field_width, field_height); SteeringBehavior::Arrive { target: lateral_target, slowing_distance: 10.0, } .calculate(ctx.player) .velocity } } /// Calculate the optimal position to support the attack fn calculate_optimal_support_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_position = ctx.tick_context.positions.ball.position; let _player_position = ctx.player.position; let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; // Determine attacking direction let attacking_direction = match ctx.player.side { Some(PlayerSide::Left) => 1.0, Some(PlayerSide::Right) => -1.0, None => 0.0, }; let goal_position = ctx.player().opponent_goal_position(); let distance_to_goal = (ball_position - goal_position).magnitude(); // Different support strategies based on attacking phase if distance_to_goal < field_width * 0.25 { // Final third - make late runs into the box self.calculate_late_box_run_position(ctx, attacking_direction, field_width, field_height) } else if distance_to_goal < field_width * 0.5 { // Middle attacking third - create passing triangles and support wide self.calculate_middle_third_support(ctx, attacking_direction, field_width, field_height) } else { // Build-up phase - provide passing options self.calculate_buildup_support_position(ctx, attacking_direction, field_width, field_height) } } /// Calculate position for late runs into the box fn calculate_late_box_run_position( &self, ctx: &StateProcessingContext, attacking_direction: f32, field_width: f32, field_height: f32, ) -> Vector3<f32> { let _ball_position = ctx.tick_context.positions.ball.position; let player_position = ctx.player.position; let goal_position = ctx.player().opponent_goal_position(); // Identify free channels between defenders let channels = self.identify_free_channels(ctx, goal_position); if let Some(best_channel) = channels.first() { // Run into the free channel let target_x = goal_position.x - (attacking_direction * 150.0); let target_y = best_channel.center_y; // Add slight curve to the run to stay onside let curve_factor = if self.is_offside_risk(ctx, Vector3::new(target_x, target_y, 0.0)) { -20.0 * attacking_direction } else { 0.0 }; return Vector3::new( target_x + curve_factor, target_y, 0.0, ).clamp_to_field(field_width, field_height); } // Default: Edge of the box for cutback opportunities let box_edge_x = goal_position.x - (attacking_direction * 180.0); let box_edge_y = if player_position.y < field_height / 2.0 { goal_position.y - 100.0 } else { goal_position.y + 100.0 }; Vector3::new(box_edge_x, box_edge_y, 0.0).clamp_to_field(field_width, field_height) } /// Calculate support position in middle third fn calculate_middle_third_support( &self, ctx: &StateProcessingContext, attacking_direction: f32, field_width: f32, field_height: f32, ) -> Vector3<f32> { // Check where attacking teammates are let attacking_players = self.get_attacking_teammates(ctx); // Create triangles with ball carrier and forwards if let Some(ball_holder) = self.find_ball_holder(ctx) { // Position to create a passing triangle let triangle_position = self.create_passing_triangle( ctx, &ball_holder, &attacking_players, attacking_direction, ); if self.is_position_valuable(ctx, triangle_position) { return triangle_position.clamp_to_field(field_width, field_height); } } // Support wide if center is congested if self.is_center_congested(ctx) { let wide_position = self.calculate_wide_support(ctx, attacking_direction); return wide_position.clamp_to_field(field_width, field_height); } // Default: Position between lines self.position_between_lines(ctx, attacking_direction) .clamp_to_field(field_width, field_height) } /// Calculate support position during build-up fn calculate_buildup_support_position( &self, ctx: &StateProcessingContext, attacking_direction: f32, field_width: f32, field_height: f32, ) -> Vector3<f32> { let ball_position = ctx.tick_context.positions.ball.position; // Provide a progressive passing option let progressive_position = Vector3::new( ball_position.x + (attacking_direction * 80.0), ball_position.y + self.calculate_lateral_movement(ctx), 0.0, ); // Ensure we're not too close to other midfielders let adjusted_position = self.avoid_midfielder_clustering(ctx, progressive_position); adjusted_position.clamp_to_field(field_width, field_height) } /// Identify free channels between defenders fn identify_free_channels(&self, ctx: &StateProcessingContext, goal_position: Vector3<f32>) -> Vec<Channel> { let mut channels = Vec::new(); let defenders = ctx.players().opponents().all() .filter(|opp| opp.tactical_positions.is_defender()) .collect::<Vec<_>>(); if defenders.len() < 2 { // If few defenders, the whole width is available channels.push(Channel { center_y: goal_position.y, width: 30.0, congestion: 0.0, }); return channels; } // Sort defenders by Y position let mut sorted_defenders = defenders.clone(); sorted_defenders.sort_by(|a, b| a.position.y.partial_cmp(&b.position.y).unwrap_or(std::cmp::Ordering::Equal) ); // Find gaps between defenders for window in sorted_defenders.windows(2) { let gap = (window[1].position.y - window[0].position.y).abs(); if gap > CHANNEL_WIDTH { channels.push(Channel { center_y: (window[0].position.y + window[1].position.y) / 2.0, width: gap, congestion: self.calculate_channel_congestion(ctx, window[0].position, window[1].position), }); } } // Sort by least congested channels.sort_by(|a, b| a.congestion.partial_cmp(&b.congestion).unwrap_or(std::cmp::Ordering::Equal) ); channels } /// Check if position risks being offside fn is_offside_risk(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> bool { let last_defender = ctx.players().opponents().all() .filter(|opp| !opp.tactical_positions.is_goalkeeper()) .min_by(|a, b| { let a_x = match ctx.player.side { Some(PlayerSide::Left) => a.position.x, Some(PlayerSide::Right) => -a.position.x, None => 0.0, }; let b_x = match ctx.player.side { Some(PlayerSide::Left) => b.position.x, Some(PlayerSide::Right) => -b.position.x, None => 0.0, }; b_x.partial_cmp(&a_x).unwrap_or(std::cmp::Ordering::Equal) }); if let Some(defender) = last_defender { match ctx.player.side { Some(PlayerSide::Left) => position.x > defender.position.x + 5.0, Some(PlayerSide::Right) => position.x < defender.position.x - 5.0, None => false, } } else { false } } /// Check if should make a late run into the box fn should_make_late_box_run(&self, ctx: &StateProcessingContext) -> bool { let distance_to_goal = ctx.ball().distance_to_opponent_goal(); let field_width = ctx.context.field_size.width as f32; // Check conditions for late run distance_to_goal < field_width * 0.3 && ctx.team().is_control_ball() && !self.is_offside_risk(ctx, ctx.player.position) && ctx.player.skills.mental.off_the_ball > 12.0 } /// Create a passing triangle position fn create_passing_triangle( &self, ctx: &StateProcessingContext, ball_holder: &MatchPlayerLite, attacking_players: &[MatchPlayerLite], attacking_direction: f32, ) -> Vector3<f32> { let ball_holder_pos = ball_holder.position; // Find the most advanced attacker let forward = attacking_players.iter() .max_by(|a, b| { let a_advance = a.position.x * attacking_direction; let b_advance = b.position.x * attacking_direction; a_advance.partial_cmp(&b_advance).unwrap_or(std::cmp::Ordering::Equal) }); if let Some(forward) = forward { // Position to create triangle let midpoint = (ball_holder_pos + forward.position) * 0.5; let perpendicular = Vector3::new( 0.0, if midpoint.y < ctx.context.field_size.height as f32 / 2.0 { 30.0 } else { -30.0 }, 0.0, ); return midpoint + perpendicular; } // Default progressive position ball_holder_pos + Vector3::new(attacking_direction * 40.0, 20.0, 0.0) } /// Get attacking teammates fn get_attacking_teammates(&self, ctx: &StateProcessingContext) -> Vec<MatchPlayerLite> { ctx.players().teammates().all() .filter(|t| t.tactical_positions.is_forward() || (t.tactical_positions.is_midfielder() && self.is_in_attacking_position(ctx, t))) .collect() } /// Check if a position is valuable for attack fn is_position_valuable(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> bool { // Not too crowded let opponents_nearby = ctx.players().opponents().all() .filter(|opp| (opp.position - position).magnitude() < 15.0) .count(); // Has passing options let teammates_in_range = ctx.players().teammates().all() .filter(|t| { let dist = (t.position - position).magnitude(); dist > 20.0 && dist < 60.0 }) .count(); opponents_nearby < 2 && teammates_in_range >= 2 } /// Check if center is congested fn is_center_congested(&self, ctx: &StateProcessingContext) -> bool { let field_height = ctx.context.field_size.height as f32; let center_y = field_height / 2.0; let ball_position = ctx.tick_context.positions.ball.position; let players_in_center = ctx.players().opponents().all() .filter(|opp| { (opp.position.y - center_y).abs() < field_height * 0.2 && (opp.position.x - ball_position.x).abs() < 50.0 }) .count(); players_in_center >= 3 } /// Calculate wide support position fn calculate_wide_support(&self, ctx: &StateProcessingContext, attacking_direction: f32) -> Vector3<f32> { let ball_position = ctx.tick_context.positions.ball.position; let field_height = ctx.context.field_size.height as f32; // Determine which flank is less occupied let left_flank_players = ctx.players().teammates().all() .filter(|t| t.position.y < field_height * 0.3) .count(); let right_flank_players = ctx.players().teammates().all() .filter(|t| t.position.y > field_height * 0.7) .count(); let target_y = if left_flank_players <= right_flank_players { field_height * 0.15 } else { field_height * 0.85 }; Vector3::new( ball_position.x + (attacking_direction * 50.0), target_y, 0.0, ) } /// Position between defensive lines fn position_between_lines(&self, ctx: &StateProcessingContext, attacking_direction: f32) -> Vector3<f32> { let defenders = ctx.players().opponents().all() .filter(|opp| opp.tactical_positions.is_defender()) .collect::<Vec<_>>(); let midfielders = ctx.players().opponents().all() .filter(|opp| opp.tactical_positions.is_midfielder()) .collect::<Vec<_>>(); if !defenders.is_empty() && !midfielders.is_empty() { let avg_def_x = defenders.iter().map(|d| d.position.x).sum::<f32>() / defenders.len() as f32; let avg_mid_x = midfielders.iter().map(|m| m.position.x).sum::<f32>() / midfielders.len() as f32; let between_x = (avg_def_x + avg_mid_x) / 2.0; let player_y = ctx.player.position.y; return Vector3::new(between_x, player_y, 0.0); } // Default progressive position ctx.player.position + Vector3::new(attacking_direction * 40.0, 0.0, 0.0) } /// Calculate lateral movement to create space fn calculate_lateral_movement(&self, ctx: &StateProcessingContext) -> f32 { let field_height = ctx.context.field_size.height as f32; let player_y = ctx.player.position.y; let center_y = field_height / 2.0; // Move away from crowded areas let crowd_factor = self.calculate_crowd_factor(ctx, ctx.player.position); if crowd_factor > 0.5 { // Move toward less crowded flank if player_y < center_y { -30.0 } else { 30.0 } } else { // Maintain width if (player_y - center_y).abs() < field_height * 0.2 { if player_y < center_y { -20.0 } else { 20.0 } } else { 0.0 } } } /// Avoid clustering with other midfielders fn avoid_midfielder_clustering(&self, ctx: &StateProcessingContext, target: Vector3<f32>) -> Vector3<f32> { let other_midfielders = ctx.players().teammates().all() .filter(|t| t.tactical_positions.is_midfielder() && t.id != ctx.player.id)
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/midfielders/states/tackling/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/tackling/mod.rs
use crate::r#match::events::Event; use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; 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 = 5.0; // Maximum distance to attempt a tackle (in meters) const FOUL_CHANCE_BASE: f32 = 0.2; // Base chance of committing a foul #[derive(Default)] pub struct MidfielderTacklingState {} impl StateProcessingHandler for MidfielderTacklingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } let ball_distance = ctx.ball().distance(); if ball_distance > 100.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )); } if !ctx.ball().is_towards_player_with_angle(0.8) { return if ctx.team().is_control_ball() { Some(StateChangeResult::with_midfielder_state( MidfielderState::AttackSupporting, )) } else { Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )) }; } let opponents = ctx.players().opponents(); let mut opponents_with_ball = opponents.with_ball(); if let Some(opponent) = opponents_with_ball.next() { let opponent_distance = ctx.tick_context.distances.get(ctx.player.id, opponent.id); if opponent_distance <= TACKLE_DISTANCE_THRESHOLD { let (tackle_success, committed_foul) = self.attempt_tackle(ctx, &opponent); if tackle_success { return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::HoldingPossession, Event::PlayerEvent(PlayerEvent::ClaimBall(ctx.player.id)), )); } else if committed_foul { return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Standing, Event::PlayerEvent(PlayerEvent::CommitFoul), )); } } } else if self.can_intercept_ball(ctx) { return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Running, Event::PlayerEvent(PlayerEvent::ClaimBall(ctx.player.id)), )); } 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 + ctx.player().separation_velocity(), ) } fn process_conditions(&self, ctx: ConditionContext) { // Tackling is explosive and very demanding physically MidfielderCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl MidfielderTacklingState { /// Attempts a tackle and returns whether it was successful and if a foul was committed. fn attempt_tackle( &self, ctx: &StateProcessingContext, opponent: &MatchPlayerLite, ) -> (bool, bool) { let mut rng = rand::rng(); 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 overall_skill = (tackling_skill + composure) / 2.0; // Calculate opponent's dribbling and agility skills let opponent_dribbling = ctx.player().skills(opponent.id).technical.dribbling / 20.0; let opponent_agility = ctx.player().skills(opponent.id).physical.agility / 20.0; // Calculate the relative skill difference between the tackler and the opponent let skill_difference = overall_skill - (opponent_dribbling + opponent_agility) / 2.0; // Calculate success chance based on the skill difference let success_chance = 0.5 + skill_difference * 0.3; let clamped_success_chance = success_chance.clamp(0.1, 0.9); // Simulate tackle success let tackle_success = rng.random::<f32>() < clamped_success_chance; // Calculate foul chance let foul_chance = if tackle_success { // Lower foul chance for successful tackles (1.0 - overall_skill) * FOUL_CHANCE_BASE + aggression * 0.05 } else { // Higher foul chance for unsuccessful tackles (1.0 - overall_skill) * FOUL_CHANCE_BASE + aggression * 0.15 }; // Simulate foul let committed_foul = rng.random::<f32>() < foul_chance; (tackle_success, committed_foul) } fn can_intercept_ball(&self, ctx: &StateProcessingContext) -> bool { if 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; if !ctx.tick_context.ball.is_owned && ball_velocity.magnitude() > 0.1 { let time_to_ball = (ball_position - player_position).magnitude() / player_speed; let ball_travel_distance = ball_velocity.magnitude() * time_to_ball; let ball_intercept_position = ball_position + ball_velocity.normalize() * ball_travel_distance; let player_intercept_distance = (ball_intercept_position - player_position).magnitude(); player_intercept_distance <= TACKLE_DISTANCE_THRESHOLD } else { 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/midfielders/states/holding_posession/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/holding_posession/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::{ConditionContext, MatchPlayerLite, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior}; use nalgebra::Vector3; const MAX_SHOOTING_DISTANCE: f32 = 300.0; // Maximum distance to attempt a shot const MIN_SHOOTING_DISTANCE: f32 = 20.0; // Minimum distance to attempt a shot (e.g., edge of penalty area) #[derive(Default)] pub struct MidfielderHoldingPossessionState {} impl StateProcessingHandler for MidfielderHoldingPossessionState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Check if the midfielder has the ball if !ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )); } if self.is_in_shooting_range(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Shooting, )); } // Check if the midfielder is being pressured by opponents if self.is_under_pressure(ctx) { // If under pressure, decide whether to dribble or pass based on the situation return if self.has_space_to_dribble(ctx) { // If there is space to dribble, transition to the dribbling state Some(StateChangeResult::with_midfielder_state( MidfielderState::Dribbling, )) } else { Some(StateChangeResult::with_midfielder_state( MidfielderState::Passing )) }; } if let Some(_) = ctx.players().teammates() .nearby(300.0) .filter(|teammate| self.is_teammate_open(ctx, teammate)).next() { // If there is an open teammate, transition to the passing state return Some(StateChangeResult::with_midfielder_state( MidfielderState::Passing )); } // If none of the above conditions are met, continue holding possession 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: 30.0, } .calculate(ctx.player) .velocity, ) } fn process_conditions(&self, ctx: ConditionContext) { // Holding possession is low intensity - controlled possession MidfielderCondition::new(ActivityIntensity::Low).process(ctx); } } impl MidfielderHoldingPossessionState { pub fn is_under_pressure(&self, ctx: &StateProcessingContext) -> bool { ctx.players().opponents().exists(50.0) } fn is_teammate_open(&self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite) -> bool { // Check if a teammate is open to receive a pass let is_in_passing_range = (teammate.position - ctx.player.position).magnitude() <= 30.0; let has_clear_passing_lane = self.has_clear_passing_lane(ctx, teammate); is_in_passing_range && has_clear_passing_lane } fn has_space_to_dribble(&self, ctx: &StateProcessingContext) -> bool { ctx.players().opponents().exists(10.0) } fn has_clear_passing_lane(&self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite) -> bool { // Check if there is a clear passing lane to a teammate without any obstructing opponents let player_position = ctx.player.position; let teammate_position = teammate.position; let passing_direction = (teammate_position - player_position).normalize(); let ray_cast_result = ctx.tick_context.space.cast_ray( player_position, passing_direction, (teammate_position - player_position).magnitude(), false, ); ray_cast_result.is_none() // No collisions with opponents } fn is_in_shooting_range(&self, ctx: &StateProcessingContext) -> bool { let distance_to_goal = ctx.ball().distance_to_opponent_goal(); distance_to_goal <= MAX_SHOOTING_DISTANCE && distance_to_goal >= MIN_SHOOTING_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/midfielders/states/dribbling/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/dribbling/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; use rand::prelude::IteratorRandom; #[derive(Default)] pub struct MidfielderDribblingState {} impl StateProcessingHandler for MidfielderDribblingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Add timeout to avoid getting stuck - reduced from 60 to 30 ticks if ctx.in_state_time > 30 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Passing // Force decision instead of just running )); } if ctx.player.has_ball(ctx) { // If the player has the ball, consider shooting, passing, or dribbling if self.is_in_shooting_position(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::DistanceShooting, )); } if self.find_open_teammate(ctx).is_some() { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Passing )); } } else { // If they don't have the ball anymore, change state return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Instead of returning zero velocity, actually dribble toward goal if ctx.player.has_ball(ctx) { // Dribble toward the goal (REMOVED random jitter that causes circular movement) let goal_pos = ctx.player().opponent_goal_position(); let player_pos = ctx.player.position; let direction = (goal_pos - player_pos).normalize(); // Calculate speed based on player's dribbling and pace let dribble_skill = ctx.player.skills.technical.dribbling / 20.0; let pace = ctx.player.skills.physical.pace / 20.0; let speed = 3.0 * (0.7 * dribble_skill + 0.3 * pace); // Add separation to avoid teammates clustering Some(direction * speed + ctx.player().separation_velocity() * 2.0) } else { // If player doesn't have the ball anymore, move toward it let ball_pos = ctx.tick_context.positions.ball.position; let player_pos = ctx.player.position; let direction = (ball_pos - player_pos).normalize(); let speed = ctx.player.skills.physical.pace * 0.3; Some(direction * speed) } } fn process_conditions(&self, ctx: ConditionContext) { // Dribbling is moderate intensity MidfielderCondition::with_velocity(ActivityIntensity::Moderate).process(ctx); } } impl MidfielderDribblingState { fn find_open_teammate<'a>(&self, ctx: &StateProcessingContext<'a>) -> Option<u32> { // Find an open teammate to pass to let teammates = ctx.players().teammates().nearby_ids(150.0); if let Some((teammate_id, _)) = teammates.choose(&mut rand::rng()) { return Some(teammate_id); } None } fn is_in_shooting_position(&self, ctx: &StateProcessingContext) -> bool { let shooting_range = 25.0; // Distance from goal to consider shooting let player_position = ctx.player.position; let goal_position = ctx.player().opponent_goal_position(); let distance_to_goal = (player_position - goal_position).magnitude(); distance_to_goal <= shooting_range } fn should_return_to_position(&self, ctx: &StateProcessingContext) -> bool { // Check if the player is far from their starting position and the team is not in possession let distance_from_start = ctx.player().distance_from_start_position(); let team_in_possession = ctx.team().is_control_ball(); distance_from_start > 20.0 && !team_in_possession } fn should_press(&self, ctx: &StateProcessingContext) -> bool { // Check if the player should press the opponent with the ball let ball_distance = ctx.ball().distance(); let pressing_distance = 150.0; // Adjust the threshold as needed !ctx.team().is_control_ball() && ball_distance < pressing_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/midfielders/states/switching_play/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/switching_play/mod.rs
use crate::r#match::events::Event; use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::player::events::{PassingEventContext, PlayerEvent}; use crate::r#match::{ ConditionContext, MatchPlayerLite, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderSwitchingPlayState {} impl StateProcessingHandler for MidfielderSwitchingPlayState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if !ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )); } // Check if there's a good opportunity to switch play if let Some((teammate_id, _)) = self.find_switch_play_target(ctx) { // If a suitable target position is found, switch play return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Passing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(teammate_id) .with_reason("MID_SWITCHING_PLAY") .build(ctx) )), )); } // If no suitable opportunity to switch play, continue with the current state None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Move towards the best position to switch play if let Some((_, teammate_position)) = self.find_switch_play_target(ctx) { let steering = SteeringBehavior::Seek { target: teammate_position, } .calculate(ctx.player); Some(steering.velocity) } else { // If no suitable target position is found, stay in the current position Some(Vector3::new(0.0, 0.0, 0.0)) } } fn process_conditions(&self, ctx: ConditionContext) { // Switching play is low intensity - tactical passing MidfielderCondition::new(ActivityIntensity::Low).process(ctx); } } impl MidfielderSwitchingPlayState { fn find_switch_play_target(&self, ctx: &StateProcessingContext) -> Option<(u32, Vector3<f32>)> { // Find the best position to switch play to let player_position = ctx.player.position; let ball_position = ctx.tick_context.positions.ball.position; // Calculate the direction perpendicular to the player's forward direction let forward_direction = (ball_position - player_position).normalize(); let perpendicular_direction = Vector3::new(-forward_direction.y, forward_direction.x, 0.0); // Find teammates on the opposite side of the field let opposite_side_teammates: Vec<MatchPlayerLite> = ctx.players().teammates() .all() .filter(|teammate| { let teammate_to_player = player_position - teammate.position; let dot_product = teammate_to_player.dot(&perpendicular_direction); dot_product > 0.0 // Teammate is on the opposite side }) .collect(); // Find the teammate with the most space let best_teammate = opposite_side_teammates.iter().max_by(|a, b| { let space_a = self.calculate_space_around_player(ctx, *a); let space_b = self.calculate_space_around_player(ctx, *b); space_a.partial_cmp(&space_b).unwrap() }); if let Some(teammate) = best_teammate.map(|teammate| teammate) { return Some((teammate.id, teammate.position)); } None } fn calculate_space_around_player( &self, ctx: &StateProcessingContext, player: &MatchPlayerLite, ) -> f32 { // Calculate the amount of free space around a player let space_radius = 10.0; // Adjust the radius as needed 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 } }
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/midfielders/states/creating_space/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/creating_space/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::{ ConditionContext, MatchPlayerLite, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; const MAX_DISTANCE_FROM_BALL: f32 = 120.0; const MIN_DISTANCE_FROM_BALL: f32 = 25.0; const SPACE_CREATION_RADIUS: f32 = 20.0; const HALF_SPACE_WIDTH: f32 = 15.0; #[derive(Default)] pub struct MidfielderCreatingSpaceState {} impl StateProcessingHandler for MidfielderCreatingSpaceState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Check if player has the ball if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } // Check if team lost possession if !ctx.team().is_control_ball() { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } // If ball is coming toward player and close, prepare to receive if ctx.ball().distance() < 80.0 && ctx.ball().is_towards_player_with_angle(0.85) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Intercepting, )); } // Check if created sufficient space and ready to receive if self.has_created_quality_space(ctx) && self.is_ready_to_receive(ctx) { // Signal availability by slight movement return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } // Make attacking run if opportunity arises if self.should_make_attacking_run(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::AttackSupporting, )); } // Don't stay in this state too long if ctx.in_state_time > 100 && !self.is_space_creation_valuable(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Find the optimal free zone on the opposite side let target_position = self.find_opposite_side_free_zone(ctx); // Add dynamic avoidance of congested areas during movement let avoidance_vector = self.calculate_congestion_avoidance(ctx); // Vary movement pattern to confuse markers and exploit space let movement_pattern = self.get_intelligent_movement_pattern(ctx); match movement_pattern { MovementPattern::Direct => { // Direct run to free space with congestion avoidance let base_velocity = SteeringBehavior::Arrive { target: target_position, slowing_distance: 15.0, } .calculate(ctx.player) .velocity; Some(base_velocity + avoidance_vector + ctx.player().separation_velocity()) } MovementPattern::Curved => { // Curved run to lose markers and find space let curved_target = self.add_intelligent_curve(ctx, target_position); let base_velocity = SteeringBehavior::Arrive { target: curved_target, slowing_distance: 20.0, } .calculate(ctx.player) .velocity; Some(base_velocity + avoidance_vector * 0.8) } MovementPattern::CheckToReceive => { // Quick check toward ball then sprint to space if ctx.in_state_time % 30 < 10 { // Check toward ball let check_position = self.calculate_check_position(ctx); Some( SteeringBehavior::Seek { target: check_position, } .calculate(ctx.player) .velocity ) } else { // Sprint to free space Some( SteeringBehavior::Pursuit { target: target_position, target_velocity: Vector3::zeros(), // Static target position } .calculate(ctx.player) .velocity + avoidance_vector ) } } MovementPattern::OppositeRun => { // New pattern: Run opposite to ball movement to find space let opposite_target = self.calculate_opposite_run_target(ctx); Some( SteeringBehavior::Arrive { target: opposite_target, slowing_distance: 10.0, } .calculate(ctx.player) .velocity + avoidance_vector * 1.2 ) } } } fn process_conditions(&self, ctx: ConditionContext) { // Creating space is moderate intensity - tactical movement MidfielderCondition::with_velocity(ActivityIntensity::Moderate).process(ctx); } } impl MidfielderCreatingSpaceState { /// Find free zone on the opposite side of play fn find_opposite_side_free_zone(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_pos = ctx.tick_context.positions.ball.position; let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; // Determine which side the ball is on let ball_on_left = ball_pos.y < field_height / 2.0; // Calculate opposite side base position let opposite_y = if ball_on_left { field_height * 0.75 // Right side } else { field_height * 0.25 // Left side }; // Find the freest zone on that side let mut best_position = Vector3::new( ball_pos.x, opposite_y, 0.0, ); let mut min_congestion = f32::MAX; // Scan a grid on the opposite side let scan_width = 80.0; let scan_depth = 100.0; let grid_step = 15.0; for x_offset in (-scan_depth as i32..=scan_depth as i32).step_by(grid_step as usize) { for y_offset in (-scan_width as i32..=scan_width as i32).step_by(grid_step as usize) { let test_pos = Vector3::new( (ball_pos.x + x_offset as f32).clamp(20.0, field_width - 20.0), (opposite_y + y_offset as f32).clamp(20.0, field_height - 20.0), 0.0, ); // Calculate dynamic congestion considering player velocities let congestion = self.calculate_dynamic_congestion(ctx, test_pos); // Prefer progressive positions let progression_bonus = self.calculate_progression_value(ctx, test_pos); // Prefer positions with good passing angles let passing_angle_bonus = self.calculate_passing_angle_value(ctx, test_pos); let total_score = congestion - progression_bonus - passing_angle_bonus; if total_score < min_congestion { min_congestion = total_score; best_position = test_pos; } } } // Apply tactical adjustments based on formation self.apply_tactical_position_adjustment(ctx, best_position) } /// Calculate congestion avoidance vector fn calculate_congestion_avoidance(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let mut avoidance = Vector3::zeros(); let player_pos = ctx.player.position; // Consider all nearby players (both teams) let avoidance_radius = 30.0; let mut total_weight = 0.0; for opponent in ctx.players().opponents().all() { let distance = (opponent.position - player_pos).magnitude(); if distance < avoidance_radius && distance > 0.1 { // Calculate repulsion force let direction = (player_pos - opponent.position).normalize(); let weight = 1.0 - (distance / avoidance_radius); avoidance += direction * weight * 15.0; total_weight += weight; } } // Also avoid teammates slightly to spread out for teammate in ctx.players().teammates().all() { if teammate.id == ctx.player.id { continue; } let distance = (teammate.position - player_pos).magnitude(); if distance < avoidance_radius * 0.7 && distance > 0.1 { let direction = (player_pos - teammate.position).normalize(); let weight = 1.0 - (distance / (avoidance_radius * 0.7)); avoidance += direction * weight * 8.0; total_weight += weight; } } if total_weight > 0.0 { avoidance / total_weight } else { avoidance } } /// Calculate dynamic congestion considering player movements fn calculate_dynamic_congestion(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> f32 { let mut congestion = 0.0; // Check opponents for opponent in ctx.players().opponents().all() { let distance = (opponent.position - position).magnitude(); // Consider opponent velocity - where they're heading let future_position = opponent.position + opponent.velocity(ctx) * 0.5; let future_distance = (future_position - position).magnitude(); if distance < 40.0 { congestion += 40.0 / (distance + 1.0); } if future_distance < 30.0 { congestion += 20.0 / (future_distance + 1.0); } } // Check teammates (less weight) for teammate in ctx.players().teammates().all() { if teammate.id == ctx.player.id { continue; } let distance = (teammate.position - position).magnitude(); if distance < 25.0 { congestion += 10.0 / (distance + 1.0); } } congestion } /// Get intelligent movement pattern based on game state fn get_intelligent_movement_pattern(&self, ctx: &StateProcessingContext) -> MovementPattern { // Analyze current situation let congestion_level = self.calculate_local_congestion(ctx); let has_marker = self.has_close_marker(ctx); let ball_moving_away = ctx.ball().velocity().magnitude() > 5.0; if has_marker && congestion_level > 5.0 { // Need to lose marker in congested area MovementPattern::Curved } else if ball_moving_away && ctx.ball().distance() > 50.0 { // Ball is moving away, make opposite run MovementPattern::OppositeRun } else if ctx.in_state_time % 60 < 15 { // Periodically check back MovementPattern::CheckToReceive } else { // Direct run to space MovementPattern::Direct } } /// Calculate intelligent curve to lose markers fn add_intelligent_curve(&self, ctx: &StateProcessingContext, target: Vector3<f32>) -> Vector3<f32> { let player_pos = ctx.player.position; // Find nearest opponent if let Some(nearest_opponent) = ctx.players().opponents().all() .min_by(|a, b| { let dist_a = (a.position - player_pos).magnitude(); let dist_b = (b.position - player_pos).magnitude(); dist_a.partial_cmp(&dist_b).unwrap_or(std::cmp::Ordering::Equal) }) { // Curve away from opponent let to_target = (target - player_pos).normalize(); let to_opponent = (nearest_opponent.position - player_pos).normalize(); // Create perpendicular vector away from opponent let perpendicular = Vector3::new(-to_target.y, to_target.x, 0.0); let away_from_opponent = if perpendicular.dot(&to_opponent) > 0.0 { -perpendicular } else { perpendicular }; // Create curved waypoint let midpoint = (player_pos + target) * 0.5; midpoint + away_from_opponent * 20.0 } else { // Default curve self.add_curve_to_path(ctx, target) } } /// Calculate target for opposite run fn calculate_opposite_run_target(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_pos = ctx.tick_context.positions.ball.position; let ball_velocity = ctx.tick_context.positions.ball.velocity; let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; // Run opposite to ball movement direction let opposite_direction = -ball_velocity.normalize(); // Calculate target based on opposite direction let base_distance = 40.0; let mut target = ball_pos + opposite_direction * base_distance; // Shift to opposite side laterally as well let lateral_shift = if ball_pos.y < field_height / 2.0 { Vector3::new(0.0, 30.0, 0.0) // Shift right } else { Vector3::new(0.0, -30.0, 0.0) // Shift left }; target += lateral_shift; // Ensure within field bounds target.x = target.x.clamp(15.0, field_width - 15.0); target.y = target.y.clamp(15.0, field_height - 15.0); target } /// Calculate progression value for a position fn calculate_progression_value(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> f32 { let goal_pos = ctx.player().opponent_goal_position(); let current_to_goal = (ctx.player.position - goal_pos).magnitude(); let test_to_goal = (position - goal_pos).magnitude(); if test_to_goal < current_to_goal { (current_to_goal - test_to_goal) * 0.5 } else { 0.0 } } /// Calculate passing angle value for a position fn calculate_passing_angle_value(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> f32 { if let Some(ball_holder) = self.find_ball_holder(ctx) { // Check angle to ball holder let to_ball_holder = (ball_holder.position - position).normalize(); // Count how many opponents are in the passing lane let opponents_in_lane = ctx.players().opponents().all() .filter(|opp| { let to_opp = opp.position - position; let projection = to_opp.dot(&to_ball_holder); if projection <= 0.0 || projection >= (ball_holder.position - position).magnitude() { return false; } let projected_point = position + to_ball_holder * projection; let perp_dist = (opp.position - projected_point).magnitude(); perp_dist < 5.0 }) .count(); if opponents_in_lane == 0 { 15.0 // Clear passing lane bonus } else { 0.0 } } else { 5.0 // Default value } } /// Apply tactical adjustments based on formation fn apply_tactical_position_adjustment(&self, ctx: &StateProcessingContext, mut position: Vector3<f32>) -> Vector3<f32> { // Get the appropriate tactics based on player's side let player_tactics = match ctx.player.side { Some(PlayerSide::Left) => &ctx.context.tactics.left, Some(PlayerSide::Right) => &ctx.context.tactics.right, None => return position, // No side assigned, return unchanged }; // Adjust based on tactical style match player_tactics.tactical_style() { crate::TacticalStyle::WidePlay | crate::TacticalStyle::WingPlay => { // Push wider in wide formations let field_height = ctx.context.field_size.height as f32; if position.y < field_height / 2.0 { position.y = (position.y - 15.0).max(10.0); } else { position.y = (position.y + 15.0).min(field_height - 10.0); } } crate::TacticalStyle::Possession => { // Stay more central for passing options let field_height = ctx.context.field_size.height as f32; let center_y = field_height / 2.0; position.y = position.y * 0.8 + center_y * 0.2; } _ => {} } position } /// Calculate local congestion around player fn calculate_local_congestion(&self, ctx: &StateProcessingContext) -> f32 { ctx.players().opponents().nearby(20.0).count() as f32 } /// Check if player has a close marker fn has_close_marker(&self, ctx: &StateProcessingContext) -> bool { ctx.players().opponents().nearby(10.0).count() > 0 } /// Make a third man run (beyond the immediate play) fn make_third_man_run(&self, ctx: &StateProcessingContext, field_width: f32, field_height: f32) -> Vector3<f32> { // Identify potential passing sequence if let Some(ball_holder) = self.find_ball_holder(ctx) { // Find likely next pass recipient if let Some(next_receiver) = self.predict_next_pass_recipient(ctx, &ball_holder) { // Position beyond the next receiver let attacking_direction = match ctx.player.side { Some(PlayerSide::Left) => 1.0, Some(PlayerSide::Right) => -1.0, None => 0.0, }; let beyond_position = Vector3::new( next_receiver.position.x + (attacking_direction * 50.0), next_receiver.position.y + self.calculate_run_angle(ctx, &next_receiver), 0.0, ); return beyond_position.clamp_to_field(field_width, field_height); } } // Fallback to progressive run self.calculate_progressive_position(ctx, field_width, field_height) } /// Create central overload fn create_central_overload(&self, ctx: &StateProcessingContext, field_width: f32, field_height: f32) -> Vector3<f32> { let ball_pos = ctx.tick_context.positions.ball.position; let field_center_y = field_height / 2.0; // Move toward center but at different depths let depth_offset = self.calculate_depth_variation(ctx); let attacking_direction = match ctx.player.side { Some(PlayerSide::Left) => 1.0, Some(PlayerSide::Right) => -1.0, None => 0.0, }; Vector3::new( ball_pos.x + (attacking_direction * depth_offset), field_center_y + self.calculate_central_lane_offset(ctx), 0.0, ).clamp_to_field(field_width, field_height) } /// Check if has created quality space fn has_created_quality_space(&self, ctx: &StateProcessingContext) -> bool { let space_radius = SPACE_CREATION_RADIUS; // No opponents in immediate vicinity let opponents_nearby = ctx.players().opponents().all() .filter(|opp| (opp.position - ctx.player.position).magnitude() < space_radius) .count(); // Good distance from ball let ball_distance = ctx.ball().distance(); let good_distance = ball_distance >= MIN_DISTANCE_FROM_BALL && ball_distance <= MAX_DISTANCE_FROM_BALL; // Clear passing lane let has_clear_lane = self.has_clear_receiving_lane(ctx); // Progressive position let is_progressive = self.is_progressive_position(ctx, ctx.player.position); opponents_nearby == 0 && good_distance && has_clear_lane && (is_progressive || ctx.in_state_time > 40) } /// Check if ready to receive pass fn is_ready_to_receive(&self, ctx: &StateProcessingContext) -> bool { // Body orientation toward ball let to_ball = (ctx.tick_context.positions.ball.position - ctx.player.position).normalize(); let player_facing = ctx.player.velocity.normalize(); let facing_ball = if ctx.player.velocity.magnitude() > 0.1 { to_ball.dot(&player_facing) > 0.5 } else { true // Standing still, assumed ready }; // Not moving too fast let controlled_movement = ctx.player.velocity.magnitude() < 5.0; facing_ball && controlled_movement } /// Should make attacking run fn should_make_attacking_run(&self, ctx: &StateProcessingContext) -> bool { let ball_in_good_position = ctx.ball().distance_to_opponent_goal() < 300.0; let team_attacking = ctx.team().is_control_ball(); let has_energy = ctx.player.player_attributes.condition_percentage() > 60; let good_off_ball = ctx.player.skills.mental.off_the_ball > 12.0; ball_in_good_position && team_attacking && has_energy && good_off_ball } /// Check if space creation is valuable fn is_space_creation_valuable(&self, ctx: &StateProcessingContext) -> bool { // Team has ball and is building attack ctx.team().is_control_ball() && ctx.ball().distance() < 150.0 && !self.too_many_players_creating_space(ctx) } /// Helper methods fn get_movement_pattern(&self, ctx: &StateProcessingContext) -> MovementPattern { let time_mod = ctx.in_state_time % 30; if time_mod < 10 { MovementPattern::Direct } else if time_mod < 20 { MovementPattern::Curved } else { MovementPattern::CheckToReceive } } fn add_curve_to_path(&self, ctx: &StateProcessingContext, target: Vector3<f32>) -> Vector3<f32> { let player_pos = ctx.player.position; let midpoint = (player_pos + target) * 0.5; // Add perpendicular offset let direction = (target - player_pos).normalize(); let perpendicular = Vector3::new(-direction.y, direction.x, 0.0); midpoint + perpendicular * 10.0 } fn calculate_check_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_pos = ctx.tick_context.positions.ball.position; let player_pos = ctx.player.position; // Move 10m toward ball let to_ball = (ball_pos - player_pos).normalize(); player_pos + to_ball * 10.0 } fn get_ball_zone(&self, ctx: &StateProcessingContext) -> BallZone { let ball_x = ctx.tick_context.positions.ball.position.x; let field_width = ctx.context.field_size.width as f32; let relative_x = match ctx.player.side { Some(PlayerSide::Left) => ball_x / field_width, Some(PlayerSide::Right) => (field_width - ball_x) / field_width, None => 0.5, }; if relative_x < 0.33 { BallZone::DefensiveThird } else if relative_x < 0.66 { BallZone::MiddleThird } else { BallZone::AttackingThird } } fn analyze_team_shape(&self, ctx: &StateProcessingContext) -> TeamShape { let teammates = ctx.players().teammates().all().collect::<Vec<_>>(); if teammates.is_empty() { return TeamShape::default(); } // Calculate spread let positions: Vec<Vector3<f32>> = teammates.iter().map(|t| t.position).collect(); let min_x = positions.iter().map(|p| p.x).fold(f32::INFINITY, f32::min); let max_x = positions.iter().map(|p| p.x).fold(f32::NEG_INFINITY, f32::max); let min_y = positions.iter().map(|p| p.y).fold(f32::INFINITY, f32::min); let max_y = positions.iter().map(|p| p.y).fold(f32::NEG_INFINITY, f32::max); TeamShape { width: max_y - min_y, depth: max_x - min_x, compactness: teammates.len() as f32 / ((max_x - min_x) * (max_y - min_y) / 1000.0), } } fn analyze_opponent_shape(&self, ctx: &StateProcessingContext) -> OpponentShape { let opponents = ctx.players().opponents().all().collect::<Vec<_>>(); let defenders = opponents.iter() .filter(|o| o.tactical_positions.is_defender()) .collect::<Vec<_>>(); if defenders.is_empty() { return OpponentShape::default(); } let def_line = defenders.iter() .map(|d| d.position.x) .sum::<f32>() / defenders.len() as f32; let field_width = ctx.context.field_size.width as f32; let high_line = match ctx.player.side { Some(PlayerSide::Left) => def_line > field_width * 0.6, Some(PlayerSide::Right) => def_line < field_width * 0.4, None => false, }; OpponentShape { high_line, compact_central: self.is_opponent_compact_central(ctx), narrow: self.is_opponent_narrow(ctx), } } fn is_half_space_occupied(&self, ctx: &StateProcessingContext, y_position: f32) -> bool { ctx.players().teammates().all() .any(|t| (t.position.y - y_position).abs() < HALF_SPACE_WIDTH) } fn can_exploit_half_space(&self, ctx: &StateProcessingContext) -> bool { let vision = ctx.player.skills.mental.vision; let off_ball = ctx.player.skills.mental.off_the_ball; vision > 13.0 && off_ball > 12.0 } fn find_lateral_space_between_lines( &self, ctx: &StateProcessingContext, defenders: &[MatchPlayerLite], midfielders: &[MatchPlayerLite], ) -> f32 { let field_height = ctx.context.field_size.height as f32; // Find gaps in coverage let mut all_positions = defenders.iter() .chain(midfielders.iter()) .map(|p| p.position.y) .collect::<Vec<_>>(); all_positions.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); // Find biggest gap let mut max_gap = 0.0; let mut gap_center = field_height / 2.0; for window in all_positions.windows(2) { let gap = window[1] - window[0]; if gap > max_gap { max_gap = gap; gap_center = (window[0] + window[1]) / 2.0; } } gap_center } fn calculate_progressive_position(&self, ctx: &StateProcessingContext, field_width: f32, field_height: f32) -> Vector3<f32> { let ball_pos = ctx.tick_context.positions.ball.position; let attacking_direction = match ctx.player.side { Some(PlayerSide::Left) => 1.0, Some(PlayerSide::Right) => -1.0, None => 0.0, }; Vector3::new( ball_pos.x + (attacking_direction * 40.0), ctx.player.position.y, 0.0, ).clamp_to_field(field_width, field_height) } fn determine_overload_strategy(&self, ctx: &StateProcessingContext) -> OverloadStrategy { // Based on team tactics and game situation if ctx.team().is_loosing() { OverloadStrategy::CreateNumericalAdvantage } else { OverloadStrategy::BalanceWidth } } fn calculate_position_congestion(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> f32 { let mut congestion = 0.0; // Weight opponents more than teammates let opponents = ctx.players().opponents().all() .filter(|o| (o.position - position).magnitude() < 30.0) .count(); let teammates = ctx.players().teammates().all() .filter(|t| (t.position - position).magnitude() < 20.0) .count(); congestion += opponents as f32 * 2.0; congestion += teammates as f32 * 0.5; congestion } fn is_progressive_position(&self, ctx: &StateProcessingContext, position: Vector3<f32>) -> bool { let current_to_goal = ctx.ball().distance_to_opponent_goal(); let test_to_goal = (position - ctx.player().opponent_goal_position()).magnitude(); test_to_goal < current_to_goal } fn find_ball_holder(&self, ctx: &StateProcessingContext) -> Option<MatchPlayerLite> { 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 Some(ctx.player().get(owner_id)); } } } None } fn predict_next_pass_recipient( &self, ctx: &StateProcessingContext, ball_holder: &MatchPlayerLite, ) -> Option<MatchPlayerLite> { // Simple prediction based on positioning ctx.players().teammates().all() .filter(|t| t.id != ball_holder.id && t.id != ctx.player.id) .min_by(|a, b| { let dist_a = (a.position - ball_holder.position).magnitude(); let dist_b = (b.position - ball_holder.position).magnitude(); dist_a.partial_cmp(&dist_b).unwrap_or(std::cmp::Ordering::Equal) }) } fn calculate_run_angle(&self, ctx: &StateProcessingContext, target: &MatchPlayerLite) -> f32 { // Angle away from target's current position if target.position.y < ctx.context.field_size.height as f32 / 2.0 { 20.0 } else { -20.0 } } fn calculate_depth_variation(&self, ctx: &StateProcessingContext) -> f32 { // Vary depth based on other midfielders let other_mids = ctx.players().teammates().all() .filter(|t| t.tactical_positions.is_midfielder() && t.id != ctx.player.id) .count(); match other_mids { 0 => 30.0, 1 => 40.0, 2 => 50.0, _ => 35.0, } } fn calculate_central_lane_offset(&self, ctx: &StateProcessingContext) -> f32 { // Slight offset to create passing lanes if ctx.in_state_time % 40 < 20 { -10.0 } else { 10.0 } } fn has_clear_receiving_lane(&self, ctx: &StateProcessingContext) -> bool { if let Some(ball_holder) = self.find_ball_holder(ctx) { let to_player = (ctx.player.position - ball_holder.position).normalize(); let distance = (ctx.player.position - ball_holder.position).magnitude(); // Check for opponents in passing lane !ctx.players().opponents().all() .any(|opp| { let to_opp = opp.position - ball_holder.position; let projection = to_opp.dot(&to_player); if projection <= 0.0 || projection >= distance { return false; } let projected_point = ball_holder.position + to_player * projection; let perp_dist = (opp.position - projected_point).magnitude(); perp_dist < 5.0 }) } else { true } } fn too_many_players_creating_space(&self, ctx: &StateProcessingContext) -> bool { // Avoid having too many players in space creation mode let creating_space_count = ctx.players().teammates().all() .filter(|t| { let distance = ctx.ball().distance(); distance > MIN_DISTANCE_FROM_BALL && distance < MAX_DISTANCE_FROM_BALL && !t.has_ball(ctx) }) .count(); creating_space_count >= 3 } fn is_opponent_compact_central(&self, ctx: &StateProcessingContext) -> bool { let field_height = ctx.context.field_size.height as f32;
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/midfielders/states/distance_shooting/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/distance_shooting/mod.rs
use crate::r#match::events::Event; use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::player::events::{PlayerEvent, ShootingEventContext}; use crate::r#match::{ ConditionContext, MatchPlayerLite, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderDistanceShootingState {} impl StateProcessingHandler for MidfielderDistanceShootingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Check if the midfielder still has the ball if !ctx.player.has_ball(ctx) { // Lost possession, transition to Pressing return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } if ctx.player().goal_distance() > 250.0 { // Too far from the goal, consider other options if self.should_pass(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Passing, )); } else if self.should_dribble(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Dribbling, )); } } // Evaluate shooting opportunity if self.is_favorable_shooting_opportunity(ctx) { // Transition to shooting state return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Shooting, Event::PlayerEvent(PlayerEvent::Shoot( ShootingEventContext::new() .with_player_id(ctx.player.id) .with_target(ctx.player().shooting_direction()) .with_reason("MID_DISTANCE_SHOOTING") .build(ctx), )), )); } 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) { // Distance shooting is very high intensity - explosive action MidfielderCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl MidfielderDistanceShootingState { fn is_favorable_shooting_opportunity(&self, ctx: &StateProcessingContext) -> bool { // Evaluate the shooting opportunity based on various factors let distance_to_goal = ctx.player().goal_distance(); let angle_to_goal = ctx.player().goal_angle(); let has_clear_shot = self.has_clear_shot(ctx); let long_shots = ctx.player.skills.technical.long_shots / 20.0; // Distance shooting only for skilled players from reasonable distance let distance_threshold = 100.0; // Maximum ~50m for long shots let angle_threshold = std::f32::consts::PI / 6.0; // 30 degrees distance_to_goal <= distance_threshold && angle_to_goal <= angle_threshold && has_clear_shot && long_shots > 0.55 // Reduced from 0.7 to 0.55 - more players can take long shots } fn should_pass(&self, ctx: &StateProcessingContext) -> bool { // Determine if the player should pass based on the game state let teammates = ctx.players().teammates(); let mut open_teammates = teammates.all() .filter(|teammate| self.is_teammate_open(ctx, teammate)); let has_open_teammate = open_teammates.next().is_some(); let under_pressure = self.is_under_pressure(ctx); has_open_teammate && under_pressure } fn should_dribble(&self, ctx: &StateProcessingContext) -> bool { // Determine if the player should dribble based on the game state let has_space = self.has_space_to_dribble(ctx); let under_pressure = self.is_under_pressure(ctx); has_space && !under_pressure } // Additional helper functions fn get_opponent_goal_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { // Get the position of the opponent's goal based on the player's side let field_width = ctx.context.field_size.width as f32; let field_length = ctx.context.field_size.width as f32; if ctx.player.side == Some(PlayerSide::Left) { Vector3::new(field_width, field_length / 2.0, 0.0) } else { Vector3::new(0.0, field_length / 2.0, 0.0) } } fn has_clear_shot(&self, ctx: &StateProcessingContext) -> bool { // Check if the player has a clear shot to the goal without any obstructing opponents let player_position = ctx.player.position; let goal_position = self.get_opponent_goal_position(ctx); let shot_direction = (goal_position - player_position).normalize(); let ray_cast_result = ctx.tick_context.space.cast_ray( player_position, shot_direction, ctx.player().goal_distance(), false, ); ray_cast_result.is_none() // No collisions with opponents } fn is_teammate_open(&self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite) -> bool { // Check if a teammate is open to receive a pass let is_in_passing_range = (teammate.position - ctx.player.position).magnitude() <= 30.0; let has_clear_passing_lane = self.has_clear_passing_lane(ctx, teammate); is_in_passing_range && has_clear_passing_lane } fn has_clear_passing_lane( &self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite, ) -> bool { // Check if there is a clear passing lane to a teammate without any obstructing opponents let player_position = ctx.player.position; let teammate_position = teammate.position; let passing_direction = (teammate_position - player_position).normalize(); let ray_cast_result = ctx.tick_context.space.cast_ray( player_position, passing_direction, (teammate_position - player_position).magnitude(), false, ); ray_cast_result.is_none() // No collisions with opponents } fn is_under_pressure(&self, ctx: &StateProcessingContext) -> bool { let pressure_distance = 15.0; ctx.players().opponents().exists(pressure_distance) } fn has_space_to_dribble(&self, ctx: &StateProcessingContext) -> bool { let dribble_distance = 10.0; !ctx.players().opponents().exists(dribble_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/midfielders/states/running/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/running/mod.rs
use crate::r#match::events::Event; use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::player::events::{PassingEventContext, PlayerEvent}; use crate::r#match::player::strategies::common::players::MatchPlayerIteratorExt; use crate::r#match::{ConditionContext, MatchPlayerLite, PassEvaluator, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior}; use nalgebra::Vector3; // Shooting distance constants for midfielders const MAX_SHOOTING_DISTANCE: f32 = 100.0; // Midfielders rarely shoot from beyond ~50m const STANDARD_SHOOTING_DISTANCE: f32 = 70.0; // Standard shooting range for midfielders const PRESSURE_CHECK_DISTANCE: f32 = 10.0; // Distance to check for opponent pressure before shooting #[derive(Default)] pub struct MidfielderRunningState {} impl StateProcessingHandler for MidfielderRunningState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { // Priority: Clear ball if congested anywhere (not just boundaries) // Allow emergency clearances even without stable possession if self.is_congested_near_boundary(ctx) || ctx.player().movement().is_congested() { // Try to find a good pass option first using the standard evaluator if let Some((target_teammate, _reason)) = self.find_best_pass_option(ctx) { return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Running, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(target_teammate.id) .with_reason("MID_RUNNING_EMERGENCY_CLEARANCE_BEST") .build(ctx), )), )); } // Fallback: find any nearby teammate within reasonable distance if let Some(target_teammate) = ctx.players().teammates().nearby(100.0).next() { return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Running, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(target_teammate.id) .with_reason("MID_RUNNING_EMERGENCY_CLEARANCE_NEARBY") .build(ctx), )), )); } } // Shooting evaluation for midfielders let goal_dist = ctx.ball().distance_to_opponent_goal(); let long_shots = ctx.player.skills.technical.long_shots / 20.0; let finishing = ctx.player.skills.technical.finishing / 20.0; // Standard shooting - close enough with clear shot if goal_dist <= STANDARD_SHOOTING_DISTANCE && ctx.player().has_clear_shot() && finishing > 0.55 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Shooting, )); } // Distance shooting - long range with good skills and minimal pressure if goal_dist <= MAX_SHOOTING_DISTANCE && ctx.player().has_clear_shot() && long_shots > 0.6 && finishing > 0.5 && !ctx.players().opponents().exists(PRESSURE_CHECK_DISTANCE) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::DistanceShooting, )); } // Enhanced passing decision based on skills and pressing // Require stable possession before allowing passes (prevents instant pass after claiming ball) if ctx.ball().has_stable_possession() && self.should_pass(ctx) { if let Some((target_teammate, _reason)) = self.find_best_pass_option(ctx) { return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Running, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(target_teammate.id) .with_reason("MID_RUNNING_SHOULD_PASS") .build(ctx), )), )); } } } else { // Without ball - check for opponent with ball first (highest priority) // CRITICAL: Tackle opponent with ball if close enough // Using new chaining syntax: nearby(100.0).with_ball(ctx) if let Some(opponent) = ctx.players().opponents().nearby(100.0).with_ball(ctx).next() { let opponent_distance = (opponent.position - ctx.player.position).magnitude(); // If opponent with ball is very close, tackle immediately if opponent_distance < 30.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Tackling, )); } // If opponent with ball is nearby, press them (already filtered by nearby(100.0)) return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } // 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_midfielder_state( MidfielderState::TakeBall, )); } } if ctx.ball().distance() < 30.0 && !ctx.ball().is_owned() { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Intercepting, )); } } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Simplified waypoint following 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: 5.0, // Fixed offset instead of random } .calculate(ctx.player) .velocity + ctx.player().separation_velocity(), ); } } // Simplified movement calculation if ctx.player.has_ball(ctx) { Some(self.calculate_simple_ball_movement(ctx)) } else if ctx.team().is_control_ball() { Some(self.calculate_simple_support_movement(ctx)) } else { Some(self.calculate_simple_defensive_movement(ctx)) } } fn process_conditions(&self, ctx: ConditionContext) { // Midfielders cover the most ground during a match - box to box running // High intensity with velocity-based adjustment MidfielderCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl MidfielderRunningState { fn find_best_pass_option<'a>( &self, ctx: &StateProcessingContext<'a>, ) -> Option<(MatchPlayerLite, &'static str)> { PassEvaluator::find_best_pass_option(ctx, 300.0) } /// Simplified ball carrying movement fn calculate_simple_ball_movement(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let goal_pos = ctx.player().opponent_goal_position(); let player_pos = ctx.player.position; // Simple decision: move toward goal with slight variation let to_goal = (goal_pos - player_pos).normalize(); // Add small lateral movement based on time for variation let lateral = if ctx.in_state_time % 60 < 30 { Vector3::new(-to_goal.y * 0.2, to_goal.x * 0.2, 0.0) } else { Vector3::new(to_goal.y * 0.2, -to_goal.x * 0.2, 0.0) }; let target = player_pos + (to_goal + lateral).normalize() * 40.0; SteeringBehavior::Arrive { target, slowing_distance: 20.0, } .calculate(ctx.player) .velocity + ctx.player().separation_velocity() } /// Simplified support movement fn calculate_simple_support_movement(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_pos = ctx.tick_context.positions.ball.position; let player_pos = ctx.player.position; // Simple triangle formation with ball let angle = if player_pos.y < ctx.context.field_size.height as f32 / 2.0 { -45.0_f32.to_radians() } else { 45.0_f32.to_radians() }; let support_offset = Vector3::new( angle.cos() * 30.0, angle.sin() * 30.0, 0.0, ); let target = ball_pos + support_offset; SteeringBehavior::Arrive { target, slowing_distance: 15.0, } .calculate(ctx.player) .velocity + ctx.player().separation_velocity() } /// Simplified defensive movement fn calculate_simple_defensive_movement(&self, ctx: &StateProcessingContext) -> Vector3<f32> { // Move toward midpoint between ball and starting position let ball_pos = ctx.tick_context.positions.ball.position; let start_pos = ctx.player.start_position; let target = (ball_pos + start_pos) * 0.5; SteeringBehavior::Arrive { target, slowing_distance: 20.0, } .calculate(ctx.player) .velocity + ctx.player().separation_velocity() } /// Enhanced passing decision that considers player skills and pressing intensity fn should_pass(&self, ctx: &StateProcessingContext) -> bool { // Get player skills let vision = ctx.player.skills.mental.vision / 20.0; let passing = ctx.player.skills.technical.passing / 20.0; let decisions = ctx.player.skills.mental.decisions / 20.0; let composure = ctx.player.skills.mental.composure / 20.0; let teamwork = ctx.player.skills.mental.teamwork / 20.0; // Assess pressing situation let pressing_intensity = self.calculate_pressing_intensity(ctx); let distance_to_goal = ctx.ball().distance_to_opponent_goal(); // 1. MUST PASS: Heavy pressing (multiple opponents very close) if pressing_intensity > 0.7 { // Even low-skilled players should pass under heavy pressure return passing > 0.3 || composure < 0.5; } // 2. FORCED PASS: Under moderate pressure with limited skills if pressing_intensity > 0.5 && (passing < 0.6 || composure < 0.6) { return true; } // 3. TACTICAL PASS: Skilled players looking for opportunities // Players with high vision and passing can spot good passes even without pressure if vision > 0.7 && passing > 0.7 { // Check if there's a better-positioned teammate if self.has_better_positioned_teammate(ctx, distance_to_goal) { return true; } } // 4. TEAM PLAY: High teamwork players distribute more if teamwork > 0.7 && decisions > 0.6 && pressing_intensity > 0.3 { // Midfielders with good teamwork pass to maintain possession and tempo return self.find_best_pass_option(ctx).is_some(); } // 5. UNDER LIGHT PRESSURE: Decide based on skills and options if pressing_intensity > 0.3 { // Better decision-makers are more likely to pass when slightly pressed let pass_likelihood = (decisions * 0.4) + (vision * 0.3) + (passing * 0.3); return pass_likelihood > 0.6; } // 6. NO PRESSURE: Continue running unless very close to goal // Very skilled passers might still look for a pass if in midfield if distance_to_goal > 300.0 && vision > 0.8 && passing > 0.8 { return self.has_teammate_in_dangerous_position(ctx); } false } /// Calculate pressing intensity based on number and proximity of opponents fn calculate_pressing_intensity(&self, ctx: &StateProcessingContext) -> f32 { let very_close = ctx.players().opponents().nearby(15.0).count() as f32; let close = ctx.players().opponents().nearby(30.0).count() as f32; let medium = ctx.players().opponents().nearby(50.0).count() as f32; // Weight closer opponents more heavily let weighted_pressure = (very_close * 0.5) + (close * 0.3) + (medium * 0.1); // Normalize to 0-1 range (assuming max 5 opponents can reasonably press) (weighted_pressure / 2.0).min(1.0) } /// Check if there's a teammate in a better position fn has_better_positioned_teammate(&self, ctx: &StateProcessingContext, current_distance: f32) -> bool { ctx.players() .teammates() .nearby(300.0) .any(|teammate| { let teammate_distance = (teammate.position - ctx.player().opponent_goal_position()).magnitude(); let is_closer = teammate_distance < current_distance * 0.8; let has_space = ctx.players().opponents().all() .filter(|opp| (opp.position - teammate.position).magnitude() < 15.0) .count() < 2; let has_clear_pass = ctx.player().has_clear_pass(teammate.id); is_closer && has_space && has_clear_pass }) } /// Check if there's a teammate in a dangerous attacking position fn has_teammate_in_dangerous_position(&self, ctx: &StateProcessingContext) -> bool { ctx.players() .teammates() .nearby(350.0) .any(|teammate| { // Prefer forwards and attacking midfielders let is_attacker = teammate.tactical_positions.is_forward() || teammate.tactical_positions.is_midfielder(); // Check if in attacking third let teammate_distance = (teammate.position - ctx.player().opponent_goal_position()).magnitude(); let field_width = ctx.context.field_size.width as f32; let in_attacking_third = teammate_distance < field_width * 0.4; // Check if in free space let in_free_space = ctx.players().opponents().all() .filter(|opp| (opp.position - teammate.position).magnitude() < 12.0) .count() < 2; // Check if making a forward run let teammate_velocity = ctx.tick_context.positions.players.velocity(teammate.id); let making_run = teammate_velocity.magnitude() > 1.5 && { let to_goal = ctx.player().opponent_goal_position() - teammate.position; teammate_velocity.normalize().dot(&to_goal.normalize()) > 0.5 }; let has_clear_pass = ctx.player().has_clear_pass(teammate.id); is_attacker && in_attacking_third && (in_free_space || making_run) && has_clear_pass }) } /// Check if player is stuck in a corner/boundary with multiple players around fn is_congested_near_boundary(&self, ctx: &StateProcessingContext) -> bool { // Check if near any boundary (within 20 units) let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; let pos = ctx.player.position; let near_boundary = pos.x < 20.0 || pos.x > field_width - 20.0 || pos.y < 20.0 || pos.y > field_height - 20.0; if !near_boundary { return false; } // Count all nearby players (teammates + opponents) within 15 units let nearby_teammates = ctx.players().teammates().nearby(15.0).count(); let nearby_opponents = ctx.players().opponents().nearby(15.0).count(); let total_nearby = nearby_teammates + nearby_opponents; // If 3 or more players nearby (congestion), need to clear total_nearby >= 3 } }
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/midfielders/states/resting/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/resting/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::{ ConditionContext, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const STAMINA_RECOVERY_THRESHOLD: f32 = 90.0; const BALL_PROXIMITY_THRESHOLD: f32 = 10.0; const MARKING_DISTANCE_THRESHOLD: f32 = 10.0; const OPPONENT_THREAT_THRESHOLD: usize = 2; #[derive(Default)] pub struct MidfielderRestingState {} impl StateProcessingHandler for MidfielderRestingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if player's stamina has recovered let stamina = ctx.player.player_attributes.condition_percentage() as f32; if stamina >= STAMINA_RECOVERY_THRESHOLD { // Transition back to Standing state return Some(StateChangeResult::with_midfielder_state( MidfielderState::Standing, )); } if ctx.ball().distance() < BALL_PROXIMITY_THRESHOLD { // If the ball is close, check for nearby opponents let opponent_nearby = self.is_opponent_nearby(ctx); return Some(StateChangeResult::with_midfielder_state(if opponent_nearby { MidfielderState::Tackling } else { MidfielderState::Intercepting })); } // 3. Check if the team is under threat if self.is_team_under_threat(ctx) { // Transition to Pressing state to help the team return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } // 4. Remain in Resting state None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Defender remains stationary or moves minimally while resting Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Resting provides recovery - negative fatigue MidfielderCondition::new(ActivityIntensity::Recovery).process(ctx); } } impl MidfielderRestingState { /// Checks if an opponent player is nearby within the MARKING_DISTANCE_THRESHOLD. fn is_opponent_nearby(&self, ctx: &StateProcessingContext) -> bool { ctx.players().opponents().exists(MARKING_DISTANCE_THRESHOLD) } /// Determines if the team is under threat based on the number of opponents in the attacking third. fn is_team_under_threat(&self, ctx: &StateProcessingContext) -> bool { let opponents_in_attacking_third = ctx .players() .opponents() .all() .filter(|opponent| self.is_in_defensive_third(opponent.position, ctx)) .count(); opponents_in_attacking_third >= OPPONENT_THREAT_THRESHOLD } /// Checks if a position is within the team's defensive third of the field. fn is_in_defensive_third(&self, position: Vector3<f32>, ctx: &StateProcessingContext) -> bool { let field_length = ctx.context.field_size.width as f32; if ctx.player.side == Some(PlayerSide::Left) { position.x < field_length / 3.0 } else { position.x > (2.0 / 3.0) * field_length } } }
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/midfielders/states/tracking_runner/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/tracking_runner/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; const TRACKING_DISTANCE_THRESHOLD: f32 = 30.0; // Maximum distance to track the runner const STAMINA_THRESHOLD: f32 = 50.0; // Minimum stamina required to continue tracking const BALL_INTERCEPTION_DISTANCE: f32 = 15.0; // Distance to switch to intercepting ball #[derive(Default)] pub struct MidfielderTrackingRunnerState {} impl StateProcessingHandler for MidfielderTrackingRunnerState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Check for ball interception opportunities first let ball_distance = ctx.ball().distance(); if ball_distance < BALL_INTERCEPTION_DISTANCE && ctx.ball().is_towards_player() { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Intercepting, )); } // Check if opponent with ball is nearby - switch to tackling if let Some(opponent_with_ball) = ctx.players().opponents().with_ball().next() { let distance = opponent_with_ball.distance(ctx); if distance < 5.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Tackling, )); } else if distance < 20.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } } let nearest_forward = ctx.players().opponents().forwards().min_by(|a, b| { let dist_a = (a.position - ctx.player.position).magnitude(); let dist_b = (b.position - ctx.player.position).magnitude(); dist_a.partial_cmp(&dist_b).unwrap() }); if let Some(runner) = nearest_forward { // Check if the midfielder has enough stamina to continue tracking if ctx.player.player_attributes.condition_percentage() < STAMINA_THRESHOLD as u32 { // If stamina is low, transition to the Defending state return Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )); } // Check if the runner is within tracking distance let distance_to_runner = (ctx.player.position - runner.position).magnitude(); if distance_to_runner > TRACKING_DISTANCE_THRESHOLD { // If the runner is too far, transition to the Defending state return Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )); } // Continue tracking the runner None } else { // If no opponent runner is found, transition to the Defending state Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { let nearest_forward = ctx.players().opponents().forwards().min_by(|a, b| { let dist_a = (a.position - ctx.player.position).magnitude(); let dist_b = (b.position - ctx.player.position).magnitude(); dist_a.partial_cmp(&dist_b).unwrap() }); // Move towards the opponent runner if let Some(runner) = nearest_forward { let steering = SteeringBehavior::Pursuit { target: runner.position, target_velocity: Vector3::zeros(), // Opponent velocity not available in lite struct } .calculate(ctx.player); Some(steering.velocity) } else { // If no runner is found, stay in the current position Some(Vector3::new(0.0, 0.0, 0.0)) } } fn process_conditions(&self, ctx: ConditionContext) { // Tracking runner is moderate intensity - sustained tracking MidfielderCondition::with_velocity(ActivityIntensity::Moderate).process(ctx); } } impl MidfielderTrackingRunnerState {}
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/midfielders/states/distributing/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/distributing/mod.rs
use crate::r#match::events::Event; use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::player::events::{PassingEventContext, PlayerEvent}; use crate::r#match::{ ConditionContext, MatchPlayerLite, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderDistributingState {} impl StateProcessingHandler for MidfielderDistributingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Find the best passing option if let Some(teammate) = self.find_best_pass_option(ctx) { return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Running, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(teammate.id) .with_reason("MID_DISTRIBUTING") .build(ctx), )), )); } 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) { // Distributing is moderate intensity MidfielderCondition::new(ActivityIntensity::Moderate).process(ctx); } } impl MidfielderDistributingState { fn find_best_pass_option<'a>( &self, ctx: &StateProcessingContext<'a>, ) -> Option<MatchPlayerLite> { let vision_range = ctx.player.skills.mental.vision * 10.0; // Adjust the factor as needed let open_teammates: Vec<MatchPlayerLite> = ctx.players().teammates() .nearby(vision_range) .filter(|t| !t.tactical_positions.is_goalkeeper()) .filter(|t| self.is_teammate_open(ctx, t) && ctx.player().has_clear_pass(t.id)) .collect(); if !open_teammates.is_empty() { let best_option = open_teammates .iter() .max_by(|a, b| { let space_a = self.calculate_space_around_player(ctx, a); let space_b = self.calculate_space_around_player(ctx, b); space_a .partial_cmp(&space_b) .unwrap_or(std::cmp::Ordering::Equal) }) .cloned(); best_option } else { None } } fn is_teammate_open(&self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite) -> bool { let opponent_distance_threshold = 5.0; // Adjust the threshold as needed let opponents_nearby = ctx .players() .opponents() .all() .filter(|opponent| { let distance = (opponent.position - teammate.position).magnitude(); distance <= opponent_distance_threshold }) .count(); opponents_nearby == 0 } fn calculate_space_around_player( &self, ctx: &StateProcessingContext, player: &MatchPlayerLite, ) -> f32 { let space_radius = 10.0; // Adjust the radius as needed 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 } }
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/midfielders/states/crossing/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/crossing/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderCrossingState {} impl StateProcessingHandler for MidfielderCrossingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if !ctx.player.has_ball(ctx) { // Lost possession, transition to Pressing return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } 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) { // Crossing is very high intensity - explosive action MidfielderCondition::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/midfielders/states/standing/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/standing/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::{ ConditionContext, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; const PRESSING_DISTANCE_THRESHOLD: f32 = 50.0; // Adjust as needed #[derive(Default)] pub struct MidfielderStandingState {} impl StateProcessingHandler for MidfielderStandingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Add timeout to prevent getting stuck in standing state if ctx.in_state_time > 30 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } if ctx.player.has_ball(ctx) { // Decide whether to hold possession or distribute the ball return if self.should_hold_possession(ctx) { Some(StateChangeResult::with_midfielder_state( MidfielderState::HoldingPossession, )) } else { Some(StateChangeResult::with_midfielder_state( MidfielderState::Distributing, )) }; } else { // Emergency: if ball is nearby, stopped, and unowned, go for it immediately if ctx.ball().should_take_ball_immediately() { return Some(StateChangeResult::with_midfielder_state( MidfielderState::TakeBall, )); } if ctx.team().is_control_ball() { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } else { // Only press/tackle if an OPPONENT has the ball if let Some(_opponent) = ctx.players().opponents().with_ball().next() { if ctx.ball().distance() < PRESSING_DISTANCE_THRESHOLD { // Transition to Pressing state to try and win the ball return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } if ctx.ball().distance() < 100.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Tackling, )); } } // Only intercept if ball is loose (not owned by anyone) if !ctx.ball().is_owned() && ctx.ball().distance() < 250.0 && ctx.ball().is_towards_player_with_angle(0.8) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Intercepting, )); } } } // Only press if opponent is nearby AND has the ball if let Some(opponent) = ctx.players().opponents().with_ball().next() { if opponent.distance(ctx) < PRESSING_DISTANCE_THRESHOLD { // Transition to Pressing state to apply pressure return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } } // 4. Check if a teammate is making a run and needs support if self.should_support_attack(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::AttackSupporting, )); } // If nothing else is happening, start moving again after a brief pause if ctx.in_state_time > 15 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } 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 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 MidfielderCondition::new(ActivityIntensity::Recovery).process(ctx); } } impl MidfielderStandingState { /// Checks if the midfielder should hold possession based on game context. fn should_hold_possession(&self, ctx: &StateProcessingContext) -> bool { // For simplicity, let's assume the midfielder holds possession if there are no immediate passing options !self.has_passing_options(ctx) } /// Determines if the midfielder has passing options. fn has_passing_options(&self, ctx: &StateProcessingContext) -> bool { const PASSING_DISTANCE_THRESHOLD: f32 = 30.0; ctx.players().teammates().exists(PASSING_DISTANCE_THRESHOLD) } /// Checks if an opponent player is nearby within the pressing threshold. fn is_opponent_nearby(&self, ctx: &StateProcessingContext) -> bool { ctx.players() .opponents() .exists(PRESSING_DISTANCE_THRESHOLD) } /// Determines if the midfielder should support an attacking play. fn should_support_attack(&self, ctx: &StateProcessingContext) -> bool { // For simplicity, assume the midfielder supports the attack if the ball is in the attacking third let field_length = ctx.context.field_size.width as f32; let attacking_third_start = if ctx.player.side == Some(PlayerSide::Left) { field_length * (2.0 / 3.0) } else { field_length / 3.0 }; let ball_position_x = ctx.tick_context.positions.ball.position.x; if ctx.player.side == Some(PlayerSide::Left) { ball_position_x > attacking_third_start } else { ball_position_x < attacking_third_start } } }
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/midfielders/states/common/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/common/mod.rs
use crate::r#match::engine::player::strategies::common::{ ActivityIntensityConfig, ConditionProcessor, LOW_CONDITION_THRESHOLD, FIELD_PLAYER_JADEDNESS_INTERVAL, JADEDNESS_INCREMENT, }; /// Midfielder-specific activity intensity configuration pub struct MidfielderConfig; impl ActivityIntensityConfig for MidfielderConfig { fn very_high_fatigue() -> f32 { 8.0 // Explosive actions tire quickly } fn high_fatigue() -> f32 { 5.0 // Base from running state } fn moderate_fatigue() -> f32 { 3.0 } fn low_fatigue() -> f32 { 1.0 } fn recovery_rate() -> f32 { -3.0 } fn sprint_multiplier() -> f32 { 1.5 // Sprinting } 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 } } /// Midfielder condition processor (type alias for clarity) pub type MidfielderCondition = ConditionProcessor<MidfielderConfig>; // 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/midfielders/states/takeball/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/takeball/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; 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 MidfielderTakeBallState {} impl StateProcessingHandler for MidfielderTakeBallState { 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_midfielder_state( MidfielderState::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_midfielder_state( MidfielderState::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 prepare to defend if opponent_distance < ball_distance - OPPONENT_ADVANTAGE_THRESHOLD { return Some(StateChangeResult::with_midfielder_state( MidfielderState::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_midfielder_state( MidfielderState::AttackSupporting, )); } } // 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); let max_speed = ctx.player.skills.max_speed_with_condition( ctx.player.player_attributes.condition, ); separation_force = separation_force * max_speed * 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 > max_speed { arrive_velocity = arrive_velocity * (max_speed / magnitude); } } Some(arrive_velocity) } fn process_conditions(&self, ctx: ConditionContext) { // Taking ball is very high intensity - explosive action to claim possession MidfielderCondition::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/midfielders/states/shooting/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/shooting/mod.rs
use crate::r#match::events::Event; use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::player::events::{PlayerEvent, ShootingEventContext}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderShootingState {} impl StateProcessingHandler for MidfielderShootingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Check if the midfielder still has the ball if !ctx.player.has_ball(ctx) { // Lost possession, transition to Pressing return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } Some(StateChangeResult::with_midfielder_state_and_event(MidfielderState::Standing, Event::PlayerEvent(PlayerEvent::Shoot( ShootingEventContext::new() .with_player_id(ctx.player.id) .with_target(ctx.player().shooting_direction()) .with_reason("MID_SHOOTING") .build(ctx) )))) } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // No slow processing needed None } fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Midfielder remains stationary while taking the shot Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Shooting is very high intensity - explosive action MidfielderCondition::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/midfielders/states/returning/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/returning/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::player::strategies::common::players::MatchPlayerIteratorExt; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderReturningState {} impl StateProcessingHandler for MidfielderReturningState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } // CRITICAL: Tackle if an opponent has the ball nearby // Using new chaining syntax: nearby(30.0).with_ball(ctx) if let Some(opponent) = ctx.players().opponents().nearby(30.0).with_ball(ctx).next() { let opponent_distance = (opponent.position - ctx.player.position).magnitude(); if opponent_distance < 30.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Tackling, )); } } if !ctx.team().is_control_ball() && ctx.ball().distance() < 250.0 && ctx.ball().is_towards_player_with_angle(0.8) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Intercepting, )); } // Use hysteresis: only transition to Walking when significantly close (< 80 units) // This prevents oscillation at the 100-unit boundary let distance_to_start = (ctx.player.position - ctx.player.start_position).magnitude(); if distance_to_start < 80.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Walking, )); } 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: 50.0, // Increased from 10.0 to slow down earlier and prevent overshoot } .calculate(ctx.player) .velocity + ctx.player().separation_velocity(), ) } fn process_conditions(&self, ctx: ConditionContext) { // Returning is moderate intensity - getting back to position MidfielderCondition::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/midfielders/states/pressing/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/pressing/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::player::strategies::common::players::MatchPlayerIteratorExt; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderPressingState {} impl StateProcessingHandler for MidfielderPressingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.in_state_time > 60 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } // Early exit if a teammate is significantly closer to avoid circular running let ball_distance = ctx.ball().distance(); let ball_position = ctx.tick_context.positions.ball.position; 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 closer by 10+ units, give up pressing if teammate_distance < ball_distance - 10.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } } // CRITICAL: Tackle if an opponent has the ball nearby // Using new chaining syntax: nearby(30.0).with_ball(ctx) if let Some(opponent) = ctx.players().opponents().nearby(30.0).with_ball(ctx).next() { let opponent_distance = (opponent.position - ctx.player.position).magnitude(); // This prevents the midfielder from just circling without tackling if opponent_distance < 30.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Tackling, )); } } // If ball is far away or team has possession, stop pressing if ctx.ball().distance() > 250.0 || !ctx.ball().is_towards_player_with_angle(0.8) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Returning, )); } // If team has possession, contribute to attack if ctx.team().is_control_ball() { return Some(StateChangeResult::with_midfielder_state( MidfielderState::AttackSupporting, )); } // Check if the pressing is ineffective (opponent still has ball after some time) if ctx.in_state_time > 30 && !self.is_making_progress(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } 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().nearby(500.0).with_ball(ctx).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 MidfielderCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl MidfielderPressingState { // New helper function to determine if pressing is making progress fn is_making_progress(&self, ctx: &StateProcessingContext) -> bool { let player_velocity = ctx.player.velocity; // Calculate dot product between player velocity and direction to ball let to_ball = ctx.tick_context.positions.ball.position - ctx.player.position; let to_ball_normalized = if to_ball.magnitude() > 0.0 { to_ball / to_ball.magnitude() } else { Vector3::new(0.0, 0.0, 0.0) }; let moving_toward_ball = player_velocity.dot(&to_ball_normalized) > 0.0; // Check if other teammates are better positioned to press let other_pressing_teammates = ctx.players().teammates().all() .filter(|t| { let dist = (t.position - ctx.tick_context.positions.ball.position).magnitude(); dist < ctx.ball().distance() * 0.8 // 20% closer than current player }) .count(); // Continue pressing if moving toward ball and not many better-positioned teammates moving_toward_ball && other_pressing_teammates < 2 } }
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/midfielders/states/passing/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/passing/mod.rs
use crate::r#match::events::Event; use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::player::events::{PassingEventContext, PlayerEvent}; use crate::r#match::{ConditionContext, MatchPlayerLite, PassEvaluator, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior}; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderPassingState {} impl StateProcessingHandler for MidfielderPassingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Check if the midfielder still has the ball if !ctx.player.has_ball(ctx) { // Lost possession, transition to Running return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } // Check if should shoot instead if self.should_shoot_instead_of_pass(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Shooting, )); } if !ctx.ball().on_own_side() { // First, look for high-value breakthrough passes (for skilled players) if let Some(breakthrough_target) = self.find_breakthrough_pass_option(ctx) { // Execute the high-quality breakthrough pass return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(breakthrough_target.id) .with_reason("MID_PASSING_BREAKTHROUGH") .build(ctx), )), )); } } // Find the best regular pass option with improved logic if let Some((target_teammate, _reason)) = self.find_best_pass_option(ctx) { return Some(StateChangeResult::with_midfielder_state_and_event( MidfielderState::Running, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(target_teammate.id) .with_reason("MID_PASSING_STATE") .build(ctx), )), )); } // If no good passing option after waiting, try something else // Reduced from 50 to 30 ticks for faster decision-making if ctx.in_state_time > 30 { return if ctx.ball().distance_to_opponent_goal() < 200.0 { Some(StateChangeResult::with_midfielder_state( MidfielderState::DistanceShooting, )) } else { Some(StateChangeResult::with_midfielder_state( MidfielderState::Dribbling, )) }; } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // If under heavy pressure, shield the ball and create space if self.is_under_heavy_pressure(ctx) { // Move away from nearest opponent to create passing space if let Some(nearest_opponent) = ctx.players().opponents().nearby(15.0).next() { let away_from_opponent = (ctx.player.position - nearest_opponent.position).normalize(); // Shield ball by moving perpendicular to goal direction let to_goal = (ctx.player().opponent_goal_position() - ctx.player.position).normalize(); let perpendicular = Vector3::new(-to_goal.y, to_goal.x, 0.0); let escape_direction = (away_from_opponent * 0.7 + perpendicular * 0.3).normalize(); return Some(escape_direction * 2.5 + ctx.player().separation_velocity()); } } // Adjust position to find better passing angles if needed if self.should_adjust_position(ctx) { if let Some(nearest_teammate) = ctx.players().teammates().nearby_to_opponent_goal() { return Some( SteeringBehavior::Arrive { target: self.calculate_better_passing_position(ctx, &nearest_teammate), slowing_distance: 30.0, } .calculate(ctx.player) .velocity + ctx.player().separation_velocity(), ); } } // Default: slow, controlled movement with ball - like scanning for options // Use separation to avoid colliding with other players Some(ctx.player().separation_velocity() * 0.5) } fn process_conditions(&self, ctx: ConditionContext) { // Passing is low intensity - minimal fatigue MidfielderCondition::new(ActivityIntensity::Low).process(ctx); } } impl MidfielderPassingState { /// Find breakthrough pass opportunities for players with high vision fn find_breakthrough_pass_option<'a>( &self, ctx: &StateProcessingContext<'a>, ) -> Option<MatchPlayerLite> { let vision_skill = ctx.player.skills.mental.vision; let passing_skill = ctx.player.skills.technical.passing; // Lowered thresholds from 15.0/14.0 to allow more players to attempt through balls if vision_skill < 12.0 || passing_skill < 11.0 { return None; } let vision_range = vision_skill * 20.0; let teammates = ctx.players().teammates(); let breakthrough_targets = teammates.all() .filter(|teammate| { let velocity = ctx.tick_context.positions.players.velocity(teammate.id); let is_moving_forward = velocity.magnitude() > 1.0; let is_attacking_player = teammate.tactical_positions.is_forward() || teammate.tactical_positions.is_midfielder(); let distance = (teammate.position - ctx.player.position).magnitude(); let would_break_lines = self.would_pass_break_defensive_lines(ctx, teammate); distance < vision_range && is_moving_forward && is_attacking_player && would_break_lines }) .collect::<Vec<_>>(); breakthrough_targets.into_iter() .max_by(|a, b| { let a_value = self.calculate_breakthrough_value(ctx, a); let b_value = self.calculate_breakthrough_value(ctx, b); a_value.partial_cmp(&b_value).unwrap_or(std::cmp::Ordering::Equal) }) } /// Improved best pass option finder that prevents clustering fn find_best_pass_option<'a>( &self, ctx: &StateProcessingContext<'a>, ) -> Option<(MatchPlayerLite, &'static str)> { PassEvaluator::find_best_pass_option(ctx, 400.0) } /// Improved space calculation around player fn calculate_improved_space_score( &self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite, ) -> f32 { // Check for opponents in different radius zones let very_close_opponents = ctx.players().opponents().all() .filter(|opp| (opp.position - teammate.position).magnitude() < 5.0) .count(); let close_opponents = ctx.players().opponents().all() .filter(|opp| { let dist = (opp.position - teammate.position).magnitude(); (5.0..10.0).contains(&dist) }) .count(); let medium_opponents = ctx.players().opponents().all() .filter(|opp| { let dist = (opp.position - teammate.position).magnitude(); (10.0..15.0).contains(&dist) }) .count(); // Calculate weighted score let space_score: f32 = 1.0 - (very_close_opponents as f32 * 0.5) - (close_opponents as f32 * 0.3) - (medium_opponents as f32 * 0.1); space_score.max(0.0) } /// Check if pass would break defensive lines fn would_pass_break_defensive_lines( &self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite, ) -> bool { let player_pos = ctx.player.position; let teammate_pos = teammate.position; let pass_direction = (teammate_pos - player_pos).normalize(); let pass_distance = (teammate_pos - player_pos).magnitude(); let opponents_between = ctx.players().opponents().all() .filter(|opponent| { let to_opponent = opponent.position - player_pos; let projection_distance = to_opponent.dot(&pass_direction); if projection_distance <= 0.0 || projection_distance >= pass_distance { return false; } let projected_point = player_pos + pass_direction * projection_distance; let perp_distance = (opponent.position - projected_point).magnitude(); perp_distance < 8.0 }) .collect::<Vec<_>>(); if opponents_between.len() >= 2 { let vision_skill = ctx.player.skills.mental.vision / 20.0; let passing_skill = ctx.player.skills.technical.passing / 20.0; let skill_factor = (vision_skill + passing_skill) / 2.0; let max_opponents = 2.0 + (skill_factor * 2.0); return opponents_between.len() as f32 <= max_opponents; } false } /// Calculate breakthrough value fn calculate_breakthrough_value( &self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite, ) -> f32 { let goal_distance = (teammate.position - ctx.player().opponent_goal_position()).magnitude(); let field_width = ctx.context.field_size.width as f32; let goal_distance_value = 1.0 - (goal_distance / field_width).clamp(0.0, 1.0); let space_value = self.calculate_improved_space_score(ctx, teammate); let player = ctx.player(); let target_skills = player.skills(teammate.id); let finishing_skill = target_skills.technical.finishing / 20.0; (goal_distance_value * 0.5) + (space_value * 0.3) + (finishing_skill * 0.2) } /// Check for clear passing lanes with improved logic fn has_clear_passing_lane(&self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite) -> bool { let player_position = ctx.player.position; let teammate_position = teammate.position; let passing_direction = (teammate_position - player_position).normalize(); let pass_distance = (teammate_position - player_position).magnitude(); let pass_skill = ctx.player.skills.technical.passing / 20.0; let vision_skill = ctx.player.skills.mental.vision / 20.0; let base_lane_width = 3.0; let skill_factor = 0.6 + (pass_skill * 0.2) + (vision_skill * 0.2); let lane_width = base_lane_width * skill_factor; let intercepting_opponents = ctx.players().opponents().all() .filter(|opponent| { let to_opponent = opponent.position - player_position; let projection_distance = to_opponent.dot(&passing_direction); if projection_distance <= 0.0 || projection_distance >= pass_distance { return false; } let projected_point = player_position + passing_direction * projection_distance; let perp_distance = (opponent.position - projected_point).magnitude(); let interception_skill = ctx.player().skills(opponent.id).technical.tackling / 20.0; let effective_width = lane_width * (1.0 - interception_skill * 0.3); perp_distance < effective_width }) .count(); intercepting_opponents == 0 } /// Check if player is heavily marked fn is_heavily_marked(&self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite) -> bool { const MARKING_DISTANCE: f32 = 5.0; const MAX_MARKERS: usize = 2; let markers = ctx.players().opponents().all() .filter(|opponent| { let distance = (opponent.position - teammate.position).magnitude(); distance <= MARKING_DISTANCE }) .collect::<Vec<_>>(); if markers.len() >= MAX_MARKERS { return true; } if markers.len() == 1 { let marker = &markers[0]; let marking_skill = ctx.player().skills(marker.id).mental.positioning; if marking_skill > 16.0 && (marker.position - teammate.position).magnitude() < 2.5 { return true; } } false } /// Check if teammate is in good position fn is_in_good_position(&self, ctx: &StateProcessingContext, teammate: &MatchPlayerLite) -> bool { let is_backward_pass = match ctx.player.side { Some(PlayerSide::Left) => teammate.position.x < ctx.player.position.x, Some(PlayerSide::Right) => teammate.position.x > ctx.player.position.x, None => false, }; let player_goal_distance = (ctx.player.position - ctx.player().opponent_goal_position()).magnitude(); let teammate_goal_distance = (teammate.position - ctx.player().opponent_goal_position()).magnitude(); let advances_toward_goal = teammate_goal_distance < player_goal_distance; if is_backward_pass { let under_pressure = self.is_under_heavy_pressure(ctx); let has_good_vision = ctx.player.skills.mental.vision > 15.0; return under_pressure || has_good_vision; } let teammate_will_be_pressured = ctx.players().opponents().all() .any(|opponent| { let current_distance = (opponent.position - teammate.position).magnitude(); let opponent_velocity = ctx.tick_context.positions.players.velocity(opponent.id); let future_opponent_pos = opponent.position + opponent_velocity * 10.0; let future_distance = (future_opponent_pos - teammate.position).magnitude(); current_distance < 15.0 && future_distance < 5.0 }); advances_toward_goal && !teammate_will_be_pressured } /// Determine if 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.long_shots / 20.0; let finishing_skill = ctx.player.skills.technical.finishing / 20.0; let shooting_ability = (shooting_skill * 0.7) + (finishing_skill * 0.3); let effective_shooting_range = 150.0 + (shooting_ability * 100.0); distance_to_goal < effective_shooting_range && ctx.player().has_clear_shot() } /// Check if under heavy pressure fn is_under_heavy_pressure(&self, ctx: &StateProcessingContext) -> bool { const PRESSURE_DISTANCE: f32 = 10.0; const PRESSURE_THRESHOLD: usize = 2; let pressing_opponents = ctx.players().opponents().nearby(PRESSURE_DISTANCE).count(); pressing_opponents >= PRESSURE_THRESHOLD } /// Check if should adjust position fn should_adjust_position(&self, ctx: &StateProcessingContext) -> bool { self.find_best_pass_option(ctx).is_none() && self.find_breakthrough_pass_option(ctx).is_none() && !self.is_under_heavy_pressure(ctx) } /// Calculate better position for passing fn calculate_better_passing_position( &self, ctx: &StateProcessingContext, target: &MatchPlayerLite, ) -> Vector3<f32> { let player_pos = ctx.player.position; let target_pos = target.position; let to_target = target_pos - player_pos; let direction = to_target.normalize(); let perpendicular = Vector3::new(-direction.y, direction.x, 0.0); let adjustment = perpendicular * 5.0; player_pos + adjustment } }
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/midfielders/states/walking/mod.rs
src/core/src/match/engine/player/strategies/midfielders/states/walking/mod.rs
use crate::r#match::midfielders::states::common::{ActivityIntensity, MidfielderCondition}; use crate::r#match::midfielders::states::MidfielderState; use crate::r#match::player::strategies::common::players::MatchPlayerIteratorExt; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use crate::IntegerUtils; use nalgebra::Vector3; #[derive(Default)] pub struct MidfielderWalkingState {} impl StateProcessingHandler for MidfielderWalkingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } // CRITICAL: Check for opponent with ball first (highest priority) // Using new chaining syntax: nearby(100.0).with_ball(ctx) if let Some(opponent) = ctx.players().opponents().nearby(100.0).with_ball(ctx).next() { let opponent_distance = (opponent.position - ctx.player.position).magnitude(); // If opponent with ball is very close, tackle immediately if opponent_distance < 30.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Tackling, )); } // If opponent with ball is nearby, press them (already filtered by nearby(100.0)) return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } // 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_midfielder_state( MidfielderState::TakeBall, )); } } if ctx.team().is_control_ball() { if ctx.ball().is_towards_player_with_angle(0.8) && ctx.ball().distance() < 250.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Intercepting, )); } } else { if ctx.ball().distance() < 200.0 && ctx.ball().stopped() { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running, )); } if ctx.ball().is_towards_player_with_angle(0.8) { if ctx.ball().distance() < 100.0 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Intercepting, )); } if ctx.ball().distance() < 150.0 && ctx.ball().is_towards_player_with_angle(0.8) { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Pressing, )); } } let nearby_opponents = ctx.players().opponents().nearby(150.0).collect::<Vec<_>>(); if !nearby_opponents.is_empty() { // If there are nearby opponents, assess the situation let ball_distance = ctx.ball().distance(); let mut closest_opponent_distance = f32::MAX; for opponent in &nearby_opponents { let distance = ctx.player().distance_to_player(opponent.id); if distance < closest_opponent_distance { closest_opponent_distance = distance; } } if ball_distance < 50.0 && closest_opponent_distance < 50.0 { // If the ball is close and an opponent is very close, transition to Tackling state return Some(StateChangeResult::with_midfielder_state( MidfielderState::Tackling, )); } } } if ctx.in_state_time > 100 { return Some(StateChangeResult::with_midfielder_state( MidfielderState::Running )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Impl ement neural network logic if necessary 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() { // 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, ); } } Some( SteeringBehavior::Wander { target: ctx.player.start_position, radius: IntegerUtils::random(5, 150) as f32, jitter: IntegerUtils::random(0, 2) as f32, distance: IntegerUtils::random(10, 250) as f32, angle: IntegerUtils::random(0, 110) as f32, } .calculate(ctx.player) .velocity, ) } fn process_conditions(&self, ctx: ConditionContext) { // Walking is low intensity - minimal fatigue MidfielderCondition::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/goalkeepers/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/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/goalkeepers/states/state.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/state.rs
use crate::r#match::goalkeepers::states::{GoalkeeperAttentiveState, GoalkeeperCatchingState, GoalkeeperClearingState, GoalkeeperComingOutState, GoalkeeperDistributingState, GoalkeeperDivingState, GoalkeeperHoldingState, GoalkeeperJumpingState, GoalkeeperKickingState, GoalkeeperPassingState, GoalkeeperPenaltyState, GoalkeeperPickingUpState, GoalkeeperPreparingForSaveState, GoalkeeperPressureState, GoalkeeperPunchingState, GoalkeeperRestingState, GoalkeeperReturningGoalState, GoalkeeperRunningState, GoalkeeperShootingState, GoalkeeperStandingState, GoalkeeperSweepingState, GoalkeeperTacklingState, GoalkeeperTakeBallState, GoalkeeperThrowingState, GoalkeeperWalkingState}; use crate::r#match::{StateProcessingResult, StateProcessor}; use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, Copy, PartialEq)] pub enum GoalkeeperState { Standing, // Standing Resting, // Resting Jumping, // Jumping Diving, // Diving to save the ball Catching, // Catching the ball with hands Punching, // Punching the ball away Kicking, // Kicking the ball Clearing, // Emergency clearance - boot the ball away HoldingBall, // Holding the ball in hands Throwing, // Throwing the ball with hands PickingUpBall, // Picking up the ball from the ground Distributing, // Distributing the ball after catching it ComingOut, // Coming out of the goal to intercept Passing, // Passing the ball ReturningToGoal, // Returning to the goal after coming out Tackling, // Tackling the ball Sweeping, // Acting as a "sweeper", clearing the ball in front of the defense line UnderPressure, // Under pressure from opponents Shooting, // Shoot to goal PreparingForSave, // Preparing to make a save PenaltySave, // Saving a penalty, Walking, // Walking TakeBall, // Take the ball, Attentive, // Attentive, Running, // Running } pub struct GoalkeeperStrategies {} impl GoalkeeperStrategies { pub fn process( state: GoalkeeperState, state_processor: StateProcessor, ) -> StateProcessingResult { match state { GoalkeeperState::Standing => { state_processor.process(GoalkeeperStandingState::default()) } GoalkeeperState::Resting => state_processor.process(GoalkeeperRestingState::default()), GoalkeeperState::Jumping => state_processor.process(GoalkeeperJumpingState::default()), GoalkeeperState::Diving => state_processor.process(GoalkeeperDivingState::default()), GoalkeeperState::Catching => { state_processor.process(GoalkeeperCatchingState::default()) } GoalkeeperState::Punching => { state_processor.process(GoalkeeperPunchingState::default()) } GoalkeeperState::Kicking => state_processor.process(GoalkeeperKickingState::default()), GoalkeeperState::Clearing => state_processor.process(GoalkeeperClearingState::default()), GoalkeeperState::HoldingBall => { state_processor.process(GoalkeeperHoldingState::default()) } GoalkeeperState::Throwing => { state_processor.process(GoalkeeperThrowingState::default()) } GoalkeeperState::PickingUpBall => { state_processor.process(GoalkeeperPickingUpState::default()) } GoalkeeperState::Distributing => { state_processor.process(GoalkeeperDistributingState::default()) } GoalkeeperState::ComingOut => { state_processor.process(GoalkeeperComingOutState::default()) } GoalkeeperState::ReturningToGoal => { state_processor.process(GoalkeeperReturningGoalState::default()) } GoalkeeperState::Tackling => { state_processor.process(GoalkeeperTacklingState::default()) } GoalkeeperState::Sweeping => { state_processor.process(GoalkeeperSweepingState::default()) } GoalkeeperState::UnderPressure => { state_processor.process(GoalkeeperPressureState::default()) } GoalkeeperState::Shooting => { state_processor.process(GoalkeeperShootingState::default()) } GoalkeeperState::PreparingForSave => { state_processor.process(GoalkeeperPreparingForSaveState::default()) } GoalkeeperState::PenaltySave => { state_processor.process(GoalkeeperPenaltyState::default()) } GoalkeeperState::Walking => state_processor.process(GoalkeeperWalkingState::default()), GoalkeeperState::Passing => state_processor.process(GoalkeeperPassingState::default()), GoalkeeperState::TakeBall => { state_processor.process(GoalkeeperTakeBallState::default()) } GoalkeeperState::Attentive => { state_processor.process(GoalkeeperAttentiveState::default()) } GoalkeeperState::Running => { state_processor.process(GoalkeeperRunningState::default())} } } } impl Display for GoalkeeperState { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { GoalkeeperState::Standing => write!(f, "Standing"), GoalkeeperState::Resting => write!(f, "Resting"), GoalkeeperState::Jumping => write!(f, "Jumping"), GoalkeeperState::Diving => write!(f, "Diving"), GoalkeeperState::Catching => write!(f, "Catching"), GoalkeeperState::Punching => write!(f, "Punching"), GoalkeeperState::Kicking => write!(f, "Kicking"), GoalkeeperState::Clearing => write!(f, "Clearing"), GoalkeeperState::HoldingBall => write!(f, "Holding Ball"), GoalkeeperState::Throwing => write!(f, "Throwing"), GoalkeeperState::PickingUpBall => write!(f, "Picking Up Ball"), GoalkeeperState::Distributing => write!(f, "Distributing"), GoalkeeperState::ComingOut => write!(f, "Coming Out"), GoalkeeperState::ReturningToGoal => write!(f, "Returning to Goal"), GoalkeeperState::Sweeping => write!(f, "Sweeping"), GoalkeeperState::UnderPressure => write!(f, "Under Pressure"), GoalkeeperState::Shooting => write!(f, "Try shoot to goal"), GoalkeeperState::PreparingForSave => write!(f, "Preparing for Save"), GoalkeeperState::PenaltySave => write!(f, "Penalty Save"), GoalkeeperState::Tackling => write!(f, "Tackling"), GoalkeeperState::Walking => write!(f, "Walking"), GoalkeeperState::Passing => write!(f, "Passing"), GoalkeeperState::TakeBall => write!(f, "Take Ball"), GoalkeeperState::Attentive => write!(f, "Attentive"), GoalkeeperState::Running => write!(f, "Running"), } } }
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/goalkeepers/states/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/mod.rs
pub mod attentive; pub mod catching; pub mod clearing; pub mod comingout; pub mod common; pub mod distributing; pub mod diving; pub mod holding; pub mod jumping; pub mod kicking; pub mod passing; pub mod penalty; pub mod picking_up; pub mod preparing_for_save; pub mod pressure; pub mod punching; pub mod resting; pub mod returning_goal; pub mod running; pub mod shooting; pub mod standing; pub mod state; pub mod sweeping; pub mod tackling; pub mod takeball; pub mod throwing; pub mod walking; pub use attentive::*; pub use catching::*; pub use clearing::*; pub use comingout::*; pub use distributing::*; pub use diving::*; pub use holding::*; pub use jumping::*; pub use kicking::*; pub use passing::*; pub use penalty::*; pub use picking_up::*; pub use preparing_for_save::*; pub use pressure::*; pub use punching::*; pub use resting::*; pub use returning_goal::*; pub use running::*; pub use shooting::*; pub use standing::*; pub use sweeping::*; pub use tackling::*; pub use takeball::*; pub use throwing::*; 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/goalkeepers/states/attentive/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/attentive/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::strategies::processor::StateChangeResult; use crate::r#match::player::strategies::processor::{StateProcessingContext, StateProcessingHandler}; use crate::r#match::{ ConditionContext, PlayerSide, SteeringBehavior, VectorExtensions, }; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperAttentiveState {} impl StateProcessingHandler for GoalkeeperAttentiveState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // First, handle if goalkeeper already has the ball if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Distributing, )); } // Check if the ball is on the goalkeeper's side of the field if ctx.ball().on_own_side() { // Calculate actual distance to ball rather than using a fixed threshold let ball_distance = ctx.ball().distance(); // If the ball is close and the goalkeeper should come out, transition to ComingOut if self.should_come_out(ctx) && ball_distance < 300.0 { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ComingOut, )); } // If the ball is moving toward the goalkeeper, prepare for save else if ctx.ball().is_towards_player_with_angle(0.8) && ball_distance < 200.0 { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::PreparingForSave, )); } // If the ball is very close to the goalkeeper, attempt to intercept it else if ball_distance < 50.0 { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ComingOut, )); } } // Check if the goalkeeper is out of position and needs to return if self.is_out_of_position(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } // Check if there's an immediate threat if self.is_under_threat(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::UnderPressure, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Calculate optimal position based on ball and goal geometry let optimal_position = self.calculate_optimal_position(ctx); let distance_to_optimal = ctx.player.position.distance_to(&optimal_position); // Use positioning skill for movement decisions let positioning_skill = ctx.player.skills.mental.positioning / 20.0; let agility = ctx.player.skills.physical.agility / 20.0; // Movement speed based on how far from optimal position if distance_to_optimal < 3.0 { // Very close to optimal - make micro-adjustments while staying alert Some( SteeringBehavior::Arrive { target: optimal_position, slowing_distance: 2.0, } .calculate(ctx.player) .velocity * (0.2 + positioning_skill * 0.1), // Very slow, precise movements ) } else if distance_to_optimal < 10.0 { // Close - smooth repositioning Some( SteeringBehavior::Arrive { target: optimal_position, slowing_distance: 5.0, } .calculate(ctx.player) .velocity * (0.4 + agility * 0.2), // Moderate speed ) } else { // Need to reposition more urgently Some( SteeringBehavior::Arrive { target: optimal_position, slowing_distance: 8.0, } .calculate(ctx.player) .velocity * (0.6 + positioning_skill * 0.2), // Faster movement ) } } fn process_conditions(&self, ctx: ConditionContext) { // Attentive state requires low intensity with focused attention, includes movement GoalkeeperCondition::with_velocity(ActivityIntensity::Low).process(ctx); } } impl GoalkeeperAttentiveState { fn is_out_of_position(&self, ctx: &StateProcessingContext) -> bool { let optimal_position = self.calculate_optimal_position(ctx); // Reduced threshold for more responsive positioning ctx.player.position.distance_to(&optimal_position) > 70.0 } fn is_under_threat(&self, ctx: &StateProcessingContext) -> bool { // Check if any opponent with the ball is near if let Some(opponent) = ctx.players().opponents().with_ball().next() { let distance_to_opponent = opponent.position.distance_to(&ctx.player.position); let penalty_area_threshold = 40.0; // If opponent with ball is in or near penalty area if distance_to_opponent < penalty_area_threshold { return true; } } // Also check if ball is moving quickly toward goal let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); let is_toward_goal = ctx.ball().is_towards_player_with_angle(0.8); if ball_speed > 15.0 && is_toward_goal && ctx.ball().distance() < 150.0 { return true; } false } fn should_come_out(&self, ctx: &StateProcessingContext) -> bool { // Ball distance and movement factors let ball_distance = ctx.ball().distance(); let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); let is_ball_moving_towards_goal = ctx.ball().is_towards_player_with_angle(0.6); // Goalkeeper skill factors let goalkeeper_skills = &ctx.player.skills; let decision_skill = goalkeeper_skills.mental.decisions; let positioning_skill = goalkeeper_skills.mental.positioning; let rushing_out_skill = (decision_skill + positioning_skill) / 2.0; // Distance thresholds - adjusted by goalkeeper skill let base_threshold = 100.0; let skill_factor = rushing_out_skill / 20.0; // Normalize to 0-1 let adjusted_threshold = base_threshold * (0.7 + skill_factor * 0.6); // Range: 70-130 // Case 1: Ball is very close and no one has possession if ball_distance < 100.0 && !ctx.ball().is_owned() { return true; } // Case 2: Ball is moving toward goal at speed if is_ball_moving_towards_goal && ball_speed > 5.0 && ball_distance < adjusted_threshold { return true; } // Case 3: Ball is loose in dangerous area if !ctx.ball().is_owned() && ball_distance < adjusted_threshold && self.is_ball_in_danger_area(ctx) { return true; } // Case 4: Opponent with ball is approaching but still at interceptable distance if let Some(opponent) = ctx.players().opponents().with_ball().next() { if ctx.player().distance_to_player(opponent.id) < adjusted_threshold * 0.8 { // Check if goalkeeper can reach ball before opponent if self.can_reach_before_opponent(ctx, &opponent) { return true; } } } false } fn can_reach_before_opponent( &self, ctx: &StateProcessingContext, opponent: &crate::r#match::MatchPlayerLite, ) -> bool { let ball_pos = ctx.tick_context.positions.ball.position; let keeper_pos = ctx.player.position; let opponent_pos = opponent.position; // Estimate distance and time for both keeper and opponent let dist_keeper_to_ball = (ball_pos - keeper_pos).magnitude(); let dist_opponent_to_ball = (ball_pos - opponent_pos).magnitude(); // Use skill-adjusted speeds let keeper_speed = ctx.player.skills.physical.acceleration * 1.2; // Boost for urgency let opponent_speed = ctx.player().skills(opponent.id).physical.pace; // Calculate estimated times let time_keeper = dist_keeper_to_ball / keeper_speed; let time_opponent = dist_opponent_to_ball / opponent_speed; // Add skill-based advantage for goalkeeper decisions let decision_advantage = ctx.player.skills.mental.decisions / 40.0; // 0-0.5 range // Return true if goalkeeper can reach ball first time_keeper < (time_opponent * (1.0 - decision_advantage)) } fn is_ball_in_danger_area(&self, ctx: &StateProcessingContext) -> bool { // Get relevant positions let ball_position = ctx.tick_context.positions.ball.position; let goal_position = ctx.ball().direction_to_own_goal(); // Calculate distance from ball to goal let distance_to_goal = (ball_position - goal_position).magnitude(); // Define danger area threshold based on field size let field_width = ctx.context.field_size.width as f32; let danger_threshold = field_width * 0.2; // 20% of field width // Check if ball is in danger area distance_to_goal < danger_threshold } fn calculate_optimal_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let goal_position = ctx.ball().direction_to_own_goal(); let ball_position = ctx.tick_context.positions.ball.position; // Calculate vector from goal to ball let goal_to_ball = ball_position - goal_position; // Normalize the vector and scale it based on goalkeeper positioning skill let positioning_skill = ctx.player.skills.mental.positioning / 20.0; // Normalize to 0-1 // Determine optimal distance - better goalkeepers position more optimally let base_distance = 30.0; let skill_adjusted_distance = base_distance * (0.8 + positioning_skill * 0.4); // Position is on the line between goal and ball, but closer to goal let new_position = if goal_to_ball.magnitude() > 0.1 { goal_position + goal_to_ball.normalize() * skill_adjusted_distance } else { // Fallback if ball is too close to goal center goal_position }; // Limit the goalkeeper's movement to stay within the penalty area self.limit_to_penalty_area(new_position, ctx) } fn limit_to_penalty_area( &self, position: Vector3<f32>, ctx: &StateProcessingContext, ) -> Vector3<f32> { // Get penalty area dimensions let penalty_area = ctx .context .penalty_area(ctx.player.side == Some(PlayerSide::Left)); // Clamp position to stay within penalty area Vector3::new( position.x.clamp(penalty_area.min.x, penalty_area.max.x), position.y.clamp(penalty_area.min.y, penalty_area.max.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/engine/player/strategies/goalkeepers/states/throwing/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/throwing/mod.rs
use crate::r#match::events::Event; use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::{PassingEventContext, PlayerEvent}; use crate::r#match::{ConditionContext, MatchPlayerLite, PassEvaluator, StateChangeResult, StateProcessingContext, StateProcessingHandler}; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperThrowingState {} impl StateProcessingHandler for GoalkeeperThrowingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if the goalkeeper has the ball if !ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // 2. Find the best teammate to kick the ball to if let Some((teammate, _reason)) = self.find_best_pass_option(ctx) { return Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(teammate.id) .with_reason("GK_THROWING") .build(ctx), )), )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Remain stationary while throwing the ball Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Throwing requires moderate intensity with focused effort GoalkeeperCondition::new(ActivityIntensity::Moderate).process(ctx); } } impl GoalkeeperThrowingState { fn find_best_pass_option<'a>( &self, ctx: &StateProcessingContext<'a>, ) -> Option<(MatchPlayerLite, &'static str)> { // Throwing has limited range, but still prefer longer throws PassEvaluator::find_best_pass_option(ctx, 150.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/goalkeepers/states/tackling/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/tackling/mod.rs
use crate::r#match::events::Event; use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::PlayerEvent; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; use rand::Rng; const TACKLE_DISTANCE_THRESHOLD: f32 = 2.0; // Maximum distance to attempt a tackle (in meters) const TACKLE_SUCCESS_BASE_CHANCE: f32 = 0.7; // Base chance of successful tackle for goalkeeper const FOUL_CHANCE_BASE: f32 = 0.1; // Base chance of committing a foul for goalkeeper #[derive(Default)] pub struct GoalkeeperTacklingState {} impl StateProcessingHandler for GoalkeeperTacklingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { let opponents = ctx.players().opponents(); let mut opponents_with_ball = opponents.with_ball(); if let Some(opponent) = opponents_with_ball.next() { // 3. Calculate the distance to the opponent let distance_to_opponent = (ctx.player.position - opponent.position).magnitude(); if distance_to_opponent > TACKLE_DISTANCE_THRESHOLD { // Opponent is too far to attempt a tackle // Transition back to appropriate state (e.g., Standing) return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // 4. Attempt the tackle let (tackle_success, committed_foul) = self.attempt_tackle(ctx); if tackle_success { // Tackle is successful let mut state_change = StateChangeResult::with_goalkeeper_state(GoalkeeperState::HoldingBall); // Gain possession of the ball state_change .events .add(Event::PlayerEvent(PlayerEvent::GainBall(ctx.player.id))); // Update opponent's state to reflect loss of possession // This assumes you have a mechanism to update other players' states // You may need to send an event or directly modify the opponent's state // Optionally reduce goalkeeper's stamina // ctx.player.player_attributes.reduce_stamina(tackle_stamina_cost); Some(state_change) } else if committed_foul { // Tackle resulted in a foul let mut state_change = StateChangeResult::with_goalkeeper_state(GoalkeeperState::Standing); // Generate a foul event state_change .events .add_player_event(PlayerEvent::CommitFoul); // Transition to appropriate state (e.g., ReactingToFoul) // You may need to define additional states for handling fouls return Some(state_change); } else { // Tackle failed without committing a foul // Transition back to appropriate state return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } } else { // No opponent with the ball found // Transition back to appropriate state Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network logic if necessary None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Move towards the opponent to attempt the tackle if let Some(opponent) = ctx.players().opponents().with_ball().next() { // Calculate direction towards the opponent let direction = (opponent.position - ctx.player.position).normalize(); // Set speed based on player's pace let speed = ctx.player.skills.physical.pace; Some(direction * speed) } else { // No opponent with the ball found // Remain stationary or move back to position Some(Vector3::new(0.0, 0.0, 0.0)) } } fn process_conditions(&self, ctx: ConditionContext) { // Tackling is a very high intensity activity requiring explosive effort GoalkeeperCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl GoalkeeperTacklingState { /// Attempts a tackle and returns whether it was successful and if a foul was committed. fn attempt_tackle(&self, ctx: &StateProcessingContext) -> (bool, bool) { let mut rng = rand::rng(); // Get goalkeeper's tackling-related skills let tackling_skill = ctx.player.skills.technical.tackling as f32 / 20.0; // Normalize to [0,1] let aggression = ctx.player.skills.mental.aggression as f32 / 20.0; let composure = ctx.player.skills.mental.composure as f32 / 20.0; let overall_skill = (tackling_skill + composure) / 2.0; // Calculate success chance let success_chance = overall_skill * TACKLE_SUCCESS_BASE_CHANCE; // Simulate tackle success let tackle_success = rng.random::<f32>() < success_chance; // Calculate foul chance let foul_chance = (1.0 - overall_skill) * FOUL_CHANCE_BASE + aggression * 0.05; // Simulate foul let committed_foul = !tackle_success && rng.random::<f32>() < foul_chance; (tackle_success, committed_foul) } }
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/goalkeepers/states/kicking/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/kicking/mod.rs
use crate::r#match::events::Event; use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::{PassingEventContext, PlayerEvent}; use crate::r#match::{ConditionContext, MatchPlayerLite, PassEvaluator, StateChangeResult, StateProcessingContext, StateProcessingHandler}; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperKickingState {} impl StateProcessingHandler for GoalkeeperKickingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if the goalkeeper has the ball if !ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // 2. Find the best teammate to kick the ball to if let Some((teammate, _reason)) = self.find_best_pass_option(ctx) { return Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(teammate.id) .with_reason("GK_KICKING") .build(ctx), )), )); } 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) { // Kicking requires moderate intensity with focused effort GoalkeeperCondition::new(ActivityIntensity::Moderate).process(ctx); } } impl GoalkeeperKickingState { fn find_best_pass_option<'a>( &self, ctx: &StateProcessingContext<'a>, ) -> Option<(MatchPlayerLite, &'static str)> { // Kicking allows for extreme long passes - search maximum range including 300m+ let max_distance = ctx.context.field_size.width as f32 * 3.0; // Get goalkeeper's kicking and vision skills let vision_skill = ctx.player.skills.mental.vision / 20.0; let kicking_skill = ctx.player.skills.technical.long_throws / 20.0; let technique_skill = ctx.player.skills.technical.technique / 20.0; let anticipation_skill = ctx.player.skills.mental.anticipation / 20.0; // Calculate extreme pass capability (kicking emphasized) let extreme_capability = (kicking_skill * 0.5) + (vision_skill * 0.3) + (technique_skill * 0.15) + (anticipation_skill * 0.05); // Determine if goalkeeper should attempt extreme clearances let can_attempt_extreme = extreme_capability > 0.7; let prefers_extreme = extreme_capability > 0.8; let mut best_option: Option<MatchPlayerLite> = None; let mut best_score = 0.0; for teammate in ctx.players().teammates().nearby(max_distance) { let distance = (teammate.position - ctx.player.position).norm(); // Calculate base score using vision-weighted evaluation let forward_progress = (teammate.position.x - ctx.player.position.x).max(0.0); let field_progress = forward_progress / ctx.context.field_size.width as f32; // Check if receiver is a forward let is_forward = matches!( teammate.tactical_positions.position_group(), crate::PlayerFieldPositionGroup::Forward ); // Check space around receiver let nearby_opponents = ctx.tick_context.distances.opponents(teammate.id, 15.0).count(); let space_factor = match nearby_opponents { 0 => 3.0, // Completely free 1 => 1.8, 2 => 1.0, _ => 0.4, }; // Distance-based scoring with vision weighting let distance_score = if distance > 300.0 { // Extreme long kicks (300m+) if !can_attempt_extreme { 0.2 // Very poor option without skills } else if prefers_extreme && is_forward { // Elite kicker targeting forward - spectacular play let extreme_bonus = (extreme_capability - 0.8) * 10.0; // 0.0 to 2.0 3.5 + extreme_bonus } else if is_forward { 2.5 + (extreme_capability * 1.5) } else { 1.0 // Avoid extreme passes to non-forwards } } else if distance > 200.0 { // Ultra-long kicks (200-300m) if extreme_capability > 0.75 { if is_forward { 3.0 + (vision_skill * 2.0) // Vision helps spot forwards } else { 1.8 } } else if extreme_capability > 0.6 { 2.0 + (kicking_skill * 1.5) } else { 1.2 } } else if distance > 100.0 { // Very long kicks (100-200m) if is_forward { 2.5 + (vision_skill * 1.0) } else { 1.8 } } else if distance > 60.0 { // Long kicks (60-100m) 2.0 } else { // Short kicks - less ideal for kicking state 0.8 }; // Position bonus let position_bonus = match teammate.tactical_positions.position_group() { crate::PlayerFieldPositionGroup::Forward => { if distance > 300.0 && prefers_extreme { 2.5 // Extreme clearance to striker } else if distance > 200.0 { 2.0 // Ultra-long to striker } else { 1.5 } } crate::PlayerFieldPositionGroup::Midfielder => { if distance > 200.0 { 0.7 // Avoid ultra-long to midfield } else { 1.2 } } crate::PlayerFieldPositionGroup::Defender => 0.3, // Avoid kicking to defenders crate::PlayerFieldPositionGroup::Goalkeeper => 0.1, }; // Combine all factors with vision-based weighting let score = distance_score * space_factor * position_bonus * (1.0 + field_progress) * (0.5 + vision_skill * 0.5); if score > best_score { best_score = score; best_option = Some(teammate); } } // Fallback to standard evaluator if no good option found if best_option.is_none() || best_score < 1.0 { PassEvaluator::find_best_pass_option(ctx, max_distance) } else { best_option.map(|teammate| (teammate, "GK_KICKING_CUSTOM_EVALUATION")) } } }
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/goalkeepers/states/catching/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/catching/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::PlayerEvent; use crate::r#match::{ConditionContext, PlayerDistanceFromStartPosition, StateChangeResult, StateProcessingContext, StateProcessingHandler}; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperCatchingState {} impl StateProcessingHandler for GoalkeeperCatchingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if self.is_catch_successful(ctx) { let mut holding_result = StateChangeResult::with_goalkeeper_state(GoalkeeperState::HoldingBall); holding_result .events .add_player_event(PlayerEvent::CaughtBall(ctx.player.id)); return Some(holding_result); } if ctx.player().position_to_distance() == PlayerDistanceFromStartPosition::Big { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )) } if ctx.in_state_time > 100 { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Distributing, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // During catching, the goalkeeper's velocity should be minimal // but we can add a small adjustment towards the ball let ball_position = ctx.tick_context.positions.ball.position; let direction = (ball_position - ctx.player.position).normalize(); let speed = 0.5; // Very low speed for final adjustments Some(direction * speed) } fn process_conditions(&self, ctx: ConditionContext) { // Catching is a moderate intensity activity requiring focused effort GoalkeeperCondition::new(ActivityIntensity::Moderate).process(ctx); } } impl GoalkeeperCatchingState { fn is_catch_successful(&self, ctx: &StateProcessingContext) -> bool { // CRITICAL: Hard maximum catch distance - no teleporting the ball! const MAX_CATCH_DISTANCE: f32 = 6.0; // Realistic goalkeeper reach (arms extended) let distance_to_ball = ctx.ball().distance(); if distance_to_ball > MAX_CATCH_DISTANCE { return false; // Ball too far away to physically catch } // CRITICAL: Goalkeeper can only catch balls that are flying TOWARDS them // If the ball is flying away, they cannot catch it (e.g., their own pass/kick) if !ctx.ball().is_towards_player_with_angle(0.8) { return false; // Ball is flying away from goalkeeper - cannot catch } // Use goalkeeper-specific skills (handling is key for catching!) let handling = ctx.player.skills.technical.first_touch; // Using first_touch as handling proxy let reflexes = ctx.player.skills.mental.concentration; // Using concentration as reflexes proxy let positioning = ctx.player.skills.technical.technique; let agility = ctx.player.skills.physical.agility; // Scale skills from 1-20 range to 0-1 range let scaled_handling = (handling - 1.0) / 19.0; let scaled_reflexes = (reflexes - 1.0) / 19.0; let scaled_positioning = (positioning - 1.0) / 19.0; let scaled_agility = (agility - 1.0) / 19.0; // Base catch skill (weighted toward handling and reflexes) let base_skill = scaled_handling * 0.4 + scaled_reflexes * 0.3 + scaled_positioning * 0.2 + scaled_agility * 0.1; let ball_speed = ctx.tick_context.positions.ball.velocity.norm(); let ball_height = ctx.tick_context.positions.ball.position.z; // Base success rate should be high for skilled keepers (0.6 - 0.95 range) let mut catch_probability = 0.5 + (base_skill * 0.45); // Ball speed modifier (additive, not multiplicative) // Slower balls are easier to catch if ball_speed < 5.0 { catch_probability += 0.15; // Very slow ball - easy catch } else if ball_speed < 10.0 { catch_probability += 0.10; // Slow ball - easier } else if ball_speed < 15.0 { catch_probability += 0.05; // Medium speed - slightly easier } else if ball_speed > 25.0 { catch_probability -= 0.15; // Very fast - harder } else if ball_speed > 20.0 { catch_probability -= 0.10; // Fast - harder } // Distance modifier (additive) // Close balls are much easier if distance_to_ball < 1.0 { catch_probability += 0.20; // Very close - very easy } else if distance_to_ball < 2.0 { catch_probability += 0.15; // Close - easier } else if distance_to_ball < 3.0 { catch_probability += 0.05; // Reasonable - slightly easier } else if distance_to_ball > 5.0 { catch_probability -= 0.20; // Too far - much harder } else if distance_to_ball > 4.0 { catch_probability -= 0.10; // Far - harder } // Height modifier (additive) // Chest height is ideal, ground and high balls are harder if ball_height >= 0.8 && ball_height <= 1.8 { catch_probability += 0.10; // Ideal catching height (chest to head) } else if ball_height < 0.3 { catch_probability -= 0.10; // Ground ball - harder to catch cleanly } else if ball_height > 2.5 { catch_probability -= 0.15; // High ball - difficult } // Check if ball is coming toward keeper (important!) if ctx.ball().is_towards_player_with_angle(0.7) { catch_probability += 0.10; // Ball coming straight at keeper } else { catch_probability -= 0.15; // Ball at awkward angle } // Bonus for elite keepers if base_skill > 0.8 { catch_probability += 0.05; // Elite keeper bonus } // Ensure catch probability is within reasonable range (min 10%, max 98%) let clamped_catch_probability = catch_probability.clamp(0.10, 0.98); // Random number between 0 and 1 let random_factor = rand::random::<f32>(); clamped_catch_probability > random_factor } }
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/goalkeepers/states/holding/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/holding/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const HOLDING_DURATION: u64 = 50; #[derive(Default)] pub struct GoalkeeperHoldingState {} impl StateProcessingHandler for GoalkeeperHoldingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // If for some reason we no longer have the ball, return to standing if !ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // After holding for a specified duration, transition to distribute the ball if ctx.in_state_time >= HOLDING_DURATION { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Distributing, )); } // No other transitions - goalkeeper should continue holding the ball // until ready to distribute it, should not try to catch the same ball // they already possess 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) { // Holding ball is a low intensity activity with minimal physical effort GoalkeeperCondition::new(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/goalkeepers/states/jumping/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/jumping/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::PlayerEvent; use crate::r#match::{ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler}; use nalgebra::Vector3; const JUMP_DURATION: u64 = 30; // Duration of jump animation in ticks const JUMP_HEIGHT: f32 = 2.5; // Maximum jump height const MIN_DIVING_DISTANCE: f32 = 1.0; // Minimum distance to dive const MAX_DIVING_DISTANCE: f32 = 5.0; // Maximum distance to dive #[derive(Default)] pub struct GoalkeeperJumpingState {} impl StateProcessingHandler for GoalkeeperJumpingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Check if jump duration is complete if ctx.in_state_time >= JUMP_DURATION { // After jump, transition to appropriate state if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::HoldingBall )); } else { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing )); } } // During jump, check if we can catch the ball if self.can_catch_ball(ctx) { let mut result = StateChangeResult::with_goalkeeper_state( GoalkeeperState::Catching ); // Add catch attempt event result.events.add_player_event(PlayerEvent::RequestBallReceive(ctx.player.id)); return Some(result); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Calculate base jump vector let jump_vector = self.calculate_jump_vector(ctx); // Add diving motion if needed let diving_vector = if self.should_dive(ctx) { self.calculate_diving_vector(ctx) } else { Vector3::zeros() }; // Calculate vertical component based on jump phase let vertical_component = self.calculate_vertical_motion(ctx); // Combine all motion components let combined_velocity = jump_vector + diving_vector + Vector3::new(0.0, 0.0, vertical_component); // Scale based on goalkeeper's jumping and agility attributes let attribute_scaling = (ctx.player.skills.physical.jumping as f32 + ctx.player.skills.physical.agility as f32) / 40.0; Some(combined_velocity * attribute_scaling) } fn process_conditions(&self, ctx: ConditionContext) { // Jumping is a very high intensity activity requiring significant energy expenditure GoalkeeperCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl GoalkeeperJumpingState { /// Check if the goalkeeper can reach and catch the ball fn can_catch_ball(&self, ctx: &StateProcessingContext) -> bool { let ball_pos = ctx.tick_context.positions.ball.position; let keeper_pos = ctx.player.position; let distance = (ball_pos - keeper_pos).magnitude(); // Calculate reach based on goalkeeper height and jumping ability let max_reach = JUMP_HEIGHT * (ctx.player.skills.physical.jumping as f32 / 20.0); // Check if ball is within reach considering vertical position let vertical_reach = (ball_pos.z - keeper_pos.z).abs() <= max_reach; let horizontal_reach = distance <= MAX_DIVING_DISTANCE; vertical_reach && horizontal_reach } /// Calculate the base jump vector towards the ball fn calculate_jump_vector(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_pos = ctx.tick_context.positions.ball.position; let keeper_pos = ctx.player.position; let to_ball = ball_pos - keeper_pos; if to_ball.magnitude() > 0.0 { to_ball.normalize() * ctx.player.skills.physical.acceleration } else { Vector3::zeros() } } /// Determine if the goalkeeper should dive fn should_dive(&self, ctx: &StateProcessingContext) -> bool { let ball_pos = ctx.tick_context.positions.ball.position; let keeper_pos = ctx.player.position; let distance = (ball_pos - keeper_pos).magnitude(); // Check if the ball is at a distance that requires diving if distance < MIN_DIVING_DISTANCE || distance > MAX_DIVING_DISTANCE { return false; } // Check if the ball is moving towards goal let ball_velocity = ctx.tick_context.positions.ball.velocity; let to_goal = ctx.ball().direction_to_own_goal() - ball_pos; ball_velocity.dot(&to_goal) > 0.0 } /// Calculate the diving motion vector fn calculate_diving_vector(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_pos = ctx.tick_context.positions.ball.position; let keeper_pos = ctx.player.position; let to_ball = ball_pos - keeper_pos; if to_ball.magnitude() > 0.0 { // Calculate diving direction considering goalkeeper's diving ability let diving_direction = to_ball.normalize(); let diving_power = ctx.player.skills.physical.jumping as f32 / 20.0; diving_direction * diving_power * 2.0 } else { Vector3::zeros() } } /// Calculate vertical motion based on jump phase fn calculate_vertical_motion(&self, ctx: &StateProcessingContext) -> f32 { let jump_phase = ctx.in_state_time as f32 / JUMP_DURATION as f32; let jump_curve = (std::f32::consts::PI * jump_phase).sin(); // Smooth jump curve // Scale jump height based on goalkeeper's jumping ability let max_height = JUMP_HEIGHT * (ctx.player.skills.physical.jumping as f32 / 20.0); jump_curve * max_height } }
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/goalkeepers/states/comingout/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/comingout/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; const CLAIM_BALL_DISTANCE: f32 = 15.0; const MAX_COMING_OUT_DISTANCE: f32 = 120.0; // Maximum distance to pursue ball #[derive(Default)] pub struct GoalkeeperComingOutState {} impl StateProcessingHandler for GoalkeeperComingOutState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { let ball_distance = ctx.ball().distance(); if self.should_dive(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Diving, )); } // If goalkeeper has reached the ball, claim it immediately // IMPORTANT: Only catch if goalkeeper is reasonably close to their goal // This prevents catching balls at center field let distance_from_goal = ctx.player().distance_from_start_position(); const MAX_DISTANCE_FROM_GOAL_TO_CATCH: f32 = 45.0; // Only catch within ~45 units of goal (slightly more lenient for ComingOut) if ball_distance < CLAIM_BALL_DISTANCE && distance_from_goal < MAX_DISTANCE_FROM_GOAL_TO_CATCH { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Catching, )); } // Check if ball is moving very fast toward goalkeeper at close range - prepare for save let ball_toward_keeper = ctx.ball().is_towards_player_with_angle(0.7); if ball_toward_keeper && ball_distance < 150.0 { // Only switch to save for very fast shots at close range return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::PreparingForSave, )); } // Check if ball is too far - be more generous with command of area let command_of_area = ctx.player.skills.mental.vision / 20.0; let max_pursuit_distance = MAX_COMING_OUT_DISTANCE * (1.0 + command_of_area * 0.5); if ball_distance > max_pursuit_distance { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } // Check if ball is on opponent's half - return to goal if !ctx.ball().on_own_side() { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } // Check if opponent has the ball if let Some(opponent) = ctx.players().opponents().with_ball().next() { let opponent_distance = opponent.distance(ctx); let opponent_ball_distance = (opponent.position - ctx.tick_context.positions.ball.position).magnitude(); // If opponent has control and is very close if opponent_ball_distance < 2.0 && opponent_distance < 20.0 { // Close opponent with ball - prepare for save/1v1 return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::PreparingForSave, )); } else if opponent_ball_distance < 4.0 { // Opponent is near ball but we might intercept let keeper_advantage = self.can_reach_ball_first(ctx, &opponent); if keeper_advantage && ball_distance < 30.0 { // We can reach it first - stay aggressive! return None; } else if opponent_distance < 25.0 { // Too risky - prepare for save return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::PreparingForSave, )); } } } // Ball is loose - be aggressive! if !ctx.ball().is_owned() { // Loose ball within reasonable distance - continue pursuit if ball_distance < max_pursuit_distance * 0.8 { return None; // Keep going! } // Even if far, continue if ball is moving towards us if ball_toward_keeper && ball_distance < max_pursuit_distance { return None; // Ball coming to us - keep pursuing } } // Check distance from goal - allow more freedom based on command of area let goal_distance = ctx.player().distance_from_start_position(); let max_goal_distance = 60.0 * (1.0 + command_of_area * 0.4); if goal_distance > max_goal_distance { // Getting far from goal - only continue if ball is very close and loose if !ctx.ball().is_owned() && ball_distance < 15.0 { return None; // Ball very close and loose, commit! } else { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { let ball_position = ctx.tick_context.positions.ball.position; let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_distance = ctx.ball().distance(); let ball_speed = ball_velocity.norm(); // Use acceleration skill to determine sprint speed let acceleration = ctx.player.skills.physical.acceleration / 20.0; // Goalkeepers should sprint aggressively when coming out // Speed multiplier: 1.4 to 2.0 (much faster than before) let speed_multiplier = 1.4 + (acceleration * 0.6); // Add urgency bonus based on ball distance and speed let urgency_multiplier = if ball_distance < 20.0 { 1.4 // Very close - maximum urgency } else if ball_distance < 40.0 { 1.2 // Medium distance - high urgency } else { 1.1 // Far distance - moderate urgency }; // Calculate interception point for moving balls let target_position = if ball_speed > 1.0 { // Ball is moving - predict interception point let keeper_sprint_speed = ctx.player.skills.physical.pace * (1.0 + acceleration * 0.5); let time_to_intercept = ball_distance / keeper_sprint_speed.max(1.0); // Predict where ball will be, with slight underprediction for safety (0.8x) ball_position + ball_velocity * time_to_intercept * 0.8 } else { // Ball is stationary - go directly to it ball_position }; // Decide steering behavior based on distance if ball_distance < 5.0 { // Very close - use Arrive for controlled claiming Some( SteeringBehavior::Arrive { target: target_position, slowing_distance: 1.0, } .calculate(ctx.player) .velocity * (speed_multiplier * 0.9), // Still fast but controllable ) } else if ball_distance < 15.0 { // Close - sprint with slight deceleration zone Some( SteeringBehavior::Arrive { target: target_position, slowing_distance: 6.0, } .calculate(ctx.player) .velocity * (speed_multiplier * urgency_multiplier), ) } else { // Far - full sprint using Pursuit for maximum speed // For fast-moving balls, add extra boost let final_multiplier = if ball_speed > 5.0 { speed_multiplier * urgency_multiplier * 1.15 } else { speed_multiplier * urgency_multiplier }; Some( SteeringBehavior::Pursuit { target: target_position, target_velocity: Vector3::zeros(), // Static target position } .calculate(ctx.player) .velocity * final_multiplier, ) } } fn process_conditions(&self, ctx: ConditionContext) { // Coming out requires high intensity as goalkeeper moves out of penalty area aggressively GoalkeeperCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl GoalkeeperComingOutState { /// Check if goalkeeper can reach ball before opponent fn can_reach_ball_first( &self, ctx: &StateProcessingContext, opponent: &crate::r#match::MatchPlayerLite, ) -> bool { let ball_position = ctx.tick_context.positions.ball.position; let ball_velocity = ctx.tick_context.positions.ball.velocity; let keeper_position = ctx.player.position; let opponent_position = opponent.position; // Distance calculations let keeper_to_ball = (ball_position - keeper_position).magnitude(); let opponent_to_ball = (ball_position - opponent_position).magnitude(); // Goalkeeper skills let keeper_acceleration = ctx.player.skills.physical.acceleration / 20.0; let keeper_anticipation = ctx.player.skills.mental.anticipation / 20.0; let keeper_agility = ctx.player.skills.physical.agility / 20.0; let keeper_pace = ctx.player.skills.physical.pace; // Opponent skills let opponent_pace = ctx.player().skills(opponent.id).physical.pace; let opponent_acceleration = ctx.player().skills(opponent.id).physical.acceleration / 20.0; // Calculate effective sprint speeds (using our improved calculation) let keeper_sprint_speed = keeper_pace * (1.0 + keeper_acceleration * 0.5); let opponent_sprint_speed = opponent_pace * (1.0 + opponent_acceleration * 0.3); // If ball is moving, predict interception point let (keeper_distance, opponent_distance) = if ball_velocity.norm() > 1.0 { // Ball is moving - calculate interception distances // Simple prediction: where will ball be when keeper/opponent reaches it let keeper_intercept_time = keeper_to_ball / keeper_sprint_speed.max(1.0); let opponent_intercept_time = opponent_to_ball / opponent_sprint_speed.max(1.0); let keeper_intercept_pos = ball_position + ball_velocity * keeper_intercept_time; let opponent_intercept_pos = ball_position + ball_velocity * opponent_intercept_time; ( (keeper_intercept_pos - keeper_position).magnitude(), (opponent_intercept_pos - opponent_position).magnitude() ) } else { // Ball is stationary (keeper_to_ball, opponent_to_ball) }; // Time estimates with actual distances let keeper_time = keeper_distance / keeper_sprint_speed.max(1.0); let opponent_time = opponent_distance / opponent_sprint_speed.max(1.0); // Goalkeeper advantages: // 1. Anticipation - better reading of the game // 2. Agility - quicker reactions // 3. Can use hands - easier to claim let anticipation_bonus = 1.0 + (keeper_anticipation * 0.3); let agility_bonus = 1.0 + (keeper_agility * 0.15); let hand_advantage = 1.2; // Can use hands to claim from further away let total_advantage = anticipation_bonus * agility_bonus * hand_advantage; // Keeper wins if their time is less than opponent's time adjusted for advantages keeper_time < (opponent_time * total_advantage) } fn should_dive(&self, ctx: &StateProcessingContext) -> bool { let ball_distance = ctx.ball().distance(); let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); let ball_position = ctx.tick_context.positions.ball.position; let keeper_position = ctx.player.position; // Goalkeeper skills let reflexes = ctx.player.skills.mental.concentration / 20.0; let agility = ctx.player.skills.physical.agility / 20.0; let bravery = ctx.player.skills.mental.bravery / 20.0; let anticipation = ctx.player.skills.mental.anticipation / 20.0; let positioning = ctx.player.skills.technical.first_touch / 20.0; // Use first_touch as positioning proxy // Ball must be moving with reasonable speed to consider diving if ball_speed < 2.5 { return false; } // Don't dive if ball is too far - even skilled keepers have limits const MAX_DIVE_DISTANCE: f32 = 8.0; let skill_adjusted_max_dive = MAX_DIVE_DISTANCE + (agility * 4.0) + (reflexes * 3.0); if ball_distance > skill_adjusted_max_dive { return false; } // Check if ball is moving towards the keeper (important - don't dive at balls going away!) let ball_towards_keeper = ctx.ball().is_towards_player_with_angle(0.5); if !ball_towards_keeper { // Ball moving away or parallel - no need to dive return false; } // Calculate how close the ball will get if keeper doesn't dive let keeper_to_ball_dir = (ball_position - keeper_position).normalize(); let ball_vel_normalized = if ball_speed > 0.01 { ball_velocity.normalize() } else { return false; }; // Dot product to see if ball trajectory will bring it close let trajectory_alignment = keeper_to_ball_dir.dot(&ball_vel_normalized); // If ball is moving towards keeper but not directly, adjust dive threshold let trajectory_factor = trajectory_alignment.max(0.0); // Calculate time until ball reaches keeper's position let time_to_reach = ball_distance / ball_speed.max(1.0); // Predict where ball will be in near future let predicted_ball_pos = ball_position + ball_velocity * time_to_reach.min(2.0); let predicted_distance = (predicted_ball_pos - keeper_position).magnitude(); // Decision factors: // 1. Ball is getting closer (predicted distance < current distance) // 2. Ball will be very close soon // 3. Keeper doesn't have time to run there let ball_getting_closer = predicted_distance < ball_distance; // Calculate if keeper can reach the ball by running let keeper_sprint_speed = ctx.player.skills.physical.pace * (1.0 + ctx.player.skills.physical.acceleration / 40.0); let time_to_run_to_ball = ball_distance / keeper_sprint_speed.max(1.0); // Dive if: // - Ball is close and getting closer // - Ball speed suggests keeper can't reach by running // - Keeper's skills support the dive decision let urgency_threshold = 0.8 + (anticipation * 0.3); // Better anticipation = earlier dive decision let dive_urgency = time_to_reach < urgency_threshold; // Different scenarios based on ball speed if ball_speed > 15.0 { // Very fast shot - need quick reflexes let reflex_threshold = 0.5 - (reflexes * 0.3); ball_getting_closer && ball_distance < (6.0 + reflexes * 5.0) && time_to_reach < reflex_threshold && trajectory_factor > 0.6 } else if ball_speed > 10.0 { // Fast shot - need good positioning and reflexes let can_catch_running = time_to_run_to_ball < time_to_reach * 1.3; if can_catch_running { // Can probably catch it running - only dive if very close or excellent skills ball_distance < 4.0 && bravery > 0.6 && ball_getting_closer } else { // Need to dive to reach ball_distance < (8.0 + agility * 3.0 + positioning * 2.0) && dive_urgency && trajectory_factor > 0.5 && bravery > 0.4 } } else if ball_speed > 5.0 { // Medium speed - keeper has more time to decide let can_catch_running = time_to_run_to_ball < time_to_reach * 1.5; if can_catch_running { // Prefer to run and catch - only dive if skills are high and ball is very close ball_distance < 3.0 && (reflexes + agility) > 1.3 && bravery > 0.7 && ball_getting_closer } else { // Ball will pass before keeper can run - dive needed ball_distance < (6.0 + agility * 4.0) && predicted_distance < 8.0 && trajectory_factor > 0.4 && bravery > 0.5 } } else { // Slow ball - generally shouldn't dive, should run and catch // Only dive if extremely close and keeper is brave/skilled ball_distance < 2.5 && ball_getting_closer && bravery > 0.8 && (reflexes + agility + positioning) > 2.0 && trajectory_factor > 0.7 } } }
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/goalkeepers/states/running/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/running/mod.rs
use crate::r#match::events::Event; use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::{PassingEventContext, PlayerEvent}; use crate::r#match::{ConditionContext, MatchPlayerLite, PassEvaluator, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior}; use crate::IntegerUtils; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperRunningState {} impl StateProcessingHandler for GoalkeeperRunningState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { if let Some((teammate, _reason)) = self.find_best_pass_option(ctx) { Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(teammate.id) .with_reason("GK_RUNNING") .build(ctx), )), )) } else { // If no pass option is available, transition to HoldingBall state // This allows the goalkeeper to look for other options or kick the ball Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::HoldingBall, )) } } else { Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { if ctx.player.has_ball(ctx) { if let Some(nearest_opponent) = ctx.players().opponents().nearby(100.0).next() { let player_goal_velocity = SteeringBehavior::Evade { target: nearest_opponent.position, } .calculate(ctx.player) .velocity; Some(player_goal_velocity) } else { Some( SteeringBehavior::Wander { target: ctx.player.start_position, radius: IntegerUtils::random(5, 150) as f32, jitter: IntegerUtils::random(0, 2) as f32, distance: IntegerUtils::random(10, 150) as f32, angle: IntegerUtils::random(0, 180) as f32, } .calculate(ctx.player) .velocity, ) } } else { let slowing_distance: f32 = { if ctx.player().goal_distance() < 200.0 { 200.0 } else { 10.0 } }; let result = SteeringBehavior::Arrive { target: ctx.tick_context.positions.ball.position, slowing_distance, } .calculate(ctx.player) .velocity; Some(result + ctx.player().separation_velocity()) } } fn process_conditions(&self, ctx: ConditionContext) { // Goalkeepers rarely run long distances, but when they do it can be intense // (coming out for balls, running back to goal, distribution runs) GoalkeeperCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl GoalkeeperRunningState { fn find_best_pass_option<'a>( &self, ctx: &StateProcessingContext<'a>, ) -> Option<(MatchPlayerLite, &'static str)> { PassEvaluator::find_best_pass_option(ctx, 500.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/goalkeepers/states/punching/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/punching/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::PlayerEvent; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const PUNCHING_DISTANCE_THRESHOLD: f32 = 2.0; // Maximum distance to attempt punching const PUNCH_SUCCESS_PROBABILITY: f32 = 0.8; // Probability of a successful punch #[derive(Default)] pub struct GoalkeeperPunchingState {} impl StateProcessingHandler for GoalkeeperPunchingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.ball().distance() > PUNCHING_DISTANCE_THRESHOLD { // Ball is too far to punch, transition to appropriate state (e.g., Jumping) return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Jumping, )); } // 2. Attempt to punch the ball let punch_success = rand::random::<f32>() < PUNCH_SUCCESS_PROBABILITY; if punch_success { // Punch is successful let mut state_change = StateChangeResult::with_goalkeeper_state(GoalkeeperState::Standing); // Determine the direction to punch the ball (e.g., towards the sidelines) let punch_direction = ctx.ball().direction_to_own_goal().normalize() * -1.0; // Generate a punch event state_change .events .add_player_event(PlayerEvent::ClearBall(punch_direction)); Some(state_change) } else { // Punch failed, transition to appropriate state (e.g., Diving) Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Diving, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Remain stationary while punching Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Punching is a very high intensity activity requiring explosive effort GoalkeeperCondition::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/goalkeepers/states/resting/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/resting/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const RESTING_STAMINA_THRESHOLD: u32 = 60; // Minimum stamina to transition out of resting state #[derive(Default)] pub struct GoalkeeperRestingState {} impl StateProcessingHandler for GoalkeeperRestingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.player_attributes.condition_percentage() >= RESTING_STAMINA_THRESHOLD { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } 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) { // Resting state has the best recovery for goalkeepers in any state GoalkeeperCondition::new(ActivityIntensity::Recovery).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/goalkeepers/states/distributing/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/distributing/mod.rs
use crate::r#match::events::Event; use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::{PassingEventContext, PlayerEvent}; use crate::r#match::{ConditionContext, MatchPlayerLite, StateChangeResult, StateProcessingContext, StateProcessingHandler}; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperDistributingState {} impl StateProcessingHandler for GoalkeeperDistributingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // If we no longer have the ball, we must have passed or lost it if !ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // Try to find the best pass option if let Some(teammate) = self.find_best_pass_option(ctx) { // Execute the pass and transition to returning to goal return Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::ReturningToGoal, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(teammate.id) .with_reason("GK_DISTRIBUTING") .build(ctx) )), )); } // Timeout after a short time if no pass is made // This prevents the goalkeeper from being stuck trying to pass forever if ctx.in_state_time > 20 { // If we still have the ball after timeout, try running to find space return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Running, )); } // If we have the ball but no good passing option yet, wait // The goalkeeper should not be trying to catch the ball since they already have it 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) { // Distributing requires moderate intensity with focused effort GoalkeeperCondition::new(ActivityIntensity::Moderate).process(ctx); } } impl GoalkeeperDistributingState { fn find_best_pass_option<'a>(&'a self, ctx: &'a StateProcessingContext<'a>) -> Option<MatchPlayerLite> { // Goalkeepers should look for long passes to start attacks // Search the entire field including ultra-long distances for goal kicks let max_distance = ctx.context.field_size.width as f32 * 2.5; // Extended for 300m+ passes // Get goalkeeper's skills to determine passing style let pass_skill = ctx.player.skills.technical.passing / 20.0; let vision_skill = ctx.player.skills.mental.vision / 20.0; let kicking_skill = ctx.player.skills.technical.long_throws / 20.0; let decision_skill = ctx.player.skills.mental.decisions / 20.0; let composure_skill = ctx.player.skills.mental.composure / 20.0; let anticipation_skill = ctx.player.skills.mental.anticipation / 20.0; let technique_skill = ctx.player.skills.technical.technique / 20.0; // Determine goalkeeper passing style based on skills let is_technical_keeper = pass_skill > 0.7 && vision_skill > 0.7; // Likes build-up play let is_long_ball_keeper = kicking_skill > 0.7 && pass_skill < 0.6; // Prefers long kicks let is_cautious_keeper = composure_skill < 0.5 || decision_skill < 0.5; // Safe, short passes let is_visionary_keeper = vision_skill > 0.8 && anticipation_skill > 0.7; // Sees through balls let is_elite_distributor = vision_skill > 0.85 && technique_skill > 0.8 && kicking_skill > 0.75; // Can attempt extreme passes let mut best_option: Option<MatchPlayerLite> = None; let mut best_score = 0.0; // Get the previous ball owner to avoid immediate pass-backs let previous_owner = ctx.tick_context.ball.last_owner; for teammate in ctx.players().teammates().nearby(max_distance) { // PREVENT PASS-BACK: Don't pass to the player who just passed to us if let Some(prev_owner_id) = previous_owner { if teammate.id == prev_owner_id { continue; // Skip this player } } let distance = (teammate.position - ctx.player.position).norm(); // PREVENT PASSING TO PLAYERS TOO CLOSE TO GOALKEEPER (creates ping-pong) if distance < 50.0 { continue; // Skip players too close to goalkeeper } // Skill-based distance preference with ultra-long pass support let distance_bonus = if is_elite_distributor { // Elite distributor: can attempt any distance with vision-based weighting if distance > 300.0 { // Extreme passes - only elite keepers should attempt let extreme_confidence = (vision_skill * 0.5) + (kicking_skill * 0.3) + (technique_skill * 0.2); 2.5 + extreme_confidence * 2.0 // Up to 4.5 for world-class keepers } else if distance > 200.0 { // Ultra-long passes - elite specialty let ultra_confidence = (vision_skill * 0.6) + (kicking_skill * 0.4); 3.0 + ultra_confidence * 1.5 // Up to 4.5 } else if distance > 100.0 { 3.5 // Very long - excellent } else if distance > 60.0 { 2.8 // Long - good } else if distance > 30.0 { 2.0 // Medium - acceptable } else { 1.5 // Short - for build-up } } else if is_long_ball_keeper { // Long ball keeper: heavily prefers long passes, vision limits ultra-long if distance > 300.0 { // Extreme passes - limited by vision if vision_skill > 0.7 { 2.5 + (vision_skill - 0.7) * 3.0 // Up to 3.4 } else { 0.8 // Avoid without vision } } else if distance > 200.0 { // Ultra-long - good kicking but needs some vision if vision_skill > 0.6 { 3.0 + (vision_skill - 0.6) * 2.0 // Up to 3.8 } else { 1.5 } } else if distance > 100.0 { 3.5 // Very long pass - excellent } else if distance > 60.0 { 2.5 // Long pass - good } else if distance > 30.0 { 0.8 // Medium pass - less preferred } else { 0.3 // Short pass - avoid } } else if is_visionary_keeper { // Visionary keeper: sees opportunities at all ranges if distance > 300.0 { // Extreme passes - vision-driven let vision_multiplier = (vision_skill - 0.8) * 5.0; // 0.0 to 1.0 2.0 + vision_multiplier + (kicking_skill * 1.5) } else if distance > 200.0 { // Ultra-long - perfect for visionary 2.8 + (vision_skill * 1.5) } else if distance > 100.0 { 3.2 // Very long - sees through balls } else if distance > 60.0 { 2.5 // Long - good vision } else if distance > 30.0 { 2.0 // Medium - builds play } else { 1.8 // Short - safe } } else if is_technical_keeper { // Technical keeper: balanced approach, builds from back if distance > 300.0 { // Extreme passes - rare for technical keepers if vision_skill > 0.75 && kicking_skill > 0.7 { 1.5 } else { 0.5 // Avoid } } else if distance > 200.0 { // Ultra-long - occasional if skilled if vision_skill > 0.7 { 1.8 } else { 0.8 } } else if distance > 100.0 { 1.5 // Very long pass - occasional } else if distance > 60.0 { 1.8 // Long pass - good option } else if distance > 30.0 { 2.0 // Medium pass - preferred for build-up } else { 1.5 // Short pass - safe option } } else if is_cautious_keeper { // Cautious keeper: prefers safe, short-medium passes if distance > 300.0 || distance > 200.0 { 0.2 // Ultra/extreme passes - too risky, avoid } else if distance > 100.0 { 0.5 // Very long pass - risky, avoid } else if distance > 60.0 { 0.8 // Long pass - risky } else if distance > 30.0 { 1.5 // Medium pass - acceptable } else { 2.5 // Short pass - safe choice } } else { // Average keeper: standard preference with limited ultra-long ability if distance > 300.0 { // Extreme passes - very limited if vision_skill > 0.7 && kicking_skill > 0.7 { 1.2 } else { 0.4 } } else if distance > 200.0 { // Ultra-long - needs good skills if vision_skill > 0.65 { 1.5 } else { 0.7 } } else if distance > 100.0 { 2.0 } else if distance > 60.0 { 1.5 } else if distance > 30.0 { 1.0 } else { 0.5 } }; // Skill-based position preference with distance consideration let position_bonus = match teammate.tactical_positions.position_group() { crate::PlayerFieldPositionGroup::Forward => { // Ultra-long passes to forwards are more valuable let ultra_long_multiplier = if distance > 300.0 { 1.5 // Extreme distance to striker - game-changing } else if distance > 200.0 { 1.3 // Ultra-long to striker - counter-attack } else { 1.0 }; if is_elite_distributor { 3.5 * ultra_long_multiplier // Elite keepers excel at finding forwards } else if is_visionary_keeper { 3.0 * ultra_long_multiplier // Visionary keepers love finding forwards } else if is_long_ball_keeper { 2.8 * ultra_long_multiplier // Long ball keepers target forwards } else if is_technical_keeper { 1.5 // Technical keepers less direct } else { 2.0 } } crate::PlayerFieldPositionGroup::Midfielder => { // Medium to long passes to midfield let long_pass_multiplier = if distance > 200.0 { 0.8 // Less ideal for ultra-long to midfield } else if distance > 100.0 { 1.2 // Good for switching play } else { 1.0 }; if is_technical_keeper { 2.5 * long_pass_multiplier // Technical keepers love midfield build-up } else if is_cautious_keeper { 2.0 * long_pass_multiplier // Safe option for cautious keepers } else if is_elite_distributor && distance > 150.0 { 2.2 * long_pass_multiplier // Elite can switch play through midfield } else { 1.5 } } crate::PlayerFieldPositionGroup::Defender => { // Short passes to defenders, avoid long ones if distance > 200.0 { 0.3 // Never ultra-long pass to defender } else if distance > 100.0 { 0.5 // Rarely long pass to defender } else if is_cautious_keeper { 2.2 // Cautious keepers prefer defenders } else if is_technical_keeper { 1.8 // Part of build-up play } else { 0.6 // Others avoid defenders } } crate::PlayerFieldPositionGroup::Goalkeeper => 0.1, }; // Check if receiver is in space let nearby_opponents = ctx.tick_context .distances .opponents(teammate.id, 15.0) .count(); let space_bonus = if nearby_opponents == 0 { 2.0 // Completely free } else if nearby_opponents == 1 { if is_cautious_keeper { 0.8 // Cautious keepers avoid any pressure } else if is_technical_keeper { 1.4 // Technical keepers trust receiver's control } else { 1.2 } } else { if is_cautious_keeper { 0.3 // Heavily avoid for cautious keepers } else { 0.6 } }; // Forward progress preference (skill-based) let forward_progress = teammate.position.x - ctx.player.position.x; let forward_bonus = if forward_progress > 0.0 { let base_forward = 1.0 + (forward_progress / ctx.context.field_size.width as f32) * 0.5; if is_visionary_keeper || is_long_ball_keeper { base_forward * 1.3 // Aggressive forward passing } else if is_cautious_keeper { base_forward * 0.8 // Less emphasis on forward progress } else { base_forward } } else { if is_cautious_keeper { 0.7 // More willing to pass back } else if is_technical_keeper { 0.5 // Build-up allows some backward passes } else { 0.2 // Others avoid backward passes } }; // Skill multipliers based on keeper abilities let skill_factor = if is_technical_keeper { (pass_skill * 0.5) + (vision_skill * 0.3) + (decision_skill * 0.2) } else if is_long_ball_keeper { (kicking_skill * 0.6) + (pass_skill * 0.2) + (vision_skill * 0.2) } else if is_visionary_keeper { (vision_skill * 0.5) + (anticipation_skill * 0.3) + (pass_skill * 0.2) } else if is_cautious_keeper { (composure_skill * 0.4) + (decision_skill * 0.4) + (pass_skill * 0.2) } else { (pass_skill * 0.4) + (vision_skill * 0.4) + (kicking_skill * 0.2) }; // Calculate final score with skill-based weighting let score = distance_bonus * position_bonus * space_bonus * forward_bonus * skill_factor; if score > best_score { best_score = score; best_option = Some(teammate); } } best_option } pub fn calculate_pass_power(&self, teammate_id: u32, ctx: &StateProcessingContext) -> f64 { let distance = ctx.tick_context.distances.get(ctx.player.id, teammate_id); let pass_skill = ctx.player.skills.technical.passing; (distance / pass_skill * 10.0) as f64 } }
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/goalkeepers/states/pressure/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/pressure/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; const PRESSURE_DISTANCE_THRESHOLD: f32 = 20.0; // Maximum distance from the goal to be considered under pressure #[derive(Default)] pub struct GoalkeeperPressureState {} impl StateProcessingHandler for GoalkeeperPressureState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Distributing )); } if ctx.player().distance_from_start_position() > PRESSURE_DISTANCE_THRESHOLD { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Move towards the start position (goal) using steering behavior let to_start_position = SteeringBehavior::Seek { target: ctx.player.start_position, } .calculate(ctx.player) .velocity; Some(to_start_position) } fn process_conditions(&self, ctx: ConditionContext) { // Under pressure requires high intensity as goalkeeper moves back quickly GoalkeeperCondition::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/goalkeepers/states/standing/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/standing/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::{ ConditionContext, MatchPlayerLite, PlayerDistanceFromStartPosition, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, VectorExtensions, }; use nalgebra::Vector3; const DANGER_ZONE_RADIUS: f32 = 30.0; const CLOSE_DANGER_DISTANCE: f32 = 80.0; const MEDIUM_THREAT_DISTANCE: f32 = 150.0; const FAR_THREAT_DISTANCE: f32 = 250.0; #[derive(Default)] pub struct GoalkeeperStandingState {} impl StateProcessingHandler for GoalkeeperStandingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // If goalkeeper has the ball, decide whether to pass or run if ctx.player.has_ball(ctx) { return if ctx.players().opponents().exists(DANGER_ZONE_RADIUS) { Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Distributing, )) } else { Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Running, )) } } let ball_distance = ctx.ball().distance(); let ball_on_own_side = ctx.ball().on_own_side(); // Skill-based threat assessment let anticipation = ctx.player.skills.mental.anticipation / 20.0; let command_of_area = ctx.player.skills.mental.vision / 20.0; // Check for immediate threats requiring urgent action if let Some(opponent) = ctx.players().opponents().with_ball().next() { let opponent_distance = opponent.distance(ctx); // Opponent very close with ball - prepare for save or come out if opponent_distance < CLOSE_DANGER_DISTANCE { // Check if should come out or prepare for shot if self.should_rush_out_for_ball(ctx, &opponent) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ComingOut, )); } else { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::PreparingForSave, )); } } // Opponent approaching - be attentive if opponent_distance < MEDIUM_THREAT_DISTANCE && ball_on_own_side { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Attentive, )); } } // Check if ball is coming toward goal if ctx.ball().is_towards_player_with_angle(0.7) && ball_on_own_side { let ball_speed = ctx.tick_context.positions.ball.velocity.norm(); if ball_speed > 5.0 { // Fast ball coming - prepare for save if ball_distance < MEDIUM_THREAT_DISTANCE * (1.0 + anticipation * 0.5) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::PreparingForSave, )); } } // Ball coming slowly - be attentive if ball_distance < FAR_THREAT_DISTANCE { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Attentive, )); } } // Check for loose ball in dangerous area if !ctx.ball().is_owned() && ball_on_own_side && ball_distance < CLOSE_DANGER_DISTANCE * (1.0 + command_of_area * 0.5) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ComingOut, )); } // Ball on own side - be attentive if ball_on_own_side && ball_distance < FAR_THREAT_DISTANCE { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Attentive, )); } // Check positioning match ctx.player().position_to_distance() { PlayerDistanceFromStartPosition::Small => { // Good positioning - check for specific threats if self.is_opponent_in_danger_zone(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::UnderPressure, )); } } PlayerDistanceFromStartPosition::Medium => { // Need to adjust position - walk to better spot return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Walking, )); } PlayerDistanceFromStartPosition::Big => { // Far from position - walk back return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Walking, )); } } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed // For now, return None to indicate no state change None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Calculate optimal position based on ball and goal let optimal_position = self.calculate_optimal_position(ctx); let distance_to_optimal = ctx.player.position.distance_to(&optimal_position); // If we're close to optimal position, make small adjustments if distance_to_optimal < 5.0 { // Very small movements to stay alert and ready Some( SteeringBehavior::Wander { target: optimal_position, radius: 2.0, jitter: 0.5, distance: 2.0, angle: (ctx.in_state_time % 360) as f32, } .calculate(ctx.player) .velocity * 0.2, // Very slow movement ) } else if distance_to_optimal < 15.0 { // Small repositioning needed Some( SteeringBehavior::Arrive { target: optimal_position, slowing_distance: 5.0, } .calculate(ctx.player) .velocity * 0.4, // Moderate speed ) } else { // Need to move to better position Some( SteeringBehavior::Arrive { target: optimal_position, slowing_distance: 10.0, } .calculate(ctx.player) .velocity * 0.6, // Faster movement ) } } fn process_conditions(&self, ctx: ConditionContext) { // Standing goalkeepers recover condition well due to low activity GoalkeeperCondition::new(ActivityIntensity::Recovery).process(ctx); } } impl GoalkeeperStandingState { fn is_opponent_in_danger_zone(&self, ctx: &StateProcessingContext) -> bool { if let Some(opponent_with_ball) = ctx.players().opponents().with_ball().next() { let opponent_distance = ctx .tick_context .distances .get(ctx.player.id, opponent_with_ball.id); return opponent_distance < DANGER_ZONE_RADIUS; } false } /// Determine if goalkeeper should rush out for the ball fn should_rush_out_for_ball(&self, ctx: &StateProcessingContext, opponent: &MatchPlayerLite) -> bool { let ball_position = ctx.tick_context.positions.ball.position; let keeper_position = ctx.player.position; let opponent_position = opponent.position; // Distance calculations let keeper_to_ball = (ball_position - keeper_position).magnitude(); let opponent_to_ball = (ball_position - opponent_position).magnitude(); // Goalkeeper skills let anticipation = ctx.player.skills.mental.anticipation / 20.0; let decisions = ctx.player.skills.mental.decisions / 20.0; let rushing_out = (anticipation + decisions) / 2.0; // Opponent skills let opponent_control = ctx.player().skills(opponent.id).technical.first_touch / 20.0; let opponent_pace = ctx.player().skills(opponent.id).physical.pace / 20.0; // Calculate time to reach ball (rough estimate) let keeper_speed = ctx.player.skills.physical.acceleration * (1.0 + rushing_out * 0.3); let opponent_speed = opponent_pace * 20.0; let keeper_time = keeper_to_ball / keeper_speed; let opponent_time = opponent_to_ball / opponent_speed; // Factors favoring rushing out: // 1. Keeper can reach ball first (with skill advantage) // 2. Ball is loose or opponent has poor control // 3. Ball is within reasonable distance let can_reach_first = keeper_time < opponent_time * (1.0 + rushing_out * 0.2); let ball_loose_or_poor_control = !ctx.ball().is_owned() || opponent_control < 0.5; let reasonable_distance = keeper_to_ball < CLOSE_DANGER_DISTANCE * 1.5; can_reach_first && ball_loose_or_poor_control && reasonable_distance } /// Calculate optimal goalkeeper position based on ball and goal fn calculate_optimal_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let goal_center = ctx.ball().direction_to_own_goal(); let ball_position = ctx.tick_context.positions.ball.position; // Goalkeeper skills affecting positioning let positioning_skill = ctx.player.skills.mental.positioning / 20.0; let command_of_area = ctx.player.skills.mental.vision / 20.0; // Calculate distance from goal to ball let goal_to_ball = ball_position - goal_center; let distance_to_ball = goal_to_ball.magnitude(); // Base distance from goal line (in meters/units) let mut optimal_distance_from_goal = 4.0; // Start about 4 units from goal line // Adjust based on ball position if ctx.ball().on_own_side() { // Ball on defensive half - position based on threat level let threat_distance = distance_to_ball.min(300.0) / 300.0; // Normalize to 0-1 // Closer ball = come out more (but not too far) optimal_distance_from_goal += (1.0 - threat_distance) * 8.0 * command_of_area; // Better positioning = more accurate placement optimal_distance_from_goal *= 0.9 + positioning_skill * 0.2; // Narrow the angle - position on line between goal and ball let direction_to_ball = if distance_to_ball > 1.0 { goal_to_ball.normalize() } else { Vector3::new(1.0, 0.0, 0.0) // Fallback if ball too close to goal }; let mut new_position = goal_center + direction_to_ball * optimal_distance_from_goal; // Lateral adjustment for angle coverage let ball_y_offset = ball_position.y - goal_center.y; let lateral_adjustment = ball_y_offset * 0.05 * positioning_skill; new_position.y += lateral_adjustment; // Keep within penalty area self.clamp_to_penalty_area(ctx, new_position) } else { // Ball on opponent's half - stay closer to goal but ready optimal_distance_from_goal = 6.0 + command_of_area * 4.0; let mut new_position = goal_center; new_position.x += optimal_distance_from_goal * (if ctx.player.side == Some(PlayerSide::Left) { 1.0 } else { -1.0 }); self.clamp_to_penalty_area(ctx, new_position) } } fn clamp_to_penalty_area( &self, ctx: &StateProcessingContext, position: Vector3<f32>, ) -> Vector3<f32> { let penalty_area = ctx .context .penalty_area(ctx.player.side == Some(PlayerSide::Left)); Vector3::new( position.x.clamp(penalty_area.min.x, penalty_area.max.x), position.y.clamp(penalty_area.min.y, penalty_area.max.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/engine/player/strategies/goalkeepers/states/common/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/common/mod.rs
use crate::r#match::engine::player::strategies::common::{ ActivityIntensityConfig, ConditionProcessor, GOALKEEPER_LOW_CONDITION_THRESHOLD, GOALKEEPER_JADEDNESS_INTERVAL, GOALKEEPER_JADEDNESS_INCREMENT, }; /// Goalkeeper-specific activity intensity configuration pub struct GoalkeeperConfig; impl ActivityIntensityConfig for GoalkeeperConfig { fn very_high_fatigue() -> f32 { 7.0 // Lower than outfield players - explosive but infrequent } fn high_fatigue() -> f32 { 4.5 // Lower than outfield players } fn moderate_fatigue() -> f32 { 2.5 } fn low_fatigue() -> f32 { 0.8 } fn recovery_rate() -> f32 { -4.0 // Better recovery than outfield players } fn sprint_multiplier() -> f32 { 1.3 // Sprinting (less demanding than outfield players) } fn jogging_multiplier() -> f32 { 0.5 } fn walking_multiplier() -> f32 { 0.2 } fn low_condition_threshold() -> i16 { GOALKEEPER_LOW_CONDITION_THRESHOLD } fn jadedness_interval() -> u64 { GOALKEEPER_JADEDNESS_INTERVAL } fn jadedness_increment() -> i16 { GOALKEEPER_JADEDNESS_INCREMENT } } /// Goalkeeper condition processor (type alias for clarity) pub type GoalkeeperCondition = ConditionProcessor<GoalkeeperConfig>; // 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/goalkeepers/states/takeball/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/takeball/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperTakeBallState {} impl StateProcessingHandler for GoalkeeperTakeBallState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } if ctx.ball().is_owned() { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Calculate base Arrive behavior let mut arrive_velocity = SteeringBehavior::Arrive { target: ctx.tick_context.positions.ball.position, slowing_distance: 15.0, } .calculate(ctx.player) .velocity; // Add separation force to prevent player stacking // BUT reduce separation when very close to ball to allow claiming const SEPARATION_RADIUS: f32 = 25.0; const SEPARATION_WEIGHT: f32 = 0.4; const BALL_CLAIM_DISTANCE: f32 = 6.7; // Reduced by 1.5x from 10.0 let target = ctx.tick_context.positions.ball.position; let distance_to_ball = (ctx.player.position - target).magnitude(); let separation_factor = if distance_to_ball < BALL_CLAIM_DISTANCE { // Reduce separation force when close to ball (linear falloff) distance_to_ball / BALL_CLAIM_DISTANCE } else { 1.0 }; 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 requires high intensity as goalkeeper moves to claim the ball GoalkeeperCondition::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/goalkeepers/states/clearing/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/clearing/mod.rs
use crate::r#match::events::Event; use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::PlayerEvent; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; use rand::Rng; /// Goalkeeper clearing state - emergency clearance of the ball away from danger #[derive(Default)] pub struct GoalkeeperClearingState {} impl StateProcessingHandler for GoalkeeperClearingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // If we don't have the ball anymore, return to standing if !ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // Execute the clearance kick if let Some(event) = self.execute_clearance(ctx) { return Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::Standing, event, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Stand still while preparing to clear Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Clearing requires moderate intensity with focused effort GoalkeeperCondition::new(ActivityIntensity::Moderate).process(ctx); } } impl GoalkeeperClearingState { /// Execute a clearance - boot the ball away from danger fn execute_clearance(&self, ctx: &StateProcessingContext) -> Option<Event> { let kicking_power = ctx.player.skills.technical.long_throws / 20.0; // Calculate clearance target - aim for sideline or upfield let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; let keeper_pos = ctx.player.position; // Determine which direction to clear based on position let mut rng = rand::rng(); let random_factor: f32 = rng.random_range(-0.3..0.3); // Aim for a moderate distance upfield and toward sideline let target_x = keeper_pos.x + (field_width * 0.4); // 40% of field upfield let target_y = if keeper_pos.y > 0.0 { field_height * 0.35 + random_factor * 15.0 // Toward top sideline } else { -field_height * 0.35 + random_factor * 15.0 // Toward bottom sideline }; let clearance_target = Vector3::new(target_x, target_y, 0.0); // Moderate power clearance let kick_force = 5.0 + (kicking_power * 1.5); // 5.0-6.5 range // Use MoveBall event for clearance let ball_direction = (clearance_target - keeper_pos).normalize(); let ball_velocity = ball_direction * kick_force * 2.5; Some(Event::PlayerEvent(PlayerEvent::MoveBall( ctx.player.id, ball_velocity, ))) } }
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/goalkeepers/states/shooting/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/shooting/mod.rs
use crate::r#match::events::EventCollection; use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::{PlayerEvent, ShootingEventContext}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperShootingState {} impl StateProcessingHandler for GoalkeeperShootingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if the goalkeeper has the ball if !ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // 4. Shoot the ball towards the opponent's goal let mut events = EventCollection::new(); events.add_player_event(PlayerEvent::Shoot(ShootingEventContext::new() .with_player_id(ctx.player.id) .with_target(ctx.player().shooting_direction()) .with_reason("GK_SHOOTING") .build(ctx))); Some(StateChangeResult::with_events(events)) } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Remain stationary while shooting Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Shooting requires moderate intensity with focused effort GoalkeeperCondition::new(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/goalkeepers/states/picking_up/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/picking_up/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::PlayerEvent; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const PICKUP_DISTANCE_THRESHOLD: f32 = 1.0; // Maximum distance to pick up the ball const PICKUP_SUCCESS_PROBABILITY: f32 = 0.9; // Probability of successfully picking up the ball #[derive(Default)] pub struct GoalkeeperPickingUpState {} impl StateProcessingHandler for GoalkeeperPickingUpState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 0. CRITICAL: Goalkeeper can only pick up balls that are NOT flying away from them // If the ball is flying away, they cannot pick it up (e.g., their own pass/kick) // Check if ball has significant velocity (not just rolling) let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); if ball_speed > 1.0 && !ctx.ball().is_towards_player_with_angle(0.8) { // Ball is flying away from goalkeeper with speed - cannot pick up return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // 1. Check if the ball is within pickup distance let ball_distance = ctx.ball().distance(); if ball_distance > PICKUP_DISTANCE_THRESHOLD { // Ball is too far to pick up, transition to appropriate state (e.g., Standing) return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // 2. Attempt to pick up the ball let pickup_success = rand::random::<f32>() < PICKUP_SUCCESS_PROBABILITY; if pickup_success { // Pickup is successful let mut state_change = StateChangeResult::with_goalkeeper_state(GoalkeeperState::HoldingBall); // Generate a pickup event state_change .events .add_player_event(PlayerEvent::CaughtBall(ctx.player.id)); Some(state_change) } else { // Pickup failed, transition to appropriate state (e.g., Diving) Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Diving, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Move towards the ball to pick it up let ball_position = ctx.tick_context.positions.ball.position; let direction = (ball_position - ctx.player.position).normalize(); let speed = ctx.player.skills.physical.pace; Some(direction * speed) } fn process_conditions(&self, ctx: ConditionContext) { // Picking up requires moderate intensity with focused effort, includes movement GoalkeeperCondition::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/goalkeepers/states/preparing_for_save/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/preparing_for_save/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; const DIVE_DISTANCE: f32 = 25.0; // Distance to attempt diving save const CATCH_DISTANCE: f32 = 25.0; // Distance to attempt catching const PUNCH_DISTANCE: f32 = 12.0; // Distance to attempt punching #[derive(Default)] pub struct GoalkeeperPreparingForSaveState {} impl StateProcessingHandler for GoalkeeperPreparingForSaveState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // If goalkeeper has the ball, transition to passing if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Passing, )); } // Check if we need to dive if self.should_dive(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Diving, )); } let ball_distance = ctx.ball().distance(); let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); // Check if we should attempt a save // IMPORTANT: Only catch if goalkeeper is reasonably close to their goal // This prevents catching balls at center field let distance_from_goal = ctx.player().distance_from_start_position(); const MAX_DISTANCE_FROM_GOAL_TO_CATCH: f32 = 40.0; // Only catch within ~40 units of goal if ball_distance < CATCH_DISTANCE && distance_from_goal < MAX_DISTANCE_FROM_GOAL_TO_CATCH { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Catching, )); } // If ball is on opponent's half, return to goal if !ctx.ball().on_own_side() { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } // If our team has control, switch to attentive if ctx.team().is_control_ball() { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Attentive, )); } // Check if we should punch (for dangerous high balls) if self.should_punch(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Punching, )); } // Check if ball is moving away and we should come out let ball_toward_goal = self.is_ball_toward_goal(ctx); if !ball_toward_goal && ball_distance < 30.0 && ball_speed < 5.0 { // Loose ball not heading to goal - come out to claim return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ComingOut, )); } // Continue preparing - position for the save None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Far from position - sprint to get there 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) { // Preparing for save requires high intensity as goalkeeper moves into position GoalkeeperCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl GoalkeeperPreparingForSaveState { /// Determine if goalkeeper should dive for the ball fn should_dive(&self, ctx: &StateProcessingContext) -> bool { let ball_distance = ctx.ball().distance(); let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); // Don't dive if ball is too far if ball_distance > DIVE_DISTANCE { return false; } // Goalkeeper skills // Use concentration as proxy for reflexes let reflexes = ctx.player.skills.mental.concentration / 20.0; let agility = ctx.player.skills.physical.agility / 20.0; let bravery = ctx.player.skills.mental.bravery / 20.0; // Check if ball is heading toward goal let toward_goal = self.is_ball_toward_goal(ctx); if !toward_goal { return false; } // Ball must be moving with some speed if ball_speed < 3.0 { return false; } // Calculate time to reach let time_to_ball = ball_distance / ball_speed.max(1.0); // Decide based on speed, distance, and skills if ball_speed > 12.0 { // Fast shot - dive if close enough ball_distance < (25.0 + reflexes * 8.0) && time_to_ball < (1.5 + reflexes * 0.5) } else if ball_speed > 7.0 { // Medium speed - consider agility ball_distance < (20.0 + agility * 5.0) && bravery > 0.4 } else { // Slow shot - dive only if very close or excellent skills ball_distance < 12.0 && (reflexes + agility) > 1.0 } } /// Determine if goalkeeper should punch the ball fn should_punch(&self, ctx: &StateProcessingContext) -> bool { let ball_distance = ctx.ball().distance(); let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); let ball_position = ctx.tick_context.positions.ball.position; // Don't punch if ball is too far if ball_distance > PUNCH_DISTANCE { return false; } // Goalkeeper skills // Use first_touch as proxy for handling, physical.jumping for aerial reach let handling = ctx.player.skills.technical.first_touch / 20.0; // Check if ball is high (would need to punch rather than catch) let ball_height = ball_position.z; let is_high_ball = ball_height > 2.0; // Ball above head height // Punch conditions: // 1. Ball is high and moving fast (hard to catch) if is_high_ball && ball_speed > 8.0 { return true; } // 2. Ball is in crowded area (safer to punch) // Check if there are opponents near the ball (within 8m of goalkeeper who is near ball) let opponents_nearby = if ball_distance < 10.0 { ctx.players().opponents().nearby(8.0).count() } else { 0 }; if opponents_nearby >= 2 && ball_distance < 10.0 { // Crowded - punch for safety unless handling is excellent return handling < 0.8; } // 3. Goalkeeper has low handling confidence if handling < 0.5 && ball_speed > 6.0 && is_high_ball { return true; } false } /// Check if ball is moving toward goal fn is_ball_toward_goal(&self, ctx: &StateProcessingContext) -> bool { let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); // Stationary ball is not moving toward goal if ball_speed < 0.5 { return false; } // Get goal direction from ball let goal_direction = ctx.ball().direction_to_own_goal(); // Check if ball velocity is pointing toward goal // Use dot product: > 0 means moving in same general direction let toward_goal_dot = ball_velocity.normalize().dot(&goal_direction.normalize()); // Consider it "toward goal" if angle is less than 90 degrees (dot > 0) // More strict for positioning: require at least 30 degree alignment toward_goal_dot > 0.5 } /// Calculate the optimal position for making a save fn calculate_optimal_save_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_position = ctx.tick_context.positions.ball.position; let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); let goal_position = ctx.ball().direction_to_own_goal(); // Goalkeeper skills let positioning = ctx.player.skills.mental.positioning / 20.0; let anticipation = ctx.player.skills.mental.anticipation / 20.0; // If ball is moving, predict where it will be let predicted_ball_position = if ball_speed > 1.0 { // Predict ball position based on goalkeeper's anticipation let prediction_time = 0.3 + (anticipation * 0.3); // 0.3-0.6 seconds ahead ball_position + ball_velocity * prediction_time } else { ball_position }; // Calculate position between ball and goal center let goal_line_position = goal_position; // Positioning ratio: how far from goal line (better positioning = better ratio) // Stay closer to goal line but move toward ball trajectory let positioning_ratio = 0.15 + (positioning * 0.15); // 15-30% toward ball // Calculate optimal position on the line between goal and ball let optimal_position = goal_line_position + (predicted_ball_position - goal_line_position) * positioning_ratio; // Ensure goalkeeper stays near the goal line (don't go too far out) let max_distance_from_goal = 8.0 + (positioning * 4.0); // 8-12 units let distance_from_goal = (optimal_position - goal_line_position).magnitude(); if distance_from_goal > max_distance_from_goal { // Clamp to max distance goal_line_position + (optimal_position - goal_line_position).normalize() * max_distance_from_goal } else { optimal_position } } }
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/goalkeepers/states/diving/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/diving/mod.rs
use crate::r#match::events::Event; use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::PlayerEvent; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const MAX_DIVE_TIME: f32 = 1.5; // Maximum time to stay in diving state (in seconds) const BALL_CLAIM_DISTANCE: f32 = 4.0; #[derive(Default)] pub struct GoalkeeperDivingState {} impl StateProcessingHandler for GoalkeeperDivingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Passing, )); } let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_moving_away = ball_velocity.dot(&(ctx.player().opponent_goal_position() - ctx.player.position)) > 0.0; if ctx.ball().distance() > 100.0 && ball_moving_away { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } if ctx.in_state_time as f32 / 100.0 > MAX_DIVE_TIME { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } if self.is_ball_caught(ctx) { return Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::Standing, Event::PlayerEvent(PlayerEvent::CaughtBall(ctx.player.id)), )); } else if self.is_ball_nearby(ctx) { return Some(StateChangeResult::with_event(Event::PlayerEvent(PlayerEvent::ClaimBall(ctx.player.id)))); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { let dive_direction = self.calculate_dive_direction(ctx); let dive_speed = self.calculate_dive_speed(ctx); Some(dive_direction * dive_speed) } fn process_conditions(&self, ctx: ConditionContext) { // Diving is a very high intensity activity requiring maximum energy expenditure GoalkeeperCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl GoalkeeperDivingState { fn calculate_dive_direction(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_position = ctx.tick_context.positions.ball.position; let ball_velocity = ctx.tick_context.positions.ball.velocity; let future_ball_position = ball_position + ball_velocity * 0.5; // Predict ball position 0.5 seconds ahead let to_future_ball = future_ball_position - ctx.player.position; let mut dive_direction = to_future_ball.normalize(); // Add some randomness to dive direction let random_angle = (rand::random::<f32>() - 0.5) * std::f32::consts::PI / 6.0; // Random angle between -30 and 30 degrees dive_direction = nalgebra::Rotation3::new(Vector3::z() * random_angle) * dive_direction; dive_direction } fn calculate_dive_speed(&self, ctx: &StateProcessingContext) -> f32 { let urgency = self.calculate_urgency(ctx); (ctx.player.skills.physical.acceleration + ctx.player.skills.physical.agility) * 0.2 * urgency } fn calculate_urgency(&self, ctx: &StateProcessingContext) -> f32 { let ball_position = ctx.tick_context.positions.ball.position; let ball_velocity = ctx.tick_context.positions.ball.velocity; let distance_to_goal = (ball_position - ctx.player().opponent_goal_position()).magnitude(); let velocity_towards_goal = ball_velocity.dot(&(ctx.player().opponent_goal_position() - ball_position)).max(0.0); let urgency: f32 = (1.0 - distance_to_goal / 100.0) * (1.0 + velocity_towards_goal / 10.0); urgency.clamp(1.0, 2.0) } fn is_ball_caught(&self, ctx: &StateProcessingContext) -> bool { // CRITICAL: Goalkeeper can only catch balls that are flying TOWARDS them // If the ball is flying away, they cannot catch it (e.g., their own pass/kick) if !ctx.ball().is_towards_player_with_angle(0.8) { return false; // Ball is flying away from goalkeeper - cannot catch } let ball_distance = ctx.ball().distance(); let ball_speed = ctx.tick_context.positions.ball.velocity.magnitude(); let catch_probability = ctx.player.skills.technical.first_touch / 20.0 * (1.0 - ball_speed / 20.0); // Adjust for ball speed let goalkeeper_height = 1.9 + (ctx.player.player_attributes.height as f32 - 180.0) / 100.0; // Height in meters let catch_distance = goalkeeper_height * 0.5; // Adjust for goalkeeper height ball_distance < catch_distance && rand::random::<f32>() < catch_probability } fn is_ball_nearby(&self, ctx: &StateProcessingContext) -> bool { let goalkeeper_height = 1.9 + (ctx.player.player_attributes.height as f32 - 180.0) / 100.0; let nearby_distance = BALL_CLAIM_DISTANCE + goalkeeper_height * 0.1; // Adjust for goalkeeper height ctx.ball().distance() < nearby_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/goalkeepers/states/sweeping/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/sweeping/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const SWEEPING_DISTANCE_THRESHOLD: f32 = 20.0; // Distance from goal to consider sweeping const SWEEPING_SPEED_MULTIPLIER: f32 = 1.2; // Multiplier for sweeping speed #[derive(Default)] pub struct GoalkeeperSweepingState {} impl StateProcessingHandler for GoalkeeperSweepingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if the ball is within the sweeping distance threshold let ball_distance = ctx.ball().distance_to_own_goal(); if ball_distance > SWEEPING_DISTANCE_THRESHOLD { // Ball is too far, transition back to appropriate state (e.g., Standing) return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // 2. Check if there are any opponents near the ball if let Some(_) = ctx.players().opponents().with_ball().next() { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Move towards the ball to sweep it away let ball_position = ctx.tick_context.positions.ball.position; let direction = (ball_position - ctx.player.position).normalize(); let speed = ctx.player.skills.physical.pace * SWEEPING_SPEED_MULTIPLIER; Some(direction * speed) } fn process_conditions(&self, ctx: ConditionContext) { // Sweeping requires high intensity as goalkeeper moves far from goal GoalkeeperCondition::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/goalkeepers/states/penalty/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/penalty/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::PlayerEvent; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const PENALTY_SAVE_PROBABILITY: f32 = 0.3; // Probability of saving a penalty #[derive(Default)] pub struct GoalkeeperPenaltyState {} impl StateProcessingHandler for GoalkeeperPenaltyState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if the ball is moving towards the goal let is_ball_moving_towards_goal = ctx.ball().is_towards_player(); if !is_ball_moving_towards_goal { // Ball is not moving towards the goal, transition to appropriate state (e.g., Standing) return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // 2. Attempt to save the penalty let save_success = rand::random::<f32>() < PENALTY_SAVE_PROBABILITY; if save_success { // Penalty save is successful let mut state_change = StateChangeResult::with_goalkeeper_state(GoalkeeperState::HoldingBall); // Generate a penalty save event state_change .events .add_player_event(PlayerEvent::CaughtBall(ctx.player.id)); Some(state_change) } else { // Penalty save failed, transition to appropriate state (e.g., Standing) Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Determine the velocity based on the penalty save attempt let save_success = rand::random::<f32>() < PENALTY_SAVE_PROBABILITY; if save_success { // Move towards the predicted ball position let predicted_ball_position = Self::predict_ball_position(ctx); let direction = (predicted_ball_position - ctx.player.position).normalize(); let speed = ctx.player.skills.physical.pace; Some(direction * speed) } else { // Remain stationary Some(Vector3::new(0.0, 0.0, 0.0)) } } fn process_conditions(&self, ctx: ConditionContext) { // Penalty saves require very high intensity with explosive effort GoalkeeperCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl GoalkeeperPenaltyState { fn predict_ball_position(ctx: &StateProcessingContext) -> Vector3<f32> { // Implement ball position prediction logic based on the penalty taker's position and shot direction // This can be enhanced with more sophisticated prediction algorithms or machine learning models // For simplicity, let's assume the goalkeeper predicts the ball position to be the center of the goal ctx.context.goal_positions.left } }
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/goalkeepers/states/passing/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/passing/mod.rs
use crate::r#match::events::Event; use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::events::{PlayerEvent, PassingEventContext}; use crate::r#match::{ConditionContext, MatchPlayerLite, PassEvaluator, StateChangeResult, StateProcessingContext, StateProcessingHandler, VectorExtensions}; use crate::PlayerFieldPositionGroup; use nalgebra::Vector3; use rand::Rng; /// Types of goalkeeper distribution #[derive(Debug, Clone, Copy, PartialEq)] enum GoalkeeperDistributionType { /// Short pass to nearby defender (0-30m) ShortPass, /// Medium pass to midfielder (30-60m) MediumPass, /// Long kick downfield to forward (60-100m+) LongKick, /// Clearance - just get the ball away from danger Clearance, /// Throw using long throw skill (15-40m) Throw, } const UNDER_PRESSURE_DISTANCE: f32 = 25.0; const SAFE_PASS_DISTANCE: f32 = 30.0; const MEDIUM_PASS_DISTANCE: f32 = 60.0; const LONG_KICK_MIN_DISTANCE: f32 = 60.0; // Reduced from 100.0 #[derive(Default)] pub struct GoalkeeperPassingState {} impl StateProcessingHandler for GoalkeeperPassingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if !ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Standing, )); } // Determine distribution type based on pressure and game situation let distribution_type = self.decide_distribution_type(ctx); // Execute the appropriate distribution match distribution_type { GoalkeeperDistributionType::Clearance => { // Emergency clearance - transition to clearing state return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Clearing, )); } GoalkeeperDistributionType::ShortPass => { if let Some(teammate) = self.find_short_pass_target(ctx) { return Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(teammate.id) .with_pass_force(2.5) // Gentle pass .with_reason("GK_PASSING_SHORT") .build(ctx) )), )); } } GoalkeeperDistributionType::MediumPass => { if let Some(teammate) = self.find_medium_pass_target(ctx) { return Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(teammate.id) .with_pass_force(4.5) // Medium power .with_reason("GK_PASSING_MEDIUM") .build(ctx) )), )); } } GoalkeeperDistributionType::LongKick => { if let Some(event) = self.execute_long_kick(ctx) { return Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::Standing, event, )); } } GoalkeeperDistributionType::Throw => { if let Some(teammate) = self.find_throw_target(ctx) { return Some(StateChangeResult::with_goalkeeper_state_and_event( GoalkeeperState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(teammate.id) .with_pass_force(3.5) // Throw power .with_reason("GK_PASSING_THROW") .build(ctx) )), )); } } } // Timeout - just do something if ctx.in_state_time > 30 { // Default to clearance after waiting too long return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Clearing, )); } 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) { // Passing requires moderate intensity with focused effort GoalkeeperCondition::new(ActivityIntensity::Moderate).process(ctx); } } impl GoalkeeperPassingState { /// Decide which type of distribution to use based on pressure and situation fn decide_distribution_type(&self, ctx: &StateProcessingContext) -> GoalkeeperDistributionType { // Check for immediate pressure let opponents_nearby = ctx.players().opponents().nearby(UNDER_PRESSURE_DISTANCE).count(); let under_heavy_pressure = opponents_nearby >= 2; let under_pressure = opponents_nearby >= 1; // Goalkeeper skills let vision = ctx.player.skills.mental.vision / 20.0; let kicking_power = ctx.player.skills.technical.long_throws / 20.0; let passing = ctx.player.skills.technical.passing / 20.0; let decisions = ctx.player.skills.mental.decisions / 20.0; // Under heavy pressure - clear it! if under_heavy_pressure { return GoalkeeperDistributionType::Clearance; } // Check available options at different ranges let has_short_option = self.count_safe_teammates(ctx, SAFE_PASS_DISTANCE) > 0; let has_medium_option = self.count_safe_teammates(ctx, MEDIUM_PASS_DISTANCE) > 0; let has_long_option = self.count_teammates_in_space(ctx, LONG_KICK_MIN_DISTANCE) > 0; // Decision logic based on pressure and skills if under_pressure { // Some pressure - prefer quick throw or short pass to safe defender if kicking_power > 0.7 && has_medium_option { return GoalkeeperDistributionType::Throw; } else if has_short_option { return GoalkeeperDistributionType::ShortPass; } else { return GoalkeeperDistributionType::Clearance; } } // No immediate pressure - use vision and decision making let mut rng = rand::rng(); let decision_random: f32 = rng.random(); // Better vision = more likely to attempt long distribution if vision > 0.7 && has_long_option && decision_random < (vision * 0.6) { return GoalkeeperDistributionType::LongKick; } // Good kicking - prefer throws for medium range if kicking_power > 0.6 && has_medium_option && decision_random < 0.4 { return GoalkeeperDistributionType::Throw; } // Good passing - prefer build-up play if passing > 0.6 && has_medium_option && decision_random < (passing * 0.7) { return GoalkeeperDistributionType::MediumPass; } // Default: safe short pass if available, otherwise medium if has_short_option { GoalkeeperDistributionType::ShortPass } else if has_medium_option { GoalkeeperDistributionType::MediumPass } else { GoalkeeperDistributionType::LongKick } } /// Find the best target for a short pass (to nearby defenders) fn find_short_pass_target(&self, ctx: &StateProcessingContext) -> Option<MatchPlayerLite> { let mut best_target = None; let mut best_score = 0.0; for teammate in ctx.players().teammates().nearby(SAFE_PASS_DISTANCE) { let distance = teammate.distance(ctx); // Prefer defenders for short passes let is_defender = matches!( teammate.tactical_positions.position_group(), PlayerFieldPositionGroup::Defender ); // Check if teammate is under pressure let opponents_near_teammate = ctx.tick_context.distances.opponents(teammate.id, 10.0).count(); let is_safe = opponents_near_teammate == 0; // Check if teammate is in good position (not marked) let space_factor = if is_safe { 2.0 } else if opponents_near_teammate == 1 { 0.7 } else { 0.2 }; // Prefer closer, safe teammates who are defenders let position_bonus = if is_defender { 1.5 } else { 1.0 }; let distance_score = (SAFE_PASS_DISTANCE - distance) / SAFE_PASS_DISTANCE; let score = distance_score * space_factor * position_bonus; if score > best_score { best_score = score; best_target = Some(teammate); } } best_target } /// Find the best target for a medium pass (to midfielders) fn find_medium_pass_target(&self, ctx: &StateProcessingContext) -> Option<MatchPlayerLite> { let mut best_target = None; let mut best_score = 0.0; for teammate in ctx.players().teammates().nearby(MEDIUM_PASS_DISTANCE) { let distance = teammate.distance(ctx); // Skip if too close (use short pass instead) if distance < SAFE_PASS_DISTANCE { continue; } // Prefer midfielders for medium passes let is_midfielder = matches!( teammate.tactical_positions.position_group(), PlayerFieldPositionGroup::Midfielder ); // Check space around receiver let opponents_near = ctx.tick_context.distances.opponents(teammate.id, 12.0).count(); let space_factor = match opponents_near { 0 => 2.0, 1 => 1.2, _ => 0.5, }; // Forward progress let forward_progress = (teammate.position.x - ctx.player.position.x).max(0.0); let progress_factor = forward_progress / 100.0; let position_bonus = if is_midfielder { 1.3 } else { 1.0 }; let score = space_factor * progress_factor * position_bonus; if score > best_score { best_score = score; best_target = Some(teammate); } } best_target } /// Find the best target for a throw (using long throw skill) fn find_throw_target(&self, ctx: &StateProcessingContext) -> Option<MatchPlayerLite> { let kicking_power = ctx.player.skills.technical.long_throws / 20.0; let max_throw_distance = 25.0 + (kicking_power * 25.0); // 25-50m range let mut best_target = None; let mut best_score = 0.0; for teammate in ctx.players().teammates().nearby(max_throw_distance) { let distance = teammate.distance(ctx); // Throws work best at 20-40m range if distance < 15.0 || distance > max_throw_distance { continue; } // Check if on the wing (throws often go wide) let is_wide = teammate.position.y.abs() > (ctx.context.field_size.height as f32 * 0.3); // Space around receiver let opponents_near = ctx.tick_context.distances.opponents(teammate.id, 10.0).count(); let space_factor = match opponents_near { 0 => 2.0, 1 => 1.0, _ => 0.4, }; let wide_bonus = if is_wide { 1.3 } else { 1.0 }; let distance_factor = 1.0 - ((distance - 20.0).abs() / max_throw_distance); let score = space_factor * wide_bonus * distance_factor; if score > best_score { best_score = score; best_target = Some(teammate); } } best_target } /// Execute a long kick downfield fn execute_long_kick(&self, ctx: &StateProcessingContext) -> Option<Event> { let _vision = ctx.player.skills.mental.vision / 20.0; let kicking_power = ctx.player.skills.technical.long_throws / 20.0; let _technique = ctx.player.skills.technical.technique / 20.0; // Reduced max distance for more realistic kicks let max_distance = ctx.context.field_size.width as f32 * 0.8; // Reduced from 1.5 let mut best_target = None; let mut best_score = 0.0; // Look for forwards in good positions for teammate in ctx.players().teammates().nearby(max_distance) { let distance = teammate.distance(ctx); // Only consider long range if distance < LONG_KICK_MIN_DISTANCE { continue; } // Strongly prefer forwards let is_forward = matches!( teammate.tactical_positions.position_group(), PlayerFieldPositionGroup::Forward ); if !is_forward { continue; } // Forward progress (reduced requirement) let forward_progress = teammate.position.x - ctx.player.position.x; if forward_progress < 30.0 { continue; // Don't kick to players not upfield } // Space around receiver let opponents_near = ctx.tick_context.distances.opponents(teammate.id, 15.0).count(); let space_factor = match opponents_near { 0 => 3.0, 1 => 1.5, 2 => 0.8, _ => 0.3, }; // Distance capability based on kicking power (reduced ranges) let distance_factor = if distance > 150.0 { kicking_power * 1.5 // Only strong kickers can reach far } else { 1.0 + kicking_power * 0.5 }; let score = space_factor * distance_factor * (forward_progress / ctx.context.field_size.width as f32); if score > best_score { best_score = score; best_target = Some(teammate); } } if let Some(target) = best_target { // Use moderate force for long kicks (reduced from 6.0-8.5) let kick_force = 4.5 + (kicking_power * 1.5); // 4.5-6.0 range Some(Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(target.id) .with_pass_force(kick_force) .with_reason("GK_PASSING_LONG_KICK") .build(ctx) ))) } else { // No good target - will need to clear from a different state None } } /// Count teammates in safe positions within range fn count_safe_teammates(&self, ctx: &StateProcessingContext, range: f32) -> usize { ctx.players() .teammates() .nearby(range) .filter(|teammate| { // Check if teammate is not heavily marked let opponents_near = ctx.tick_context.distances.opponents(teammate.id, 8.0).count(); opponents_near < 2 }) .count() } /// Count teammates in space at long range fn count_teammates_in_space(&self, ctx: &StateProcessingContext, min_distance: f32) -> usize { // Reduced max distance for more realistic searches let max_distance = ctx.context.field_size.width as f32 * 0.8; ctx.players() .teammates() .nearby(max_distance) .filter(|teammate| { let distance = teammate.distance(ctx); if distance < min_distance { return false; } // Must be forward let is_forward = matches!( teammate.tactical_positions.position_group(), PlayerFieldPositionGroup::Forward ); if !is_forward { return false; } // Must have some space let opponents_near = ctx.tick_context.distances.opponents(teammate.id, 15.0).count(); opponents_near <= 1 }) .count() } }
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/goalkeepers/states/walking/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/walking/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::player::strategies::processor::StateChangeResult; use crate::r#match::player::strategies::processor::{StateProcessingContext, StateProcessingHandler}; use crate::r#match::{ ConditionContext, PlayerSide, SteeringBehavior, VectorExtensions, }; use crate::IntegerUtils; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperWalkingState {} impl StateProcessingHandler for GoalkeeperWalkingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // If goalkeeper has the ball, immediately transition to passing if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Distributing, )); } // Check ball proximity and threat level let ball_distance = ctx.ball().distance(); let ball_on_own_side = ctx.ball().on_own_side(); // Improved threat assessment using goalkeeper skills let threat_level = self.assess_threat_level(ctx); // Transition to Attentive if ball is on own side and moderately close if ball_on_own_side { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Attentive, )); } // Check if ball is coming directly at goalkeeper if ctx.ball().is_towards_player_with_angle(0.85) && ball_distance < 200.0 { // Use anticipation skill to determine response timing let anticipation_factor = ctx.player.skills.mental.anticipation / 20.0; let reaction_distance = 250.0 + (anticipation_factor * 100.0); // Better anticipation = earlier reaction if ball_distance < reaction_distance { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::PreparingForSave, )); } } // Use decision-making skill for coming out if self.should_come_out_advanced(ctx) && ball_distance < 250.0 { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ComingOut, )); } // Check positioning using goalkeeper-specific skills if self.is_significantly_out_of_position(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::ReturningToGoal, )); } // Check for immediate threats using concentration skill if threat_level > 0.7 { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::UnderPressure, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Calculate optimal position using goalkeeper skills let optimal_position = self.calculate_intelligent_position(ctx); if ctx.player.position.distance_to(&optimal_position) < 10.0 { // Small adjustments - use wander for natural movement Some( SteeringBehavior::Wander { target: optimal_position, radius: 50.0, jitter: 1.0, distance: 50.0, angle: IntegerUtils::random(0, 360) as f32, } .calculate(ctx.player) .velocity * 0.5, // Slow movement for fine positioning ) } else { // Need to reposition - use arrive for smooth movement Some( SteeringBehavior::Arrive { target: optimal_position, slowing_distance: 15.0, } .calculate(ctx.player) .velocity, ) } } fn process_conditions(&self, ctx: ConditionContext) { // Walking state has low intensity but more activity than standing GoalkeeperCondition::with_velocity(ActivityIntensity::Low).process(ctx); } } impl GoalkeeperWalkingState { /// Assess threat level using goalkeeper mental skills fn assess_threat_level(&self, ctx: &StateProcessingContext) -> f32 { let mut threat = 0.0; // Use concentration to assess multiple threats let concentration_factor = ctx.player.skills.mental.concentration / 20.0; // Check for opponents with ball if let Some(opponent_with_ball) = ctx.players().opponents().with_ball().next() { let distance_to_opponent = opponent_with_ball.position.distance_to(&ctx.player.position); // Better concentration means better threat assessment if distance_to_opponent < 50.0 { threat += 0.8 * concentration_factor; } else if distance_to_opponent < 100.0 { threat += 0.5 * concentration_factor; } } // Check ball velocity and trajectory let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); // Use anticipation to predict threats let anticipation_factor = ctx.player.skills.mental.anticipation / 20.0; if ball_speed > 10.0 && ctx.ball().is_towards_player_with_angle(0.6) { threat += 0.4 * anticipation_factor; } threat.min(1.0) } /// Advanced decision for coming out using goalkeeper skills fn should_come_out_advanced(&self, ctx: &StateProcessingContext) -> bool { let ball_distance = ctx.ball().distance(); let goalkeeper_skills = &ctx.player.skills; // Key skills for coming out decisions let decision_skill = goalkeeper_skills.mental.decisions / 20.0; let rushing_out = goalkeeper_skills.technical.long_throws / 20.0; // Goalkeeper-specific skill let command_of_area = goalkeeper_skills.mental.vision / 20.0; // Goalkeeper-specific let anticipation = goalkeeper_skills.mental.anticipation / 20.0; // Combined skill factor for coming out let coming_out_ability = (decision_skill + rushing_out + command_of_area + anticipation) / 4.0; // Base threshold adjusted by skills let base_threshold = 100.0; let skill_adjusted_threshold = base_threshold * (0.6 + coming_out_ability * 0.8); // Range: 60-140 // Check if ball is loose and in dangerous area let ball_loose = !ctx.ball().is_owned(); let ball_in_danger_zone = ball_distance < skill_adjusted_threshold; // Check if goalkeeper can reach ball first if ball_loose && ball_in_danger_zone { // Use acceleration and agility for reach calculation let reach_ability = (goalkeeper_skills.physical.acceleration + goalkeeper_skills.physical.agility) / 40.0; // Check if any opponent is closer for opponent in ctx.players().opponents().nearby(150.0) { let opp_distance_to_ball = (opponent.position - ctx.tick_context.positions.ball.position).magnitude(); let keeper_distance_to_ball = ball_distance; // Factor in goalkeeper's reach ability if opp_distance_to_ball < keeper_distance_to_ball * (1.0 - reach_ability * 0.3) { return false; // Opponent will reach first } } return true; } false } /// Check if significantly out of position using positioning skill fn is_significantly_out_of_position(&self, ctx: &StateProcessingContext) -> bool { let optimal_position = self.calculate_intelligent_position(ctx); let current_distance = ctx.player.position.distance_to(&optimal_position); // Use positioning skill to determine tolerance let positioning_skill = ctx.player.skills.mental.positioning / 20.0; let tolerance = 120.0 - (positioning_skill * 40.0); // Better positioning = tighter tolerance (80-120) current_distance > tolerance } /// Calculate intelligent position using multiple goalkeeper skills fn calculate_intelligent_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let goal_position = ctx.ball().direction_to_own_goal(); let ball_position = ctx.tick_context.positions.ball.position; let ball_distance_to_goal = (ball_position - goal_position).magnitude(); // Use positioning and command of area skills let positioning_skill = ctx.player.skills.mental.positioning / 20.0; let command_of_area = ctx.player.skills.mental.vision / 20.0; let communication = ctx.player.skills.mental.leadership / 20.0; // Calculate angle to ball for positioning let angle_to_ball = if ball_distance_to_goal > 0.1 { (ball_position - goal_position).normalize() } else { ctx.player.start_position }; // Base distance from goal line let mut optimal_distance = 3.0; // Start closer to goal // Adjust based on ball position and goalkeeper skills if ctx.ball().on_own_side() { // Ball on own half - position based on threat let threat_factor = ball_distance_to_goal / (ctx.context.field_size.width as f32 * 0.5); // Better command of area = more aggressive positioning optimal_distance += (15.0 - threat_factor * 10.0) * command_of_area; // Better positioning = more accurate placement optimal_distance *= 0.8 + positioning_skill * 0.4; // If ball is wide, adjust position laterally let ball_y_offset = ball_position.y - goal_position.y; let lateral_adjustment = ball_y_offset * 0.1 * positioning_skill; // Better positioning = better angle coverage // Calculate the position let mut new_position = goal_position + angle_to_ball * optimal_distance; new_position.y += lateral_adjustment; // Ensure within penalty area self.limit_to_penalty_area(new_position, ctx) } else { // Ball on opponent's half - position for distribution or counter let sweeper_keeper_ability = (command_of_area + communication) / 2.0; // Modern sweeper-keeper positioning optimal_distance = 8.0 + (sweeper_keeper_ability * 12.0); // 8-20 units from goal // Position more centrally when ball is far let mut new_position = goal_position; new_position.x += optimal_distance * (if ctx.player.side == Some(PlayerSide::Left) { 1.0 } else { -1.0 }); self.limit_to_penalty_area(new_position, ctx) } } /// Limit position to penalty area with some flexibility based on skills fn limit_to_penalty_area( &self, position: Vector3<f32>, ctx: &StateProcessingContext, ) -> Vector3<f32> { let penalty_area = ctx .context .penalty_area(ctx.player.side == Some(PlayerSide::Left)); // Allow slight extension for sweeper-keepers with high command of area let command_of_area = ctx.player.skills.mental.vision / 20.0; let extension_factor = 1.0 + (command_of_area * 0.1); // Up to 10% extension for excellent keepers let extended_min_x = penalty_area.min.x - (2.0 * extension_factor); let extended_max_x = penalty_area.max.x + (2.0 * extension_factor); Vector3::new( position.x.clamp(extended_min_x, extended_max_x), position.y.clamp(penalty_area.min.y, penalty_area.max.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/engine/player/strategies/goalkeepers/states/returning_goal/mod.rs
src/core/src/match/engine/player/strategies/goalkeepers/states/returning_goal/mod.rs
use crate::r#match::goalkeepers::states::common::{ActivityIntensity, GoalkeeperCondition}; use crate::r#match::goalkeepers::states::state::GoalkeeperState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; #[derive(Default)] pub struct GoalkeeperReturningGoalState {} impl StateProcessingHandler for GoalkeeperReturningGoalState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Distributing, )); } if ctx.player().distance_from_start_position() < 50.0 { return Some(StateChangeResult::with_goalkeeper_state( GoalkeeperState::Walking, )); } 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 to goal requires high intensity as goalkeeper moves back quickly GoalkeeperCondition::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/common/mod.rs
src/core/src/match/engine/player/strategies/common/mod.rs
pub mod ball; pub mod players; pub mod states; pub mod team; pub mod passing; pub use ball::{BallOperationsImpl, MatchBallLogic}; pub use passing::*; pub use players::*; pub use states::*; pub use team::*;
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/common/ball.rs
src/core/src/match/engine/player/strategies/common/ball.rs
use crate::r#match::result::VectorExtensions; use crate::r#match::{BallSide, PlayerSide, StateProcessingContext}; use nalgebra::Vector3; pub struct BallOperationsImpl<'b> { ctx: &'b StateProcessingContext<'b>, } impl<'b> BallOperationsImpl<'b> { pub fn new(ctx: &'b StateProcessingContext<'b>) -> Self { BallOperationsImpl { ctx } } } impl<'b> BallOperationsImpl<'b> { pub fn on_own_side(&self) -> bool { match self.side() { BallSide::Left => self.ctx.player.side == Some(PlayerSide::Left), BallSide::Right => self.ctx.player.side == Some(PlayerSide::Right), } } pub fn distance(&self) -> f32 { self.ctx .tick_context .positions .ball .position .distance_to(&self.ctx.player.position) } pub fn velocity(&self) -> Vector3<f32> { self.ctx .tick_context .positions .ball .velocity } #[inline] pub fn speed(&self) -> f32 { self.ctx.tick_context.positions.ball.velocity.norm() } #[inline] pub fn stopped(&self) -> bool { let velocity = self.ctx.tick_context.positions.ball.velocity; velocity.x == 0.0 && velocity.y == 0.0 } #[inline] pub fn is_owned(&self) -> bool { self.ctx.tick_context.ball.is_owned } #[inline] pub fn is_in_flight(&self) -> bool { self.ctx.tick_context.ball.is_in_flight_state > 0 } #[inline] pub fn owner_id(&self) -> Option<u32> { self.ctx.tick_context.ball.current_owner } #[inline] pub fn previous_owner_id(&self) -> Option<u32> { self.ctx.tick_context.ball.last_owner } /// Check if the current player has had stable possession long enough to make controlled actions /// Returns true if the player has owned the ball for at least MIN_POSSESSION_FOR_ACTIONS ticks #[inline] pub fn has_stable_possession(&self) -> bool { const MIN_POSSESSION_FOR_ACTIONS: u32 = 2; // Require at least 2 ticks (~0.03 seconds) of possession if self.owner_id() == Some(self.ctx.player.id) { self.ctx.tick_context.ball.ownership_duration >= MIN_POSSESSION_FOR_ACTIONS } else { false } } pub fn is_towards_player(&self) -> bool { let (is_towards, _) = MatchBallLogic::is_heading_towards_player( &self.ctx.tick_context.positions.ball.position, &self.ctx.tick_context.positions.ball.velocity, &self.ctx.player.position, 0.95, ); is_towards } pub fn is_towards_player_with_angle(&self, angle: f32) -> bool { let (is_towards, _) = MatchBallLogic::is_heading_towards_player( &self.ctx.tick_context.positions.ball.position, &self.ctx.tick_context.positions.ball.velocity, &self.ctx.player.position, angle, ); is_towards } pub fn distance_to_own_goal(&self) -> f32 { let target_goal = match self.ctx.player.side { Some(PlayerSide::Left) => Vector3::new( self.ctx.context.goal_positions.left.x, self.ctx.context.goal_positions.left.y, 0.0, ), Some(PlayerSide::Right) => Vector3::new( self.ctx.context.goal_positions.right.x, self.ctx.context.goal_positions.right.y, 0.0, ), _ => Vector3::new(0.0, 0.0, 0.0), }; self.ctx .tick_context .positions .ball .position .distance_to(&target_goal) } pub fn direction_to_own_goal(&self) -> Vector3<f32> { match self.ctx.player.side { Some(PlayerSide::Left) => self.ctx.context.goal_positions.left, Some(PlayerSide::Right) => self.ctx.context.goal_positions.right, _ => panic!("no player side"), } } pub fn direction_to_opponent_goal(&self) -> Vector3<f32> { self.ctx.player().opponent_goal_position() } pub fn distance_to_opponent_goal(&self) -> f32 { let target_goal = match self.ctx.player.side { Some(PlayerSide::Left) => Vector3::new( self.ctx.context.goal_positions.right.x, self.ctx.context.goal_positions.right.y, 0.0, ), Some(PlayerSide::Right) => Vector3::new( self.ctx.context.goal_positions.left.x, self.ctx.context.goal_positions.left.y, 0.0, ), _ => Vector3::new(0.0, 0.0, 0.0), }; self.ctx .tick_context .positions .ball .position .distance_to(&target_goal) } #[inline] pub fn on_own_third(&self) -> bool { let field_length = self.ctx.context.field_size.width as f32; let ball_x = self.ctx.tick_context.positions.ball.position.x; if self.ctx.player.side == Some(PlayerSide::Left) { // Home team defends the left side (negative X) ball_x < -field_length / 3.0 } else { // Away team defends the right side (positive X) ball_x > field_length / 3.0 } } pub fn in_own_penalty_area(&self) -> bool { // TODO let penalty_area = self .ctx .context .penalty_area(self.ctx.player.side == Some(PlayerSide::Left)); let ball_position = self.ctx.tick_context.positions.ball.position; (penalty_area.min.x..=penalty_area.max.x).contains(&ball_position.x) && (penalty_area.min.y..=penalty_area.max.y).contains(&ball_position.y) } #[inline] pub fn side(&self) -> BallSide { if (self.ctx.tick_context.positions.ball.position.x as usize) <= self.ctx.context.field_size.half_width { return BallSide::Left; } BallSide::Right } /// Check if current player has been notified to take the ball #[inline] pub fn is_player_notified(&self) -> bool { self.ctx.tick_context.ball.notified_players.contains(&self.ctx.player.id) } /// Check if ball should be taken immediately (emergency situation) /// Common pattern: ball is nearby/notified, unowned, and stopped/slow-moving /// Increased distance and velocity thresholds to catch slow rolling balls pub fn should_take_ball_immediately(&self) -> bool { self.should_take_ball_immediately_with_distance(50.0) // Increased from 33.3 } /// Check if ball should be taken immediately with custom distance threshold pub fn should_take_ball_immediately_with_distance(&self, distance_threshold: f32) -> bool { let is_nearby = self.distance() < distance_threshold; let is_notified = self.is_player_notified(); if (is_nearby || is_notified) && !self.is_owned() { let ball_velocity = self.speed(); if ball_velocity < 3.0 { // Increased from 1.0 to catch slow rolling balls return true; } } false } /// Check if ball is nearby and available (unowned or slow moving) pub fn is_nearby_and_available(&self, distance: f32) -> bool { self.distance() < distance && (!self.is_owned() || self.speed() < 2.0) } /// Check if ball is in attacking third relative to player's team pub fn in_attacking_third(&self) -> bool { let field_length = self.ctx.context.field_size.width as f32; self.distance_to_opponent_goal() < field_length / 3.0 } /// Check if ball is in middle third of the field pub fn in_middle_third(&self) -> bool { !self.on_own_third() && !self.in_attacking_third() } /// Get field position as percentage (0.0 = own goal, 1.0 = opponent goal) pub fn field_position_percentage(&self) -> f32 { let field_length = self.ctx.context.field_size.width as f32; let distance_to_own = self.distance_to_own_goal(); (distance_to_own / field_length).clamp(0.0, 1.0) } } pub struct MatchBallLogic; impl MatchBallLogic { pub fn is_heading_towards_player( ball_position: &Vector3<f32>, ball_velocity: &Vector3<f32>, player_position: &Vector3<f32>, angle: f32, ) -> (bool, f32) { let velocity_xy = Vector3::new(ball_velocity.x, ball_velocity.y, 0.0); let ball_to_player_xy = Vector3::new( player_position.x - ball_position.x, player_position.y - ball_position.y, 0.0, ); let velocity_norm = velocity_xy.norm(); let direction_norm = ball_to_player_xy.norm(); let normalized_velocity = velocity_xy / velocity_norm; let normalized_direction = ball_to_player_xy / direction_norm; let dot_product = normalized_velocity.dot(&normalized_direction); (dot_product >= angle, dot_product) } } #[cfg(test)] mod tests { use super::*; use nalgebra::Vector3; #[test] fn test_is_heading_towards_player_true() { let ball_position = Vector3::new(0.0, 0.0, 0.0); let ball_velocity = Vector3::new(1.0, 1.0, 0.0); let player_position = Vector3::new(5.0, 5.0, 0.0); let angle = 0.9; let (result, dot_product) = MatchBallLogic::is_heading_towards_player( &ball_position, &ball_velocity, &player_position, angle, ); assert!(result); assert!(dot_product > angle); } #[test] fn test_is_heading_towards_player_false() { let ball_position = Vector3::new(0.0, 0.0, 0.0); let ball_velocity = Vector3::new(1.0, 1.0, 0.0); let player_position = Vector3::new(-5.0, -5.0, 0.0); let angle = 0.9; let (result, dot_product) = MatchBallLogic::is_heading_towards_player( &ball_position, &ball_velocity, &player_position, angle, ); assert!(!result); assert!(dot_product < angle); } #[test] fn test_is_heading_towards_player_perpendicular() { let ball_position = Vector3::new(0.0, 0.0, 0.0); let ball_velocity = Vector3::new(1.0, 0.0, 0.0); let player_position = Vector3::new(0.0, 5.0, 0.0); let angle = 0.9; let (result, dot_product) = MatchBallLogic::is_heading_towards_player( &ball_position, &ball_velocity, &player_position, angle, ); assert!(!result); assert!(dot_product < angle); } }
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/common/team/team.rs
src/core/src/match/engine/player/strategies/common/team/team.rs
use crate::r#match::{MatchContext, MatchPlayerLite, PlayerSide, StateProcessingContext}; use crate::{PlayerFieldPositionGroup, Tactics}; use nalgebra::Vector3; pub struct TeamOperationsImpl<'b> { ctx: &'b StateProcessingContext<'b>, } impl<'b> TeamOperationsImpl<'b> { pub fn new(ctx: &'b StateProcessingContext<'b>) -> Self { TeamOperationsImpl { ctx } } } impl<'b> TeamOperationsImpl<'b> { pub fn tactics(&self) -> &Tactics { match self.ctx.player.side { Some(PlayerSide::Left) => &self.ctx.context.tactics.left, Some(PlayerSide::Right) => &self.ctx.context.tactics.right, None => { panic!("unknown player side") } } } pub fn is_control_ball(&self) -> bool { let current_player_team_id = self.ctx.player.team_id; // First check: if a player from player's team has the ball if let Some(owner_id) = self.ctx.ball().owner_id() { if let Some(ball_owner) = self.ctx.context.players.by_id(owner_id) { return ball_owner.team_id == current_player_team_id; } } // Second check: if previous owner was from player's team if let Some(prev_owner_id) = self.ctx.ball().previous_owner_id() { if let Some(prev_ball_owner) = self.ctx.context.players.by_id(prev_owner_id) { if prev_ball_owner.team_id == current_player_team_id { // Check if the ball is still heading in a favorable direction for the team // or if a teammate is clearly going to get it let ball_velocity = self.ctx.tick_context.positions.ball.velocity; // If ball has significant velocity and is heading toward opponent's goal if ball_velocity.magnitude() > 1.0 { // Determine which way is "forward" based on team side let forward_direction = match self.ctx.player.side { Some(PlayerSide::Left) => Vector3::new(1.0, 0.0, 0.0), // Left team attacks right Some(PlayerSide::Right) => Vector3::new(-1.0, 0.0, 0.0), // Right team attacks left None => Vector3::new(0.0, 0.0, 0.0), }; // If ball is moving forward or toward a teammate let dot_product = ball_velocity.normalize().dot(&forward_direction); if dot_product > 0.1 { return true; } // If a teammate is clearly going for the ball and is close if self.is_teammate_chasing_ball() { return true; } } } } } // If we get here, we need to check if any player from our team // is closer to the ball than any opponent let ball_pos = self.ctx.tick_context.positions.ball.position; let closest_teammate_dist = self.ctx.players().teammates().all() .map(|p| (p.position - ball_pos).magnitude()) .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); let closest_opponent_dist = self.ctx.players().opponents().all() .map(|p| (p.position - ball_pos).magnitude()) .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); // If a teammate is significantly closer to the ball than any opponent if let (Some(team_dist), Some(opp_dist)) = (closest_teammate_dist, closest_opponent_dist) { if team_dist < opp_dist * 0.7 { // Teammate is at least 30% closer return true; } } false } pub fn is_leading(&self) -> bool { !self.is_loosing() } pub fn is_loosing(&self) -> bool { if self.ctx.player.team_id == self.ctx.context.score.home_team.team_id { self.ctx.context.score.home_team < self.ctx.context.score.away_team } else { self.ctx.context.score.away_team < self.ctx.context.score.home_team } } pub fn is_teammate_chasing_ball(&self) -> bool { let ball_position = self.ctx.tick_context.positions.ball.position; self.ctx .players() .teammates() .all() .any(|player| { // Check if player is heading toward the ball let player_position = self.ctx.tick_context.positions.players.position(player.id); let player_velocity = self.ctx.tick_context.positions.players.velocity(player.id); if player_velocity.magnitude() < 0.1 { return false; } let direction_to_ball = (ball_position - player_position).normalize(); let player_direction = player_velocity.normalize(); let dot_product = direction_to_ball.dot(&player_direction); // Player is moving toward the ball dot_product > 0.85 && // And is closer or has better position (ball_position - player_position).magnitude() < (ball_position - self.ctx.player.position).magnitude() * 1.2 }) } // Determine if this player is the best positioned to chase the ball pub fn is_best_player_to_chase_ball(&self) -> bool { let ball_position = self.ctx.tick_context.positions.ball.position; // Don't chase the ball if a teammate already has it if let Some(owner_id) = self.ctx.ball().owner_id() { if let Some(owner) = self.ctx.context.players.by_id(owner_id) { if owner.team_id == self.ctx.player.team_id { // A teammate has the ball, don't try to take it return false; } } } // Check if the player is already the closest to the ball on their team // Calculate player's "ball-chasing score" based on distance, position, and attributes let calculate_score = |player: &MatchPlayerLite, _context: &MatchContext| -> f32 { let pos = self.ctx.tick_context.positions.players.position(player.id); let dist = (ball_position - pos).magnitude(); let player_ops = self.ctx.player(); let player = player_ops.get(player.id); let skills = player_ops.skills(player.id); let pace_factor = skills.physical.pace / 20.0; let acceleration_factor = skills.physical.acceleration / 20.0; let position_factor = match player.tactical_positions.position_group() { // Forwards and midfielders are more likely to chase the ball PlayerFieldPositionGroup::Forward => 1.2, PlayerFieldPositionGroup::Midfielder => 1.1, PlayerFieldPositionGroup::Defender => 0.9, PlayerFieldPositionGroup::Goalkeeper => 0.5, }; // Lower score is better dist * (1.0 / (pace_factor * acceleration_factor * position_factor * 0.5 + 0.5)) }; let player_score = calculate_score(&self.ctx.player.into(), &self.ctx.context); // Compare against other teammates !self.ctx .players() .teammates() .all() .any(|player| calculate_score(&player, &self.ctx.context) < player_score * 0.8) // 20% threshold to avoid constant switching } }
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/common/team/mod.rs
src/core/src/match/engine/player/strategies/common/team/mod.rs
pub mod team; pub use team::*;
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/common/passing/mod.rs
src/core/src/match/engine/player/strategies/common/passing/mod.rs
pub mod evaluator; pub use evaluator::*;
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/common/passing/evaluator.rs
src/core/src/match/engine/player/strategies/common/passing/evaluator.rs
use crate::r#match::{MatchPlayer, MatchPlayerLite, PlayerSide, StateProcessingContext}; /// Comprehensive pass evaluation result #[derive(Debug, Clone)] pub struct PassEvaluation { /// Overall success probability [0.0 - 1.0] pub success_probability: f32, /// Risk level [0.0 - 1.0] where 1.0 is highest risk pub risk_level: f32, /// Expected value of the pass pub expected_value: f32, /// Breakdown of factors pub factors: PassFactors, /// Whether this pass is recommended pub is_recommended: bool, } #[derive(Debug, Clone)] pub struct PassFactors { pub distance_factor: f32, pub angle_factor: f32, pub pressure_factor: f32, pub receiver_positioning: f32, pub passer_ability: f32, pub receiver_ability: f32, pub tactical_value: f32, } pub struct PassEvaluator; impl PassEvaluator { /// Evaluate a potential pass from one player to another pub fn evaluate_pass( ctx: &StateProcessingContext, passer: &MatchPlayer, receiver: &MatchPlayerLite, ) -> PassEvaluation { let pass_vector = receiver.position - passer.position; let pass_distance = pass_vector.norm(); // Calculate individual factors let distance_factor = Self::calculate_distance_factor(pass_distance, passer); let angle_factor = Self::calculate_angle_factor(ctx, passer, receiver); let pressure_factor = Self::calculate_pressure_factor(ctx, passer); let receiver_positioning = Self::calculate_receiver_positioning(ctx, receiver); let passer_ability = Self::calculate_passer_ability(ctx, passer, pass_distance); let receiver_ability = Self::calculate_receiver_ability(ctx, receiver); let tactical_value = Self::calculate_tactical_value(ctx, receiver); let factors = PassFactors { distance_factor, angle_factor, pressure_factor, receiver_positioning, passer_ability, receiver_ability, tactical_value, }; // Calculate success probability using weighted factors let success_probability = Self::calculate_success_probability(&factors); // Calculate risk level (inverse of some success factors) let risk_level = Self::calculate_risk_level(&factors); // Calculate expected value considering success probability and tactical value let expected_value = success_probability * tactical_value; // Determine if pass is recommended based on thresholds let is_recommended = success_probability > 0.6 && risk_level < 0.7; PassEvaluation { success_probability, risk_level, expected_value, factors, is_recommended, } } /// Calculate how distance affects pass success fn calculate_distance_factor(distance: f32, passer: &MatchPlayer) -> f32 { let passing_skill = passer.skills.technical.passing; let vision_skill = passer.skills.mental.vision; let technique_skill = passer.skills.technical.technique; // Vision and technique extend effective passing range let vision_bonus = (vision_skill / 20.0) * 1.5; let _technique_bonus = (technique_skill / 20.0) * 0.5; let optimal_range = passing_skill * (2.5 + vision_bonus); let max_effective_range = passing_skill * (5.0 + vision_bonus * 2.0); let ultra_long_threshold = 200.0; let extreme_long_threshold = 300.0; if distance <= optimal_range { // Short to medium passes - very high success 1.0 - (distance / optimal_range * 0.1) } else if distance <= max_effective_range { // Long passes (60-100m) - declining success (less penalty with high vision) let excess = distance - optimal_range; let range = max_effective_range - optimal_range; let base_decline = 0.9 - (excess / range * 0.5); // Vision reduces the decline penalty base_decline + (vision_skill / 20.0 * 0.1) } else if distance <= ultra_long_threshold { // Very long passes (100-200m) - vision and technique critical let excess = distance - max_effective_range; let range = ultra_long_threshold - max_effective_range; let skill_factor = (vision_skill / 20.0 * 0.6) + (technique_skill / 20.0 * 0.3); let base_factor = 0.5 - (excess / range * 0.25); (base_factor + skill_factor * 0.3).clamp(0.2, 0.7) } else if distance <= extreme_long_threshold { // Ultra-long passes (200-300m) - only elite players can execute let skill_factor = (vision_skill / 20.0 * 0.7) + (technique_skill / 20.0 * 0.3); // Require high skills for these passes if skill_factor > 0.7 { // Elite passer - can attempt with decent success (0.4 + skill_factor * 0.2).clamp(0.3, 0.6) } else if skill_factor > 0.5 { // Good passer - risky but possible (0.3 + skill_factor * 0.15).clamp(0.2, 0.45) } else { // Average/poor passer - very low success 0.15 } } else { // Extreme long passes (300m+) - goalkeeper clearances, desperate plays let skill_factor = (vision_skill / 20.0 * 0.5) + (technique_skill / 20.0 * 0.35) + (passing_skill / 20.0 * 0.15); // Only world-class passers have reasonable success if skill_factor > 0.8 { 0.5 // Elite - still challenging } else if skill_factor > 0.6 { 0.35 // Good - very risky } else { 0.2 // Poor - mostly luck } } } /// Calculate how the angle between passer's facing and pass direction affects success fn calculate_angle_factor( ctx: &StateProcessingContext, passer: &MatchPlayer, receiver: &MatchPlayerLite, ) -> f32 { let pass_direction = (receiver.position - passer.position).normalize(); let passer_velocity = ctx.tick_context.positions.players.velocity(passer.id); if passer_velocity.norm() < 0.1 { // Standing still - can pass in any direction easily return 0.95; } let facing_direction = passer_velocity.normalize(); let dot_product = pass_direction.dot(&facing_direction); // Convert dot product to angle factor // 1.0 = same direction, -1.0 = opposite direction if dot_product > 0.7 { // Forward passes - easiest 1.0 } else if dot_product > 0.0 { // Diagonal passes - moderate difficulty 0.8 + (dot_product * 0.2) } else if dot_product > -0.5 { // Sideways to backward passes - harder 0.6 + ((dot_product + 0.5) * 0.4) } else { // Backward passes while moving forward - very difficult 0.5 + ((dot_product + 1.0) * 0.2) } } /// Calculate pressure on the passer from opponents fn calculate_pressure_factor( ctx: &StateProcessingContext, passer: &MatchPlayer, ) -> f32 { const PRESSURE_RADIUS: f32 = 15.0; let nearby_opponents: Vec<(u32, f32)> = ctx.tick_context .distances .opponents(passer.id, PRESSURE_RADIUS) .collect(); if nearby_opponents.is_empty() { return 1.0; // No pressure } // Calculate pressure based on closest opponent and number of opponents let closest_distance = nearby_opponents .iter() .map(|(_, dist)| *dist) .min_by(|a, b| a.partial_cmp(b).unwrap()) .unwrap_or(PRESSURE_RADIUS); let num_opponents = nearby_opponents.len() as f32; // Pressure from distance let distance_pressure = (closest_distance / PRESSURE_RADIUS).clamp(0.0, 1.0); // Additional pressure from multiple opponents let number_pressure = (1.0 - (num_opponents - 1.0) * 0.15).max(0.5); // Mental attributes help under pressure let composure_factor = passer.skills.mental.composure / 20.0; let decision_factor = passer.skills.mental.decisions / 20.0; let base_pressure = distance_pressure * number_pressure; let pressure_with_mentals = base_pressure + (1.0 - base_pressure) * composure_factor * decision_factor; pressure_with_mentals.clamp(0.3, 1.0) } /// Evaluate receiver's positioning quality fn calculate_receiver_positioning( ctx: &StateProcessingContext, receiver: &MatchPlayerLite, ) -> f32 { const VERY_CLOSE_RADIUS: f32 = 3.0; const CLOSE_RADIUS: f32 = 7.0; const MEDIUM_RADIUS: f32 = 12.0; // Check opponents at multiple distance ranges for nuanced space evaluation let all_opponents: Vec<(u32, f32)> = ctx.tick_context .distances .opponents(receiver.id, MEDIUM_RADIUS) .collect(); // Count opponents in each zone let very_close_opponents = all_opponents.iter() .filter(|(_, dist)| *dist < VERY_CLOSE_RADIUS) .count(); let close_opponents = all_opponents.iter() .filter(|(_, dist)| *dist >= VERY_CLOSE_RADIUS && *dist < CLOSE_RADIUS) .count(); let medium_opponents = all_opponents.iter() .filter(|(_, dist)| *dist >= CLOSE_RADIUS && *dist < MEDIUM_RADIUS) .count(); // Calculate space quality with heavy penalties for nearby opponents let space_factor = if very_close_opponents > 0 { // Very tightly marked - poor option 0.2 - (very_close_opponents as f32 * 0.1).min(0.15) } else if close_opponents > 0 { // Marked but manageable 0.6 - (close_opponents as f32 * 0.15).min(0.3) } else if medium_opponents > 0 { // Some pressure but good space 0.85 - (medium_opponents as f32 * 0.1).min(0.2) } else { // Completely free - excellent option 1.0 }; // Check if receiver is moving into space or standing still let receiver_velocity = ctx.tick_context.positions.players.velocity(receiver.id); let movement_factor = if receiver_velocity.norm() > 1.5 { // Moving into space - excellent 1.15 } else if receiver_velocity.norm() > 0.5 { // Some movement - good 1.05 } else { // Standing still - acceptable but not ideal 0.95 }; // Off the ball movement skill affects positioning quality let players = ctx.player(); let skills = players.skills(receiver.id); let off_ball_factor = skills.mental.off_the_ball / 20.0; let positioning_factor = skills.mental.positioning / 20.0; (space_factor * movement_factor * (0.7 + off_ball_factor * 0.15 + positioning_factor * 0.15)).clamp(0.1, 1.0) } /// Calculate passer's ability to execute this pass fn calculate_passer_ability(_ctx: &StateProcessingContext, passer: &MatchPlayer, distance: f32) -> f32 { let passing_skill = passer.skills.technical.passing / 20.0; let technique_skill = passer.skills.technical.technique / 20.0; let vision_skill = passer.skills.mental.vision / 20.0; // For short passes, technique matters more // For long passes, passing skill matters more let short_pass_weight = 1.0 - (distance / 100.0).min(1.0); let ability = passing_skill * (0.5 + short_pass_weight * 0.2) + technique_skill * (0.3 + short_pass_weight * 0.2) + vision_skill * 0.2; // Condition affects ability let condition_factor = passer.player_attributes.condition as f32 / 10000.0; (ability * condition_factor).clamp(0.3, 1.0) } /// Calculate receiver's ability to control the pass fn calculate_receiver_ability(ctx: &StateProcessingContext, receiver: &MatchPlayerLite) -> f32 { let players = ctx.player(); let skills = players.skills(receiver.id); let first_touch = skills.technical.first_touch / 20.0; let technique = skills.technical.technique / 20.0; let anticipation = skills.mental.anticipation / 20.0; let ability = first_touch * 0.5 + technique * 0.3 + anticipation * 0.2; // Condition affects ability let player_attributes = players.attributes(receiver.id); let condition_factor = player_attributes.condition as f32 / 10000.0; (ability * condition_factor).clamp(0.3, 1.0) } /// Calculate tactical value of the pass fn calculate_tactical_value( ctx: &StateProcessingContext, receiver: &MatchPlayerLite, ) -> f32 { let ball_position = ctx.tick_context.positions.ball.position; let receiver_position = receiver.position; let passer_position = ctx.player.position; // Determine which direction is forward based on player side let forward_direction_multiplier = match ctx.player.side { Some(PlayerSide::Left) => 1.0, // Left team attacks right (positive X) Some(PlayerSide::Right) => -1.0, // Right team attacks left (negative X) None => 1.0, }; // Calculate actual forward progress (positive = forward, negative = backward) let field_width = ctx.context.field_size.width as f32; let forward_progress = ((receiver_position.x - ball_position.x) * forward_direction_multiplier) / field_width; // Strong penalty for backward passes, strong reward for forward let forward_value = if forward_progress < 0.0 { // Backward pass - heavy penalty unless under extreme pressure let pressure_factor = 1.0 - ctx.player.skills.mental.composure / 20.0; forward_progress * 2.0 * pressure_factor.max(0.3) // -0.6 to -0.1 } else { // Forward pass - strong reward forward_progress * 1.5 // Up to 1.5 }; // Distance bonus: prefer passes of 20-50m over very short (< 15m) or very long let pass_distance = (receiver_position - passer_position).norm(); let distance_value = if pass_distance < 10.0 { // Very short pass - only good under pressure 0.3 } else if pass_distance < 20.0 { // Short pass - acceptable 0.6 } else if pass_distance < 50.0 { // Ideal passing range - good progression 1.0 } else if pass_distance < 80.0 { // Long pass - still valuable 0.8 } else if pass_distance < 150.0 { // Very long pass - situational 0.6 } else { // Extreme distance - only with high vision let vision_skill = ctx.player.skills.mental.vision / 20.0; 0.4 * vision_skill }; // Long cross-field passes - reward vision players for switching play let vision_skill = ctx.player.skills.mental.vision / 20.0; let technique_skill = ctx.player.skills.technical.technique / 20.0; let long_pass_bonus = if pass_distance > 300.0 { // Extreme distance (300m+) - goalkeeper goal kicks, desperate clearances (vision_skill * 0.5 + technique_skill * 0.3) * 0.5 } else if pass_distance > 200.0 { // Ultra-long diagonal (200-300m) - switches play across entire field (vision_skill * 0.45 + technique_skill * 0.25) * 0.4 } else if pass_distance > 100.0 { // Very long cross-field switch (100-200m) - valuable for high vision players vision_skill * 0.3 } else if pass_distance > 60.0 { // Long pass (60-100m) - some bonus for vision vision_skill * 0.15 } else { 0.0 }; // Passes to advanced positions are more valuable let position_value = match receiver.tactical_positions.position_group() { crate::PlayerFieldPositionGroup::Forward => 1.0, crate::PlayerFieldPositionGroup::Midfielder => 0.7, crate::PlayerFieldPositionGroup::Defender => 0.4, crate::PlayerFieldPositionGroup::Goalkeeper => 0.2, }; // Weighted combination - heavily favor forward progress and good distance let tactical_value = forward_value * 0.55 + // Increased from 0.50 - even more favor for forward passes distance_value * 0.22 + // Slightly reduced from 0.25 position_value * 0.13 + // Reduced from 0.15 long_pass_bonus * 0.10; // Keep same // Allow negative tactical values for backward passes (don't clamp to 0.1 minimum) // This properly penalizes backward passes to GK // Increased cap from 1.3 to 1.8 to better reward excellent penetrating opportunities tactical_value.clamp(-0.5, 1.8) } /// Calculate overall success probability from factors fn calculate_success_probability(factors: &PassFactors) -> f32 { // Weighted combination of all factors // Reduced receiver positioning weight to allow passes to marked attackers let probability = factors.distance_factor * 0.15 + factors.angle_factor * 0.12 + factors.pressure_factor * 0.12 + factors.receiver_positioning * 0.25 + // Reduced from 0.30 to allow penetrating passes factors.passer_ability * 0.15 + // Increased from 0.13 factors.receiver_ability * 0.10 + factors.tactical_value * 0.11; // Increased from 0.08 to reward forward play probability.clamp(0.1, 0.99) } /// Calculate overall risk level fn calculate_risk_level(factors: &PassFactors) -> f32 { // Risk is inverse of safety factors // Poor receiver positioning (crowded by opponents) is now a major risk let risk = (1.0 - factors.distance_factor) * 0.20 + (1.0 - factors.pressure_factor) * 0.20 + (1.0 - factors.receiver_positioning) * 0.40 + // Increased from 0.20 (1.0 - factors.receiver_ability) * 0.20; risk.clamp(0.0, 1.0) } /// Calculate interception risk from opponents along the pass path fn calculate_interception_risk( ctx: &StateProcessingContext, passer: &MatchPlayer, receiver: &MatchPlayerLite, ) -> f32 { let pass_vector = receiver.position - passer.position; let pass_distance = pass_vector.norm(); let pass_direction = pass_vector.normalize(); // Check for opponents who could intercept the pass let intercepting_opponents = ctx.players().opponents().all() .filter(|opponent| { let to_opponent = opponent.position - passer.position; let projection_distance = to_opponent.dot(&pass_direction); // Only consider opponents between passer and receiver if projection_distance <= 0.0 || projection_distance >= pass_distance { return false; } // Calculate perpendicular distance from pass line let projected_point = passer.position + pass_direction * projection_distance; let perp_distance = (opponent.position - projected_point).norm(); // Consider opponent's interception ability let players = ctx.player(); let opponent_skills = players.skills(opponent.id); let interception_ability = opponent_skills.technical.tackling / 20.0; let anticipation = opponent_skills.mental.anticipation / 20.0; // Better opponents can intercept from further away let effective_radius = 3.0 + (interception_ability + anticipation) * 2.0; perp_distance < effective_radius }) .count(); // Convert count to risk factor if intercepting_opponents == 0 { 0.0 // No risk } else if intercepting_opponents == 1 { 0.3 // Moderate risk } else if intercepting_opponents == 2 { 0.6 // High risk } else { 0.9 // Very high risk } } /// Find the best pass option from available teammates with skill-based personality /// Returns (teammate, reason) tuple pub fn find_best_pass_option( ctx: &StateProcessingContext, max_distance: f32, ) -> Option<(MatchPlayerLite, &'static str)> { let mut best_option: Option<MatchPlayerLite> = None; let mut best_score = 0.0; // Determine player's passing personality based on skills let pass_skill = ctx.player.skills.technical.passing / 20.0; let vision_skill = ctx.player.skills.mental.vision / 20.0; let flair_skill = ctx.player.skills.mental.flair / 20.0; let decision_skill = ctx.player.skills.mental.decisions / 20.0; let composure_skill = ctx.player.skills.mental.composure / 20.0; let teamwork_skill = ctx.player.skills.mental.teamwork / 20.0; let _anticipation_skill = ctx.player.skills.mental.anticipation / 20.0; // Define passing personalities let is_playmaker = vision_skill > 0.75 && flair_skill > 0.65; // Creative, through balls let is_direct = flair_skill > 0.7 && pass_skill > 0.65; // Risky, aggressive forward passes let is_conservative = decision_skill < 0.5 || composure_skill < 0.5; // Safe, sideways passes let is_team_player = teamwork_skill > 0.75 && pass_skill > 0.65; // Finds best positioned teammates let is_pragmatic = decision_skill > 0.75 && pass_skill > 0.6; // Smart, calculated passes // Calculate minimum pass distance based on pressure // NOTE: This filter prevents "too short" passes that don't progress the ball let is_under_pressure = ctx.players().opponents().exists(25.0); let min_pass_distance = if is_under_pressure { // Under pressure, allow any distance 0.0 } else { // Not under pressure, discourage very short passes (but allow them) // This is handled by scoring bonuses instead of hard filtering 0.0 }; // Get previous ball owner to prevent ping-pong passes let previous_owner_id = ctx.ball().previous_owner_id(); for teammate in ctx.players().teammates().nearby(max_distance) { // PING-PONG PREVENTION: Don't pass back to the player who just passed to you if let Some(prev_owner) = previous_owner_id { if teammate.id == prev_owner { continue; // Skip this teammate } } let pass_distance = (teammate.position - ctx.player.position).norm(); // MINIMUM DISTANCE FILTER: Skip teammates that are too close unless under pressure if pass_distance < min_pass_distance { continue; } let evaluation = Self::evaluate_pass(ctx, ctx.player, &teammate); let interception_risk = Self::calculate_interception_risk(ctx, ctx.player, &teammate); // Base positioning bonus let positioning_bonus = evaluation.factors.receiver_positioning * 2.0; // Skill-based space quality evaluation let space_quality = if is_conservative { // Conservative players prefer free receivers but less extreme if evaluation.factors.receiver_positioning > 0.85 { 1.8 // Reduced from 2.0 - completely free players } else if evaluation.factors.receiver_positioning > 0.65 { 1.3 // Increased from 1.2 - good space } else if evaluation.factors.receiver_positioning > 0.45 { 0.8 // New tier - acceptable space } else { 0.4 // Increased from 0.3 - will attempt if needed } } else if is_playmaker { // Playmakers trust teammates to handle some pressure if evaluation.factors.receiver_positioning > 0.75 { 1.7 // Increased from 1.6 } else if evaluation.factors.receiver_positioning > 0.5 { 1.4 // Increased from 1.3 - still okay with moderate space } else if evaluation.factors.receiver_positioning > 0.3 { 1.0 // New tier - willing to attempt tighter passes } else { 0.7 // Reduced penalty for very tight spaces } } else if is_direct { // Direct players less concerned about space, more about attacking position if evaluation.factors.receiver_positioning > 0.6 { 1.6 // Increased from 1.5 } else if evaluation.factors.receiver_positioning > 0.4 { 1.2 // New tier } else { 0.9 // Reduced from 1.0 - will attempt most passes } } else { // Standard space evaluation - slightly more aggressive if evaluation.factors.receiver_positioning > 0.75 { 1.6 // Increased from 1.5 } else if evaluation.factors.receiver_positioning > 0.55 { 1.3 // Increased from 1.2 } else if evaluation.factors.receiver_positioning > 0.35 { 1.0 // Improved threshold from 0.4 } else { 0.7 // Increased from 0.6 } }; // Skill-based interception risk tolerance let risk_tolerance = if is_direct { 0.3 // Willing to take risks } else if is_conservative { 0.8 // Avoid any risk } else if is_playmaker { 0.4 // Moderate risk for creative passes } else { 0.5 // Standard risk avoidance }; let interception_penalty = 1.0 - (interception_risk * risk_tolerance); // Add distance preference bonus - widened optimal range to encourage penetration let optimal_distance_bonus = if is_under_pressure { // Under pressure, all safe passes are good 1.0 } else if pass_distance >= 20.0 && pass_distance <= 70.0 { // Widened optimal range (was 15-40m, now 20-70m) for penetrating passes 1.4 // Increased from 1.3 } else if pass_distance >= 15.0 && pass_distance < 20.0 { // Short passes - acceptable 1.1 // New tier } else if pass_distance < 15.0 { // Very short - discouraged unless necessary 0.7 } else if pass_distance <= 100.0 { // Long passes (70-100m) - still valuable 1.2 // New tier - was implicitly 1.0 } else { // Very long passes - situational 1.0 }; // Distance preference based on personality let distance_preference = if is_playmaker { // Playmakers love long through balls and switches if pass_distance > 300.0 { // Extreme passes - only if vision is elite if vision_skill > 0.85 { 1.8 // World-class playmaker - go for spectacular passes } else { 0.8 // Too risky for most } } else if pass_distance > 200.0 { // Ultra-long switches - playmaker specialty if vision_skill > 0.75 { 1.6 // High vision - loves these passes } else { 1.1 } } else if pass_distance > 100.0 { 1.5 // Very long passes - excellent for playmakers } else if pass_distance > 80.0 { 1.4 } else if pass_distance > 50.0 { 1.2 } else { 1.0 } } else if is_direct { // Direct players prefer forward passes of any length let forward_progress = teammate.position.x - ctx.player.position.x; if forward_progress > 0.0 { 1.3 } else { 0.6 // Avoid backward passes } } else if is_conservative { // Conservative players prefer short, safe passes if pass_distance < 30.0 { 1.4 } else if pass_distance < 50.0 { 1.0 } else { 0.7 // Avoid long passes } } else if is_team_player { // Team players maximize teammate positioning 1.0 + (evaluation.factors.receiver_positioning * 0.3) } else if is_pragmatic { // Pragmatic players balance all factors if evaluation.expected_value > 0.6 { 1.3 // Good tactical value } else { 1.0 } } else { 1.0 }; // GOALKEEPER PENALTY: Almost completely eliminate passing to goalkeeper let is_goalkeeper = matches!( teammate.tactical_positions.position_group(), crate::PlayerFieldPositionGroup::Goalkeeper ); let goalkeeper_penalty = if is_goalkeeper { // Calculate if this is a backward pass let forward_direction_multiplier = match ctx.player.side { Some(PlayerSide::Left) => 1.0, Some(PlayerSide::Right) => -1.0, None => 1.0, }; let is_backward_pass = ((teammate.position.x - ctx.player.position.x) * forward_direction_multiplier) < 0.0; // Check if player is in attacking third let field_width = ctx.context.field_size.width as f32; let player_field_position = (ctx.player.position.x * forward_direction_multiplier) / field_width; let in_attacking_third = player_field_position > 0.66; if in_attacking_third && is_backward_pass { // In attacking third, passing backward to GK is NEVER acceptable 0.00001 // Virtually zero } else if is_backward_pass { // Backward pass to GK in middle/defensive third - still very bad 0.0001 } else if evaluation.factors.pressure_factor < 0.2 { // Forward/sideways pass under EXTREME pressure - GK is emergency option 0.02 } else { // Normal play - virtually eliminate GK passes 0.0005 } } else { 1.0 // No penalty for non-GK }; // Calculate final score with personality-based weighting let score = if evaluation.factors.pressure_factor < 0.5 { // Under heavy pressure - personality affects decision if is_conservative { // Conservative: safety is paramount (evaluation.success_probability * 2.0 + positioning_bonus) * interception_penalty * space_quality * optimal_distance_bonus * goalkeeper_penalty } else if is_direct { // Direct: still look for forward options (evaluation.expected_value * 1.5 + positioning_bonus * 0.3) * interception_penalty * space_quality * distance_preference * optimal_distance_bonus * goalkeeper_penalty } else { // Others: prioritize safety AND space (evaluation.success_probability + positioning_bonus) * interception_penalty * space_quality * 1.3 * optimal_distance_bonus * goalkeeper_penalty } } else { // Normal situation - personality-based preferences apply
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/common/players/teammates.rs
src/core/src/match/engine/player/strategies/common/players/teammates.rs
use crate::r#match::{MatchPlayerLite, PlayerSide, StateProcessingContext}; use crate::PlayerFieldPositionGroup; pub struct PlayerTeammatesOperationsImpl<'b> { ctx: &'b StateProcessingContext<'b>, } impl<'b> PlayerTeammatesOperationsImpl<'b> { pub fn new(ctx: &'b StateProcessingContext<'b>) -> Self { PlayerTeammatesOperationsImpl { ctx } } } impl<'b> PlayerTeammatesOperationsImpl<'b> { pub fn all(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.teammates_for_team(self.ctx.player.id, self.ctx.player.team_id, None) } pub fn players_with_ball(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.teammates_for_team(self.ctx.player.id, self.ctx.player.team_id, Some(true)) } pub fn players_without_ball(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.teammates_for_team(self.ctx.player.id, self.ctx.player.team_id, Some(false)) } pub fn defenders(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.teammates_by_position(PlayerFieldPositionGroup::Defender, self.ctx.player.team_id) } pub fn forwards(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.teammates_by_position(PlayerFieldPositionGroup::Forward, self.ctx.player.team_id) } fn teammates_by_position( &'b self, position_group: PlayerFieldPositionGroup, team_id: u32, ) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.ctx .context .players .players .values() .filter(move |player| { player.team_id == team_id && player.tactical_position.current_position.position_group() == position_group }) .map(|player| MatchPlayerLite { id: player.id, position: self.ctx.tick_context.positions.players.position(player.id), tactical_positions: player.tactical_position.current_position }) } fn teammates_for_team( &'b self, player_id: u32, team_id: u32, has_ball: Option<bool>, ) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.ctx .context .players .players .values() .filter(move |player| { // Check if player matches team criteria if player.id == player_id || player.team_id != team_id { return false; } // Check if player matches has_ball criteria match has_ball { None => true, // No filter, include all teammates Some(true) => self.ctx.ball().owner_id() == Some(player.id), // Only teammates with ball Some(false) => self.ctx.ball().owner_id() != Some(player.id) // Only teammates without ball } }) .map(|player| MatchPlayerLite { id: player.id, position: self.ctx.tick_context.positions.players.position(player.id), tactical_positions: player.tactical_position.current_position }) } pub fn nearby(&'b self, max_distance: f32) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.nearby_range(1.0, max_distance) } pub fn nearby_range(&'b self, min_distance: f32, max_distance: f32) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.ctx .tick_context .distances .teammates(self.ctx.player.id, min_distance, max_distance) .map(|(pid, _)| MatchPlayerLite { id: pid, position: self.ctx.tick_context.positions.players.position(pid), tactical_positions: self.ctx.context.players.by_id(pid).expect(&format!( "unknown player = {}", pid )).tactical_position.current_position }) } pub fn nearby_to_opponent_goal(&'b self) -> Option<MatchPlayerLite> { let mut teammates: Vec<MatchPlayerLite> = self.nearby(300.0).collect(); if teammates.is_empty() { return None; } teammates.sort_by(|a, b| a.position.x.partial_cmp(&b.position.x).unwrap()); if self.ctx.player.side == Some(PlayerSide::Right) { Some(teammates[0]) } else { Some(teammates[teammates.len() - 1]) } } pub fn nearby_ids(&self, max_distance: f32) -> impl Iterator<Item = (u32, f32)> + 'b { const MIN_DISTANCE: f32 = 1.0; // Changed from 50.0 to allow closer teammates self.ctx .tick_context .distances .teammates(self.ctx.player.id, MIN_DISTANCE, max_distance) } pub fn exists(&self, max_distance: f32) -> bool { const MIN_DISTANCE: f32 = 0.0; self.ctx .tick_context .distances .teammates(self.ctx.player.id, MIN_DISTANCE, max_distance) .any(|_| 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/common/players/player.rs
src/core/src/match/engine/player/strategies/common/players/player.rs
use crate::r#match::result::VectorExtensions; use crate::r#match::{ MatchPlayer, MatchPlayerLite, PlayerDistanceFromStartPosition, PlayerSide, StateProcessingContext, }; use crate::{PlayerAttributes, PlayerSkills}; use nalgebra::Vector3; use rand::Rng; use crate::r#match::player::strategies::players::{DefensiveOperationsImpl, MovementOperationsImpl, PassingOperationsImpl, PressureOperationsImpl, ShootingOperationsImpl, SkillOperationsImpl}; pub struct PlayerOperationsImpl<'p> { ctx: &'p StateProcessingContext<'p>, } impl<'p> PlayerOperationsImpl<'p> { pub fn new(ctx: &'p StateProcessingContext<'p>) -> Self { PlayerOperationsImpl { ctx } } } impl<'p> PlayerOperationsImpl<'p> { pub fn get(&self, player_id: u32) -> MatchPlayerLite { MatchPlayerLite { id: player_id, position: self.ctx.tick_context.positions.players.position(player_id), tactical_positions: self .ctx .context .players .by_id(player_id) .expect(&format!("unknown player = {}", player_id)) .tactical_position .current_position, } } pub fn skills(&self, player_id: u32) -> &PlayerSkills { let player = self.ctx.context.players.by_id(player_id).unwrap(); &player.skills } pub fn attributes(&self, player_id: u32) -> &PlayerAttributes { let player = self.ctx.context.players.by_id(player_id).unwrap(); &player.player_attributes } pub fn on_own_side(&self) -> bool { let field_half_width = self.ctx.context.field_size.width / 2; self.ctx.player.side == Some(PlayerSide::Left) && self.ctx.player.position.x < field_half_width as f32 } pub fn shooting_direction(&self) -> Vector3<f32> { let goal_position = self.opponent_goal_position(); let distance_to_goal = self.goal_distance(); // Get player skills let finishing = self.skills(self.ctx.player.id).technical.finishing; let technique = self.skills(self.ctx.player.id).technical.technique; let composure = self.skills(self.ctx.player.id).mental.composure; let long_shots = self.skills(self.ctx.player.id).technical.long_shots; // Normalize skills (0.0 to 1.0) let finishing_factor = (finishing - 1.0) / 19.0; let technique_factor = (technique - 1.0) / 19.0; let composure_factor = (composure - 1.0) / 19.0; let long_shots_factor = (long_shots - 1.0) / 19.0; // Check pressure from defenders let nearby_defenders = self.ctx.players().opponents().nearby(10.0).count(); let pressure_factor = 1.0 - (nearby_defenders as f32 * 0.15).min(0.5); // Distance factor (closer = more accurate) let distance_factor = if distance_to_goal < 150.0 { 1.0 - (distance_to_goal / 300.0) } else { // For long shots, use long_shots skill 0.5 * long_shots_factor }; // Overall accuracy (0.0 to 1.0, higher = more accurate) let accuracy = (finishing_factor * 0.4 + technique_factor * 0.25 + composure_factor * 0.2 + distance_factor * 0.15) * pressure_factor; // Goal dimensions (using goal post standard size) let goal_width = 73.0; // Standard goal width in decimeters let mut rng = rand::rng(); // Determine shot type based on distance and skills let is_placement_shot = distance_to_goal < 150.0 && finishing > 12.0; let mut target = goal_position; if is_placement_shot { // Close range: Aim for corners (like real strikers) // Choose a corner based on angle and randomness let aim_preference = rng.random_range(0.0..1.0); // Determine horizontal target (Y-axis - width) let y_target = if aim_preference < 0.5 { // Aim for left post area -goal_width * 0.35 } else { // Aim for right post area goal_width * 0.35 }; // Determine vertical target (Z-axis - height, if supported) // For now, shots are 2D so we focus on Y placement // Add accuracy-based deviation from intended corner let y_deviation = rng.random_range(-goal_width * 0.2..goal_width * 0.2) * (1.0 - accuracy); target.y += y_target + y_deviation; } else { // Long range: More central but with larger deviation // Players try to keep it on target rather than picking corners let y_base = rng.random_range(-goal_width * 0.15..goal_width * 0.15); // Larger deviation for long shots based on accuracy let y_deviation = rng.random_range(-goal_width * 0.35..goal_width * 0.35) * (1.0 - accuracy); target.y += y_base + y_deviation; } // Add slight depth deviation (X-axis) based on technique // Poor technique can cause shots to go over or fall short let x_deviation = rng.random_range(-5.0..5.0) * (1.0 - technique_factor); target.x += x_deviation; // Mental composure affects shot under pressure if nearby_defenders > 0 { let panic_factor = 1.0 - composure_factor; let panic_deviation_y = rng.random_range(-goal_width * 0.15..goal_width * 0.15) * panic_factor; let panic_deviation_x = rng.random_range(-8.0..8.0) * panic_factor; target.y += panic_deviation_y; target.x += panic_deviation_x; } target } pub fn opponent_goal_position(&self) -> Vector3<f32> { match self.ctx.player.side { Some(PlayerSide::Left) => self.ctx.context.goal_positions.right, Some(PlayerSide::Right) => self.ctx.context.goal_positions.left, _ => Vector3::new(0.0, 0.0, 0.0), } } pub fn distance_from_start_position(&self) -> f32 { self.ctx .player .start_position .distance_to(&self.ctx.player.position) } pub fn position_to_distance(&self) -> PlayerDistanceFromStartPosition { MatchPlayerLogic::distance_to_start_position(self.ctx.player) } pub fn is_tired(&self) -> bool { self.ctx.player.player_attributes.condition_percentage() > 50 } pub fn pass_teammate_power(&self, teammate_id: u32) -> f32 { let distance = self.ctx.tick_context.distances.get(self.ctx.player.id, teammate_id); // Use multiple skills to determine pass power let pass_skill = self.ctx.player.skills.technical.passing / 20.0; let technique_skill = self.ctx.player.skills.technical.technique / 20.0; let strength_skill = self.ctx.player.skills.physical.strength / 20.0; // Calculate skill-weighted factor let skill_factor = (pass_skill * 0.6) + (technique_skill * 0.2) + (strength_skill * 0.2); // More skilled players can hit passes at more appropriate power levels let max_pass_distance = self.ctx.context.field_size.width as f32 * 0.8; // Use distance-scaled power with proper minimum for very short passes // Very short passes (< 10m) should use proportionally less power let distance_factor = if distance < 10.0 { // For very short passes, scale linearly from 0.05 to 0.125 (0.05 + (distance / 10.0) * 0.075).clamp(0.05, 0.125) } else { // For longer passes, use the normal scaling with lower minimum (distance / max_pass_distance).clamp(0.125, 1.0) }; // Calculate base power with adjusted ranges for better control let min_power = 0.3; let max_power = 2.5; let base_power = min_power + (max_power - min_power) * skill_factor * distance_factor; // Add slight randomization let random_factor = rand::rng().random_range(0.9..1.1); // Players with better skills have less randomization let final_random_factor = 1.0 + (random_factor - 1.0) * (1.0 - skill_factor * 0.5); base_power * final_random_factor } pub fn kick_teammate_power(&self, teammate_id: u32) -> f32 { let distance = self .ctx .tick_context .distances .get(self.ctx.player.id, teammate_id); let kick_skill = self.ctx.player.skills.technical.free_kicks / 20.0; let raw_power = distance / (kick_skill * 100.0); let min_power = 0.1; let max_power = 1.0; let normalized_power = (raw_power - min_power) / (max_power - min_power); normalized_power.clamp(0.0, 1.0) } pub fn throw_teammate_power(&self, teammate_id: u32) -> f32 { let distance = self .ctx .tick_context .distances .get(self.ctx.player.id, teammate_id); let throw_skill = self.ctx.player.skills.technical.long_throws / 20.0; let raw_power = distance / (throw_skill * 100.0); let min_power = 0.1; let max_power = 1.0; let normalized_power = (raw_power - min_power) / (max_power - min_power); normalized_power.clamp(0.0, 1.0) } pub fn shoot_goal_power(&self) -> f64 { let goal_distance = self.goal_distance(); // Calculate the base shooting power based on the player's relevant skills let shooting_technique = self.ctx.player.skills.technical.technique; let shooting_power = self.ctx.player.skills.technical.long_shots; let finishing_skill = self.ctx.player.skills.technical.finishing; let player_strength = self.ctx.player.skills.physical.strength; // Normalize the skill values to a range between 0.5 and 1.5 let technique_factor = 0.5 + (shooting_technique / 20.0); let power_factor = 0.5 + (shooting_power / 20.0); let finishing_factor = 0.5 + (finishing_skill / 20.0); let strength_factor = 0.3 + (player_strength / 20.0) * 0.7; // Calculate distance factor that increases power for longer distances // Close shots: ~1.0, Long shots: ~1.5 let max_field_distance = self.ctx.context.field_size.width as f32; let distance_factor = 1.0 + (goal_distance / max_field_distance).min(1.0) * 0.5; // Calculate the shooting power - skills have impact now // Reduced base power significantly to keep speeds reasonable (20% above original) let base_power = 2.4; // Reduced from 8.0 to get closer to original speeds with 20% increase let skill_multiplier = (technique_factor * 0.3) + (power_factor * 0.35) + (finishing_factor * 0.2) + (strength_factor * 0.15); let shooting_power = base_power * skill_multiplier * distance_factor; // Ensure the shooting power is within a reasonable range // Target: original was ~0.5-2.5, now aiming for ~0.6-3.0 (20% increase) let min_power = 0.6; let max_power = 3.0; shooting_power.clamp(min_power, max_power) as f64 } pub fn distance_to_player(&self, player_id: u32) -> f32 { self.ctx .tick_context .distances .get(self.ctx.player.id, player_id) } pub fn goal_angle(&self) -> f32 { // Calculate the angle between the player's facing direction and the goal direction let player_direction = self.ctx.player.velocity.normalize(); let goal_direction = (self.goal_position() - self.ctx.player.position).normalize(); player_direction.angle(&goal_direction) } pub fn goal_distance(&self) -> f32 { let player_position = self.ctx.player.position; let goal_position = self.goal_position(); (player_position - goal_position).magnitude() } pub fn goal_position(&self) -> Vector3<f32> { let field_width = self.ctx.context.field_size.width as f32; let field_height = self.ctx.context.field_size.height as f32; if self.ctx.player.side == Some(PlayerSide::Left) { Vector3::new(field_width, field_height / 2.0, 0.0) } else { Vector3::new(0.0, field_height / 2.0, 0.0) } } pub fn has_clear_pass(&self, player_id: u32) -> bool { let player_position = self.ctx.player.position; let target_player_position = self.ctx.tick_context.positions.players.position(player_id); let direction_to_player = (target_player_position - player_position).normalize(); // Check if the distance to the target player is within a reasonable pass range let distance_to_player = self.ctx.player().distance_to_player(player_id); // Check if there are any opponents obstructing the pass let ray_cast_result = self.ctx.tick_context.space.cast_ray( player_position, direction_to_player, distance_to_player, false, ); ray_cast_result.is_none() } pub fn has_clear_shot(&self) -> bool { let player_position = self.ctx.player.position; let goal_position = self.ctx.player().opponent_goal_position(); let direction_to_goal = (goal_position - player_position).normalize(); // Check if the distance to the goal is within the player's shooting range let distance_to_goal = self.ctx.player().goal_distance(); // Check if there are any opponents obstructing the shot let ray_cast_result = self.ctx.tick_context.space.cast_ray( player_position, direction_to_goal, distance_to_goal, false, ); ray_cast_result.is_none() } pub fn separation_velocity(&self) -> Vector3<f32> { let players = self.ctx.players(); let teammates = players.teammates(); let opponents = players.opponents(); let mut separation = Vector3::zeros(); // Balanced parameters to prevent oscillation while maintaining separation const SEPARATION_RADIUS: f32 = 30.0; const SEPARATION_STRENGTH: f32 = 20.0; // Reduced from 25.0 to prevent excessive force const MIN_SEPARATION_DISTANCE: f32 = 3.0; // Reduced threshold for emergency separation // Apply separation from teammates for other_player in teammates.nearby(SEPARATION_RADIUS) { let to_other = other_player.position - self.ctx.player.position; let distance = to_other.magnitude(); if distance > 0.0 && distance < SEPARATION_RADIUS { // Using cubic falloff for smoother separation (reduced from quartic) let direction = -to_other.normalize(); let strength = SEPARATION_STRENGTH * (1.0f32 - distance / SEPARATION_RADIUS).powf(3.0); separation += direction * strength; // Gentle emergency separation when very close (reduced multiplier to prevent oscillation) if distance < MIN_SEPARATION_DISTANCE { let emergency_multiplier = (MIN_SEPARATION_DISTANCE / distance).min(1.5); // Reduced from 3.0x to 1.5x separation += direction * SEPARATION_STRENGTH * emergency_multiplier * 0.5; // Half strength } } } // Apply separation from opponents (slightly stronger effect) for other_player in opponents.nearby(SEPARATION_RADIUS * 0.8) { let to_other = other_player.position - self.ctx.player.position; let distance = to_other.magnitude(); if distance > 0.0 && distance < SEPARATION_RADIUS * 0.8 { let direction = -to_other.normalize(); let strength = SEPARATION_STRENGTH * 0.8 * (1.0f32 - distance / (SEPARATION_RADIUS * 0.8)).powf(3.0); separation += direction * strength; // Gentle emergency separation when very close (reduced to prevent oscillation) if distance < MIN_SEPARATION_DISTANCE { let emergency_multiplier = (MIN_SEPARATION_DISTANCE / distance).min(1.5); // Reduced from 2.5x to 1.5x separation += direction * SEPARATION_STRENGTH * 0.4 * emergency_multiplier; // Reduced strength } } } // Add minimal random jitter to separation for natural movement (reduced to prevent twitching) if separation.magnitude() > 0.1 { let jitter = Vector3::new( (rand::random::<f32>() - 0.5) * 0.3, // Reduced from 0.8 to 0.3 (rand::random::<f32>() - 0.5) * 0.3, // Reduced from 0.8 to 0.3 0.0, ); separation += jitter; } // Clamp separation force to reasonable limits to prevent excessive velocities // Separation should add to steering, not dominate it const MAX_SEPARATION_FORCE: f32 = 15.0; let separation_magnitude = separation.magnitude(); if separation_magnitude > MAX_SEPARATION_FORCE { separation = separation * MAX_SEPARATION_FORCE / separation_magnitude; } separation } /// Get pressure operations for assessing game pressure pub fn pressure(&self) -> PressureOperationsImpl<'p> { PressureOperationsImpl::new(self.ctx) } /// Get shooting operations for shooting decisions pub fn shooting(&self) -> ShootingOperationsImpl<'p> { ShootingOperationsImpl::new(self.ctx) } /// Get passing operations for passing decisions pub fn passing(&self) -> PassingOperationsImpl<'p> { PassingOperationsImpl::new(self.ctx) } /// Get defensive operations for defensive positioning pub fn defensive(&self) -> DefensiveOperationsImpl<'p> { DefensiveOperationsImpl::new(self.ctx) } /// Get movement operations for space-finding and positioning pub fn movement(&self) -> MovementOperationsImpl<'p> { MovementOperationsImpl::new(self.ctx) } /// Get skill operations for skill-based calculations pub fn skill(&self) -> SkillOperationsImpl<'p> { SkillOperationsImpl::new(self.ctx) } } pub struct MatchPlayerLogic; impl MatchPlayerLogic { pub fn distance_to_start_position(player: &MatchPlayer) -> PlayerDistanceFromStartPosition { let start_position_distance = player.position.distance_to(&player.start_position); if start_position_distance < 100.0 { PlayerDistanceFromStartPosition::Small } else if start_position_distance < 250.0 { PlayerDistanceFromStartPosition::Medium } else { PlayerDistanceFromStartPosition::Big } } }
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/common/players/opponents.rs
src/core/src/match/engine/player/strategies/common/players/opponents.rs
use crate::r#match::{MatchPlayerLite, StateProcessingContext}; use crate::PlayerFieldPositionGroup; pub struct PlayerOpponentsOperationsImpl<'b> { ctx: &'b StateProcessingContext<'b>, } impl<'b> PlayerOpponentsOperationsImpl<'b> { pub fn new(ctx: &'b StateProcessingContext<'b>) -> Self { PlayerOpponentsOperationsImpl { ctx } } } impl<'b> PlayerOpponentsOperationsImpl<'b> { pub fn all(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.opponents_for_team(self.ctx.player.id, self.ctx.player.team_id, None) } pub fn with_ball(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.opponents_for_team(self.ctx.player.id, self.ctx.player.team_id, Some(true)) } pub fn without_ball(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.opponents_for_team(self.ctx.player.id, self.ctx.player.team_id, Some(false)) } pub fn nearby(&self, distance: f32) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.ctx .tick_context .distances .opponents(self.ctx.player.id, distance) .map(|(pid, _)| MatchPlayerLite { id: pid, position: self.ctx.tick_context.positions.players.position(pid), tactical_positions: self.ctx.context.players.by_id(pid).expect(&format!( "unknown player = {}", pid )).tactical_position.current_position }) } pub fn nearby_raw(&self, distance: f32) -> impl Iterator<Item = (u32, f32)> + 'b { self.ctx .tick_context .distances .opponents(self.ctx.player.id, distance) } pub fn exists(&self, distance: f32) -> bool { self.ctx .tick_context .distances .opponents(self.ctx.player.id, distance) .any(|_| true) } pub fn goalkeeper(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.opponents_by_position( PlayerFieldPositionGroup::Goalkeeper, self.ctx.player.team_id, ) } pub fn forwards(&'b self) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.opponents_by_position(PlayerFieldPositionGroup::Forward, self.ctx.player.team_id) } fn opponents_by_position( &'b self, position_group: PlayerFieldPositionGroup, team_id: u32, ) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.ctx .context .players .players .values() .filter(move |player| { player.team_id != team_id && player.tactical_position.current_position.position_group() == position_group }) .map(|player| MatchPlayerLite { id: player.id, position: self.ctx.tick_context.positions.players.position(player.id), tactical_positions: player.tactical_position.current_position }) } fn opponents_for_team( &'b self, player_id: u32, team_id: u32, has_ball: Option<bool>, ) -> impl Iterator<Item = MatchPlayerLite> + 'b { self.ctx .context .players .players .values() .filter(move |player| { // Check if player matches team criteria (different team) if player.id == player_id || player.team_id == team_id { return false; } // Check if player matches has_ball criteria let matches_ball_filter = match has_ball { None => true, // No filter, include all opponents Some(true) => self.ctx.ball().owner_id() == Some(player.id), // Only opponents with ball Some(false) => self.ctx.ball().owner_id() != Some(player.id) // Only opponents without ball }; matches_ball_filter }) .map(|player| MatchPlayerLite { id: player.id, position: self.ctx.tick_context.positions.players.position(player.id), tactical_positions: player.tactical_position.current_position }) } }
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/common/players/mod.rs
src/core/src/match/engine/player/strategies/common/players/mod.rs
pub mod opponents; pub mod player; pub mod players; pub mod skills; pub mod teammates; pub mod iters; pub mod ops; pub use opponents::*; pub use player::*; pub use players::*; pub use skills::*; pub use teammates::*; pub use iters::*; pub use ops::*;
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/common/players/skills.rs
src/core/src/match/engine/player/strategies/common/players/skills.rs
use crate::r#match::StateProcessingContext; /// Operations for skill-based calculations pub struct SkillOperationsImpl<'p> { ctx: &'p StateProcessingContext<'p>, } impl<'p> SkillOperationsImpl<'p> { pub fn new(ctx: &'p StateProcessingContext<'p>) -> Self { SkillOperationsImpl { ctx } } /// Normalize skill value to 0.0-1.0 range (divides by 20.0) #[inline] pub fn normalized(&self, skill_value: f32) -> f32 { (skill_value / 20.0).clamp(0.0, 1.0) } /// Calculate adjusted threshold based on skill /// Formula: base_value * (min_factor + skill * range_factor) pub fn adjusted_threshold( &self, base_value: f32, skill_value: f32, min_factor: f32, range_factor: f32, ) -> f32 { let skill = self.normalized(skill_value); base_value * (min_factor + skill * range_factor) } /// Combine multiple skills with weights into a single factor /// Example: combined_factor(&[(finishing, 0.5), (composure, 0.3), (technique, 0.2)]) pub fn combined_factor(&self, skills_with_weights: &[(f32, f32)]) -> f32 { skills_with_weights .iter() .map(|(skill, weight)| self.normalized(*skill) * weight) .sum::<f32>() .clamp(0.0, 1.0) } /// Get player's dribbling ability (0.0-1.0) pub fn dribbling_ability(&self) -> f32 { let dribbling = self.ctx.player.skills.technical.dribbling; let agility = self.ctx.player.skills.physical.agility; let technique = self.ctx.player.skills.technical.technique; self.combined_factor(&[(dribbling, 0.5), (agility, 0.3), (technique, 0.2)]) } /// Get player's passing ability (0.0-1.0) pub fn passing_ability(&self) -> f32 { let passing = self.ctx.player.skills.technical.passing; let vision = self.ctx.player.skills.mental.vision; let technique = self.ctx.player.skills.technical.technique; self.combined_factor(&[(passing, 0.5), (vision, 0.3), (technique, 0.2)]) } /// Get player's shooting ability (0.0-1.0) pub fn shooting_ability(&self) -> f32 { let finishing = self.ctx.player.skills.technical.finishing; let composure = self.ctx.player.skills.mental.composure; let technique = self.ctx.player.skills.technical.technique; self.combined_factor(&[(finishing, 0.5), (composure, 0.3), (technique, 0.2)]) } /// Get player's defensive ability (0.0-1.0) pub fn defensive_ability(&self) -> f32 { let tackling = self.ctx.player.skills.technical.tackling; let marking = self.ctx.player.skills.mental.positioning; let aggression = self.ctx.player.skills.mental.aggression; self.combined_factor(&[(tackling, 0.5), (marking, 0.3), (aggression, 0.2)]) } /// Get player's physical ability (0.0-1.0) pub fn physical_ability(&self) -> f32 { let pace = self.ctx.player.skills.physical.pace; let stamina = self.ctx.player.skills.physical.stamina; let strength = self.ctx.player.skills.physical.strength; self.combined_factor(&[(pace, 0.4), (stamina, 0.3), (strength, 0.3)]) } /// Get player's mental ability (0.0-1.0) pub fn mental_ability(&self) -> f32 { let decisions = self.ctx.player.skills.mental.decisions; let positioning = self.ctx.player.skills.mental.positioning; let vision = self.ctx.player.skills.mental.vision; self.combined_factor(&[(decisions, 0.4), (positioning, 0.3), (vision, 0.3)]) } /// Get stamina factor based on condition (0.0-1.0) pub fn stamina_factor(&self) -> f32 { self.ctx.player.player_attributes.condition_percentage() as f32 / 100.0 } /// Check if player is tired (stamina below threshold) pub fn is_tired(&self, threshold: u32) -> bool { self.ctx.player.player_attributes.condition_percentage() < threshold } /// Calculate fatigue factor for movement (0.0-1.0, accounts for time in state) pub fn fatigue_factor(&self, state_duration: u64) -> f32 { let stamina = self.stamina_factor(); let time_factor = (1.0 - (state_duration as f32 / 500.0)).max(0.5); stamina * time_factor } }
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/common/players/players.rs
src/core/src/match/engine/player/strategies/common/players/players.rs
use crate::r#match::{ PlayerOpponentsOperationsImpl, PlayerTeammatesOperationsImpl, StateProcessingContext, }; pub struct PlayersOperationsImpl<'p> { ctx: &'p StateProcessingContext<'p>, } impl<'p> PlayersOperationsImpl<'p> { pub fn new(ctx: &'p StateProcessingContext<'p>) -> Self { PlayersOperationsImpl { ctx } } } impl<'p> PlayersOperationsImpl<'p> { // Teammates pub fn teammates(&self) -> PlayerTeammatesOperationsImpl<'p> { PlayerTeammatesOperationsImpl::new(self.ctx) } // Opponents pub fn opponents(&self) -> PlayerOpponentsOperationsImpl<'p> { PlayerOpponentsOperationsImpl::new(self.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/common/players/iters/mod.rs
src/core/src/match/engine/player/strategies/common/players/iters/mod.rs
pub mod ball_iterators_ext; pub use ball_iterators_ext::*;
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/common/players/iters/ball_iterators_ext.rs
src/core/src/match/engine/player/strategies/common/players/iters/ball_iterators_ext.rs
use crate::r#match::{MatchPlayerLite, StateProcessingContext}; /// Extension trait for Iterator<Item = MatchPlayerLite> to enable chaining filters pub trait MatchPlayerIteratorExt<'a>: Iterator<Item = MatchPlayerLite> + Sized { /// Filter players who have the ball fn with_ball(self, ctx: &'a StateProcessingContext<'a>) -> WithBallIterator<'a, Self> { WithBallIterator { inner: self, ctx, has_ball: true, } } /// Filter players who don't have the ball fn without_ball(self, ctx: &'a StateProcessingContext<'a>) -> WithBallIterator<'a, Self> { WithBallIterator { inner: self, ctx, has_ball: false, } } } // Implement the trait for all iterators that yield MatchPlayerLite impl<'a, I> MatchPlayerIteratorExt<'a> for I where I: Iterator<Item = MatchPlayerLite> {} /// Iterator adapter that filters players based on ball possession pub struct WithBallIterator<'a, I> { inner: I, ctx: &'a StateProcessingContext<'a>, has_ball: bool, } impl<'a, I> Iterator for WithBallIterator<'a, I> where I: Iterator<Item = MatchPlayerLite>, { type Item = MatchPlayerLite; fn next(&mut self) -> Option<Self::Item> { self.inner.find(|player| { let player_has_ball = self.ctx.ball().owner_id() == Some(player.id); player_has_ball == self.has_ball }) } }
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/common/players/ops/defensive.rs
src/core/src/match/engine/player/strategies/common/players/ops/defensive.rs
use crate::r#match::{MatchPlayerLite, PlayerSide, StateProcessingContext}; use crate::PlayerFieldPositionGroup; use nalgebra::Vector3; /// Operations for defensive positioning and tactics pub struct DefensiveOperationsImpl<'p> { ctx: &'p StateProcessingContext<'p>, } const THREAT_SCAN_DISTANCE: f32 = 70.0; const DANGEROUS_RUN_SPEED: f32 = 3.0; const DANGEROUS_RUN_ANGLE: f32 = 0.7; impl<'p> DefensiveOperationsImpl<'p> { pub fn new(ctx: &'p StateProcessingContext<'p>) -> Self { DefensiveOperationsImpl { ctx } } /// Scan for opponents making dangerous runs toward goal pub fn scan_for_dangerous_runs(&self) -> Option<MatchPlayerLite> { self.scan_for_dangerous_runs_with_distance(THREAT_SCAN_DISTANCE) } /// Scan for dangerous runs with custom scan distance pub fn scan_for_dangerous_runs_with_distance( &self, scan_distance: f32, ) -> Option<MatchPlayerLite> { let own_goal_position = self.ctx.ball().direction_to_own_goal(); // Find opponents making dangerous runs within extended range let dangerous_runners: Vec<MatchPlayerLite> = self .ctx .players() .opponents() .nearby(scan_distance) .filter(|opp| { let velocity = opp.velocity(self.ctx); let speed = velocity.norm(); // Must be moving at significant speed if speed < DANGEROUS_RUN_SPEED { return false; } // Check if running toward our goal let to_goal = (own_goal_position - opp.position).normalize(); let velocity_dir = velocity.normalize(); let alignment = velocity_dir.dot(&to_goal); if alignment < DANGEROUS_RUN_ANGLE { return false; } // Check if in attacking position (closer to our goal than most defenders) let defender_x = self.ctx.player.position.x; let is_in_dangerous_position = if own_goal_position.x < self.ctx.context.field_size.width as f32 / 2.0 { opp.position.x < defender_x + 20.0 // Attacker is ahead or close } else { opp.position.x > defender_x - 20.0 }; alignment >= DANGEROUS_RUN_ANGLE && is_in_dangerous_position }) .collect(); if dangerous_runners.is_empty() { return None; } // Return the closest dangerous runner dangerous_runners .iter() .min_by(|a, b| { let dist_a = a.distance(self.ctx); let dist_b = b.distance(self.ctx); dist_a.partial_cmp(&dist_b).unwrap() }) .copied() } /// Find the opponent defensive line position pub fn find_defensive_line(&self) -> f32 { let defenders: Vec<f32> = self .ctx .players() .opponents() .all() .filter(|p| p.tactical_positions.is_defender()) .map(|p| match self.ctx.player.side { Some(PlayerSide::Left) => p.position.x, Some(PlayerSide::Right) => p.position.x, None => p.position.x, }) .collect(); if defenders.is_empty() { self.ctx.context.field_size.width as f32 / 2.0 } else { // Return the position of the last defender match self.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, } } } /// Find the own team's defensive line position pub fn find_own_defensive_line(&self) -> f32 { let defenders: Vec<f32> = self .ctx .players() .teammates() .defenders() .map(|p| match self.ctx.player.side { Some(PlayerSide::Left) => p.position.x, Some(PlayerSide::Right) => p.position.x, None => p.position.x, }) .collect(); if defenders.is_empty() { self.ctx.context.field_size.width as f32 / 2.0 } else { defenders.iter().sum::<f32>() / defenders.len() as f32 } } /// Check if there's exploitable space behind opponent defense pub fn check_space_behind_defense(&self, defensive_line: f32) -> bool { let player_x = self.ctx.player.position.x; match self.ctx.player.side { Some(PlayerSide::Left) => { // Space exists if defensive line is high and there's room behind defensive_line < self.ctx.context.field_size.width as f32 * 0.7 && player_x < defensive_line + 20.0 } Some(PlayerSide::Right) => { defensive_line > self.ctx.context.field_size.width as f32 * 0.3 && player_x > defensive_line - 20.0 } None => false, } } /// Check if player is the last defender pub fn is_last_defender(&self) -> bool { self.ctx .players() .teammates() .defenders() .all(|d| match self.ctx.player.side { Some(PlayerSide::Left) => d.position.x >= self.ctx.player.position.x, Some(PlayerSide::Right) => d.position.x <= self.ctx.player.position.x, None => false, }) } /// Check if should hold defensive line pub fn should_hold_defensive_line(&self) -> bool { let ball_ops = self.ctx.ball(); let defenders: Vec<MatchPlayerLite> = self.ctx.players().teammates().defenders().collect(); if defenders.is_empty() { return false; } let avg_defender_x = defenders.iter().map(|d| d.position.x).sum::<f32>() / defenders.len() as f32; (self.ctx.player.position.x - avg_defender_x).abs() < 5.0 && ball_ops.distance() > 200.0 && !self.ctx.team().is_control_ball() } /// Check if should mark an opponent pub fn should_mark_opponent(&self, opponent: &MatchPlayerLite, marking_distance: f32) -> bool { let distance = (opponent.position - self.ctx.player.position).magnitude(); if distance > marking_distance { return false; } // Mark if opponent is in dangerous position let opponent_distance_to_goal = (opponent.position - self.ctx.ball().direction_to_own_goal()).magnitude(); let own_distance_to_goal = (self.ctx.player.position - self.ctx.ball().direction_to_own_goal()).magnitude(); // Opponent is closer to our goal than we are opponent_distance_to_goal < own_distance_to_goal + 10.0 } /// Get the nearest opponent to mark pub fn find_opponent_to_mark(&self, max_distance: f32) -> Option<MatchPlayerLite> { self.ctx .players() .opponents() .nearby(max_distance) .filter(|opp| self.should_mark_opponent(opp, max_distance)) .min_by(|a, b| { let dist_a = a.distance(self.ctx); let dist_b = b.distance(self.ctx); dist_a.partial_cmp(&dist_b).unwrap() }) } /// Calculate optimal covering position pub fn calculate_covering_position(&self) -> Vector3<f32> { let goal_position = self.ctx.ball().direction_to_own_goal(); let ball_position = self.ctx.tick_context.positions.ball.position; // Position between ball and goal let to_ball = ball_position - goal_position; let covering_distance = to_ball.magnitude() * 0.3; // 30% of the way from goal to ball goal_position + to_ball.normalize() * covering_distance } /// Check if in dangerous defensive position (near own goal) pub fn in_dangerous_position(&self) -> bool { let distance_to_goal = (self.ctx.player.position - self.ctx.ball().direction_to_own_goal()) .magnitude(); let danger_threshold = self.ctx.context.field_size.width as f32 * 0.15; // 15% of field width distance_to_goal < danger_threshold } }
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/common/players/ops/pressure.rs
src/core/src/match/engine/player/strategies/common/players/ops/pressure.rs
use crate::r#match::{MatchPlayerLite, StateProcessingContext}; /// Operations for assessing pressure situations on the field pub struct PressureOperationsImpl<'p> { ctx: &'p StateProcessingContext<'p>, } impl<'p> PressureOperationsImpl<'p> { pub fn new(ctx: &'p StateProcessingContext<'p>) -> Self { PressureOperationsImpl { ctx } } /// Check if player is under immediate pressure (at least one opponent very close) pub fn is_under_immediate_pressure(&self) -> bool { self.is_under_immediate_pressure_with_distance(30.0) } /// Check if player is under immediate pressure with custom distance pub fn is_under_immediate_pressure_with_distance(&self, distance: f32) -> bool { self.ctx.players().opponents().exists(distance) } /// Check if player is under heavy pressure (multiple opponents nearby) pub fn is_under_heavy_pressure(&self) -> bool { self.is_under_heavy_pressure_with_params(8.0, 2) } /// Check if player is under heavy pressure with custom parameters pub fn is_under_heavy_pressure_with_params(&self, distance: f32, threshold: usize) -> bool { self.pressing_opponents_count(distance) >= threshold } /// Count pressing opponents within distance pub fn pressing_opponents_count(&self, distance: f32) -> usize { self.ctx.players().opponents().nearby(distance).count() } /// Check if a teammate is marked by opponents pub fn is_teammate_marked(&self, teammate: &MatchPlayerLite, marking_distance: f32) -> bool { self.ctx .players() .opponents() .all() .filter(|opp| (opp.position - teammate.position).magnitude() < marking_distance) .count() >= 1 } /// Check if a teammate is heavily marked (multiple opponents or very close marking) pub fn is_teammate_heavily_marked(&self, teammate: &MatchPlayerLite) -> bool { let marking_distance = 8.0; let close_marking_distance = 3.0; let markers = self .ctx .players() .opponents() .all() .filter(|opp| (opp.position - teammate.position).magnitude() < marking_distance) .count(); let close_markers = self .ctx .players() .opponents() .all() .filter(|opp| (opp.position - teammate.position).magnitude() < close_marking_distance) .count(); markers >= 2 || (markers >= 1 && close_markers > 0) } /// Get the closest pressing opponent pub fn closest_pressing_opponent(&self, max_distance: f32) -> Option<MatchPlayerLite> { self.ctx .players() .opponents() .nearby(max_distance) .min_by(|a, b| { let dist_a = a.distance(self.ctx); let dist_b = b.distance(self.ctx); dist_a.partial_cmp(&dist_b).unwrap() }) } /// Calculate pressure intensity (0.0 = no pressure, 1.0 = extreme pressure) pub fn pressure_intensity(&self) -> f32 { let close_opponents = self.pressing_opponents_count(10.0) as f32; let medium_opponents = self.pressing_opponents_count(20.0) as f32; let far_opponents = self.pressing_opponents_count(30.0) as f32; // Weight closer opponents more heavily let intensity = (close_opponents * 0.5 + medium_opponents * 0.3 + far_opponents * 0.2) / 3.0; intensity.min(1.0) } /// Check if there's space around the player (inverse of pressure) pub fn has_space_around(&self, min_distance: f32) -> bool { !self.ctx.players().opponents().exists(min_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/common/players/ops/shooting.rs
src/core/src/match/engine/player/strategies/common/players/ops/shooting.rs
use crate::r#match::{StateProcessingContext}; /// Operations for shooting decision-making pub struct ShootingOperationsImpl<'p> { ctx: &'p StateProcessingContext<'p>, } // Realistic shooting distances (field is typically 840 units) const MAX_SHOOTING_DISTANCE: f32 = 250.0; // ~60m - absolute max for long shots const MIN_SHOOTING_DISTANCE: f32 = 1.0; const VERY_CLOSE_RANGE_DISTANCE: f32 = 50.0; // ~20m - anyone can shoot const CLOSE_RANGE_DISTANCE: f32 = 70.0; // ~30m - close range shots const OPTIMAL_SHOOTING_DISTANCE: f32 = 110.0; // ~40m - ideal shooting distance const MEDIUM_RANGE_DISTANCE: f32 = 150.0; // ~45m - medium range shots // Shooting decision thresholds const SHOOT_OVER_PASS_CLOSE_THRESHOLD: f32 = 60.0; // Always prefer shooting if closer than this const SHOOT_OVER_PASS_MEDIUM_THRESHOLD: f32 = 70.0; // Shoot over pass for decent finishers const EXCELLENT_OPPORTUNITY_CLOSE_RANGE: f32 = 130.0; // Distance for close-range excellent opportunity // Teammate advantage thresholds (multipliers) const TEAMMATE_ADVANTAGE_RATIO: f32 = 0.4; // Teammate must be this much closer to prevent shot impl<'p> ShootingOperationsImpl<'p> { pub fn new(ctx: &'p StateProcessingContext<'p>) -> Self { ShootingOperationsImpl { ctx } } /// Check if player is in shooting range (skill-aware) pub fn in_shooting_range(&self) -> bool { let distance_to_goal = self.ctx.ball().distance_to_opponent_goal(); let shooting_skill = self.ctx.player.skills.technical.finishing / 20.0; let long_shot_skill = self.ctx.player.skills.technical.long_shots / 20.0; // Very close range - even poor finishers should shoot! if distance_to_goal <= VERY_CLOSE_RANGE_DISTANCE { return true; } // Close range shots (most common) - almost anyone can shoot from close range if distance_to_goal >= MIN_SHOOTING_DISTANCE && distance_to_goal <= CLOSE_RANGE_DISTANCE { return true; } // Medium range shots - requires decent finishing if distance_to_goal <= OPTIMAL_SHOOTING_DISTANCE && shooting_skill > 0.5 { return true; } // Medium-long range shots - moderate skill requirement (new tier) if distance_to_goal <= MEDIUM_RANGE_DISTANCE && long_shot_skill > 0.5 && shooting_skill > 0.45 { return true; } // Long range shots - skilled players (reduced from 0.75/0.65 to 0.6/0.5) if distance_to_goal <= MAX_SHOOTING_DISTANCE && long_shot_skill > 0.6 && shooting_skill > 0.5 { return true; } false } /// Check for excellent shooting opportunity (clear sight, good distance, no pressure) pub fn has_excellent_opportunity(&self) -> bool { let distance = self.ctx.ball().distance_to_opponent_goal(); let clear_shot = self.ctx.player().has_clear_shot(); // Very close to goal - excellent opportunity if any space if distance <= EXCELLENT_OPPORTUNITY_CLOSE_RANGE { let low_pressure = !self.ctx.players().opponents().exists(5.0); return clear_shot && low_pressure; } // Medium to optimal range - need good angle too if distance > MIN_SHOOTING_DISTANCE && distance <= MEDIUM_RANGE_DISTANCE { let low_pressure = !self.ctx.players().opponents().exists(10.0); let good_angle = self.has_good_angle(); return clear_shot && low_pressure && good_angle; } false } /// Check shooting angle quality pub fn has_good_angle(&self) -> bool { let goal_angle = self.ctx.player().goal_angle(); // Good angle is less than 45 degrees off center goal_angle < std::f32::consts::PI / 4.0 } /// Determine if should shoot instead of looking for pass pub fn should_shoot_over_pass(&self) -> bool { let distance = self.ctx.ball().distance_to_opponent_goal(); let has_clear_shot = self.ctx.player().has_clear_shot(); let confidence = self.ctx.player.skills.mental.composure / 20.0; let finishing = self.ctx.player.skills.technical.finishing / 20.0; let long_shots = self.ctx.player.skills.technical.long_shots / 20.0; // Close range - almost always shoot if clear if distance <= SHOOT_OVER_PASS_CLOSE_THRESHOLD && has_clear_shot { return finishing > 0.5 || distance <= VERY_CLOSE_RANGE_DISTANCE; } // Medium range - shoot if decent skills if distance <= SHOOT_OVER_PASS_MEDIUM_THRESHOLD && has_clear_shot && finishing > 0.55 { return true; } // Optimal distance with good overall ability if distance <= OPTIMAL_SHOOTING_DISTANCE && has_clear_shot && (confidence + finishing) / 2.0 > 0.6 { return true; } // Medium-long range with good long shot skills if distance <= MEDIUM_RANGE_DISTANCE && has_clear_shot && long_shots > 0.5 && finishing > 0.45 && !self.ctx.players().opponents().exists(10.0) { return true; } // Check if teammates are in MUCH better positions let better_positioned_teammate = self .ctx .players() .teammates() .nearby(100.0) .any(|t| { let t_dist = (t.position - self.ctx.player().opponent_goal_position()).magnitude(); t_dist < distance * TEAMMATE_ADVANTAGE_RATIO }); // Shoot if no better teammate and clear shot within medium range !better_positioned_teammate && has_clear_shot && distance <= MEDIUM_RANGE_DISTANCE } /// Check if in close range for finishing pub fn in_close_range(&self) -> bool { let distance = self.ctx.ball().distance_to_opponent_goal(); distance >= MIN_SHOOTING_DISTANCE && distance <= CLOSE_RANGE_DISTANCE } /// Check if in optimal shooting distance pub fn in_optimal_range(&self) -> bool { let distance = self.ctx.ball().distance_to_opponent_goal(); distance >= MIN_SHOOTING_DISTANCE && distance <= OPTIMAL_SHOOTING_DISTANCE } /// Get shooting confidence factor (0.0 - 1.0) pub fn shooting_confidence(&self) -> f32 { let finishing = self.ctx.player.skills.technical.finishing / 20.0; let composure = self.ctx.player.skills.mental.composure / 20.0; let technique = self.ctx.player.skills.technical.technique / 20.0; let distance_factor = self.distance_factor(); let pressure_factor = self.pressure_factor(); // Combine factors let skill_factor = finishing * 0.5 + composure * 0.3 + technique * 0.2; (skill_factor * distance_factor * pressure_factor).clamp(0.0, 1.0) } /// Get distance factor for shooting confidence (1.0 = optimal, 0.0 = too far/close) fn distance_factor(&self) -> f32 { let distance = self.ctx.ball().distance_to_opponent_goal(); if distance < MIN_SHOOTING_DISTANCE { return 0.3; // Too close, awkward angle } if distance <= OPTIMAL_SHOOTING_DISTANCE { // Optimal range - linear increase to peak return (distance / OPTIMAL_SHOOTING_DISTANCE).min(1.0); } if distance <= MAX_SHOOTING_DISTANCE { // Beyond optimal - linear decrease let beyond_optimal = distance - OPTIMAL_SHOOTING_DISTANCE; let range = MAX_SHOOTING_DISTANCE - OPTIMAL_SHOOTING_DISTANCE; return 1.0 - (beyond_optimal / range); } 0.0 // Too far } /// Get pressure factor for shooting confidence (1.0 = no pressure, 0.0 = extreme pressure) fn pressure_factor(&self) -> f32 { let close_opponents = self.ctx.players().opponents().nearby(5.0).count(); let medium_opponents = self.ctx.players().opponents().nearby(10.0).count(); if close_opponents >= 2 { return 0.3; } else if close_opponents == 1 { return 0.6; } else if medium_opponents >= 2 { return 0.8; } 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/match/engine/player/strategies/common/players/ops/mod.rs
src/core/src/match/engine/player/strategies/common/players/ops/mod.rs
pub mod defensive; pub mod movement; pub mod passing; pub mod pressure; pub mod shooting; pub use defensive::*; pub use movement::*; pub use passing::*; pub use pressure::*; pub use shooting::*;
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/common/players/ops/passing.rs
src/core/src/match/engine/player/strategies/common/players/ops/passing.rs
use crate::r#match::{MatchPlayerLite, PassEvaluator, PlayerSide, StateProcessingContext}; use nalgebra::Vector3; /// Operations for passing decision-making pub struct PassingOperationsImpl<'p> { ctx: &'p StateProcessingContext<'p>, } impl<'p> PassingOperationsImpl<'p> { pub fn new(ctx: &'p StateProcessingContext<'p>) -> Self { PassingOperationsImpl { ctx } } /// Check if a pass direction is forward (toward opponent goal) pub fn is_forward_pass(&self, from_pos: &Vector3<f32>, to_pos: &Vector3<f32>) -> bool { match self.ctx.player.side { Some(PlayerSide::Left) => to_pos.x > from_pos.x, Some(PlayerSide::Right) => to_pos.x < from_pos.x, None => false, } } /// Check if passing to teammate would be a forward pass pub fn is_forward_pass_to(&self, teammate: &MatchPlayerLite) -> bool { self.is_forward_pass(&self.ctx.player.position, &teammate.position) } /// Find a safe pass option when under pressure pub fn find_safe_pass_option(&self) -> Option<MatchPlayerLite> { self.find_safe_pass_option_with_distance(50.0) } /// Find a safe pass option with custom max distance pub fn find_safe_pass_option_with_distance(&self, max_distance: f32) -> Option<MatchPlayerLite> { let teammates = self.ctx.players().teammates(); // Prioritize closest teammates with clear passing lanes let safe_options: Vec<MatchPlayerLite> = teammates .nearby(max_distance) .filter(|t| { self.ctx.player().has_clear_pass(t.id) && !self.is_teammate_under_pressure(t) }) .collect(); // Find the safest option by direction and pressure safe_options.into_iter().min_by(|a, b| { // Compare how "away from danger" the pass would be let a_safety = self.calculate_pass_safety(a); let b_safety = self.calculate_pass_safety(b); b_safety .partial_cmp(&a_safety) .unwrap_or(std::cmp::Ordering::Equal) }) } /// Find the best pass option using the PassEvaluator pub fn find_best_pass_option(&self) -> Option<(MatchPlayerLite, &'static str)> { PassEvaluator::find_best_pass_option(self.ctx, 300.0) } /// Find the best pass option with custom max distance pub fn find_best_pass_option_with_distance(&self, max_distance: f32) -> Option<(MatchPlayerLite, &'static str)> { PassEvaluator::find_best_pass_option(self.ctx, max_distance) } /// Calculate how safe a pass would be based on direction and receiver situation pub fn calculate_pass_safety(&self, target: &MatchPlayerLite) -> f32 { // Get vectors for calculations let pass_vector = target.position - self.ctx.player.position; let to_own_goal = self.ctx.ball().direction_to_own_goal() - self.ctx.player.position; // Calculate how much this pass moves away from own goal (higher is better) let pass_away_from_goal = -(pass_vector.normalize().dot(&to_own_goal.normalize())); // Calculate space around target player let space_factor = 1.0 - (self .ctx .players() .opponents() .all() .filter(|o| (o.position - target.position).magnitude() < 10.0) .count() as f32 * 0.2) .min(0.8); // Return combined safety score pass_away_from_goal + space_factor } /// Check if there are safe passing options available pub fn has_safe_passing_option(&self, teammates: &[MatchPlayerLite]) -> bool { teammates.iter().any(|teammate| { let has_clear_lane = self.ctx.player().has_clear_pass(teammate.id); let not_marked = !self.is_teammate_under_pressure(teammate); has_clear_lane && not_marked }) } /// Check if a teammate is under pressure pub fn is_teammate_under_pressure(&self, teammate: &MatchPlayerLite) -> bool { self.ctx .players() .opponents() .all() .filter(|o| (o.position - teammate.position).magnitude() < 10.0) .count() >= 1 } /// Find any teammate as a last resort option pub fn find_any_teammate(&self) -> Option<MatchPlayerLite> { self.find_any_teammate_with_distance(200.0) } /// Find any teammate with custom max distance pub fn find_any_teammate_with_distance(&self, max_distance: f32) -> Option<MatchPlayerLite> { // Get the closest teammate regardless of quality self.ctx .players() .teammates() .nearby(max_distance) .min_by(|a, b| { let dist_a = (a.position - self.ctx.player.position).magnitude(); let dist_b = (b.position - self.ctx.player.position).magnitude(); dist_a .partial_cmp(&dist_b) .unwrap_or(std::cmp::Ordering::Equal) }) } /// Check for forward passes to better positioned teammates pub fn has_forward_pass_to_better_teammate( &self, teammates: &[MatchPlayerLite], current_distance_to_goal: f32, ) -> bool { let player_pos = self.ctx.player.position; teammates.iter().any(|teammate| { // Must be a forward pass direction let is_forward = self.is_forward_pass(&player_pos, &teammate.position); if !is_forward { return false; } // Teammate must be much closer to goal let teammate_distance = (teammate.position - self.ctx.player().opponent_goal_position()).magnitude(); let is_much_closer = teammate_distance < current_distance_to_goal * 0.6; let not_heavily_marked = !self.is_teammate_heavily_marked(teammate); let has_clear_lane = self.ctx.player().has_clear_pass(teammate.id); is_much_closer && not_heavily_marked && has_clear_lane }) } /// Check if teammate is heavily marked pub fn is_teammate_heavily_marked(&self, teammate: &MatchPlayerLite) -> bool { let marking_distance = 8.0; let close_distance = 3.0; let markers = self .ctx .players() .opponents() .all() .filter(|o| (o.position - teammate.position).magnitude() < marking_distance) .count(); let close_markers = self .ctx .players() .opponents() .all() .filter(|o| (o.position - teammate.position).magnitude() < close_distance) .count(); markers >= 2 || (markers >= 1 && close_markers > 0) } /// Check if there's a teammate in a dangerous attacking position pub fn has_teammate_in_dangerous_position( &self, teammates: &[MatchPlayerLite], current_distance_to_goal: f32, ) -> bool { teammates.iter().any(|teammate| { let teammate_distance = (teammate.position - self.ctx.player().opponent_goal_position()).magnitude(); // Check if teammate is in a good attacking position let in_attacking_position = teammate_distance < current_distance_to_goal * 1.1; // Check if teammate is in free space let in_free_space = self .ctx .players() .opponents() .all() .filter(|opp| (opp.position - teammate.position).magnitude() < 12.0) .count() < 2; // Check if teammate is making a forward run let teammate_velocity = self .ctx .tick_context .positions .players .velocity(teammate.id); let making_run = teammate_velocity.magnitude() > 2.0 && { let to_goal = self.ctx.player().opponent_goal_position() - teammate.position; teammate_velocity.normalize().dot(&to_goal.normalize()) > 0.5 }; let has_clear_pass = self.ctx.player().has_clear_pass(teammate.id); has_clear_pass && in_attacking_position && (in_free_space || making_run) }) } /// Check for any good passing option (balanced assessment) pub fn has_good_passing_option(&self, teammates: &[MatchPlayerLite]) -> bool { teammates.iter().any(|teammate| { let has_clear_lane = self.ctx.player().has_clear_pass(teammate.id); let has_space = self .ctx .players() .opponents() .all() .filter(|opp| (opp.position - teammate.position).magnitude() < 10.0) .count() < 2; // Prefer forward passes let is_forward_pass = self.is_forward_pass_to(teammate); has_clear_lane && has_space && is_forward_pass }) } }
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/common/players/ops/movement.rs
src/core/src/match/engine/player/strategies/common/players/ops/movement.rs
use crate::r#match::{MatchPlayerLite, StateProcessingContext}; use nalgebra::Vector3; /// Operations for movement and space-finding pub struct MovementOperationsImpl<'p> { ctx: &'p StateProcessingContext<'p>, } impl<'p> MovementOperationsImpl<'p> { pub fn new(ctx: &'p StateProcessingContext<'p>) -> Self { MovementOperationsImpl { ctx } } /// Find space to dribble into pub fn find_dribbling_space(&self) -> Option<Vector3<f32>> { let player_pos = self.ctx.player.position; let goal_direction = (self.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 = self .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 } /// Find the best gap in opponent defense pub fn find_best_gap_in_defense(&self) -> Option<Vector3<f32>> { let player_pos = self.ctx.player.position; let goal_pos = self.ctx.player().opponent_goal_position(); let opponents: Vec<MatchPlayerLite> = self .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 } /// Find optimal attacking path considering opponents pub fn find_optimal_attacking_path(&self) -> Option<Vector3<f32>> { let player_pos = self.ctx.player.position; let goal_pos = self.ctx.player().opponent_goal_position(); // Look for gaps in defense if let Some(gap) = self.find_best_gap_in_defense() { 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 !self .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 } /// Calculate support run position for a ball holder pub fn calculate_support_run_position(&self, holder_pos: Vector3<f32>) -> Vector3<f32> { let player_pos = self.ctx.player.position; let field_height = self.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; if is_central { self.calculate_central_support_position(holder_pos) } else { self.calculate_wide_support_position(holder_pos) } } /// Calculate wide support position (for wingers) fn calculate_wide_support_position(&self, holder_pos: Vector3<f32>) -> Vector3<f32> { let player_pos = self.ctx.player.position; let field_height = self.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 }; // Stay ahead of ball carrier (increased distance to prevent clustering) let target_x = match self.ctx.player.side { Some(crate::r#match::PlayerSide::Left) => holder_pos.x + 80.0, Some(crate::r#match::PlayerSide::Right) => holder_pos.x - 80.0, None => holder_pos.x, }; Vector3::new(target_x, target_y, 0.0) } /// Calculate central support position (for central players) fn calculate_central_support_position(&self, holder_pos: Vector3<f32>) -> Vector3<f32> { let field_height = self.ctx.context.field_size.height as f32; let player_pos = self.ctx.player.position; // Move into space between defenders (increased distance) let target_x = match self.ctx.player.side { Some(crate::r#match::PlayerSide::Left) => holder_pos.x + 90.0, Some(crate::r#match::PlayerSide::Right) => holder_pos.x - 90.0, None => holder_pos.x, }; // Gentle pull toward center let center_pull = (field_height / 2.0 - player_pos.y) * 0.2; 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, ) } /// Check if player is congested near boundary pub fn is_congested_near_boundary(&self) -> bool { let field_width = self.ctx.context.field_size.width as f32; let field_height = self.ctx.context.field_size.height as f32; let pos = self.ctx.player.position; let near_boundary = pos.x < 20.0 || pos.x > field_width - 20.0 || pos.y < 20.0 || pos.y > field_height - 20.0; if !near_boundary { return false; } // Count all nearby players (teammates + opponents) let nearby_teammates = self.ctx.players().teammates().nearby(15.0).count(); let nearby_opponents = self.ctx.players().opponents().nearby(15.0).count(); let total_nearby = nearby_teammates + nearby_opponents; // If 3 or more players nearby (congestion) total_nearby >= 2 } /// Check if player is in general congestion (anywhere on field) /// This prevents mid-field clustering where multiple players get stuck pub fn is_congested(&self) -> bool { const CONGESTION_RADIUS: f32 = 20.0; // Check within 20 units const CONGESTION_THRESHOLD: usize = 4; // 4+ players = congested // Count all nearby players (teammates + opponents) let nearby_teammates = self.ctx.players().teammates().nearby(CONGESTION_RADIUS).count(); let nearby_opponents = self.ctx.players().opponents().nearby(CONGESTION_RADIUS).count(); let total_nearby = nearby_teammates + nearby_opponents; // If 4 or more players clustered together total_nearby >= CONGESTION_THRESHOLD } /// Calculate better passing position to escape pressure pub fn calculate_better_passing_position(&self) -> Option<Vector3<f32>> { let player_pos = self.ctx.player.position; let goal_pos = self.ctx.ball().direction_to_own_goal(); // Find positions of nearby opponents creating pressure let nearby_opponents: Vec<MatchPlayerLite> = self.ctx.players().opponents().nearby(15.0).collect(); if nearby_opponents.is_empty() { return None; } // Calculate average position of pressing opponents let avg_opponent_pos = nearby_opponents .iter() .fold(Vector3::zeros(), |acc, p| acc + p.position) / nearby_opponents.len() as f32; // Calculate direction away from pressure and perpendicular to goal line let away_from_pressure = (player_pos - avg_opponent_pos).normalize(); let to_goal = (goal_pos - player_pos).normalize(); // Create a movement perpendicular to goal line let perpendicular = Vector3::new(-to_goal.y, to_goal.x, 0.0).normalize(); // Blend the two directions (more weight to away from pressure) let direction = (away_from_pressure * 0.7 + perpendicular * 0.3).normalize(); // Move slightly in the calculated direction Some(player_pos + direction * 5.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/common/states/mod.rs
src/core/src/match/engine/player/strategies/common/states/mod.rs
pub mod injured; pub mod constants; pub mod activity_intensity; pub mod condition; pub use injured::*; pub use constants::*; pub use activity_intensity::*; pub use condition::*;
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/common/states/condition.rs
src/core/src/match/engine/player/strategies/common/states/condition.rs
use crate::r#match::ConditionContext; use super::activity_intensity::{ActivityIntensity, ActivityIntensityConfig}; use super::constants::{MAX_CONDITION, MAX_JADEDNESS, FATIGUE_RATE_MULTIPLIER, RECOVERY_RATE_MULTIPLIER}; /// Generic condition processor with role-specific configurations pub struct ConditionProcessor<T: ActivityIntensityConfig> { intensity: ActivityIntensity, _phantom: std::marker::PhantomData<T>, } impl<T: ActivityIntensityConfig> ConditionProcessor<T> { /// Create a new condition processor (always uses velocity-based calculation) pub fn new(intensity: ActivityIntensity) -> Self { Self { intensity, _phantom: std::marker::PhantomData, } } /// Create a new condition processor with velocity-based intensity (deprecated, use new()) /// Kept for backward compatibility pub fn with_velocity(intensity: ActivityIntensity) -> Self { Self::new(intensity) } /// Process condition changes based on activity intensity and player attributes /// Calculation: 75% velocity-based, 25% intensity-based pub fn process(self, ctx: ConditionContext) { let stamina_skill = ctx.player.skills.physical.stamina; let natural_fitness = ctx.player.skills.physical.natural_fitness; // Stamina affects how tired the player gets (better stamina = less fatigue) // Range: 0.5x to 1.5x (high stamina players tire 50% slower) let stamina_factor = 1.5 - (stamina_skill / 20.0); // Natural fitness affects recovery and fatigue resistance let fitness_factor = 1.3 - (natural_fitness / 20.0) * 0.6; // Calculate velocity-based fatigue (75% of total effect) let velocity_magnitude = ctx.player.velocity.norm(); let max_speed = ctx.player.skills.max_speed_with_condition( ctx.player.player_attributes.condition, ); let velocity_fatigue = if velocity_magnitude < 0.3 { // Resting - recovery -4.0 * 1.5 // Negative = recovery, boosted for visibility } else { let intensity_ratio = if max_speed > 0.0 { (velocity_magnitude / max_speed).clamp(0.0, 1.0) } else { 0.5 }; // Velocity-based fatigue: scales from 0 (walking) to 10 (sprinting) if intensity_ratio < 0.3 { 1.0 // Walking slowly } else if intensity_ratio < 0.6 { 3.0 // Jogging } else if intensity_ratio < 0.85 { 6.0 // Running } else { // Sprinting - varies by role if T::sprint_multiplier() > 1.55 { 10.0 // Forwards (highest) } else if T::sprint_multiplier() > 1.4 { 9.0 // Defenders/Midfielders } else { 7.0 // Goalkeepers (lowest) } } }; // Calculate intensity-based fatigue modifier (25% of total effect) let base_intensity_fatigue = self.intensity.base_fatigue::<T>(); // Normalize intensity contribution to be smaller let intensity_fatigue = base_intensity_fatigue * 0.3; // Combine: 75% velocity + 25% intensity let combined_fatigue = velocity_fatigue * 0.75 + intensity_fatigue * 0.25; // Apply rate multiplier based on whether it's fatigue or recovery let rate_multiplier = if combined_fatigue < 0.0 { RECOVERY_RATE_MULTIPLIER } else { FATIGUE_RATE_MULTIPLIER }; let condition_change = (combined_fatigue * stamina_factor * fitness_factor * rate_multiplier) as i16; // Apply condition change (clamped to 0..MAX_CONDITION) ctx.player.player_attributes.condition = (ctx.player.player_attributes.condition - condition_change).clamp(0, MAX_CONDITION); // If condition drops very low, slightly increase jadedness (long-term tiredness) if ctx.player.player_attributes.condition < T::low_condition_threshold() && ctx.in_state_time % T::jadedness_interval() == 0 { // Increase jadedness slightly when very tired ctx.player.player_attributes.jadedness = (ctx.player.player_attributes.jadedness + T::jadedness_increment()).min(MAX_JADEDNESS); } } }
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/common/states/constants.rs
src/core/src/match/engine/player/strategies/common/states/constants.rs
/// Maximum condition value (Football Manager style) pub const MAX_CONDITION: i16 = 10000; /// Global fatigue rate multiplier (lower = slower condition decrease) pub const FATIGUE_RATE_MULTIPLIER: f32 = 0.200; /// Recovery rate multiplier (lower = slower condition recovery) /// Set to 0.333 (0.5 / 1.5) to make condition recovery 3x slower pub const RECOVERY_RATE_MULTIPLIER: f32 = 0.233; /// Condition threshold below which jadedness increases pub const LOW_CONDITION_THRESHOLD: i16 = 2000; /// Condition threshold for goalkeepers jadedness pub const GOALKEEPER_LOW_CONDITION_THRESHOLD: i16 = 1500; /// Jadedness check interval for field players (ticks) pub const FIELD_PLAYER_JADEDNESS_INTERVAL: u64 = 100; /// Jadedness check interval for goalkeepers (ticks) pub const GOALKEEPER_JADEDNESS_INTERVAL: u64 = 150; /// Maximum jadedness value pub const MAX_JADEDNESS: i16 = 10000; /// Jadedness increase per check when condition is low (field players) pub const JADEDNESS_INCREMENT: i16 = 5; /// Jadedness increase per check when condition is low (goalkeepers) pub const GOALKEEPER_JADEDNESS_INCREMENT: i16 = 3;
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/common/states/activity_intensity.rs
src/core/src/match/engine/player/strategies/common/states/activity_intensity.rs
/// Activity intensity levels for condition processing #[derive(Debug, Clone, Copy)] pub enum ActivityIntensity { /// Very high intensity - explosive actions (shooting, finishing, heading, tackling, sliding) VeryHigh, /// High intensity - sustained running, pressing, intercepting, dribbling High, /// Moderate intensity - assisting, creating space, marking, tracking, returning, covering Moderate, /// Low intensity - walking, passing Low, /// Recovery - standing still, resting, holding line with minimal movement Recovery, } /// Trait for role-specific activity intensity configurations pub trait ActivityIntensityConfig { /// Get the base fatigue for very high intensity activities fn very_high_fatigue() -> f32; /// Get the base fatigue for high intensity activities fn high_fatigue() -> f32; /// Get the base fatigue for moderate intensity activities fn moderate_fatigue() -> f32; /// Get the base fatigue for low intensity activities fn low_fatigue() -> f32; /// Get the recovery rate (negative value) fn recovery_rate() -> f32; /// Get the sprint intensity multiplier fn sprint_multiplier() -> f32; /// Get the running intensity multiplier fn running_multiplier() -> f32 { 1.0 // Default for all roles } /// Get the jogging intensity multiplier fn jogging_multiplier() -> f32; /// Get the walking intensity multiplier fn walking_multiplier() -> f32; /// Get the low condition threshold for jadedness fn low_condition_threshold() -> i16; /// Get the jadedness check interval fn jadedness_interval() -> u64; /// Get the jadedness increment per check fn jadedness_increment() -> i16; } impl ActivityIntensity { /// Get the base fatigue for this activity intensity with the given config pub fn base_fatigue<T: ActivityIntensityConfig>(&self) -> f32 { match self { ActivityIntensity::VeryHigh => T::very_high_fatigue(), ActivityIntensity::High => T::high_fatigue(), ActivityIntensity::Moderate => T::moderate_fatigue(), ActivityIntensity::Low => T::low_fatigue(), ActivityIntensity::Recovery => T::recovery_rate(), } } }
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/common/states/injured/mod.rs
src/core/src/match/engine/player/strategies/common/states/injured/mod.rs
use crate::r#match::player::strategies::processor::StateChangeResult; use crate::r#match::player::strategies::processor::{StateProcessingContext, StateProcessingHandler}; use crate::r#match::{ConditionContext}; use nalgebra::Vector3; #[derive(Default)] pub struct CommonInjuredState {} impl StateProcessingHandler for CommonInjuredState { fn try_fast(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { 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) {} }
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/defenders/decision.rs
src/core/src/match/engine/player/strategies/defenders/decision.rs
pub enum DefenderDecision { RunTowardsBall, StandStill, AdjustPosition, RunTowardsGoal, MarkOpponent, Run, }
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/defenders/mod.rs
src/core/src/match/engine/player/strategies/defenders/mod.rs
pub mod decision; 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/defenders/states/state.rs
src/core/src/match/engine/player/strategies/defenders/states/state.rs
use crate::r#match::defenders::states::{ DefenderBlockingState, DefenderClearingState, DefenderCoveringState, DefenderHeadingState, DefenderHoldingLineState, DefenderInterceptingState, DefenderMarkingState, DefenderOffsideTrapState, DefenderPassingState, DefenderPressingState, DefenderPushingUpState, DefenderRestingState, DefenderReturningState, DefenderRunningState, DefenderShootingState, DefenderSlidingTackleState, DefenderStandingState, DefenderTacklingState, DefenderTakeBallState, DefenderTrackingBackState, DefenderWalkingState, }; use crate::r#match::{StateProcessingResult, StateProcessor}; use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, Copy, PartialEq)] pub enum DefenderState { Standing, // Standing Covering, // Covering the ball PushingUp, // Pushing the ball up Resting, // Resting after an attack Passing, // Passing the ball Running, // Running in the direction of the ball Blocking, // Blocking a shot or pass Intercepting, // Intercepting a pass Marking, // Marking an attacker Clearing, // Clearing the ball from the danger zone Heading, // Heading the ball, often during corners or crosses SlidingTackle, // Sliding tackle Tackling, // Tackling the ball Pressing, // Pressing the opponent TrackingBack, // Tracking back to defense after an attack HoldingLine, // Holding the defensive line OffsideTrap, // Setting up an offside trap, Returning, // Returning the ball, Walking, // Walking around, TakeBall, // Take the ball, Shooting, // Shoting the ball, } pub struct DefenderStrategies {} impl DefenderStrategies { pub fn process(state: DefenderState, state_processor: StateProcessor) -> StateProcessingResult { // let common_state = state_processor.process(DefenderCommonState::default()); // // if common_state.state.is_some() { // return common_state; // } match state { DefenderState::Standing => state_processor.process(DefenderStandingState::default()), DefenderState::Resting => state_processor.process(DefenderRestingState::default()), DefenderState::Passing => state_processor.process(DefenderPassingState::default()), DefenderState::Blocking => state_processor.process(DefenderBlockingState::default()), DefenderState::Intercepting => { state_processor.process(DefenderInterceptingState::default()) } DefenderState::Marking => state_processor.process(DefenderMarkingState::default()), DefenderState::Clearing => state_processor.process(DefenderClearingState::default()), DefenderState::Heading => state_processor.process(DefenderHeadingState::default()), DefenderState::SlidingTackle => { state_processor.process(DefenderSlidingTackleState::default()) } DefenderState::Pressing => state_processor.process(DefenderPressingState::default()), DefenderState::TrackingBack => { state_processor.process(DefenderTrackingBackState::default()) } DefenderState::HoldingLine => { state_processor.process(DefenderHoldingLineState::default()) } DefenderState::OffsideTrap => { state_processor.process(DefenderOffsideTrapState::default()) } DefenderState::Running => state_processor.process(DefenderRunningState::default()), DefenderState::Returning => state_processor.process(DefenderReturningState::default()), DefenderState::Walking => state_processor.process(DefenderWalkingState::default()), DefenderState::Tackling => state_processor.process(DefenderTacklingState::default()), DefenderState::Covering => state_processor.process(DefenderCoveringState::default()), DefenderState::PushingUp => state_processor.process(DefenderPushingUpState::default()), DefenderState::TakeBall => state_processor.process(DefenderTakeBallState::default()), DefenderState::Shooting => state_processor.process(DefenderShootingState::default()), } } } impl Display for DefenderState { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { DefenderState::Standing => write!(f, "Standing"), DefenderState::Resting => write!(f, "Resting"), DefenderState::Passing => write!(f, "Passing"), DefenderState::Blocking => write!(f, "Blocking"), DefenderState::Intercepting => write!(f, "Intercepting"), DefenderState::Marking => write!(f, "Marking"), DefenderState::Clearing => write!(f, "Clearing"), DefenderState::Heading => write!(f, "Heading"), DefenderState::SlidingTackle => write!(f, "Sliding Tackle"), DefenderState::Pressing => write!(f, "Pressing"), DefenderState::TrackingBack => write!(f, "Tracking Back"), DefenderState::HoldingLine => write!(f, "Holding Line"), DefenderState::OffsideTrap => write!(f, "Offside Trap"), DefenderState::Running => write!(f, "Running"), DefenderState::Returning => write!(f, "Returning"), DefenderState::Walking => write!(f, "Walking"), DefenderState::Tackling => write!(f, "Tackling"), DefenderState::Covering => write!(f, "Covering"), DefenderState::PushingUp => write!(f, "Pushing Up"), DefenderState::TakeBall => write!(f, "Take Ball"), DefenderState::Shooting => write!(f, "Shooting"), } } }
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/defenders/states/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/mod.rs
pub mod blocking; pub mod clearing; pub mod covering; pub mod heading; pub mod holding_line; pub mod intercepting; pub mod marking; pub mod offside_trap; pub mod passing; pub mod pressing; pub mod pushingup; pub mod resting; pub mod returning; pub mod running; pub mod shooting; pub mod sliding_tackle; pub mod standing; pub mod state; pub mod tackling; pub mod takeball; pub mod tracking_back; pub mod walking; pub mod common; pub use blocking::*; pub use clearing::*; pub use covering::*; pub use heading::*; pub use holding_line::*; pub use intercepting::*; pub use marking::*; pub use offside_trap::*; pub use passing::*; pub use pressing::*; pub use pushingup::*; pub use resting::*; pub use returning::*; pub use running::*; pub use shooting::*; pub use sliding_tackle::*; pub use standing::*; pub use state::*; pub use tackling::*; pub use takeball::*; pub use tracking_back::*; 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/defenders/states/marking/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/marking/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const MARKING_DISTANCE_THRESHOLD: f32 = 10.0; // Desired distance to maintain from the opponent const TACKLING_DISTANCE_THRESHOLD: f32 = 3.0; // Distance within which the defender can tackle const STAMINA_THRESHOLD: f32 = 20.0; // Minimum stamina to continue marking const BALL_PROXIMITY_THRESHOLD: f32 = 10.0; // Distance to consider the ball as close const HEADING_HEIGHT: f32 = 1.5; const HEADING_DISTANCE: f32 = 5.0; #[derive(Default)] pub struct DefenderMarkingState {} impl StateProcessingHandler for DefenderMarkingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if the defender has enough stamina to continue marking let stamina = ctx.player.player_attributes.condition_percentage() as f32; if stamina < STAMINA_THRESHOLD { // Transition to Resting state if stamina is low return Some(StateChangeResult::with_defender_state( DefenderState::Resting, )); } // Check if ball is aerial and at heading height let ball_position = ctx.tick_context.positions.ball.position; let ball_distance = ctx.ball().distance(); if ball_position.z > HEADING_HEIGHT && ball_distance < HEADING_DISTANCE && ctx.ball().is_towards_player_with_angle(0.6) { return Some(StateChangeResult::with_defender_state( DefenderState::Heading, )); } // 2. Identify the most dangerous opponent player to mark if let Some(opponent_to_mark) = self.find_most_dangerous_opponent(ctx) { let distance_to_opponent = opponent_to_mark.distance(ctx); // 4. If the opponent has the ball and is within tackling distance, attempt a tackle if opponent_to_mark.has_ball(ctx) && distance_to_opponent < TACKLING_DISTANCE_THRESHOLD { return Some(StateChangeResult::with_defender_state( DefenderState::Tackling, )); } // 5. If the opponent is beyond the marking distance threshold, switch to Running state to catch up if distance_to_opponent > MARKING_DISTANCE_THRESHOLD * 1.5 { return Some(StateChangeResult::with_defender_state( DefenderState::Running, )); } // 6. If the ball is close to the defender, consider intercepting if ctx.ball().distance() < BALL_PROXIMITY_THRESHOLD && !opponent_to_mark.has_ball(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Intercepting, )); } // 7. Continue marking (no state change) None } else { // No opponent to mark found // Transition back to HoldingLine or appropriate state Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed // For now, return None to indicate no state change None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Move to maintain position relative to the opponent being marked // Identify the most dangerous opponent player to mark if let Some(opponent_to_mark) = self.find_most_dangerous_opponent(ctx) { // Calculate desired position to maintain proper marking let opponent_future_position = opponent_to_mark.position + opponent_to_mark.velocity(ctx); let desired_position = opponent_future_position - (opponent_to_mark.velocity(ctx).normalize() * MARKING_DISTANCE_THRESHOLD); let direction = (desired_position - ctx.player.position).normalize(); // Set speed based on player's pace let speed = ctx.player.skills.physical.pace; // Use pace attribute Some(direction * speed) } else { // No opponent to mark found // Remain stationary or return to default position Some(Vector3::new(0.0, 0.0, 0.0)) } } fn process_conditions(&self, ctx: ConditionContext) { // Marking involves constant movement following opponent - moderate intensity DefenderCondition::with_velocity(ActivityIntensity::Moderate).process(ctx); } } impl DefenderMarkingState { /// Find the most dangerous opponent to mark based on multiple factors fn find_most_dangerous_opponent(&self, ctx: &StateProcessingContext) -> Option<crate::r#match::MatchPlayerLite> { // Extended search range to catch dangerous runs from distance let nearby_opponents: Vec<_> = ctx.players().opponents().nearby(150.0).collect(); if nearby_opponents.is_empty() { return None; } let player_ops = ctx.player(); // Calculate danger score for each opponent let mut best_opponent = None; let mut best_score = f32::MIN; for opponent in nearby_opponents { let mut danger_score = 0.0; // Factor 1: Has the ball (VERY dangerous) if opponent.has_ball(ctx) { danger_score += 100.0; } // Factor 2: Distance to our goal (closer = more dangerous) let own_goal_position = ctx.ball().direction_to_own_goal(); let distance_to_own_goal = (opponent.position - own_goal_position).magnitude(); danger_score += (500.0 - distance_to_own_goal) / 10.0; // Max 50 points // Factor 3: Distance to defender (closer = needs marking) let distance_to_defender = opponent.distance(ctx); danger_score += (100.0 - distance_to_defender.min(100.0)) / 5.0; // Max 20 points // Factor 4: Opponent facing our goal (attacking posture) - ENHANCED let opponent_velocity = opponent.velocity(ctx); let to_our_goal = (own_goal_position - opponent.position).normalize(); let speed = opponent_velocity.norm(); if speed > 0.1 { let velocity_dir = opponent_velocity.normalize(); let alignment = velocity_dir.dot(&to_our_goal); if alignment > 0.0 { // Base points for running towards goal danger_score += alignment * 30.0; // Bonus for dangerous runs: high speed + good alignment if speed > 3.0 && alignment > 0.7 { danger_score += 25.0; // Additional points for clear dangerous run } } } // Factor 5: Ball proximity (if opponent doesn't have ball, closer to ball = more dangerous) if !opponent.has_ball(ctx) { let ball_position = ctx.tick_context.positions.ball.position; let distance_to_ball = (opponent.position - ball_position).magnitude(); danger_score += (50.0 - distance_to_ball.min(50.0)) / 5.0; // Max 10 points } // Factor 6: Opponent skill level (better players are more dangerous) let opponent_skills = player_ops.skills(opponent.id); let attacking_skill = (opponent_skills.physical.pace + opponent_skills.technical.dribbling + opponent_skills.technical.finishing) / 3.0; danger_score += attacking_skill / 20.0; // Max ~5 points for elite attacker // Update best if this opponent is more dangerous if danger_score > best_score { best_score = danger_score; best_opponent = Some(opponent); } } best_opponent } }
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/defenders/states/intercepting/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/intercepting/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior}; use nalgebra::Vector3; const HEADING_HEIGHT: f32 = 1.5; const HEADING_DISTANCE: f32 = 5.0; #[derive(Default)] pub struct DefenderInterceptingState {} impl StateProcessingHandler for DefenderInterceptingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Running, )); } // Check if ball is aerial and at heading height let ball_position = ctx.tick_context.positions.ball.position; let ball_distance = ctx.ball().distance(); if ball_position.z > HEADING_HEIGHT && ball_distance < HEADING_DISTANCE && ctx.ball().is_towards_player_with_angle(0.6) { return Some(StateChangeResult::with_defender_state( DefenderState::Heading, )); } if ball_distance < 20.0 { return Some(StateChangeResult::with_defender_state( DefenderState::Tackling, )); } if !ctx.ball().is_towards_player_with_angle(0.8) || ball_distance > 100.0 { return Some(StateChangeResult::with_defender_state( DefenderState::Returning, )); } if !self.can_reach_before_opponent(ctx) { // If not, transition to Pressing or HoldingLine state return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { 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 involves high-intensity sprinting to reach the ball DefenderCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl DefenderInterceptingState { 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/defenders/states/covering/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/covering/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; const MARKING_DISTANCE: f32 = 15.0; const INTERCEPTION_DISTANCE: f32 = 100.0; const FIELD_THIRD_THRESHOLD: f32 = 0.33; const PUSH_UP_HYSTERESIS: f32 = 0.05; const THREAT_SCAN_DISTANCE: f32 = 70.0; const DANGEROUS_RUN_SPEED: f32 = 3.0; const DANGEROUS_RUN_ANGLE: f32 = 0.7; const MIN_STATE_TIME_DEFAULT: u64 = 200; // Reduced from 300 const MIN_STATE_TIME_WITH_THREAT: u64 = 50; // Fast reaction when threats detected #[derive(Default)] pub struct DefenderCoveringState {} impl StateProcessingHandler for DefenderCoveringState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Adaptive reaction time based on threat detection let min_time = if self.has_dangerous_threat_nearby(ctx) { MIN_STATE_TIME_WITH_THREAT } else { MIN_STATE_TIME_DEFAULT }; if ctx.in_state_time < min_time { return None; } let ball_ops = ctx.ball(); if ball_ops.on_own_side() { return Some(StateChangeResult::with_defender_state( DefenderState::Standing, )); } if ball_ops.distance_to_opponent_goal() < ctx.context.field_size.width as f32 * (FIELD_THIRD_THRESHOLD - PUSH_UP_HYSTERESIS) && self.should_push_up(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::PushingUp, )); } if let Some(_) = ctx.players().opponents().nearby(MARKING_DISTANCE).next() { return Some(StateChangeResult::with_defender_state( DefenderState::Marking, )); } if ball_ops.is_towards_player() && ball_ops.distance() < INTERCEPTION_DISTANCE { return Some(StateChangeResult::with_defender_state( DefenderState::Intercepting, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { Some( SteeringBehavior::Pursuit { target: self.calculate_optimal_covering_position(ctx), target_velocity: Vector3::zeros(), // Static target position } .calculate(ctx.player) .velocity, ) } fn process_conditions(&self, ctx: ConditionContext) { // Covering space involves moving to cover gaps - moderate intensity DefenderCondition::with_velocity(ActivityIntensity::Moderate).process(ctx); } } impl DefenderCoveringState { fn should_push_up(&self, ctx: &StateProcessingContext) -> bool { let ball_ops = ctx.ball(); let player_ops = ctx.player(); let ball_in_attacking_third = ball_ops.distance_to_opponent_goal() < ctx.context.field_size.width as f32 * FIELD_THIRD_THRESHOLD; let team_in_possession = ctx.team().is_control_ball(); let defender_not_last_man = !self.is_last_defender(ctx); ball_in_attacking_third && team_in_possession && defender_not_last_man && player_ops.distance_from_start_position() < ctx.context.field_size.width as f32 * 0.25 } fn is_last_defender(&self, ctx: &StateProcessingContext) -> bool { ctx.players().teammates().defenders() .all(|d| d.position.x >= ctx.player.position.x) } fn calculate_optimal_covering_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_position = ctx.tick_context.positions.ball.position; let player_position = ctx.player.position; let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; // Calculate the center of the middle third with slight offset towards own goal let middle_third_center = Vector3::new( field_width * 0.4, // Moved slightly back from 0.5 field_height * 0.5, 0.0, ); // Get direction to own goal and normalize it let ball_to_goal = (ctx.ball().direction_to_own_goal() - ball_position).normalize(); // Calculate base covering position with better distance scaling let covering_distance = (ball_position - ctx.ball().direction_to_own_goal()).magnitude() * 0.35; let covering_position = ball_position + ball_to_goal * covering_distance.min(field_width * 0.3); // Apply exponential moving average for position smoothing const SMOOTHING_FACTOR: f32 = 0.15; // Adjust this value (0.0 to 1.0) to control smoothing let previous_position = ctx.player.position; // Check for dangerous spaces that need covering let dangerous_space = self.find_dangerous_space(ctx); // Calculate blended position with weighted factors let target_position = if let Some(danger_pos) = dangerous_space { // Prioritize covering dangerous space Vector3::new( danger_pos.x * 0.5 + covering_position.x * 0.3 + player_position.x * 0.2, danger_pos.y * 0.5 + covering_position.y * 0.3 + player_position.y * 0.2, 0.0, ) } else { // Default covering behavior - reduced middle_third bias Vector3::new( covering_position.x * 0.5 + middle_third_center.x * 0.3 + // Reduced from 0.4 player_position.x * 0.2, // Increased from 0.1 covering_position.y * 0.5 + middle_third_center.y * 0.3 + player_position.y * 0.2, 0.0, ) }; // Apply smoothing between frames let smoothed_position = previous_position.lerp(&target_position, SMOOTHING_FACTOR); // Ensure the position stays within reasonable bounds let max_distance_from_center = field_width * 0.35; let position_relative_to_center = smoothed_position - middle_third_center; let capped_position = if position_relative_to_center.magnitude() > max_distance_from_center { middle_third_center + position_relative_to_center.normalize() * max_distance_from_center } else { smoothed_position }; // Final boundary check Vector3::new( capped_position.x.clamp(field_width * 0.1, field_width * 0.7), // Prevent getting too close to either goal capped_position.y.clamp(field_height * 0.1, field_height * 0.9), // Keep away from sidelines 0.0, ) } /// Check if there are dangerous threats nearby that require immediate attention fn has_dangerous_threat_nearby(&self, ctx: &StateProcessingContext) -> bool { // Check for immediate threats within marking distance if ctx.players().opponents().nearby(MARKING_DISTANCE).next().is_some() { return true; } // Check for dangerous runs let own_goal_position = ctx.ball().direction_to_own_goal(); ctx.players() .opponents() .nearby(THREAT_SCAN_DISTANCE) .any(|opp| { let velocity = opp.velocity(ctx); let speed = velocity.norm(); if speed < DANGEROUS_RUN_SPEED { return false; } let to_goal = (own_goal_position - opp.position).normalize(); let velocity_dir = velocity.normalize(); let alignment = velocity_dir.dot(&to_goal); alignment >= DANGEROUS_RUN_ANGLE }) } /// Find dangerous space that needs to be covered (e.g., unmarked attackers in dangerous positions) fn find_dangerous_space(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { let own_goal_position = ctx.ball().direction_to_own_goal(); // Find opponents making dangerous runs or in dangerous positions let dangerous_opponents: Vec<_> = ctx .players() .opponents() .nearby(THREAT_SCAN_DISTANCE) .filter(|opp| { let velocity = opp.velocity(ctx); let speed = velocity.norm(); // Either running toward goal OR in a dangerous static position if speed >= DANGEROUS_RUN_SPEED { let to_goal = (own_goal_position - opp.position).normalize(); let velocity_dir = velocity.normalize(); velocity_dir.dot(&to_goal) >= DANGEROUS_RUN_ANGLE } else { // Check if in dangerous static position (between ball and goal) let ball_pos = ctx.tick_context.positions.ball.position; let distance_to_goal = (opp.position - own_goal_position).magnitude(); let ball_distance_to_goal = (ball_pos - own_goal_position).magnitude(); // Opponent is closer to goal than ball and within threatening distance distance_to_goal < ball_distance_to_goal && distance_to_goal < 300.0 } }) .collect(); if dangerous_opponents.is_empty() { return None; } // Find the most dangerous opponent's position let most_dangerous = dangerous_opponents .iter() .min_by(|a, b| { let dist_a = (a.position - own_goal_position).magnitude(); let dist_b = (b.position - own_goal_position).magnitude(); dist_a.partial_cmp(&dist_b).unwrap() })?; // Calculate position between the dangerous opponent and our goal let direction_to_goal = (own_goal_position - most_dangerous.position).normalize(); Some(most_dangerous.position + direction_to_goal * 15.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/defenders/states/tackling/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/tackling/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::events::Event; 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 = 15.0; const FOUL_CHANCE_BASE: f32 = 0.2; const PRESSING_DISTANCE: f32 = 70.0; const RETURN_DISTANCE: f32 = 100.0; #[derive(Default)] pub struct DefenderTacklingState {} impl StateProcessingHandler for DefenderTacklingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // If we have the ball or our team controls it, transition to running if ctx.player.has_ball(ctx) || ctx.team().is_control_ball() { return Some(StateChangeResult::with_defender_state( DefenderState::Running, )); } // Check if there's an opponent with the ball if let Some(opponent) = ctx.players().opponents().with_ball().next() { let distance_to_opponent = opponent.distance(ctx); // If opponent is too far for tackling, press instead if distance_to_opponent > PRESSING_DISTANCE { return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } // If opponent is close but not in tackle range, keep pressing if distance_to_opponent > TACKLE_DISTANCE_THRESHOLD { return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } // We're close enough to tackle! let (tackle_success, committed_foul) = self.attempt_sliding_tackle(ctx, &opponent); return if tackle_success { Some(StateChangeResult::with_defender_state_and_event( DefenderState::Standing, Event::PlayerEvent(PlayerEvent::GainBall(ctx.player.id)), )) } else if committed_foul { Some(StateChangeResult::with_defender_state_and_event( DefenderState::Standing, Event::PlayerEvent(PlayerEvent::CommitFoul), )) } else { None }; } else { // Ball is loose - check for interception if self.can_intercept_ball(ctx) { // Ball is loose and we can intercept it return Some(StateChangeResult::with_defender_state_and_event( DefenderState::Running, Event::PlayerEvent(PlayerEvent::ClaimBall(ctx.player.id)), )); } // If ball is too far away and not coming toward us, return to position let ball_distance = ctx.ball().distance(); if ball_distance > RETURN_DISTANCE && !ctx.ball().is_towards_player_with_angle(0.8) { return Some(StateChangeResult::with_defender_state( DefenderState::Returning, )); } // Fallback: if ball is loose and very close, try to claim it if !ctx.tick_context.ball.is_owned && ball_distance < 5.0 { return Some(StateChangeResult::with_defender_state_and_event( DefenderState::Running, Event::PlayerEvent(PlayerEvent::ClaimBall(ctx.player.id)), )); } // If opponent is near the player but doesn't have the ball, maybe it's better to transition to pressing if let Some(close_opponent) = ctx.players().opponents().nearby(15.0).next() { if close_opponent.distance(ctx) < 10.0 { return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } } } if ctx.in_state_time > 30 { let ball_distance = ctx.ball().distance(); if ball_distance > PRESSING_DISTANCE { return Some(StateChangeResult::with_defender_state(DefenderState::Returning)); } } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network logic if necessary None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { let target = self.calculate_intelligent_target(ctx); Some( SteeringBehavior::Pursuit { target, target_velocity: Vector3::zeros(), // Static/calculated target position } .calculate(ctx.player) .velocity + ctx.player().separation_velocity(), ) } fn process_conditions(&self, ctx: ConditionContext) { // Tackling is explosive and very demanding physically DefenderCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl DefenderTacklingState { fn calculate_intelligent_target(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_position = ctx.tick_context.positions.ball.position; let player_position = ctx.player.position; let own_goal_position = ctx.ball().direction_to_own_goal(); // Check if ball is dangerously close to own goal let ball_distance_to_own_goal = (ball_position - own_goal_position).magnitude(); let is_ball_near_own_goal = ball_distance_to_own_goal < ctx.context.field_size.width as f32 * 0.2; // Check if we're between the ball and our goal let player_distance_to_own_goal = (player_position - own_goal_position).magnitude(); let is_player_closer_to_goal = player_distance_to_own_goal < ball_distance_to_own_goal; if is_ball_near_own_goal && !is_player_closer_to_goal { // If ball is near our goal and we're not between ball and goal, // position ourselves between the ball and the goal let ball_to_goal_direction = (own_goal_position - ball_position).normalize(); let intercept_distance = 5.0; // Stand 5 units in front of the ball towards our goal ball_position + ball_to_goal_direction * intercept_distance } else { // Otherwise, pursue the ball directly ball_position } } fn attempt_sliding_tackle( &self, ctx: &StateProcessingContext, opponent: &MatchPlayerLite, ) -> (bool, bool) { let mut rng = rand::rng(); 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 overall_skill = (tackling_skill + composure) / 2.0; let opponent_dribbling = ctx.player().skills(opponent.id).technical.dribbling / 20.0; let opponent_agility = ctx.player().skills(opponent.id).physical.agility / 20.0; let skill_difference = overall_skill - (opponent_dribbling + opponent_agility) / 2.0; let success_chance = 0.5 + skill_difference * 0.3; let clamped_success_chance = success_chance.clamp(0.1, 0.9); let tackle_success = rng.random::<f32>() < clamped_success_chance; let foul_chance = if tackle_success { (1.0 - overall_skill) * FOUL_CHANCE_BASE + aggression * 0.05 } else { (1.0 - overall_skill) * FOUL_CHANCE_BASE + aggression * 0.15 }; let committed_foul = rng.random::<f32>() < foul_chance; (tackle_success, committed_foul) } fn exists_nearby(&self, ctx: &StateProcessingContext) -> bool { const DISTANCE: f32 = 30.0; ctx.players().opponents().exists(DISTANCE) || ctx.players().teammates().exists(DISTANCE) } fn can_intercept_ball(&self, ctx: &StateProcessingContext) -> bool { if self.exists_nearby(ctx) { 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; if !ctx.tick_context.ball.is_owned && ball_velocity.magnitude() > 0.1 { let time_to_ball = (ball_position - player_position).magnitude() / player_speed; let ball_travel_distance = ball_velocity.magnitude() * time_to_ball; let ball_intercept_position = ball_position + ball_velocity.normalize() * ball_travel_distance; let player_intercept_distance = (ball_intercept_position - player_position).magnitude(); player_intercept_distance <= TACKLE_DISTANCE_THRESHOLD } else { 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/defenders/states/holding_line/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/holding_line/mod.rs
use nalgebra::Vector3; use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ConditionContext, MatchPlayerLite, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler}; const MAX_DEFENSIVE_LINE_DEVIATION: f32 = 50.0; // Maximum distance from line before switching to Running const BALL_PROXIMITY_THRESHOLD: f32 = 100.0; const MARKING_DISTANCE_THRESHOLD: f32 = 30.0; #[derive(Default)] pub struct DefenderHoldingLineState {} impl StateProcessingHandler for DefenderHoldingLineState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Calculate the defensive line position (x-axis: goal-to-goal) let defensive_line_position = self.calculate_defensive_line_position(ctx); // 2. Calculate the distance from the defender to the defensive line let distance_from_line = (ctx.player.position.x - defensive_line_position).abs(); // 3. If the defender is too far from the defensive line, switch to Running state if distance_from_line > MAX_DEFENSIVE_LINE_DEVIATION { return Some(StateChangeResult::with_defender_state( DefenderState::Running, )); } if ctx.ball().distance() < 250.0 && ctx.ball().is_towards_player_with_angle(0.8) { return Some(StateChangeResult::with_defender_state( DefenderState::Intercepting )); } if ctx.ball().distance() < BALL_PROXIMITY_THRESHOLD { let opponent_nearby = self.is_opponent_nearby(ctx); return Some(StateChangeResult::with_defender_state(if opponent_nearby { DefenderState::Marking } else { DefenderState::Intercepting })); } // 6. Check if we should set up an offside trap if self.should_set_offside_trap(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::OffsideTrap, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed // For now, return None to indicate no state change None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { let defensive_line_position = self.calculate_defensive_line_position(ctx); let current_position = ctx.player.position; // Target position uses x for defensive line, keeps y (lateral position) and z the same let target_position = Vector3::new(defensive_line_position, current_position.y, current_position.z); // Calculate the distance between the current position and the target position let distance = (target_position - current_position).magnitude(); // Define a minimum distance threshold to prevent oscillation const MIN_DISTANCE_THRESHOLD: f32 = 2.0; // Small threshold for smooth positioning const SLOWING_DISTANCE: f32 = 15.0; // Start slowing down within this distance if distance > MIN_DISTANCE_THRESHOLD { // Calculate the direction from the current position to the target position let direction = (target_position - current_position).normalize(); // Smooth speed factor based on distance - slows down as approaching target let speed_factor = if distance > SLOWING_DISTANCE { 1.0 // Full speed when far from line } else { // Gradual slowdown as approaching the line (distance / SLOWING_DISTANCE).clamp(0.2, 1.0) }; // Base speed for holding line (slower, more controlled movement) let base_speed = 1.5; let pace_influence = (ctx.player.skills.physical.pace / 20.0).clamp(0.5, 1.5); // Calculate the velocity with controlled speed let velocity = direction * base_speed * speed_factor * pace_influence; Some(velocity) } else { // If the distance is below the threshold, return zero velocity to prevent oscillation Some(Vector3::zeros()) } } fn process_conditions(&self, ctx: ConditionContext) { // Holding line involves minimal movement - allows for recovery DefenderCondition::with_velocity(ActivityIntensity::Recovery).process(ctx); } } impl DefenderHoldingLineState { /// Calculates the defensive line position based on team tactics and defender positions. /// Returns the average x-position (goal-to-goal axis) of defenders. fn calculate_defensive_line_position(&self, ctx: &StateProcessingContext) -> f32 { let defenders: Vec<MatchPlayerLite> = ctx.players().teammates().defenders().collect(); // Calculate the average x-position of defenders to determine the defensive line // X-axis is the goal-to-goal direction, which is what we want for a defensive line let sum_x_positions: f32 = defenders.iter().map(|p| p.position.x).sum(); sum_x_positions / defenders.len() as f32 } /// Checks if an opponent player is nearby within the MARKING_DISTANCE_THRESHOLD. fn is_opponent_nearby(&self, ctx: &StateProcessingContext) -> bool { ctx.players().opponents().exists(MARKING_DISTANCE_THRESHOLD) } /// Determines if the team should set up an offside trap. fn should_set_offside_trap(&self, ctx: &StateProcessingContext) -> bool { // Check if opponents are positioned ahead of the defensive line let defensive_line_position = self.calculate_defensive_line_position(ctx); let opponents_ahead = ctx .players() .opponents() .all() .filter(|opponent| { if ctx.player.side == Some(PlayerSide::Left) { opponent.position.x < defensive_line_position } else { opponent.position.x > defensive_line_position } }) .count(); // If multiple opponents are ahead, consider setting up an offside trap opponents_ahead >= 2 } }
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/defenders/states/running/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/running/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, MatchPlayerLite, PlayerDistanceFromStartPosition, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use crate::IntegerUtils; use nalgebra::Vector3; const MAX_SHOOTING_DISTANCE: f32 = 80.0; // Defenders rarely shoot, only from close range #[derive(Default)] pub struct DefenderRunningState {} impl StateProcessingHandler for DefenderRunningState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { if self.is_in_shooting_range(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Shooting, )); } if self.has_clear_shot(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Shooting, )); } if self.should_pass(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Passing, )); } if self.should_clear(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Clearing, )); } } else { if ctx.player().position_to_distance() == PlayerDistanceFromStartPosition::Big { return Some(StateChangeResult::with_defender_state( DefenderState::Returning, )); } // Only tackle if an opponent has the ball if let Some(_opponent) = ctx.players().opponents().with_ball().next() { if ctx.ball().distance() < 200.0 { return Some(StateChangeResult::with_defender_state( DefenderState::Tackling, )); } } else if !ctx.ball().is_owned() && self.should_intercept(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Intercepting, )); } } 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 + ctx.player().separation_velocity(), ); } } Some( SteeringBehavior::Arrive { target: ctx.player().opponent_goal_position(), slowing_distance: if ctx.player.has_ball(ctx) { 150.0 } else { 100.0 }, } .calculate(ctx.player) .velocity + ctx.player().separation_velocity(), ) } fn process_conditions(&self, ctx: ConditionContext) { // Running is physically demanding - reduce condition based on intensity and player's stamina // Use velocity-based calculation to account for sprinting vs jogging DefenderCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl DefenderRunningState { pub fn should_clear(&self, ctx: &StateProcessingContext) -> bool { // Original: Clear if in own penalty area with nearby opponents if ctx.ball().in_own_penalty_area() && ctx.players().opponents().exists(100.0) { return true; } // Clear if congested anywhere (not just boundaries) if self.is_congested_near_boundary(ctx) || ctx.player().movement().is_congested() { return true; } false } /// Check if player is stuck in a corner/boundary with multiple players around fn is_congested_near_boundary(&self, ctx: &StateProcessingContext) -> bool { // Check if near any boundary (within 20 units) let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; let pos = ctx.player.position; let near_boundary = pos.x < 20.0 || pos.x > field_width - 20.0 || pos.y < 20.0 || pos.y > field_height - 20.0; if !near_boundary { return false; } // Count all nearby players (teammates + opponents) within 15 units let nearby_teammates = ctx.players().teammates().nearby(15.0).count(); let nearby_opponents = ctx.players().opponents().nearby(15.0).count(); let total_nearby = nearby_teammates + nearby_opponents; // If 3 or more players nearby (congestion), need to clear total_nearby >= 3 } pub fn should_pass(&self, ctx: &StateProcessingContext) -> bool { if ctx.players().opponents().exists(20.0) { return true; } let game_vision_skill = ctx.player.skills.mental.vision; let game_vision_threshold = 14.0; // Adjust this value based on your game balance if game_vision_skill >= game_vision_threshold { if let Some(_) = self.find_open_teammate_on_opposite_side(ctx) { return true; } } false } fn find_open_teammate_on_opposite_side( &self, ctx: &StateProcessingContext, ) -> Option<MatchPlayerLite> { let player_position = ctx.player.position; let field_width = ctx.context.field_size.width as f32; let opposite_side_x = match ctx.player.side { Some(PlayerSide::Left) => field_width * 0.75, Some(PlayerSide::Right) => field_width * 0.25, None => return None, }; let mut open_teammates: Vec<MatchPlayerLite> = ctx .players() .teammates() .nearby(200.0) .filter(|teammate| { if teammate.tactical_positions.is_goalkeeper() { return false; } let is_on_opposite_side = match ctx.player.side { Some(PlayerSide::Left) => teammate.position.x > opposite_side_x, Some(PlayerSide::Right) => teammate.position.x < opposite_side_x, None => false, }; let is_open = !ctx .players() .opponents() .nearby(20.0) .any(|opponent| opponent.id == teammate.id); is_on_opposite_side && is_open }) .collect(); if open_teammates.is_empty() { None } else { open_teammates.sort_by(|a, b| { let dist_a = (a.position - player_position).magnitude(); let dist_b = (b.position - player_position).magnitude(); dist_a.partial_cmp(&dist_b).unwrap() }); Some(open_teammates[0]) } } fn is_in_shooting_range(&self, ctx: &StateProcessingContext) -> bool { let distance_to_goal = ctx.ball().distance_to_opponent_goal(); distance_to_goal <= MAX_SHOOTING_DISTANCE && ctx.player().has_clear_shot() } fn has_clear_shot(&self, ctx: &StateProcessingContext) -> bool { if ctx.ball().distance_to_opponent_goal() < MAX_SHOOTING_DISTANCE { return ctx.player().has_clear_shot(); } false } fn should_intercept(&self, ctx: &StateProcessingContext) -> bool { // Don't intercept if a teammate has the ball 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 { // A teammate has the ball, don't try to intercept return false; } } } // Only intercept if you're the best player to chase the ball if !ctx.team().is_best_player_to_chase_ball() { return false; } // Check if the ball is moving toward this player and is close enough if ctx.ball().distance() < 200.0 && ctx.ball().is_towards_player_with_angle(0.8) { return true; } // Check if the ball is very close and no teammate is clearly going for it if ctx.ball().distance() < 50.0 && !ctx.team().is_teammate_chasing_ball() { 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/defenders/states/resting/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/resting/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const STAMINA_RECOVERY_THRESHOLD: f32 = 90.0; const BALL_PROXIMITY_THRESHOLD: f32 = 10.0; const MARKING_DISTANCE_THRESHOLD: f32 = 10.0; const OPPONENT_THREAT_THRESHOLD: usize = 2; #[derive(Default)] pub struct DefenderRestingState {} impl StateProcessingHandler for DefenderRestingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if player's stamina has recovered let stamina = ctx.player.player_attributes.condition_percentage() as f32; if stamina >= STAMINA_RECOVERY_THRESHOLD { // Transition back to HoldingLine state return Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )); } // 2. Check if the ball is close let ball_distance = (ctx.tick_context.positions.ball.position - ctx.player.position).magnitude(); if ball_distance < BALL_PROXIMITY_THRESHOLD { // If the ball is close, check for nearby opponents let opponent_nearby = self.is_opponent_nearby(ctx); return Some(StateChangeResult::with_defender_state(if opponent_nearby { DefenderState::Marking } else { DefenderState::Intercepting })); } // 3. Check if the team is under threat if self.is_team_under_threat(ctx) { // Transition to Pressing state to help the team return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } // 4. Remain in Resting state None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Defender remains stationary or moves minimally while resting Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Resting provides maximum recovery - dedicated recovery state DefenderCondition::new(ActivityIntensity::Recovery).process(ctx); } } impl DefenderRestingState { /// Checks if an opponent player is nearby within the MARKING_DISTANCE_THRESHOLD. fn is_opponent_nearby(&self, ctx: &StateProcessingContext) -> bool { ctx.players().opponents().exists(MARKING_DISTANCE_THRESHOLD) } /// Determines if the team is under threat based on the number of opponents in the attacking third. fn is_team_under_threat(&self, ctx: &StateProcessingContext) -> bool { let opponents_in_attacking_third = ctx.players().opponents().all() .filter(|opponent| self.is_in_defensive_third(opponent.position, ctx)) .count(); opponents_in_attacking_third >= OPPONENT_THREAT_THRESHOLD } /// Checks if a position is within the team's defensive third of the field. fn is_in_defensive_third(&self, position: Vector3<f32>, ctx: &StateProcessingContext) -> bool { let field_length = ctx.context.field_size.width as f32; if ctx.player.side == Some(PlayerSide::Left) { position.x < field_length / 3.0 } else { position.x > (2.0 / 3.0) * field_length } } }
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/defenders/states/sliding_tackle/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/sliding_tackle/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::events::Event; use crate::r#match::player::events::PlayerEvent; use crate::r#match::{ConditionContext, MatchPlayerLite, StateChangeResult, StateProcessingContext, StateProcessingHandler}; use nalgebra::Vector3; use rand::Rng; const TACKLE_DISTANCE_THRESHOLD: f32 = 2.0; // Maximum distance to attempt a sliding tackle (in meters) const TACKLE_SUCCESS_BASE_CHANCE: f32 = 0.6; // Base chance of successful tackle const FOUL_CHANCE_BASE: f32 = 0.2; // Base chance of committing a foul const STAMINA_THRESHOLD: f32 = 25.0; // Minimum stamina to attempt a sliding tackle #[derive(Default)] pub struct DefenderSlidingTackleState {} impl StateProcessingHandler for DefenderSlidingTackleState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check defender's stamina let stamina = ctx.player.player_attributes.condition_percentage() as f32; if stamina < STAMINA_THRESHOLD { // Transition to Resting state if stamina is too low return Some(StateChangeResult::with_defender_state( DefenderState::Resting, )); } // 2. Identify the opponent player with the ball if let Some(opponent) = ctx.players().opponents().with_ball().next() { // 3. Calculate the distance to the opponent let distance_to_opponent = (ctx.player.position - opponent.position).magnitude(); if distance_to_opponent > TACKLE_DISTANCE_THRESHOLD { // Opponent is too far to attempt a sliding tackle // Transition back to appropriate state (e.g., Pressing) return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } // 4. Attempt the sliding tackle let (tackle_success, committed_foul) = self.attempt_sliding_tackle(ctx, &opponent); if tackle_success { // Tackle is successful let mut state_change = StateChangeResult::with_defender_state(DefenderState::Standing); // Gain possession of the ball state_change .events .add(Event::PlayerEvent(PlayerEvent::GainBall(ctx.player.id))); // Update opponent's state to reflect loss of possession // This assumes you have a mechanism to update other players' states // You may need to send an event or directly modify the opponent's state // Optionally reduce defender's stamina // ctx.player.player_attributes.reduce_stamina(tackle_stamina_cost); Some(state_change) } else if committed_foul { // Tackle resulted in a foul let mut state_change = StateChangeResult::with_defender_state(DefenderState::Standing); // Generate a foul event state_change .events .add(Event::PlayerEvent(PlayerEvent::CommitFoul)); // Transition to appropriate state (e.g., ReactingToFoul) // You may need to define additional states for handling fouls Some(state_change) } else { // Tackle failed without committing a foul // Transition back to appropriate state Some(StateChangeResult::with_defender_state( DefenderState::Standing, )) } } else { // No opponent with the ball found // Transition back to appropriate state Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network logic if necessary None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Move towards the opponent to attempt the sliding tackle // Get the opponent with the ball if let Some(opponent) = ctx.players().opponents().with_ball().next() { // Calculate direction towards the opponent let direction = (opponent.position - ctx.player.position).normalize(); // Set speed based on player's pace, increased slightly for the slide let speed = ctx.player.skills.physical.pace * 1.1; // Increase speed by 10% Some(direction * speed) } else { // No opponent with the ball found // Remain stationary or move back to position Some(Vector3::new(0.0, 0.0, 0.0)) } } fn process_conditions(&self, ctx: ConditionContext) { // Sliding tackle is explosive and very demanding - high energy output DefenderCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl DefenderSlidingTackleState { /// Attempts a sliding tackle and returns whether it was successful and if a foul was committed. fn attempt_sliding_tackle( &self, ctx: &StateProcessingContext, _opponent: &MatchPlayerLite, ) -> (bool, bool) { let mut rng = rand::rng(); // Get defender's tackling-related skills let tackling_skill = ctx.player.skills.technical.tackling / 20.0; // Normalize to [0,1] let aggression = ctx.player.skills.mental.aggression / 20.0; let composure = ctx.player.skills.mental.composure / 20.0; let overall_skill = (tackling_skill + composure) / 2.0; // Calculate success chance let success_chance = overall_skill * TACKLE_SUCCESS_BASE_CHANCE; // Simulate tackle success let tackle_success = rng.random::<f32>() < success_chance; // Calculate foul chance let foul_chance = (1.0 - overall_skill) * FOUL_CHANCE_BASE + aggression * 0.1; // Simulate foul let committed_foul = !tackle_success && rng.random::<f32>() < foul_chance; (tackle_success, committed_foul) } }
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/defenders/states/standing/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/standing/mod.rs
use nalgebra::Vector3; use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, MatchPlayerLite, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; const INTERCEPTION_DISTANCE: f32 = 200.0; const CLEARING_DISTANCE: f32 = 50.0; const STANDING_TIME_LIMIT: u64 = 300; const WALK_DISTANCE_THRESHOLD: f32 = 15.0; const MARKING_DISTANCE: f32 = 15.0; const FIELD_THIRD_THRESHOLD: f32 = 0.33; const PRESSING_DISTANCE: f32 = 45.0; // Reduced from 100.0 - more realistic press trigger const PRESSING_DISTANCE_DEFENSIVE_THIRD: f32 = 35.0; // Even tighter in own defensive third const TACKLE_DISTANCE: f32 = 30.0; const BLOCKING_DISTANCE: f32 = 15.0; const HEADING_HEIGHT: f32 = 1.5; const HEADING_DISTANCE: f32 = 5.0; const THREAT_SCAN_DISTANCE: f32 = 70.0; // Extended range for detecting dangerous runs const DANGEROUS_RUN_SPEED: f32 = 3.0; // Minimum speed to consider a run dangerous const DANGEROUS_RUN_ANGLE: f32 = 0.7; // Dot product threshold for running toward goal #[derive(Default)] pub struct DefenderStandingState {} impl StateProcessingHandler for DefenderStandingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { let ball_ops = ctx.ball(); if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Running, )); } // Emergency: if ball is nearby, stopped, and unowned, go for it immediately if ball_ops.should_take_ball_immediately() { return Some(StateChangeResult::with_defender_state( DefenderState::TakeBall, )); } // Check for nearby opponents with the ball - press them aggressively if let Some(opponent) = ctx.players().opponents().with_ball().next() { let distance_to_opponent = opponent.distance(ctx); if distance_to_opponent < TACKLE_DISTANCE { return Some(StateChangeResult::with_defender_state( DefenderState::Tackling, )); } // Context-aware pressing distance: tighter in defensive third let pressing_threshold = if ctx.ball().on_own_side() && ctx.ball().distance_to_own_goal() < ctx.context.field_size.width as f32 * FIELD_THIRD_THRESHOLD { PRESSING_DISTANCE_DEFENSIVE_THIRD } else { PRESSING_DISTANCE }; if distance_to_opponent < pressing_threshold { return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } } // Check for aerial balls requiring heading if self.should_head_ball(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Heading, )); } // Check for shots requiring blocking if self.should_block_shot(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Blocking, )); } // Check for ball interception opportunities if ctx.ball().on_own_side() { if ball_ops.is_towards_player_with_angle(0.8) && ball_ops.distance() < INTERCEPTION_DISTANCE { return Some(StateChangeResult::with_defender_state( DefenderState::Intercepting, )); } // Only press if opponent has the ball, not just if team doesn't have control if let Some(_opponent) = ctx.players().opponents().with_ball().next() { if ball_ops.distance() < PRESSING_DISTANCE { return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } } } if self.should_push_up(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::PushingUp, )); } if self.should_hold_defensive_line(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )); } // Check for dangerous runs before covering space // This ensures defenders pick up attacking threats early if let Some(_dangerous_runner) = self.scan_for_dangerous_runs(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Marking, )); } if self.should_cover_space(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Covering, )); } // Walk or hold line more readily on attacking side if self.should_transition_to_walking(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Walking, )); } if ctx.in_state_time > 30 { return Some(StateChangeResult::with_defender_state( DefenderState::Walking, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { 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::zeros()) } fn process_conditions(&self, ctx: ConditionContext) { // Standing still allows for condition recovery DefenderCondition::with_velocity(ActivityIntensity::Recovery).process(ctx); } } impl DefenderStandingState { fn should_transition_to_walking(&self, ctx: &StateProcessingContext) -> bool { let player_ops = ctx.player(); let ball_ops = ctx.ball(); let is_tired = player_ops.is_tired(); let standing_too_long = ctx.in_state_time > STANDING_TIME_LIMIT; let ball_far_away = ball_ops.distance() > INTERCEPTION_DISTANCE * 2.0; // Fixed: inverted logic - should check if there are NO nearby threats let no_immediate_threat = ctx .players() .opponents() .nearby(CLEARING_DISTANCE) .next() .is_none(); let close_to_optimal_position = player_ops.distance_from_start_position() < WALK_DISTANCE_THRESHOLD; let team_in_control = ctx.team().is_control_ball(); (is_tired || standing_too_long) && (ball_far_away || close_to_optimal_position) && no_immediate_threat && team_in_control } fn should_push_up(&self, ctx: &StateProcessingContext) -> bool { let ball_ops = ctx.ball(); let player_ops = ctx.player(); let ball_in_attacking_third = ball_ops.distance_to_opponent_goal() < ctx.context.field_size.width as f32 * FIELD_THIRD_THRESHOLD; let team_in_possession = ctx.team().is_control_ball(); let defender_not_last_man = !self.is_last_defender(ctx); ball_in_attacking_third && team_in_possession && defender_not_last_man && player_ops.distance_from_start_position() < ctx.context.field_size.width as f32 * 0.25 } fn should_hold_defensive_line(&self, ctx: &StateProcessingContext) -> bool { ctx.player().defensive().should_hold_defensive_line() } fn should_cover_space(&self, ctx: &StateProcessingContext) -> bool { let ball_ops = ctx.ball(); let player_ops = ctx.player(); let ball_in_middle_third = ball_ops.distance_to_opponent_goal() > ctx.context.field_size.width as f32 * FIELD_THIRD_THRESHOLD && ball_ops.distance_to_own_goal() > ctx.context.field_size.width as f32 * FIELD_THIRD_THRESHOLD; // Check for both immediate threats AND dangerous runs let no_immediate_threat = ctx .players() .opponents() .nearby(MARKING_DISTANCE) .next() .is_none(); let no_dangerous_runs = self.scan_for_dangerous_runs(ctx).is_none(); let not_in_optimal_position = player_ops.distance_from_start_position() > WALK_DISTANCE_THRESHOLD; ball_in_middle_third && no_immediate_threat && no_dangerous_runs && not_in_optimal_position } /// Scan for opponents making dangerous runs toward goal fn scan_for_dangerous_runs(&self, ctx: &StateProcessingContext) -> Option<MatchPlayerLite> { ctx.player().defensive().scan_for_dangerous_runs() } fn is_last_defender(&self, ctx: &StateProcessingContext) -> bool { ctx.player().defensive().is_last_defender() } fn should_head_ball(&self, ctx: &StateProcessingContext) -> bool { let ball_position = ctx.tick_context.positions.ball.position; let ball_distance = ctx.ball().distance(); // Ball must be at heading height and close enough ball_position.z > HEADING_HEIGHT && ball_distance < HEADING_DISTANCE && ctx.ball().is_towards_player_with_angle(0.6) } fn should_block_shot(&self, ctx: &StateProcessingContext) -> bool { let ball_distance = ctx.ball().distance(); let ball_velocity = ctx.tick_context.positions.ball.velocity; let ball_speed = ball_velocity.norm(); // Check if ball is moving fast towards the defender if ball_speed < 8.0 || ball_distance > BLOCKING_DISTANCE { return false; } // Check if ball is coming towards player if !ctx.ball().is_towards_player_with_angle(0.7) { return false; } // Check if opponent recently shot (ball is fast and low) let ball_height = ctx.tick_context.positions.ball.position.z; if ball_height > 2.0 { return false; // Too high, not a shot } // Check if there's an opponent nearby who might have shot let opponent_nearby = ctx .players() .opponents() .nearby(30.0) .any(|opp| opp.has_ball(ctx) || opp.distance(ctx) < 15.0); opponent_nearby && ball_distance < BLOCKING_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/defenders/states/common/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/common/mod.rs
use crate::r#match::engine::player::strategies::common::{ ActivityIntensityConfig, ConditionProcessor, LOW_CONDITION_THRESHOLD, FIELD_PLAYER_JADEDNESS_INTERVAL, JADEDNESS_INCREMENT, }; /// Defender-specific activity intensity configuration pub struct DefenderConfig; impl ActivityIntensityConfig for DefenderConfig { fn very_high_fatigue() -> f32 { 8.0 // Explosive actions tire quickly } fn high_fatigue() -> f32 { 5.0 // Base from running state } fn moderate_fatigue() -> f32 { 3.0 } fn low_fatigue() -> f32 { 1.0 } fn recovery_rate() -> f32 { -3.0 } fn sprint_multiplier() -> f32 { 1.5 // Sprinting } 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 } } /// Defender condition processor (type alias for clarity) pub type DefenderCondition = ConditionProcessor<DefenderConfig>; // 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/defenders/states/blocking/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/blocking/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const BLOCK_DISTANCE_THRESHOLD: f32 = 2.0; // Maximum distance to attempt a block (in meters) #[derive(Default)] pub struct DefenderBlockingState {} impl StateProcessingHandler for DefenderBlockingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Standing )); } if ctx.ball().distance() > BLOCK_DISTANCE_THRESHOLD { return Some(StateChangeResult::with_defender_state( DefenderState::Standing, )); } if ctx.ball().is_towards_player_with_angle(0.9) { // Defender is not in the path of the ball return Some(StateChangeResult::with_defender_state( DefenderState::Standing, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network logic if necessary None } fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Defender may need to adjust position slightly to attempt block // Calculate minimal movement towards the blocking position // For simplicity, we'll assume the defender remains stationary Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Blocking is standing ready to block - low intensity with recovery DefenderCondition::new(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/defenders/states/takeball/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/takeball/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; // TakeBall distance and threshold 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 DefenderTakeBallState {} impl StateProcessingHandler for DefenderTakeBallState { 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_defender_state( DefenderState::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_defender_state( DefenderState::Returning, )); } // 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 prepare to defend if opponent_distance < ball_distance - OPPONENT_ADVANTAGE_THRESHOLD { return Some(StateChangeResult::with_defender_state( DefenderState::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_defender_state( DefenderState::HoldingLine, )); } } // 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: 0.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 = 10.0; const MIN_SEPARATION_FACTOR: f32 = 0.25; // Minimum 25% separation - allows closer approach with larger claiming radius let distance_to_ball = (ctx.player.position - target).magnitude(); let separation_factor = if distance_to_ball < BALL_CLAIM_DISTANCE { // Reduce separation force when close to ball, but never below 25% let linear_factor = distance_to_ball / BALL_CLAIM_DISTANCE; MIN_SEPARATION_FACTOR + (linear_factor * (1.0 - MIN_SEPARATION_FACTOR)) } else { 1.0 }; 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 involves movement towards ball - moderate intensity DefenderCondition::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/defenders/states/clearing/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/clearing/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::player::state::PlayerState; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; #[derive(Default)] pub struct DefenderClearingState {} impl StateProcessingHandler for DefenderClearingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { let mut state = StateChangeResult::with(PlayerState::Defender(DefenderState::Standing)); // Get player's position and ball's current position let player_position = ctx.player.position; let ball_position = ctx.tick_context.positions.ball.position; let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; let field_center_x = field_width / 2.0; let field_center_y = field_height / 2.0; // Check if ball is at or near a boundary const BOUNDARY_THRESHOLD: f32 = 5.0; let at_left_boundary = ball_position.x <= BOUNDARY_THRESHOLD; let at_right_boundary = ball_position.x >= field_width - BOUNDARY_THRESHOLD; let at_top_boundary = ball_position.y >= field_height - BOUNDARY_THRESHOLD; let at_bottom_boundary = ball_position.y <= BOUNDARY_THRESHOLD; let at_boundary = at_left_boundary || at_right_boundary || at_top_boundary || at_bottom_boundary; // Determine the target position for clearing let target_position = if at_boundary { // If at boundary, clear toward center of field to escape the corner/edge // Add variation to avoid predictability let offset_x = if at_left_boundary { field_width * 0.3 } else if at_right_boundary { field_width * 0.7 } else { field_center_x }; let offset_y = if at_top_boundary { field_height * 0.7 } else if at_bottom_boundary { field_height * 0.3 } else { field_center_y }; Vector3::new(offset_x, offset_y, 0.0) } else { // Normal clear: opposite side of field if player_position.x < field_center_x { Vector3::new(field_width * 0.8, ball_position.y, 0.0) } else { Vector3::new(field_width * 0.2, ball_position.y, 0.0) } }; // Calculate the direction vector to the target position let direction_to_target = (target_position - ball_position).normalize(); // Use higher clearing speed - especially critical when stuck at boundary let clear_speed = if at_boundary { 80.0 } else { 50.0 }; // Calculate horizontal velocity let horizontal_velocity = direction_to_target * clear_speed; // Add upward velocity for aerial clearance // Higher lift when at boundary to ensure ball escapes let z_velocity = if at_boundary { 15.0 } else { 8.0 }; // Combine horizontal and vertical components let ball_velocity = Vector3::new( horizontal_velocity.x, horizontal_velocity.y, z_velocity, ); // Add the clear ball event with the calculated velocity state .events .add_player_event(PlayerEvent::ClearBall(ball_velocity)); // Return the updated state with the clearing event Some(state) } 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) { // Clearing involves powerful kicking action - explosive effort DefenderCondition::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/defenders/states/shooting/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/shooting/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::events::Event; use crate::r#match::player::events::{PlayerEvent, ShootingEventContext}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; #[derive(Default)] pub struct DefenderShootingState {} impl StateProcessingHandler for DefenderShootingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { Some(StateChangeResult::with_defender_state_and_event( DefenderState::Standing, Event::PlayerEvent(PlayerEvent::Shoot( ShootingEventContext::new() .with_player_id(ctx.player.id) .with_target(ctx.player().shooting_direction()) .with_reason("DEF_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 explosive - powerful leg action requires significant energy DefenderCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl DefenderShootingState {}
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/defenders/states/returning/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/returning/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, MATCH_TIME_MS, }; use nalgebra::Vector3; #[derive(Default)] pub struct DefenderReturningState {} impl StateProcessingHandler for DefenderReturningState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { if ctx.player.has_ball(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Passing, )); } if ctx.player().distance_from_start_position() < 10.0 { return Some(StateChangeResult::with_defender_state( DefenderState::Standing, )); } if ctx.team().is_control_ball() { if ctx.player().distance_from_start_position() < 5.0 { return Some(StateChangeResult::with_defender_state( DefenderState::Standing, )); } } else { // 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_defender_state( DefenderState::TakeBall, )); } } if ctx.ball().distance() < 100.0{ return Some(StateChangeResult::with_defender_state( DefenderState::Tackling, )); } if ctx.ball().is_towards_player_with_angle(0.8) && ctx.ball().distance() < 200.0 { return Some(StateChangeResult::with_defender_state( DefenderState::Intercepting )); } if ctx.team().is_loosing() && ctx.context.total_match_time > (MATCH_TIME_MS - 180) && ctx.ball().distance() < 30.0 { return Some(StateChangeResult::with_defender_state( DefenderState::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 to position involves jogging back - moderate intensity DefenderCondition::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/defenders/states/pressing/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/pressing/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; const TACKLING_DISTANCE_THRESHOLD: f32 = 5.0; // Distance within which the defender can tackle (increased from 3.0) const PRESSING_DISTANCE_THRESHOLD: f32 = 50.0; // Max distance to consider pressing const PRESSING_DISTANCE_DEFENSIVE_THIRD: f32 = 35.0; // Tighter in defensive third const CLOSE_PRESSING_DISTANCE: f32 = 15.0; // Distance for aggressive pressing const STAMINA_THRESHOLD: f32 = 40.0; // Increased from 30.0 - prevent overexertion const FIELD_THIRD_THRESHOLD: f32 = 0.33; #[derive(Default)] pub struct DefenderPressingState {} impl StateProcessingHandler for DefenderPressingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if the defender has enough stamina to continue pressing let stamina = ctx.player.player_attributes.condition_percentage() as f32; if stamina < STAMINA_THRESHOLD { // Transition to Resting state if stamina is low return Some(StateChangeResult::with_defender_state( DefenderState::Resting, )); } // 2. Identify the opponent player with the ball if let Some(opponent) = ctx.players().opponents().with_ball().next() { let distance_to_opponent = opponent.distance(ctx); // 4. If close enough to tackle, transition to Tackling state if distance_to_opponent < TACKLING_DISTANCE_THRESHOLD { return Some(StateChangeResult::with_defender_state( DefenderState::Tackling, )); } // Context-aware pressing distance: tighter in defensive third let pressing_threshold = if ctx.ball().on_own_side() && ctx.ball().distance_to_own_goal() < ctx.context.field_size.width as f32 * FIELD_THIRD_THRESHOLD { PRESSING_DISTANCE_DEFENSIVE_THIRD } else { PRESSING_DISTANCE_THRESHOLD }; // 5. If the opponent is too far away, stop pressing if distance_to_opponent > pressing_threshold { // Transition back to HoldingLine or appropriate state return Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )); } // 6. Check if pressing is creating dangerous gaps if self.is_creating_dangerous_gap(ctx, opponent.position) { // Drop back to maintain defensive shape return Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )); } // 7. Continue pressing (no state change) None } else { // No opponent with the ball found (perhaps ball is free) // Transition back to appropriate state Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network processing if needed None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Move towards the opponent with the ball let opponents = ctx.players().opponents(); let mut opponent_with_ball = opponents.with_ball(); if let Some(opponent) = opponent_with_ball.next() { let distance_to_opponent = opponent.distance(ctx); // Calculate direction towards the opponent let direction = (opponent.position - ctx.player.position).normalize(); // Set speed based on player's acceleration and pace let speed = ctx.player.skills.physical.pace; // Use pace attribute let pressing_velocity = direction * speed; // Reduce separation velocity when actively pressing to allow close approach // When very close, disable separation entirely to enable tackling let separation = if distance_to_opponent < CLOSE_PRESSING_DISTANCE { ctx.player().separation_velocity() * 0.2 // Minimal separation when close } else { ctx.player().separation_velocity() * 0.5 // Reduced separation when pressing }; return Some(pressing_velocity + separation); } None } fn process_conditions(&self, ctx: ConditionContext) { // Pressing is very demanding - high intensity chasing and pressure DefenderCondition::with_velocity(ActivityIntensity::High).process(ctx); } } impl DefenderPressingState { /// Check if pressing is creating a dangerous gap in the defensive line fn is_creating_dangerous_gap(&self, ctx: &StateProcessingContext, _opponent_pos: Vector3<f32>) -> bool { let own_goal = ctx.ball().direction_to_own_goal(); let player_pos = ctx.player.position; // Get all defenders let defenders: Vec<_> = ctx.players().teammates().defenders().collect(); if defenders.is_empty() { return false; } // Calculate the average defensive line position let avg_defender_x = defenders.iter().map(|d| d.position.x).sum::<f32>() / defenders.len() as f32; // Check if this defender is significantly ahead of the defensive line let distance_ahead_of_line = if own_goal.x < ctx.context.field_size.width as f32 / 2.0 { avg_defender_x - player_pos.x // Defending left side } else { player_pos.x - avg_defender_x // Defending right side }; // If more than 25m ahead of the line, might be creating a gap if distance_ahead_of_line > 25.0 { // Check if there are dangerous opponents behind the presser let dangerous_opponents = ctx.players() .opponents() .nearby(70.0) .filter(|opp| { // Check if opponent is between presser and goal let opp_distance_to_goal = (opp.position - own_goal).magnitude(); let presser_distance_to_goal = (player_pos - own_goal).magnitude(); opp_distance_to_goal < presser_distance_to_goal }) .count(); // If there are 2+ dangerous opponents behind, pressing creates a gap return dangerous_opponents >= 2; } 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/defenders/states/pushingup/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/pushingup/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; const TACKLING_DISTANCE_THRESHOLD: f32 = 2.0; const PRESSING_DISTANCE_THRESHOLD: f32 = 20.0; const STAMINA_THRESHOLD: f32 = 30.0; const FIELD_THIRD_THRESHOLD: f32 = 0.33; const MAX_PUSH_UP_DISTANCE: f32 = 0.7; const PUSH_UP_HYSTERESIS: f32 = 0.05; // Hysteresis to prevent rapid state changes #[derive(Default)] pub struct DefenderPushingUpState {} impl StateProcessingHandler for DefenderPushingUpState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { let ball_ops = ctx.ball(); if ball_ops.on_own_side() { return Some(StateChangeResult::with_defender_state( DefenderState::TrackingBack, )); } if !ctx.team().is_control_ball() { if let Some(opponent) = ctx.players().opponents().nearby(TACKLING_DISTANCE_THRESHOLD).next() { let distance_to_opponent = ctx .tick_context .distances .get(opponent.id, ctx.player.id); if distance_to_opponent <= TACKLING_DISTANCE_THRESHOLD { return Some(StateChangeResult::with_defender_state( DefenderState::Tackling, )); } if distance_to_opponent <= PRESSING_DISTANCE_THRESHOLD && ctx.player.skills.physical.stamina > STAMINA_THRESHOLD { return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } } // Instead of immediately switching to Covering, introduce a transition state return Some(StateChangeResult::with_defender_state( DefenderState::Covering, )); } if self.should_retreat(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::TrackingBack, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { let optimal_position = self.calculate_optimal_pushing_up_position(ctx); Some( SteeringBehavior::Pursuit { target: optimal_position, target_velocity: Vector3::zeros(), // Static target position } .calculate(ctx.player) .velocity, ) } fn process_conditions(&self, ctx: ConditionContext) { // Pushing up involves moving forward with the team - moderate intensity DefenderCondition::with_velocity(ActivityIntensity::Moderate).process(ctx); } } impl DefenderPushingUpState { fn should_retreat(&self, ctx: &StateProcessingContext) -> bool { let field_width = ctx.context.field_size.width as f32; let max_push_up_x = field_width * (MAX_PUSH_UP_DISTANCE + PUSH_UP_HYSTERESIS); ctx.player.position.x > max_push_up_x || self.is_last_defender(ctx) } fn is_last_defender(&self, ctx: &StateProcessingContext) -> bool { ctx.players() .teammates() .defenders() .all(|d| d.position.x <= ctx.player.position.x) } fn calculate_optimal_pushing_up_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let ball_position = ctx.tick_context.positions.ball.position; let player_position = ctx.player.position; let field_width = ctx.context.field_size.width as f32; let field_height = ctx.context.field_size.height as f32; let attacking_third_center = Vector3::new( field_width * (1.0 - FIELD_THIRD_THRESHOLD / 2.0), field_height * 0.5, 0.0, ); let teammates = ctx.players().teammates(); let attacking_teammates = teammates.all().into_iter() .filter(|p| p.position.x > field_width * 0.5) .collect::<Vec<_>>(); let avg_attacking_position = if !attacking_teammates.is_empty() { attacking_teammates .iter() .fold(Vector3::zeros(), |acc, p| acc + p.position) / attacking_teammates.len() as f32 } else { attacking_third_center }; let support_position = (ball_position + avg_attacking_position) * 0.5; let optimal_position = (support_position * 0.5 + attacking_third_center * 0.3 + player_position * 0.2) .cap_magnitude(field_width * MAX_PUSH_UP_DISTANCE); Vector3::new( optimal_position .x .clamp(field_width * 0.5, field_width * MAX_PUSH_UP_DISTANCE), optimal_position.y.clamp(0.0, field_height), 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/engine/player/strategies/defenders/states/offside_trap/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/offside_trap/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ConditionContext, MatchPlayer, MatchPlayerLite, PlayerSide, StateChangeResult, StateProcessingContext, StateProcessingHandler}; use nalgebra::Vector3; use rand::Rng; const OFFSIDE_TRAP_DISTANCE: f32 = 5.0; // Distance to move forward to set the trap const OFFSIDE_TRAP_SPEED_MULTIPLIER: f32 = 1.2; // Speed multiplier when executing the trap #[derive(Default)] pub struct DefenderOffsideTrapState {} impl StateProcessingHandler for DefenderOffsideTrapState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // 1. Check if the team is defending a lead and there is limited time remaining let defending_lead = ctx.team().is_loosing() && ctx.context.time.is_running_out(); // 2. Check if the opponent's playing style and formation are suitable for an offside trap let opponent_style_suitable = self.is_opponent_style_suitable(ctx); // 3. Evaluate the defensive line's cohesion and communication let defensive_line_cohesion = self.evaluate_defensive_line_cohesion(ctx); // 4. Consider the individual defender's attributes let defender_attributes_suitable = self.are_defender_attributes_suitable(ctx); if defending_lead && opponent_style_suitable && defensive_line_cohesion && defender_attributes_suitable { // Execute the offside trap let trap_success = self.attempt_offside_trap(ctx); if trap_success { // Offside trap is successful Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )) } else { // Offside trap failed; opponent may be through on goal Some(StateChangeResult::with_defender_state( DefenderState::TrackingBack, )) } } else { // Conditions for setting up an offside trap are not met Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network logic if necessary None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Move forward smoothly to execute the offside trap let target_position = self.calculate_offside_trap_target_position(ctx); let current_position = ctx.player.position; let direction = (target_position - current_position).normalize(); // Calculate the distance to the target position let distance_to_target = (target_position - current_position).magnitude(); // Define a threshold distance for smooth deceleration let deceleration_threshold = 100.0; // Calculate the base speed based on the player's pace attribute let base_speed = ctx.player.skills.physical.pace; // Adjust the speed based on player attributes let agility_factor = ctx.player.skills.physical.agility / 20.0; let acceleration_factor = ctx.player.skills.physical.acceleration / 20.0; let stamina_factor = ctx.player.player_attributes.condition_percentage() as f32 / 100.0; let adjusted_speed = base_speed * agility_factor * acceleration_factor * stamina_factor; // Calculate the target speed based on the distance to the target position let target_speed = if distance_to_target <= deceleration_threshold { // Smoothly decelerate as the player approaches the target position adjusted_speed * OFFSIDE_TRAP_SPEED_MULTIPLIER * (distance_to_target / deceleration_threshold) } else { // Move at the adjusted offside trap speed adjusted_speed * OFFSIDE_TRAP_SPEED_MULTIPLIER }; // Define an acceleration factor and a blending factor let acceleration_factor = 0.1; let blending_factor = 0.8; // Calculate the target velocity let target_velocity = direction * target_speed; // Update the player's velocity based on the acceleration factor and blending factor let current_velocity = ctx.player.velocity; let new_velocity = current_velocity + (target_velocity - current_velocity) * acceleration_factor; let blended_velocity = current_velocity * (1.0 - blending_factor) + new_velocity * blending_factor; Some(blended_velocity) } fn process_conditions(&self, ctx: ConditionContext) { // Offside trap involves quick coordinated movement - moderate intensity DefenderCondition::with_velocity(ActivityIntensity::Moderate).process(ctx); } } impl DefenderOffsideTrapState { fn is_opponent_style_suitable(&self, ctx: &StateProcessingContext) -> bool { // Offside trap works best against certain opponent styles: // - Teams with fast attackers who run in behind // - Teams that play with high attacking lines // - Teams without exceptional passing/vision to break the trap let opponent_attackers: Vec<MatchPlayerLite> = ctx .players() .opponents() .all() .filter(|p| { // Filter for attackers (those positioned in attacking areas) let ball_ops = ctx.ball(); let distance_to_our_goal = (p.position - ball_ops.direction_to_own_goal()).magnitude(); distance_to_our_goal > 200.0 // Attackers are usually far from our goal }) .collect(); if opponent_attackers.is_empty() { return true; // No attackers present, trap is safe } // Calculate average opponent attacker speed let player_ops = ctx.player(); let total_speed: f32 = opponent_attackers .iter() .map(|p| player_ops.skills(p.id).physical.pace) .sum(); let avg_opponent_speed = total_speed / opponent_attackers.len() as f32; // Calculate average opponent passing/vision let total_vision: f32 = opponent_attackers .iter() .map(|p| player_ops.skills(p.id).mental.vision) .sum(); let avg_opponent_vision = total_vision / opponent_attackers.len() as f32; // Trap is suitable if: // 1. Opponents are fast (70+) - they rely on pace, not passing // 2. OR opponents have low vision (<60) - can't break trap with passes // 3. AND there are not too many attackers (overwhelming the defense) let opponents_are_fast = avg_opponent_speed >= 70.0; let opponents_lack_vision = avg_opponent_vision < 60.0; let reasonable_attacker_count = opponent_attackers.len() <= 3; (opponents_are_fast || opponents_lack_vision) && reasonable_attacker_count } fn evaluate_defensive_line_cohesion(&self, ctx: &StateProcessingContext) -> bool { // Evaluate the defensive line's cohesion and communication let defenders: Vec<&MatchPlayer> = ctx.players().teammates().defenders().filter_map(|defender| { ctx.context.players.by_id(defender.id) }).collect(); // Calculate the average experience and communication attributes of the defenders let total_experience = defenders.iter().map(|p| p.player_attributes.potential_ability as u32).sum::<u32>(); let total_communication = defenders.iter().map(|p| p.skills.mental.teamwork as u32).sum::<u32>(); let avg_experience = total_experience as f32 / defenders.len() as f32; let avg_communication = total_communication as f32 / defenders.len() as f32; // Check if the average experience and communication exceed certain thresholds // Adjust the thresholds based on your specific game balance avg_experience >= 70.0 && avg_communication >= 75.0 } fn are_defender_attributes_suitable(&self, ctx: &StateProcessingContext) -> bool { // Check if the individual defender's attributes are suitable for executing an offside trap let positioning = ctx.player.skills.mental.positioning; let anticipation = ctx.player.skills.mental.anticipation; let speed = ctx.player.skills.physical.pace; // Check if the defender's attributes exceed certain thresholds // Adjust the thresholds based on your specific game balance positioning >= 15.0 && anticipation >= 15.0 && speed >= 70.0 } fn attempt_offside_trap(&self, ctx: &StateProcessingContext) -> bool { // Get the positions of opponents and the defensive line let defensive_line_position = self.calculate_defensive_line_position(ctx); let opponent_positions: Vec<f32> = ctx .players() .opponents() .all() .map(|p| p.position.x) .collect(); // Calculate the success probability based on teamwork and concentration let teamwork = ctx.player.skills.mental.teamwork as f32 / 20.0; let concentration = ctx.player.skills.mental.concentration as f32 / 20.0; let mut rng = rand::rng(); let success_probability = (teamwork + concentration) / 2.0; // Determine the offside trap outcome let offside_trap_successful = rng.random::<f32>() < success_probability; if offside_trap_successful { // Check if any opponent is caught offside let caught_offside = opponent_positions.iter().any(|&x| { if ctx.player.side == Some(PlayerSide::Left) { x > defensive_line_position } else { x < defensive_line_position } }); caught_offside } else { false } } fn calculate_defensive_line_position(&self, ctx: &StateProcessingContext) -> f32 { let defenders: Vec<MatchPlayerLite> = ctx .players() .teammates() .defenders() .collect(); let sum_x: f32 = defenders.iter().map(|p| p.position.x).sum(); let avg_x = sum_x / defenders.len() as f32; // Adjust the defensive line position based on the team's tactics // You can modify this calculation based on your specific game mechanics let adjustment = 5.0; // Adjust this value as needed if ctx.player.side == Some(PlayerSide::Left) { avg_x + adjustment } else { avg_x - adjustment } } fn calculate_offside_trap_target_position(&self, ctx: &StateProcessingContext) -> Vector3<f32> { let player_position = ctx.player.position; let defensive_line_position = self.calculate_defensive_line_position(ctx); // Calculate the target position for the offside trap if ctx.player.side.unwrap() == PlayerSide::Left { Vector3::new(defensive_line_position + OFFSIDE_TRAP_DISTANCE, player_position.y, 0.0) } else { Vector3::new(defensive_line_position - OFFSIDE_TRAP_DISTANCE, player_position.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/engine/player/strategies/defenders/states/heading/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/heading/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, ShootingEventContext}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, }; use nalgebra::Vector3; use crate::r#match::events::Event; const HEADING_HEIGHT_THRESHOLD: f32 = 1.5; // Minimum height to consider heading (meters) const HEADING_DISTANCE_THRESHOLD: f32 = 1.5; // Maximum distance to the ball for heading (meters) const HEADING_SUCCESS_THRESHOLD: f32 = 0.5; // Threshold for heading success based on skills #[derive(Default)] pub struct DefenderHeadingState {} impl StateProcessingHandler for DefenderHeadingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { let ball_position = ctx.tick_context.positions.ball.position; if ctx.ball().distance() > HEADING_DISTANCE_THRESHOLD { // Transition back to appropriate state (e.g., HoldingLine) return Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )); } // Check if the ball is at a height suitable for heading if ball_position.z < HEADING_HEIGHT_THRESHOLD { // Ball is too low to head return Some(StateChangeResult::with_defender_state( DefenderState::Standing, )); } // 2. Attempt to head the ball if self.attempt_heading(ctx) { Some(StateChangeResult::with_defender_state_and_event(DefenderState::HoldingLine, Event::PlayerEvent(PlayerEvent::Shoot( ShootingEventContext::new() .with_player_id(ctx.player.id) .with_target(ctx.player().shooting_direction()) .with_reason("DEF_HEADING") .build(ctx) )))) } else { // Heading failed; transition to appropriate state (e.g., Standing) Some(StateChangeResult::with_defender_state( DefenderState::Standing, )) } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Implement neural network logic if necessary None } fn velocity(&self, _ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // Defender is stationary while attempting to head the ball Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Heading involves jumping and explosive neck/body movement DefenderCondition::new(ActivityIntensity::VeryHigh).process(ctx); } } impl DefenderHeadingState { /// Determines if the defender successfully heads the ball based on skills and random chance. fn attempt_heading(&self, ctx: &StateProcessingContext) -> bool { let heading_skill = ctx.player.skills.technical.heading / 20.0; // Normalize skill to [0,1] let jumping_skill = ctx.player.skills.physical.jumping / 20.0; let overall_skill = (heading_skill + jumping_skill) / 2.0; // Simulate chance of success let random_value: f32 = rand::random(); // Generates a random float between 0.0 and 1.0 overall_skill > (random_value + HEADING_SUCCESS_THRESHOLD) } }
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/defenders/states/tracking_back/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/tracking_back/mod.rs
use crate::r#match::defenders::states::DefenderState; use crate::r#match::defenders::states::common::{DefenderCondition, ActivityIntensity}; use crate::r#match::{ ConditionContext, PlayerDistanceFromStartPosition, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, MATCH_TIME_MS, }; use nalgebra::Vector3; const CLOSE_TO_START_DISTANCE: f32 = 10.0; const BALL_INTERCEPTION_DISTANCE: f32 = 30.0; #[derive(Default)] pub struct DefenderTrackingBackState {} impl StateProcessingHandler for DefenderTrackingBackState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Check if the defender has reached their starting position if ctx.player().distance_from_start_position() < CLOSE_TO_START_DISTANCE { return Some(StateChangeResult::with_defender_state( DefenderState::Standing, )); } // Check if the ball is close and moving towards the player if ctx.ball().distance() < BALL_INTERCEPTION_DISTANCE && ctx.ball().is_towards_player() { return Some(StateChangeResult::with_defender_state( DefenderState::Intercepting, )); } // If the team is losing and there's little time left, consider a more aggressive stance if ctx.team().is_loosing() && ctx.context.total_match_time > (MATCH_TIME_MS - 300) { return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } // If the player is tired, switch to a less demanding state if ctx.player().is_tired() { return Some(StateChangeResult::with_defender_state( DefenderState::HoldingLine, )); } // If the ball is on the team's own side, prioritize defensive positioning if ctx.ball().on_own_side() { match ctx.player().position_to_distance() { PlayerDistanceFromStartPosition::Big => None, // Continue tracking back PlayerDistanceFromStartPosition::Medium => Some( StateChangeResult::with_defender_state(DefenderState::HoldingLine), ), PlayerDistanceFromStartPosition::Small => Some( StateChangeResult::with_defender_state(DefenderState::Standing), ), } } else { None // Continue tracking back if the ball is on the opponent's side } } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { let start_position = ctx.player.start_position; let distance_from_start = ctx.player().distance_from_start_position(); // Calculate urgency based on game situation let urgency = if ctx.ball().on_own_side() { // Ball on own side - more urgent to get back 1.5 } else if ctx.team().is_loosing() && ctx.context.total_match_time > (MATCH_TIME_MS - 300) { // Losing late in game - less urgent to defend 0.8 } else { 1.0 }; // Use Arrive behavior with slowing distance based on how far we are let slowing_distance = if distance_from_start > 50.0 { 15.0 // Far away - longer slowing distance } else { 10.0 // Close - shorter slowing distance }; Some( SteeringBehavior::Arrive { target: start_position, slowing_distance, } .calculate(ctx.player) .velocity * urgency, ) } fn process_conditions(&self, ctx: ConditionContext) { // Tracking back is running back to defensive position - moderate intensity DefenderCondition::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/defenders/states/passing/mod.rs
src/core/src/match/engine/player/strategies/defenders/states/passing/mod.rs
use crate::r#match::defenders::states::common::{ActivityIntensity, DefenderCondition}; use crate::r#match::defenders::states::DefenderState; use crate::r#match::events::Event; use crate::r#match::player::events::{PassingEventContext, PlayerEvent}; use crate::r#match::{ ConditionContext, StateChangeResult, StateProcessingContext, StateProcessingHandler, SteeringBehavior, }; use nalgebra::Vector3; #[derive(Default)] pub struct DefenderPassingState {} impl StateProcessingHandler for DefenderPassingState { fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult> { // Check if the defender still has the ball if !ctx.player.has_ball(ctx) { // Lost possession, transition to appropriate state return Some(StateChangeResult::with_defender_state( DefenderState::Pressing, )); } // Under heavy pressure - make a quick decision if ctx.player().pressure().is_under_heavy_pressure() { return if let Some(safe_option) = ctx.player().passing().find_safe_pass_option() { Some(StateChangeResult::with_defender_state_and_event( DefenderState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(safe_option.id) .with_reason("DEF_PASSING_UNDER_PRESSURE") .build(ctx), )), )) } else { // No safe option, clear the ball Some(StateChangeResult::with_defender_state( DefenderState::Clearing, )) }; } // Normal passing situation - evaluate options more carefully if let Some((best_target, _reason)) = ctx.player().passing().find_best_pass_option() { // Execute the pass return Some(StateChangeResult::with_defender_state_and_event( DefenderState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(best_target.id) .with_reason("DEF_PASSING_NORMAL") .build(ctx), )), )); } // If no good passing option and close to own goal, consider clearing if ctx.player().defensive().in_dangerous_position() { return Some(StateChangeResult::with_defender_state( DefenderState::Clearing, )); } // If viable to dribble out of pressure if self.can_dribble_effectively(ctx) { return Some(StateChangeResult::with_defender_state( DefenderState::Running, )); } // Time-based fallback - don't get stuck in this state too long if ctx.in_state_time > 50 { // If we've been in this state for a while, make a decision // Try to find ANY teammate to pass to if let Some(any_teammate) = ctx.player().passing().find_any_teammate() { return Some(StateChangeResult::with_defender_state_and_event( DefenderState::Standing, Event::PlayerEvent(PlayerEvent::PassTo( PassingEventContext::new() .with_from_player_id(ctx.player.id) .with_to_player_id(any_teammate.id) .with_reason("DEF_PASSING_TIMEOUT") .build(ctx), )), )); } // If no teammates at all, clear the ball if ctx.in_state_time > 75 { return Some(StateChangeResult::with_defender_state( DefenderState::Clearing, )); } // Otherwise start running with the ball return Some(StateChangeResult::with_defender_state( DefenderState::Running, )); } None } fn process_slow(&self, _ctx: &StateProcessingContext) -> Option<StateChangeResult> { None } fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>> { // While holding the ball and looking for pass options, move slowly or stand still // If player should adjust position to find better passing angles if self.should_adjust_position(ctx) { // Calculate target position based on the defensive situation if let Some(target_position) = ctx.player().movement().calculate_better_passing_position() { return Some( SteeringBehavior::Arrive { target: target_position, slowing_distance: 5.0, // Short distance for subtle movement } .calculate(ctx.player) .velocity, ); } } // Default to very slow movement or stationary Some(Vector3::new(0.0, 0.0, 0.0)) } fn process_conditions(&self, ctx: ConditionContext) { // Passing is a quick action with minimal physical effort - very low intensity DefenderCondition::new(ActivityIntensity::Low).process(ctx); } } impl DefenderPassingState { /// Determine if player can effectively dribble out of the current situation fn can_dribble_effectively(&self, ctx: &StateProcessingContext) -> bool { // Check player's dribbling skill let dribbling_skill = ctx.player.skills.technical.dribbling / 20.0; // Check if there's space to dribble into let opposition_ahead = ctx.players().opponents().nearby(20.0).count(); // Defenders typically need more space and skill to dribble effectively dribbling_skill > 0.8 && opposition_ahead < 1 } /// Determine if player should adjust position to find better passing angles fn should_adjust_position(&self, ctx: &StateProcessingContext) -> bool { // Don't adjust if we've been in state too long if ctx.in_state_time > 40 { return false; } let under_immediate_pressure = ctx.players().opponents().exists(5.0); let has_clear_option = ctx.player().passing().find_best_pass_option().is_some(); // Adjust position if not under immediate pressure and no clear options !under_immediate_pressure && !has_clear_option } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false