

CODE 

# robot1_advanced.py - Advanced intelligent Robot 1 for Webots
from controller import Robot



# Robot and motor setup
robot = Robot()
left_motor = robot.getDevice('left wheel motor')
right_motor = robot.getDevice('right wheel motor')
left_motor.setPosition(float('inf'))
right_motor.setPosition(float('inf'))
left_motor.setVelocity(0.0)
right_motor.setVelocity(0.0)

# Sensors setup
ir_ball_sensor = robot.getDevice('ir_ball_sensor')
ir_ball_sensor.enable(TIME_STEP)

compass = robot.getDevice('compass')
compass.enable(TIME_STEP)

sonar = robot.getDevice('sonar')
sonar.enable(TIME_STEP)

gps = robot.getDevice('gps')
gps.enable(TIME_STEP)

# Robot speed settings
MAX_SPEED = 6.28
TURN_SPEED = 0.5 * MAX_SPEED
FORWARD_SPEED = 0.6 * MAX_SPEED

# Movement function
def move(left_speed, right_speed):
    left_motor.setVelocity(left_speed)
    right_motor.setVelocity(right_speed)

# Function to calculate goal direction
def goal_direction(gps_values):
    goal_x = 1.0  # adjust according to opponent goal position
    dx = goal_x - gps_values[0]
    return dx

# Function to move and push ball toward goal
def shoot_toward_goal(ball_direction, gps_values):
    target_dx = goal_direction(gps_values)
    
    if -0.1 < ball_direction < 0.1:
        move(FORWARD_SPEED, FORWARD_SPEED)
    elif ball_direction >= 0.1:
        move(0.4 * MAX_SPEED, 0.6 * MAX_SPEED)
    else:
        move(0.6 * MAX_SPEED, 0.4 * MAX_SPEED)

# Main control loop
while robot.step(TIME_STEP) != -1:
    ball_value = ir_ball_sensor.getValue()
    obstacle_distance = sonar.getValue()
    gps_values = gps.getValues()
    compass_values = compass.getValues()
    ball_direction = ball_value - 0.5

    # Obstacle avoidance
    if obstacle_distance < 0.2:
        move(-0.5 * MAX_SPEED, -0.5 * MAX_SPEED)
        continue

    # Search for ball if not detected
    if ball_value > 0.9:
        move(TURN_SPEED, -TURN_SPEED)
        continue

    # Control ball and move toward goal
    shoot_toward_goal(ball_direction, gps_values)

