# Initialization
initialize_sensors()  # IR, compass, sonar, GPS
set_initial_state("SEARCH")

# Main loop
while simulation_is_running():
    update_sensor_data()

    # Ball detection
    ball_position = get_ball_position_from_IR_or_GPS()
    robot_position = get_robot_position_from_GPS()
    heading = get_heading_from_compass()
    obstacles = get_obstacle_data_from_sonar()

    # State machine
    if state == "SEARCH":
        if ball_position is detected:
            set_state("CHASE")
        else:
            wander_randomly()

    elif state == "CHASE":
        if obstacle_in_path(obstacles):
            set_state("AVOID")
        elif close_to_ball(robot_position, ball_position):
            set_state("ALIGN")
        else:
            move_toward(ball_position, heading)

    elif state == "ALIGN":
        goal_position = get_goal_position()
        if aligned_with_goal(robot_position, ball_position, goal_position):
            set_state("SHOOT")
        else:
            adjust_orientation_toward(goal_position)

    elif state == "SHOOT":
        kick_ball()
        set_state("SEARCH")

    elif state == "AVOID":
        perform_obstacle_avoidance(obstacles)
        set_state("CHASE")

    # Safety check
    if near_field_boundary(robot_position):
        steer_away_from_boundary()