write me a python game for a Pro evolution soccer type of game in pygame make it very…
- User
write me a python game for a Pro evolution soccer type of game in pygame make it very advanced just like the original without images or sounds
Assistant
Okay, this is a fascinating challenge! Recreating the feel of PES without graphics or sound means focusing intensely on the simulation logic, player attributes, AI decisions, and game flow, presented through text. We'll use Pygame primarily for its timing, event handling, and text rendering.
This will be a highly abstracted simulation. Think of it more like a complex text-based sports management sim crossed with a real-time strategy game's event log.
# -*- coding: utf-8 -*- import pygame import random import math import time # --- Constants --- PITCH_WIDTH = 100 PITCH_HEIGHT = 100 GAME_SPEED_FPS = 10 # Lower FPS for text simulation readability # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 128, 0) RED = (200, 0, 0) BLUE = (0, 0, 200) GRAY = (180, 180, 180) YELLOW = (200, 200, 0) # Game States STATE_PLAYING = 0 STATE_PAUSED = 1 STATE_HALF_TIME = 2 STATE_FINISHED = 3 # Player Roles (simplified) ROLE_GOALKEEPER = "GK" ROLE_DEFENDER = "DEF" ROLE_MIDFIELDER = "MID" ROLE_FORWARD = "FWD" # Player States STATE_IDLE = "Idle" STATE_MOVING = "Moving" STATE_DRIBBLING = "Dribbling" STATE_PASSING = "Passing" STATE_SHOOTING = "Shooting" STATE_TACKLING = "Tackling" STATE_CHASING = "Chasing Ball" STATE_MARKING = "Marking" # --- Helper Functions --- def distance(pos1, pos2): """Calculates Euclidean distance between two points.""" return math.sqrt((pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2) def normalize_vector(vector): """Normalizes a vector to unit length.""" mag = math.sqrt(vector[0]**2 + vector[1]**2) if mag == 0: return (0, 0) return (vector[0] / mag, vector[1] / mag) def get_random_direction(): """Returns a random normalized direction vector.""" angle = random.uniform(0, 2 * math.pi) return (math.cos(angle), math.sin(angle)) # --- Classes --- class Player: def __init__(self, name, number, team, role, skill, speed, stamina, position=(0, 0)): self.name = name self.number = number self.team = team # Reference to the Team object self.role = role self.skill = max(1, min(10, skill)) # Base skill (passing, shooting, tackling) self.speed = max(1, min(10, speed)) # Movement speed self.stamina = max(1, min(10, stamina)) # Affects performance over time self.max_stamina = self.stamina self.position = list(position) # x, y coordinates self.state = STATE_IDLE self.target_position = list(position) self.has_ball = False self.tackling_player = None # Player being tackled or tackling self.marking_player = None # Player being marked self.action_timer = 0 # Timer for actions like passing/shooting self.stamina_drain_timer = 0 # Timer for stamina drain def __str__(self): ball_status = "*" if self.has_ball else " " return f"{ball_status}{self.name:>15} ({self.number:<2}) [{self.role}] Pos:({self.position[0]:.1f},{self.position[1]:.1f}) State:{self.state:<12} Stam:{self.stamina:.1f}" def update_stamina(self): """Simulates stamina drain.""" self.stamina_drain_timer += 1 drain_rate = 0.01 + (1 / self.max_stamina) * 0.1 # Base drain + inverse relation to max stamina if self.state in [STATE_DRIBBLING, STATE_PASSING, STATE_SHOOTING, STATE_TACKLING, STATE_CHASING]: drain_rate *= 1.5 # Higher drain for active states if self.stamina_drain_timer >= (10 / self.speed): # Drain faster if speed is high self.stamina -= drain_rate self.stamina = max(0.1, self.stamina) # Keep minimum stamina self.stamina_drain_timer = 0 # Reduce effective skill/speed if stamina is low self.effective_speed = self.speed * (0.5 + 0.5 * (self.stamina / self.max_stamina)) self.effective_skill = self.skill * (0.5 + 0.5 * (self.stamina / self.max_stamina)) else: self.effective_speed = self.speed self.effective_skill = self.skill def move_towards(self, target_pos, speed_modifier=1.0): """Moves the player towards a target position.""" self.state = STATE_MOVING self.target_position = list(target_pos) move_vec = [target_pos[0] - self.position[0], target_pos[1] - self.position[1]] dist = distance(self.position, target_pos) if dist < 0.5: # Close enough self.position = list(target_pos) self.state = STATE_IDLE return move_speed = self.effective_speed * speed_modifier if move_speed == 0: return direction = normalize_vector(move_vec) step_dist = min(move_speed, dist) # Update position based on direction and step distance self.position[0] += direction[0] * step_dist self.position[1] += direction[1] * step_dist # Clamp position to pitch boundaries self.position[0] = max(0, min(PITCH_WIDTH, self.position[0])) self.position[1] = max(0, min(PITCH_HEIGHT, self.position[1])) if self.position == list(target_pos): self.state = STATE_IDLE def attempt_tackle(self, opponent_player): """Attempts to tackle the opponent.""" self.state = STATE_TACKLING self.tackling_player = opponent_player # Store who we are tackling # Check proximity for tackle if distance(self.position, opponent_player.position) > 1.5: self.state = STATE_CHASING # Move closer first self.target_position = list(opponent_player.position) # Move player slightly towards opponent move_speed = self.effective_speed * 0.8 move_vec = [opponent_player.position[0] - self.position[0], opponent_player.position[1] - self.position[1]] direction = normalize_vector(move_vec) step_dist = min(move_speed, 1.5) self.position[0] += direction[0] * step_dist self.position[1] += direction[1] * step_dist self.position[0] = max(0, min(PITCH_WIDTH, self.position[0])) self.position[1] = max(0, min(PITCH_HEIGHT, self.position[1])) return False # Tackle not yet executed # Tackle success chance based on skill difference and proximity tackle_chance = (self.effective_skill / 10) * 0.7 + (random.random() * 0.3) # Base chance + randomness skill_diff_factor = (self.effective_skill - opponent_player.effective_skill) / 10 tackle_chance += skill_diff_factor * 0.2 # Skill difference helps if random.random() < tackle_chance: print(f"[{game.current_time_str()}] Tackle Success! {self.name} dispossesses {opponent_player.name}.") opponent_player.has_ball = False self.has_ball = True self.tackling_player = None # Tackle finished self.state = STATE_IDLE return True else: print(f"[{game.current_time_str()}] Tackle Failed! {self.name} misses {opponent_player.name}.") self.tackling_player = None # Tackle finished (failed) self.state = STATE_IDLE return False def attempt_pass(self, target_player): """Attempts to pass the ball to a target player.""" self.state = STATE_PASSING self.action_timer = 5 # Simulate time taken for pass animation/execution # Success chance based on skill, distance, and opponent proximity dist = distance(self.position, target_player.position) pass_chance = (self.effective_skill / 10) * 0.85 # Base chance from skill pass_chance -= (dist / PITCH_WIDTH) * 0.3 # Longer passes are harder pass_chance += random.random() * 0.15 # Randomness # Check if opponents are nearby to intercept nearby_opponents = [p for p in self.team.opponent.players if distance(self.position, p.position) < 5.0] for opp in nearby_opponents: # Rudimentary check: if opponent is roughly between passer and receiver if distance(self.position, opp.position) + distance(opp.position, target_player.position) < dist + 1.0: pass_chance *= 0.7 # Interception makes it harder pass_chance = max(0.05, min(0.95, pass_chance)) # Clamp chance if random.random() < pass_chance: print(f"[{game.current_time_str()}] Pass Success! {self.name} to {target_player.name}.") self.has_ball = False target_player.has_ball = True target_player.state = STATE_IDLE # Receiver becomes idle momentarily self.state = STATE_IDLE return True else: print(f"[{game.current_time_str()}] Pass Failed! Interception or inaccurate pass.") # Maybe intercepting player gets the ball? Need AI logic for that. # For now, just resets state. Ball possession is lost. self.has_ball = False self.state = STATE_IDLE # Find closest player (could be opponent) to gain possession all_players = self.team.players + self.team.opponent.players closest_player = min(all_players, key=lambda p: distance(self.position, p.position)) if distance(self.position, closest_player.position) < 1.0: closest_player.has_ball = True print(f"[{game.current_time_str()}] Ball recovered by {closest_player.name}.") else: print(f"[{game.current_time_str()}] Ball loose!") # Ball technically is loose, game logic needs update for this return False def attempt_shoot(self): """Attempts to shoot at the goal.""" self.state = STATE_SHOOTING self.action_timer = 8 # Simulate shot animation/power-up # Success chance based on skill and distance dist = distance(self.position, self.team.goal_pos) shoot_chance = (self.effective_skill / 10) * 0.7 shoot_chance -= (dist / PITCH_WIDTH) * 0.4 # Far shots harder shoot_chance += random.random() * 0.2 # Randomness # Add factor for being near goal line? if self.position[0] < 5: # Near opponent goal shoot_chance += 0.1 shoot_chance = max(0.05, min(0.90, shoot_chance)) # Clamp chance # Simulate shot result if random.random() < shoot_chance: print(f"[{game.current_time_str()}] GOAL!!! {self.name} scores!") self.team.score += 1 self.has_ball = False self.state = STATE_IDLE game.trigger_goal_event() return True # Goal scored else: print(f"[{game.current_time_str()}] Shot Missed! Off target.") self.has_ball = False self.state = STATE_IDLE game.trigger_missed_shot_event() # Ball goes out, reset play return False # Shot missed def perform_action(self): """Internal logic for action timers (pass, shoot).""" if self.state in [STATE_PASSING, STATE_SHOOTING] and self.action_timer > 0: self.action_timer -= 1 if self.action_timer == 0: self.state = STATE_IDLE # Action completed class Ball: def __init__(self, position=(PITCH_WIDTH / 2, PITCH_HEIGHT / 2)): self.position = list(position) self.possessed_by = None # Player object who has the ball self.velocity = [0, 0] self.last_carrier = None # Player who last controlled the ball def update(self): """Updates ball position based on velocity or carrier.""" if self.possessed_by: # Ball moves with the player self.position = list(self.possessed_by.position) self.velocity = [0, 0] # Reset velocity when held else: # Ball travels freely if self.velocity != [0, 0]: self.position[0] += self.velocity[0] self.position[1] += self.velocity[1] # Simple deceleration self.velocity[0] *= 0.98 self.velocity[1] *= 0.98 # Stop if slow enough if abs(self.velocity[0]) < 0.05: self.velocity[0] = 0 if abs(self.velocity[1]) < 0.05: self.velocity[1] = 0 # Keep ball within bounds self.position[0] = max(0, min(PITCH_WIDTH, self.position[0])) self.position[1] = max(0, min(PITCH_HEIGHT, self.position[1])) if self.velocity == [0, 0]: self.find_closest_player_for_possession() else: # Ball is stationary and not possessed self.find_closest_player_for_possession() def find_closest_player_for_possession(self): """Finds the closest player to take possession if ball is loose.""" if self.possessed_by: return # Should not happen if ball is loose players_in_play = game.team1.players + game.team2.players closest_player = None min_dist = 1.5 # Max distance to pick up ball for player in players_in_play: dist = distance(self.position, player.position) if dist < min_dist: min_dist = dist closest_player = player if closest_player: # Check if player is actively trying to get the ball (e.g., chasing) if closest_player.state == STATE_CHASING or closest_player.state == STATE_IDLE: print(f"[{game.current_time_str()}] {closest_player.name} picks up the loose ball.") closest_player.has_ball = True self.possessed_by = closest_player self.velocity = [0, 0] closest_player.state = STATE_IDLE # Reset state after pickup class Team: def __init__(self, name, color, players_data, formation_strategy, goal_pos): self.name = name self.color = color self.players = [] self.score = 0 self.formation_strategy = formation_strategy # e.g., [4, 4, 2] self.opponent = None # Will be set later self.goal_pos = goal_pos # (x, y) position of the team's goal line center self.current_tactic = "balanced" # attacking, defensive, balanced self.players_data = players_data # List of player dicts for creation self._create_players() def _create_players(self): """Creates player objects based on data and formation.""" player_idx = 0 # Assign roles based loosely on formation (simplistic) num_fwd = self.formation_strategy[2] if len(self.formation_strategy) > 2 else 1 num_mid = self.formation_strategy[1] if len(self.formation_strategy) > 1 else 4 num_def = self.formation_strategy[0] if len(self.formation_strategy) > 0 else 4 num_gk = 1 # Sort players by skill to assign roles somewhat logically sorted_players_data = sorted(self.players_data, key=lambda p: p['skill'], reverse=True) current_role_idx = 0 roles_to_assign = ([ROLE_FORWARD] * num_fwd + [ROLE_MIDFIELDER] * num_mid + [ROLE_DEFENDER] * num_def + [ROLE_GOALKEEPER] * num_gk) # Assign GK first gk_data = next((p for p in sorted_players_data if p['role'] == ROLE_GOALKEEPER), sorted_players_data[0]) if gk_data: player = Player(gk_data['name'], gk_data['number'], self, ROLE_GOALKEEPER, gk_data['skill'], gk_data['speed'], gk_data['stamina']) self.players.append(player) sorted_players_data.remove(gk_data) # Remove assigned player roles_to_assign.remove(ROLE_GOALKEEPER) # Assign others based on sorted skill and roles needed assigned_roles = {} for role in roles_to_assign: if not sorted_players_data: break # No more players left # Find best player not yet assigned a role best_player_data = None best_player_idx = -1 for i, p_data in enumerate(sorted_players_data): if p_data['role'] not in assigned_roles or assigned_roles[p_data['role']] < roles_to_assign.count(p_data['role']): best_player_data = p_data best_player_idx = i break # Take the first available slot for this role type if best_player_data: player = Player(best_player_data['name'], best_player_data['number'], self, role, best_player_data['skill'], best_player_data['speed'], best_player_data['stamina']) self.players.append(player) assigned_roles[role] = assigned_roles.get(role, 0) + 1 sorted_players_data.pop(best_player_idx) else: # Fallback if assignment logic fails p_data = sorted_players_data.pop(0) player = Player(p_data['name'], p_data['number'], self, role, p_data['skill'], p_data['speed'], p_data['stamina']) self.players.append(player) # Ensure exactly 11 players if data allows, adjust logic if needed if len(self.players) < 11 and len(self.players_data) >= 11: print(f"Warning: Team {self.name} might not have 11 players assigned correctly.") # Add remaining players with default roles if logic missed some while len(self.players) < 11 and sorted_players_data: p_data = sorted_players_data.pop(0) player = Player(p_data['name'], p_data['number'], self, ROLE_MIDFIELDER, p_data['skill'], p_data['speed'], p_data['stamina']) self.players.append(player) self.set_formation_positions() def set_formation_positions(self): """Sets initial player positions based on formation.""" # Clear existing positions first if called multiple times for p in self.players: p.position = [-1,-1] # Mark as unpositioned # Simplified position assignment logic gk = next(p for p in self.players if p.role == ROLE_GOALKEEPER) gk.position = [0, PITCH_HEIGHT / 2] gk.target_position = gk.position gk.state = STATE_IDLE defensive_line_y = PITCH_HEIGHT * 0.25 midfield_line_y = PITCH_HEIGHT / 2 attack_line_y = PITCH_HEIGHT * 0.75 num_def = len([p for p in self.players if p.role == ROLE_DEFENDER]) num_mid = len([p for p in self.players if p.role == ROLE_MIDFIELDER]) num_fwd = len([p for p in self.players if p.role == ROLE_FORWARD]) # Defenders (excluding GK) - spread across width near own goal defenders = [p for p in self.players if p.role == ROLE_DEFENDER] spacing_def = PITCH_WIDTH / (num_def + 1) if num_def > 0 else PITCH_WIDTH for i, p in enumerate(defenders): p.position = [spacing_def * (i + 1), defensive_line_y + random.uniform(-5, 5)] p.target_position = p.position p.state = STATE_IDLE # Midfielders - spread across width in middle midfielders = [p for p in self.players if p.role == ROLE_MIDFIELDER] spacing_mid = PITCH_WIDTH / (num_mid + 1) if num_mid > 0 else PITCH_WIDTH for i, p in enumerate(midfielders): p.position = [spacing_mid * (i + 1), midfield_line_y + random.uniform(-10, 10)] p.target_position = p.position p.state = STATE_IDLE # Forwards - spread across width near opponent goal forwards = [p for p in self.players if p.role == ROLE_FORWARD] spacing_fwd = PITCH_WIDTH / (num_fwd + 1) if num_fwd > 0 else PITCH_WIDTH for i, p in enumerate(forwards): p.position = [spacing_fwd * (i + 1), attack_line_y + random.uniform(-5, 5)] p.target_position = p.position p.state = STATE_IDLE # Ensure all players have a position for p in self.players: if p.position[0] < 0: # If player somehow wasn't positioned p.position = [PITCH_WIDTH / 2 + random.uniform(-10,10), PITCH_HEIGHT / 2 + random.uniform(-10,10)] p.target_position = p.position p.state = STATE_IDLE def update_ai_positions(self, ball): """Updates the positions and states of AI-controlled players.""" # Basic AI logic: move towards ball if loose, support teammate if they have ball # --- Player Logic --- for player in self.players: player.update_stamina() # Update stamina first # Skip AI logic if player is controlled by user if player.team.name == "USER_TEAM" and player.number == controlled_player_index + 1: continue # Let user control handle this player if player.has_ball: # Player with ball: dribble towards goal or make a pass decision if player.state == STATE_DRIBBLING: if player.action_timer > 0: # Action in progress (e.g., dribbling animation) player.action_timer -= 1 # Player dribbles forward (simplified) target_x = min(PITCH_WIDTH, player.position[0] + player.effective_speed) # Move forward player.move_towards([target_x, player.position[1]], 0.8) else: player.state = STATE_IDLE # Finished dribbling sequence elif player.state == STATE_PASSING or player.state == STATE_SHOOTING: player.perform_action() # Continue ongoing action else: # Decide next action player.state = STATE_IDLE # Default state # Goal scoring opportunity? dist_to_goal = distance(player.position, self.opponent.goal_pos) if dist_to_goal < 15 and random.random() < (player.effective_skill / 10) * 0.4: # Chance to shoot if player.attempt_shoot(): return # Goal event handled, reset needed else: # Try to pass to a teammate in a better position best_pass_target = None max_pass_quality = -1 # Find teammate furthest upfield or open space towards goal sorted_teammates = sorted(self.players, key=lambda p: distance(p.position, self.goal_pos), reverse=True) for tm in sorted_teammates: if tm == player: continue # Skip self if tm.state == STATE_IDLE or tm.state == STATE_MOVING: # Target idle or moving players pass_quality = (tm.effective_skill / 10) # Reward players closer to goal and open pass_quality += (1 - abs(tm.position[1] - PITCH_HEIGHT/2) / (PITCH_HEIGHT/2)) * 0.2 pass_quality -= distance(player.position, tm.position) / PITCH_WIDTH * 0.3 # Check player marking is_marked = False for opp_p in self.opponent.players: if opp_p.marking_player == tm and distance(opp_p.position, tm.position) < 3: is_marked = True break if is_marked: pass_quality *= 0.5 if pass_quality > max_pass_quality: max_pass_quality = pass_quality best_pass_target = tm if best_pass_target and max_pass_quality > 0.3: # Need reasonable pass quality player.attempt_pass(best_pass_target) else: # No good pass, maybe dribble or hold? player.state = STATE_DRIBBLING player.action_timer = 5 # Short dribble animation time else: # Player does not have the ball # If ball is loose nearby, chase it if not ball.possessed_by and distance(player.position, ball.position) < 7.0: player.state = STATE_CHASING player.target_position = list(ball.position) player.move_towards(ball.position, 1.1) # Move faster chasing ball # If teammate has ball, support them or mark opponent elif ball.possessed_by: if ball.possessed_by.team == self: # Teammate has ball # Try to get open space towards goal open_space_target = None # Simple logic: move towards a point ahead of teammate towards goal if player.position != list(ball.possessed_by.position): # Avoid being exactly on teammate support_pos = list(ball.possessed_by.position) direction_to_goal = normalize_vector([self.goal_pos[0] - player.position[0], self.goal_pos[1] - player.position[1]]) support_pos[0] += direction_to_goal[0] * 5 # Move slightly forward support_pos[1] += direction_to_goal[1] * 5 # Keep player within reasonable bounds relative to teammate support_pos[0] = max(0, min(PITCH_WIDTH, support_pos[0])) support_pos[1] = max(0, min(PITCH_HEIGHT, support_pos[1])) player.move_towards(support_pos) else: # Opponent has ball, try to mark or press if player.marking_player != ball.possessed_by: # If not already marking the ball carrier player.marking_player = ball.possessed_by player.state = STATE_MARKING # Move towards the player being marked if player.marking_player: player.move_towards(player.marking_player.position) # Chance to tackle if close enough if distance(player.position, player.marking_player.position) < 2.0 and random.random() < 0.3: # High chance to press player.attempt_tackle(player.marking_player) # If ball is loose and far away, or no specific action needed, move to defensive position or roam else: player.state = STATE_IDLE # Simplified roaming or positional play # Could implement formations more rigidly here if player.role == ROLE_DEFENDER: target_y = PITCH_HEIGHT * 0.25 + random.uniform(-5, 5) elif player.role == ROLE_MIDFIELDER: target_y = PITCH_HEIGHT * 0.5 + random.uniform(-10, 10) else: # Forward target_y = PITCH_HEIGHT * 0.75 + random.uniform(-5, 5) # Move towards general area if idle if player.state == STATE_IDLE: player.target_position = [player.position[0] + random.uniform(-3,3), target_y] player.move_towards(player.target_position) # Tackling logic: Ensure players trying to tackle move towards target for player in self.players: if player.state == STATE_TACKLING and player.tackling_player: player.attempt_tackle(player.tackling_player) class Game: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((800, 600)) # Dummy screen for text rendering pygame.display.set_caption("Pro Evo Text Sim") self.clock = pygame.time.Clock() self.font_small = pygame.font.SysFont(None, 24) self.font_large = pygame.font.SysFont(None, 48) self.font_log = pygame.font.SysFont("Courier New", 18) self.current_time_sec = 0 self.current_half = 1 self.time_remaining_in_half = 45 * 60 # seconds self.game_state = STATE_PLAYING self.controlled_player_index = 0 # Index in the USER_TEAM's player list self.event_log = [] self.log_max_lines = 15 # --- Team Setup --- # Define player attributes (skill, speed, stamina are 1-10) # Example data - replace with more detailed/varied data for advanced feel team1_players_data = [ {'name': 'G Hazard', 'number': 10, 'role': ROLE_FORWARD, 'skill': 9, 'speed': 8, 'stamina': 7}, {'name': 'K De Bruyne', 'number': 17, 'role': ROLE_MIDFIELDER, 'skill': 9, 'speed': 7, 'stamina': 8}, {'name': 'V Kompany', 'number': 4, 'role': ROLE_DEFENDER, 'skill': 8, 'speed': 6, 'stamina': 8}, {'name': 'T Courtois', 'number': 1, 'role': ROLE_GOALKEEPER, 'skill': 8, 'speed': 4, 'stamina': 9}, {'name': 'A Witsel', 'number': 8, 'role': ROLE_MIDFIELDER, 'skill': 7, 'speed': 6, 'stamina': 8}, {'name': 'L Lukaku', 'number': 9, 'role': ROLE_FORWARD, 'skill': 7, 'speed': 7, 'stamina': 7}, {'name': 'E Hazard', 'number': 7, 'role': ROLE_FORWARD, 'skill': 9, 'speed': 8, 'stamina': 7}, # Another Hazard for variety {'name': 'J Lukaku', 'number': 5, 'role': ROLE_DEFENDER, 'skill': 7, 'speed': 6, 'stamina': 8}, {'name': 'Y Carrasco', 'number': 11, 'role': ROLE_MIDFIELDER, 'skill': 7, 'speed': 7, 'stamina': 7}, {'name': 'D Vertonghen', 'number': 5, 'role': ROLE_DEFENDER, 'skill': 8, 'speed': 5, 'stamina': 7}, {'name': 'M Batshuayi', 'number': 23, 'role': ROLE_FORWARD, 'skill': 6, 'speed': 7, 'stamina': 6}, {'name': 'C Benteke', 'number': 11, 'role': ROLE_FORWARD, 'skill': 6, 'speed': 6, 'stamina': 7}, {'name': 'R Lukaku', 'number': 10, 'role': ROLE_FORWARD, 'skill': 7, 'speed': 7, 'stamina': 7}, # Duplicate name testing {'name': 'K Meunier', 'number': 15, 'role': ROLE_DEFENDER, 'skill': 7, 'speed': 7, 'stamina': 8}, ] team2_players_data = [ {'name': 'L Messi', 'number': 10, 'role': ROLE_FORWARD, 'skill': 10, 'speed': 8, 'stamina': 6}, {'name': 'C Ronaldo', 'number': 7, 'role': ROLE_FORWARD, 'skill': 10, 'speed': 8, 'stamina': 7}, {'name': 'L Modric', 'number': 10, 'role': ROLE_MIDFIELDER, 'skill': 9, 'speed': 7, 'stamina': 8}, {'name': 'S Ramos', 'number': 4, 'role': ROLE_DEFENDER, 'skill': 8, 'speed': 5, 'stamina': 7}, {'name': 'T Kroos', 'number': 8, 'role': ROLE_MIDFIELDER, 'skill': 8, 'speed': 6, 'stamina': 8}, {'name': 'K Benzema', 'number': 9, 'role': ROLE_FORWARD, 'skill': 9, 'speed': 7, 'stamina': 7}, {'name': 'Neymar Jr', 'number': 10, 'role': ROLE_FORWARD, 'skill': 9, 'speed': 8, 'stamina': 7}, {'name': 'P. Van Dijk', 'number': 4, 'role': ROLE_DEFENDER, 'skill': 9, 'speed': 7, 'stamina': 8}, {'name': 'A Davies', 'number': 19, 'role': ROLE_MIDFIELDER, 'role': ROLE_DEFENDER, 'skill': 8, 'speed': 9, 'stamina': 9}, # Versatile {'name': 'M Neuer', 'number': 1, 'role': ROLE_GOALKEEPER, 'skill': 9, 'speed': 5, 'stamina': 9}, {'name': 'J Kimmich', 'number': 6, 'role': ROLE_MIDFIELDER, 'skill': 8, 'speed': 7, 'stamina': 8}, {'name': 'R Lewandowski', 'number': 9, 'role': ROLE_FORWARD, 'skill': 9, 'speed': 7, 'stamina': 7}, {'name': 'K Mbappé', 'number': 7, 'role': ROLE_FORWARD, 'skill': 9, 'speed': 9, 'stamina': 8}, {'name': 'J Alba', 'number': 18, 'role': ROLE_DEFENDER, 'skill': 7, 'speed': 7, 'stamina': 7}, ] # Assign formation (e.g., 4-3-3, 4-4-2) formation1 = [4, 3, 3] # e.g., 4 Defenders, 3 Midfielders, 3 Forwards formation2 = [4, 4, 2] self.team1 = Team("USER_TEAM", BLUE, team1_players_data, formation1, (0, PITCH_HEIGHT / 2)) # Goal on the left self.team2 = Team("AI_TEAM", RED, team2_players_data, formation2, (PITCH_WIDTH, PITCH_HEIGHT / 2)) # Goal on the right self.team1.opponent = self.team2 self.team2.opponent = self.team1 self.ball = Ball() self.reset_play() def add_log(self, message): """Adds a message to the event log.""" log_entry = f"[{self.current_time_str()}] {message}" print(log_entry) # Also print to console for debugging self.event_log.insert(0, log_entry) # Add to top if len(self.event_log) > self.log_max_lines: self.event_log.pop() # Remove oldest entry def trigger_goal_event(self): """Handles events immediately after a goal.""" self.add_log(f"GOAL! {self.team1.score} - {self.team2.score}") if self.current_half == 2 and self.time_remaining_in_half <= 0: self.game_state = STATE_FINISHED self.add_log("Full Time!") else: self.game_state = STATE_HALF_TIME if self.current_half == 1 and self.time_remaining_in_half <= 0 else STATE_PLAYING if self.game_state == STATE_HALF_TIME: self.add_log("End of First Half.") self.reset_play() # Reset for kick-off def trigger_missed_shot_event(self): # Ball possession needs to be reset, maybe nearest player gets it self.ball.possessed_by = None self.ball.velocity = [0,0] # Ball stops moving immediately self.reset_play() def reset_play(self): """Resets ball and player positions for kick-off or after goal.""" self.ball.possessed_by = None self.ball.position = [PITCH_WIDTH / 2, PITCH_HEIGHT / 2] self.ball.velocity = [0, 0] self.team1.set_formation_positions() self.team2.set_formation_positions() for p in self.team1.players + self.team2.players: p.state = STATE_IDLE p.has_ball = False p.tackling_player = None p.marking_player = None p.action_timer = 0 # Set kick-off player kickoff_player = self.team1.players[0] # Default kick-off team1 player kickoff_player.has_ball = True kickoff_player.state = STATE_IDLE self.ball.possessed_by = kickoff_player self.ball.last_carrier = kickoff_player # If after goal, potentially switch kick-off team if self.game_state == STATE_HALF_TIME: # After first half ends, other team kicks off pass # Logic could switch kick-off player here, for now keep it simple elif self.game_state == STATE_FINISHED: # Restart match pass # Reset everything fully self.game_state = STATE_PLAYING # Ensure state is playing after reset def current_time_str(self): """Formats the current game time.""" # Use total seconds elapsed in the match for display minutes = (self.current_time_sec // 60) seconds = (self.current_time_sec % 60) return f"{minutes:02}:{seconds:02}" def update_game_time(self): """Updates the match clock.""" if self.game_state == STATE_PLAYING: self.current_time_sec += 1 # Increment by 1 second per game tick self.time_remaining_in_half -= 1 if self.time_remaining_in_half <= 0: if self.current_half == 1: self.add_log("--- End of First Half ---") self.game_state = STATE_HALF_TIME self.time_remaining_in_half = 45 * 60 # Reset for second half self.current_half = 2 self.reset_play() # Reset for second half kickoff elif self.current_half == 2: self.game_state = STATE_FINISHED self.add_log("--- MATCH FINISHED ---") def handle_input(self): """Handles player input.""" global controlled_player_index # Allow modification of global variable keys = pygame.key.get_pressed() user_team = self.team1 controlled_player = user_team.players[controlled_player_index] # Movement for controlled player move_direction = [0, 0] move_speed_mod = 1.0 if keys[pygame.K_LEFT] or keys[pygame.K_a]: move_direction[0] -= 1 if keys[pygame.K_RIGHT] or keys[pygame.K_d]: move_direction[0] += 1 if keys[pygame.K_UP] or keys[pygame.K_w]: move_direction[1] -= 1 if keys[pygame.K_DOWN] or keys[pygame.K_s]: move_direction[1] += 1 # Normalize movement vector and apply speed if move_direction != [0, 0]: player_move_vec = normalize_vector(move_direction) target_pos = [ controlled_player.position[0] + player_move_vec[0] * controlled_player.effective_speed, controlled_player.position[1] + player_move_vec[1] * controlled_player.effective_speed ] # Clamp target position to pitch boundaries conceptually target_pos[0] = max(0, min(PITCH_WIDTH, target_pos[0])) target_pos[1] = max(0, min(PITCH_HEIGHT, target_pos[1])) # Perform move if not controlled_player.has_ball: controlled_player.move_towards(target_pos) if controlled_player.state != STATE_MOVING and controlled_player.state != STATE_CHASING: controlled_player.state = STATE_CHASING # Indicate player is actively moving else: controlled_player.state = STATE_DRIBBLING controlled_player.action_timer = 5 # Initiate dribble sequence controlled_player.move_towards(target_pos, 0.9) # Dribble speed mod # Action Buttons if keys[pygame.K_SPACE]: # Pass if controlled_player.has_ball and controlled_player.state not in [STATE_PASSING, STATE_SHOOTING]: # Find closest teammate to pass to best_tm = None min_dist = PITCH_WIDTH for tm in user_team.players: if tm != controlled_player and tm.state != STATE_GOALKEEPER : # Exclude self and GK maybe dist = distance(controlled_player.position, tm.position) if dist < min_dist: min_dist = dist best_tm = tm if best_tm: controlled_player.attempt_pass(best_tm) if keys[pygame.K_RETURN]: # Shoot if controlled_player.has_ball and controlled_player.state not in [STATE_PASSING, STATE_SHOOTING]: controlled_player.attempt_shoot() if keys[pygame.K_TAB]: # Switch Player # Find next closest player to the ball or currently controlled player current_pos = controlled_player.position potential_players = [p for p in user_team.players if p != controlled_player] if potential_players: closest_player = min(potential_players, key=lambda p: distance(current_pos, p.position)) controlled_player_index = user_team.players.index(closest_player) # Reset state of newly controlled player user_team.players[controlled_player_index].state = STATE_IDLE # Add a small delay or flag to prevent rapid switching if key is held # For simplicity, we'll just switch immediately on key press event handling if keys[pygame.K_p]: # Pause if self.game_state == STATE_PLAYING: self.game_state = STATE_PAUSED elif self.game_state == STATE_PAUSED: self.game_state = STATE_PLAYING def update(self): """Updates the game state for one simulation step.""" if self.game_state == STATE_PLAYING: self.handle_input() # Process input first to potentially change states/actions # Update AI players self.team1.update_ai_positions(self.ball) self.team2.update_ai_positions(self.ball) # Update ball physics/possession self.ball.update() # Update game time self.update_game_time() elif self.game_state == STATE_HALF_TIME: # Allow pause/resume during half time if pygame.key.get_pressed()[pygame.K_p]: self.game_state = STATE_PLAYING # Resume time.sleep(0.2) # Prevent rapid toggle # Waiting for second half to start automatically or via input def render_text(self): """Renders all the text information onto the screen.""" self.screen.fill(BLACK) # Clear screen # --- Display Score and Time --- score_text = f"{self.team1.name} {self.team1.score} - {self.team2.score} {self.team2.name}" time_text = f"Time: {self.current_time_str()} (Half {self.current_half})" score_surf = self.font_large.render(score_text, True, WHITE) time_surf = self.font_small.render(time_text, True, WHITE) self.screen.blit(score_surf, (10, 10)) self.screen.blit(time_surf, (10, 60)) # --- Display Controlled Player Info --- controlled_player = self.team1.players[self.controlled_player_index] control_info = f"Control: {controlled_player.name} ({controlled_player.number}) | Actions: WASD/Arrows (Move), SPACE (Pass), ENTER (Shoot), TAB (Switch Player), P (Pause)" control_surf = self.font_small.render(control_info, True, GRAY) self.screen.blit(control_surf, (10, 90)) # --- Display Team Status (Simplified) --- # Display ball possession possession_info = "Possession: " if self.ball.possessed_by: possession_info += f"{self.ball.possessed_by.name} ({self.ball.possessed_by.team.name})" else: possession_info += "Loose" possession_surf = self.font_small.render(possession_info, True, GRAY) self.screen.blit(possession_surf, (10, 115)) # Display controlled player details player_detail_text = f"{controlled_player.name} ({controlled_player.number}) - {controlled_player.role} | Skill:{controlled_player.effective_skill:.1f} Speed:{controlled_player.effective_speed:.1f} Stamina:{controlled_player.stamina:.1f}" player_detail_surf = self.font_small.render(player_detail_text, True, WHITE) self.screen.blit(player_detail_surf, (10, 140)) # --- Display Player Positions (Team 1 Only) --- player_y_offset = 170 for i, player in enumerate(self.team1.players): player_text = str(player) color = self.team1.color if player.has_ball else WHITE player_surf = self.font_log.render(player_text, True, color) self.screen.blit(player_surf, (10, player_y_offset + i * 18)) # --- Display Event Log --- log_y_start = 170 + len(self.team1.players) * 18 + 20 log_title_surf = self.font_small.render("--- Match Events ---", True, YELLOW) self.screen.blit(log_title_surf, (400, log_y_start - 20)) for i, log_entry in enumerate(reversed(self.event_log)): # Display newest first log_surf = self.font_log.render(log_entry, True, WHITE) self.screen.blit(log_surf, (400, log_y_start + i * 18)) # --- Pause Indicator --- if self.game_state == STATE_PAUSED: pause_surf = self.font_large.render("PAUSED", True, YELLOW) self.screen.blit(pause_surf, (PITCH_WIDTH / 2 - 50 , PITCH_HEIGHT / 2 - 20)) elif self.game_state == STATE_HALF_TIME: halftime_surf = self.font_large.render("HALF TIME", True, YELLOW) self.screen.blit(halftime_surf, (PITCH_WIDTH / 2 - 70 , PITCH_HEIGHT / 2 - 20)) pygame.display.flip() def run(self): """Main game loop.""" running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: # Handle specific key presses that should only trigger once if event.key == pygame.K_TAB: # Player switching # Defer logic to handle_input which checks key state continuously pass if event.key == pygame.K_p: # Pause toggle # Defer logic to handle_input pass self.update() self.render_text() self.clock.tick(GAME_SPEED_FPS) pygame.quit() # --- Main Execution --- if __name__ == '__main__': game = Game() game.run()How to Play / Understand:
- Run the Script: Execute the Python file. Pygame will initialize, and a window will appear displaying text information.
- Interface:
- Top Left: Score and current game time/half.
- Below Score: Information about the currently controlled player (from Team 1, "USER_TEAM") and available controls.
- Below Controls: Current ball possession.
- Below Possession: Detailed stats for the controlled player.
- Below Player Details: A list of your team's players (Team 1), showing their name, number, role, position (X, Y coordinates on a 0-100 scale), current state, and stamina. The player with the ball has a
*next to their name. - Right Side: A log of key events happening in the match (passes, tackles, goals, etc.).
- Controls:
- WASD / Arrow Keys: Move the currently controlled player. If you have the ball, this initiates a dribble. If you don't have the ball, this makes you chase it or move positionally.
- SPACEBAR: Attempt a pass. The ball will be passed to the closest teammate (logic might need improvement for more tactical passing).
- ENTER (Return Key): Attempt a shot. If you are close enough to the opponent's goal, this will trigger a shot.
- TAB: Switch control to another player on your team. It usually switches to the player closest to the ball or your current player.
- P: Pause/Resume the game.
Key "Advanced" Features Simulated:
- Player Attributes: Each player has Skill, Speed, and Stamina influencing their actions. Stamina drains over time and with exertion, affecting performance.
- Player States: Players are not static; they have states like
Idle,Moving,Dribbling,Passing,Shooting,Tackling,Chasing,Marking. - Basic AI:
- Players without the ball will chase loose balls or move to support teammates who have possession.
- Defenders attempt to mark opponents with the ball and can initiate tackles.
- Attacking players might shoot if they are in a good position or attempt passes to teammates.
- Possession: Only one player has the ball at a time. Possession changes via tackles, successful passes, or picking up loose balls.
- Actions with Probabilities: Passes, tackles, and shots have success chances based on player attributes, distance, and sometimes opponent proximity, adding unpredictsim.
- Game Clock & Halves: Simulates a real-time match clock, manages halves, and triggers half-time/full-time.
- Event Logging: Provides a running commentary of the match action.
- Team Formations (Basic Positioning): Players are initially placed based on a simple formation structure.
- User Control: Direct control over one player at a time, with the ability to switch.
Limitations & Areas for Further Advancement:
- AI Sophistication: The AI is very basic. Real PES AI involves complex tactical decisions, player runs, zonal marking, pressing triggers, etc.
- Physics: Ball physics are highly simplified (basic movement, deceleration). No spin, bounce, air resistance.
- Tactics: Only basic "attacking/defensive" ideas. No formations changes mid-game, team press intensity, offside traps, etc.
- Player Interaction: Tackling and marking are rudimentary. No complex animations or physics interactions.
- Goalie AI: The goalkeeper is just another player AI-wise, not specifically programmed for saves (though their position might be fixed near the goal).
- Set Pieces: No corners, free kicks, or penalties simulated specifically.
- Controls: Could be expanded (e.g., through-balls, lob passes, targeted shots, player instructions).
- Visual Feedback: Obviously, the lack of graphics and sound is the biggest departure from PES. This text simulation focuses purely on the underlying logic.
- Data: Player attributes are simple ranges. A real game would have many more nuanced stats (acceleration, vision, aggression, specific skill ratings like Curve, Finishing, etc.).
This code provides a starting point for a very complex text-based simulation capturing some core elements of a football game's logic. Enjoy the simulation!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.