Beispiel #1
0
 /*Execute each of the agent's yearly actions in turn*/
 public void step(SimState state) {
   if (Model.instance().generateLifeProb() == 101) {
     mode = LifeStage.DYING;
   }
   // earn
   if (mode == LifeStage.EARNING) {
     this.earnIncome();
     mode = LifeStage.TRADING;
     Model.instance().schedule.scheduleOnceIn(.1, this);
     // trade
   } else if (mode == LifeStage.TRADING) {
     // this.tradeWithRandomAgents();
     this.checkThreeProducers();
     mode = LifeStage.CONSUMING;
     Model.instance().schedule.scheduleOnceIn(.1, this);
     // consume
   } else if (mode == LifeStage.CONSUMING) {
     this.consume();
     // System.out.printf("food price: %f, id: %d, Make: %d\n",expPrice[1],myId,producedCommodity);
     // mode = LifeStage.BIRTHING;
     mode = LifeStage.EARNING;
     Model.instance().schedule.scheduleOnceIn(.8, this);
     age++;
     // child
   } /*else if(mode == LifeStage.BIRTHING){
        this.considerHavingAChild();
        mode = LifeStage.DYING;
        Model.instance().schedule.scheduleOnceIn(.1,this);
     //death
     }*/ else if (mode == LifeStage.DYING) {
     this.considerDeath();
     // mode = LifeStage.EARNING;
   }
 }
Beispiel #2
0
 /*Probabilistically determine whether an agent will have a child
 and add a new agent to the schedule if so*/
 public void considerHavingAChild() {
   int prob = Model.instance().generateChild();
   if (age >= 20 && age < 35) {
     if (prob > 90) {
       Human newchild = new Human(this);
       Model.instance().schedule.scheduleOnceIn(.6, newchild);
       Model.instance().incrementPopulation();
     }
   }
 }
Beispiel #3
0
 private void trade(int x, Human other) {
   // Determine how low and high the agents are in the given good (not Giffen good)
   double deficit = minThreshold[x] - commoditiesHeld[x];
   double surplus = other.commoditiesHeld[x] - other.minThreshold[x];
   // Sell only if the buyer is willing to pay more than the seller wants???
   // if(expPrice[x]>other.expPrice[x]){//SELLER HAS MONOPOLISTIC CONTROL!!! MAYDAY!
   // Haggle to the price being the average of the two expecteds
   double price = (expPrice[x] + other.expPrice[x]) / 2;
   double diff = price - expPrice[x];
   // Bring both agents' expectations a tenth of the way to the average
   diff /= 10;
   expPrice[x] += diff;
   diff = price - other.expPrice[x];
   diff /= 10;
   other.expPrice[x] += diff;
   // Decide the amount to buy so as not to bring buyer above or seller below need level
   if (deficit > surplus) {
     money -= surplus * price;
     other.money += surplus * price;
     other.commoditiesHeld[x] -= surplus;
     commoditiesHeld[x] += surplus;
   } else {
     money -= deficit * price;
     other.money += deficit * price;
     other.commoditiesHeld[x] -= deficit;
     commoditiesHeld[x] += deficit;
   }
   // Increment model-wide trades
   Model.instance().incrementTrades();
   /*}else{
   other.expPrice[x] = other.expPrice[x]-((other.expPrice[x]-expPrice[x])/10);
   expPrice[x] = expPrice[x]+((other.expPrice[x]-expPrice[x])/10);
   }*/
 }
Beispiel #4
0
  // Constructors & destructors
  // --------------------------------------------------------------------------
  // This constructor is called for initial agents
  public Human() {
    myId = nextAgentNum++;
    mode = LifeStage.EARNING;
    /*if (myId == 0 || myId == 1) {
    producedCommodity = myId;
    } else {*/
    producedCommodity = Model.instance().generateMake(this);
    // }
    residentCommunity = Model.instance().generateCommunity(this);
    age = 0; // Model.instance().generateAge();
    money = Model.MONEY;
    children = new ArrayList<Human>();
    minThreshold = new double[Commodity.NUM_COMM]; // Between 0 and 5
    commoditiesHeld = new double[Commodity.NUM_COMM];
    expPrice = new double[Commodity.NUM_COMM];
    chokeQuant = new double[Commodity.NUM_COMM];
    demandSlope = new double[Commodity.NUM_COMM];
    budget = new double[Commodity.NUM_COMM];

    // New trade variables
    alpha = new double[Commodity.NUM_COMM];
    beta = new double[Commodity.NUM_COMM];
    goodUtils = new double[Commodity.NUM_COMM];
    utilsDollar = new double[Commodity.NUM_COMM];
    budgetExp = new double[Commodity.NUM_COMM];

    timesTraded = 0;
    for (int i = 0; i < Commodity.NUM_COMM; i++) {
      minThreshold[i] =
          Commodity.getCommNum(i)
              .getAmtCons(); // Model.instance().generateNeedCommodityThreshold();
      /* while( minThreshold[i]< Commodity.getCommNum(i).getAmtCons()) {
      minThreshold[i]=Model.instance().generateNeedCommodityThreshold();
      }*/
      Commodity.getCommNum(i).incNeed(minThreshold[i]);
      expPrice[i] = Model.instance().generateExpPrice();
      chokeQuant[i] = Model.instance().generateChokeQuant();
      demandSlope[i] = Model.instance().generateDemandSlope();
      alpha[i] = Model.instance().generateAlpha();
      beta[i] = Model.instance().generateBeta();
      commoditiesHeld[i] = 0;
    }
    allNeeds = 0;
    for (int i = 0; i < Commodity.NUM_COMM; i++) {
      allNeeds += minThreshold[i];
    }
    amountProduced = Model.instance().generateAmountProduced();
    totalAmountProduced += amountProduced;
    Commodity.getCommNum(producedCommodity).incMakerNum(amountProduced);
    Model.instance().addToActors(this);
    // Model.instance().addToProducers(producedCommodity, this);
  }
Beispiel #5
0
 // This constructor is called for new children
 public Human(Human progenitor) {
   mode = LifeStage.EARNING;
   parent = progenitor;
   myId = nextAgentNum++;
   producedCommodity = Model.instance().generateMake(this);
   residentCommunity = parent.residentCommunity;
   age = 0;
   money = 100;
   children = new ArrayList<Human>();
   minThreshold = new double[Commodity.NUM_COMM]; // Between 0 and 5
   commoditiesHeld = new double[Commodity.NUM_COMM];
   timesTraded = 0;
   for (int i = 0; i < Commodity.NUM_COMM; i++) {
     minThreshold[i] = Model.instance().generateNeedCommodityThreshold();
     while (minThreshold[i] < Commodity.getCommNum(i).getAmtCons()) {
       minThreshold[i] = Model.instance().generateNeedCommodityThreshold();
     }
     Commodity.getCommNum(i).incNeed(minThreshold[i]);
     expPrice[i] = Model.instance().generateExpPrice();
     commoditiesHeld[i] = 0;
   }
   allNeeds = 0;
   for (int i = 0; i < Commodity.NUM_COMM; i++) {
     allNeeds += minThreshold[i];
   }
   amountProduced = Model.instance().generateAmountProduced();
   Commodity.getCommNum(producedCommodity).incMakerNum(amountProduced);
   parent.children.add(this);
   Model.instance().addToActors(this);
   Model.instance().addToCommunity(residentCommunity, this);
 }
Beispiel #6
0
 /*Give an even portion of the agent's goods to all the children*/
 private void omniBequeath(Human man) {
   if (man.children.size() == 0) {
     // std::cout<<"Childless ";
     /*TODO remove holdings from model*/
   } else {
     if (man.children.size() > 1) {
       Model.instance().addToWealthRedistributed(man.getWealth());
       Model.instance().incrementOmniEvent();
     }
     for (int i = 0; i < man.children.size(); i++) {
       for (int j = 0; j < Commodity.NUM_COMM; j++) {
         double progeny = man.children.size();
         man.children.get(i).commoditiesHeld[j] += man.commoditiesHeld[j] / progeny;
         man.children.get(i).money += man.money / progeny;
       }
     }
   }
 }
Beispiel #7
0
  public void earnIncome() {
    // If they didn't empty their inventory, lower price
    // Model.instance().showNumOfProducers();
    String message;
    if (Model.instance().findProducer(producedCommodity, this) && Model.instance().getTick() > 1) {
      // cph Decrease price by changeProp to represent unsold inventory
      expPrice[producedCommodity] /= changeProp;
      if (producedCommodity == GOOD) {
        message =
            "Due to surplus inventory, price of "
                + Integer.toString(GOOD)
                + " falls to "
                + Double.toString(expPrice[producedCommodity]);
        debug(message, PRICE);
      }
    }
    /*if((producedCommodity != 5) && (Model.instance().getNumProducers(producedCommodity)>15)){
    producedCommodity = 5;
    }*/
    if (Model.instance().generateSwitch() < Model.SWITCH_PROZ && Model.instance().getTick() > 1) {
      // Remove from current production arrayList
      int com = 0;
      double max = 0;
      for (int i = 0; i < Commodity.NUM_COMM; i++) {
        if (expPrice[i] > max) {
          com = i;
          max = expPrice[i];
        }
      }
      Model.instance().removeFromProducers(producedCommodity, this);
      producedCommodity = com;
    }
    if (Model.instance().findProducer(producedCommodity, this)) {

    } else {
      // Add to new production arrayList
      Model.instance().addToProducers(producedCommodity, this);
    }

    if (producedCommodity == 0) {
      // System.out.println("I produce A!");
    } else {
      // System.out.println("I produce something else!");
    }
    // if(age > 3 && producedCommodity == 1){

    // }else{
    commoditiesHeld[producedCommodity] += amountProduced; // Units?
    Commodity.getCommNum(producedCommodity).produce(amountProduced);
    totalMoney += money;
    makeBudget();
    // }
  }
Beispiel #8
0
 // Initiate random trades with other agents
 public void tradeWithRandomAgents() {
   /*
     Ok, new plan. Trading with communities in play.
     Generate a number every time, if you are below, trade in community.
     If you're above, you may trade with the world at large.
   */
   for (int i = 0; i < Model.NUM_TRADERS; i++) {
     int roll = (Model.instance().generateOutsideTrade());
     // if(roll>Model.INTROVERT_DIAL) {
     buyFrom(Model.instance().getRandomGlobalMember());
     /*} else {
     buyFrom(Model.instance().getRandomCommunityMember(residentCommunity));
     }*/
     /*int k=0;
     for(int j=0; j<Commodity.NUM_COMM; j++){
     if(checkStatus(j)==CommodityStatus.DEFICIENT){
     k=1;
     }
     }
     if(k==0){
     break;
     }*/
   }
 }
Beispiel #9
0
/**
 * Main GUI controller.
 *
 * @author paspiz85
 */
public class MainController implements ApplicationAwareController {

  private static int toInt(final double n) {
    return (int) Math.round(n);
  }

  private Application application;

  @FXML private ComboBox<String> autoAttackComboBox;

  @FXML private CheckBox collectResourcesCheckBox;

  @FXML private GridPane configGridPane;

  @FXML private AnchorPane controlPane;

  @FXML private TextField deField;

  @FXML private CheckBox detectEmptyCollectorsCheckBox;

  @FXML private Label donateLabel;

  @FXML private Hyperlink donateLink;

  @FXML private TextField elixirField;

  @FXML private CheckBox extraFuncCheckBox;

  @FXML private Hyperlink githubLink;

  @FXML private TextField goldField;

  @FXML private ImageView heartImage;

  @FXML private CheckBox isMatchAllConditionsCheckBox;

  protected final Logger logger = Logger.getLogger(getClass().getName());

  @FXML private ComboBox<Level> logLevelComboBox;

  @FXML private TextField maxThField;

  private final Model model = Model.instance();

  private final Platform platform = Platform.instance();

  @FXML private ComboBox<Troop> rax1ComboBox;

  @FXML private ComboBox<Troop> rax2ComboBox;

  @FXML private ComboBox<Troop> rax3ComboBox;

  @FXML private ComboBox<Troop> rax4ComboBox;

  @FXML private ComboBox<Troop> rax5ComboBox;

  @FXML private ComboBox<Troop> rax6ComboBox;

  @FXML private Label trainTroopsSliderPreview;

  @FXML private Button settingsButton;

  @FXML private AnchorPane setupPane;

  @FXML private Button startButton;

  @FXML private Button scriptsButton;

  @FXML private Button stopButton;

  @FXML private TextArea textArea;

  @FXML private Slider trainTroopsSlider;

  @FXML private Label versionLabel;

  @FXML private WebView webView;

  @Override
  public void afterShow() {
    final boolean autostart =
        Boolean.parseBoolean(application.getParameters().getNamed().get("autostart"));
    if (autostart) {
      javafx.application.Platform.runLater(
          () -> {
            final Alert dialog = new Alert(AlertType.INFORMATION);
            dialog.initOwner(application.getPrimaryStage());
            dialog.setHeaderText("Autostart in 10 seconds. Close this dialog to cancel");
            dialog.show();
            final Task<Void> sleeper =
                new Task<Void>() {

                  @Override
                  protected Void call() throws Exception {
                    try {
                      Thread.sleep(10000);
                    } catch (final Exception e) {
                      logger.log(Level.SEVERE, e.getMessage(), e);
                    }
                    return null;
                  }
                };
            sleeper.setOnSucceeded(
                event -> {
                  if (dialog.isShowing()) {
                    dialog.close();
                    startButton.fire();
                  }
                });
            new Thread(sleeper, "autostartThread").start();
          });
    }
  }

  private void alert(final String str) {
    platformRunNow(
        () -> {
          final Alert dialog = new Alert(AlertType.INFORMATION);
          dialog.initOwner(application.getPrimaryStage());
          dialog.setHeaderText(str);
          final Optional<ButtonType> result = dialog.showAndWait();
        });
  }

  private boolean autoAdjustResolution() {
    final boolean[] ret = new boolean[1];
    try {
      platformRunNow(
          () -> {
            final Alert dialog = new Alert(AlertType.CONFIRMATION);
            dialog.initOwner(application.getPrimaryStage());
            dialog.setTitle("Resolution");
            dialog.setHeaderText("Confirm changing resolution");
            dialog.setContentText(
                String.format(
                    "Game must run in resolution %s.\n"
                        + "Click YES to change it automatically, NO to do it later.\n",
                    platform.getExpectedSize().toString()));
            final Optional<ButtonType> result = dialog.showAndWait();
            ret[0] = result.isPresent() && result.get() == ButtonType.OK;
          });
    } catch (final Exception e) {
      logger.log(Level.SEVERE, "Unable to setup resolution", e);
    }
    return ret[0];
  }

  private boolean confirm(final String str) {
    final boolean[] toReturn = new boolean[1];
    platformRunNow(
        () -> {
          final Alert dialog = new Alert(AlertType.CONFIRMATION);
          dialog.initOwner(application.getPrimaryStage());
          dialog.setHeaderText(str);
          final Optional<ButtonType> result = dialog.showAndWait();
          toReturn[0] = result.isPresent() && result.get() == ButtonType.OK;
        });
    return toReturn[0];
  }

  @FXML
  public void handleCancelButtonAction() {
    showSettings(false);
  }

  @FXML
  public void handleSaveButtonAction() {
    model.saveSettings(
        (settings) -> {
          if (!goldField.getText().isEmpty()) {
            settings.setGoldThreshold(Integer.parseInt(goldField.getText()));
          }
          if (!elixirField.getText().isEmpty()) {
            settings.setElixirThreshold(Integer.parseInt(elixirField.getText()));
          }
          if (!deField.getText().isEmpty()) {
            settings.setDarkElixirThreshold(Integer.parseInt(deField.getText()));
          }
          if (!maxThField.getText().isEmpty()) {
            settings.setMaxThThreshold(Integer.parseInt(maxThField.getText()));
          }
          settings.setDetectEmptyCollectors(detectEmptyCollectorsCheckBox.isSelected());
          settings.setMatchAllConditions(isMatchAllConditionsCheckBox.isSelected());
          settings.setCollectResources(collectResourcesCheckBox.isSelected());
          settings.setTrainMaxTroops(toInt(trainTroopsSlider.getValue()));
          settings.setLogLevel(logLevelComboBox.getValue());
          settings.setAttackStrategy(autoAttackComboBox.getValue());
          settings.getRaxInfo()[0] = rax1ComboBox.getValue();
          settings.getRaxInfo()[1] = rax2ComboBox.getValue();
          settings.getRaxInfo()[2] = rax3ComboBox.getValue();
          settings.getRaxInfo()[3] = rax4ComboBox.getValue();
          settings.getRaxInfo()[4] = rax5ComboBox.getValue();
          settings.getRaxInfo()[5] = rax6ComboBox.getValue();
          settings.setExtraFunctions(extraFuncCheckBox.isSelected());
        });
    showSettings(false);
  }

  @FXML
  public void handleScriptsButtonAction() {
    final ChoiceDialog<String> dialog = new ChoiceDialog<>(null, model.getScripts());
    dialog.initOwner(application.getPrimaryStage());
    dialog.setTitle("Scripts");
    dialog.setHeaderText("Select script to run");
    dialog.setContentText("Script:");
    dialog.setSelectedItem(model.getLastRunnedScript());
    final Optional<String> result = dialog.showAndWait();
    if (result.isPresent()) {
      try {
        model.runScript(result.get());
      } catch (final IllegalAccessException e) {
        logger.warning(e.getMessage());
      }
    }
  }

  @FXML
  public void handleSettingsButtonAction() {
    showSettings(true);
  }

  @FXML
  public void handleStartButtonAction() {
    model.start();
  }

  @FXML
  public void handleStopButtonAction() {
    model.stop();
    startButton.requestFocus();
  }

  private void initFooter() {
    webView.getEngine().load(BuildInfo.instance().getAdUrl());
    webView
        .getEngine()
        .locationProperty()
        .addListener(
            (observable, oldValue, newValue) -> {
              if (BuildInfo.instance().getAdUrl().equals(oldValue)) {
                application.getHostServices().showDocument(newValue);
              }
            });
    final Thread reloadThread =
        new Thread(
            () -> {
              while (true) {
                try {
                  Thread.sleep(60000);
                  javafx.application.Platform.runLater(
                      () -> {
                        webView.getEngine().reload();
                      });
                } catch (final Exception e) {
                  logger.log(Level.FINE, "Refresh failed", e);
                }
              }
            },
            "AdvReloader");
    reloadThread.setDaemon(true);
    reloadThread.start();
  }

  private void initHeader() {
    versionLabel.setText(BuildInfo.instance().getFullName());
    githubLink.setText(BuildInfo.instance().getRepositoryUrl());
    model.checkForUpdate(
        () -> {
          javafx.application.Platform.runLater(
              () -> {
                versionLabel.setText(BuildInfo.instance().getFullName() + " (UPDATE AVAILABLE!)");
                githubLink.setText(BuildInfo.instance().getLatestVersionUrl());
              });
        });
    githubLink.setOnAction(
        event -> {
          application.getHostServices().showDocument(githubLink.getText());
          githubLink.setVisited(false);
        });
    final Image heartIcon = new Image(getClass().getResourceAsStream("heart.png"));
    donateLink.setGraphic(new ImageView(heartIcon));
    donateLink.setOnAction(
        event -> {
          application.getHostServices().showDocument(BuildInfo.instance().getDonateUrl());
          donateLink.setVisited(false);
        });
  }

  @FXML
  private void initialize() {
    LogHandler.initialize(textArea);
    ScriptManager.instance().setAlert((str) -> alert(str));
    ScriptManager.instance().setConfirm((str) -> confirm(str));
    ScriptManager.instance().setPrompt((str, defValue) -> prompt(str, defValue));
    ScriptManager.instance().setSelect((str, options) -> select(str, options));
    model.initialize(() -> autoAdjustResolution(), () -> updateUI());
    initHeader();
    initFooter();
    initSettingsPane();
    updateUI();
    startButton.requestFocus();
  }

  private void initSettingsPane() {
    trainTroopsSlider.setMin(0);
    trainTroopsSlider.setMax(Settings.MAX_TRAIN_TROOPS);
    trainTroopsSlider.setBlockIncrement(1);
    trainTroopsSlider
        .valueProperty()
        .addListener(
            (observable, oldValue, newValue) -> {
              trainTroopsSliderPreview.setText(
                  String.format("%d", MainController.toInt(newValue.doubleValue())));
            });
    final Troop[] availableTroops = model.getAvailableTroops();
    rax1ComboBox.getItems().addAll(availableTroops);
    rax2ComboBox.getItems().addAll(availableTroops);
    rax3ComboBox.getItems().addAll(availableTroops);
    rax4ComboBox.getItems().addAll(availableTroops);
    rax5ComboBox.getItems().addAll(availableTroops);
    rax6ComboBox.getItems().addAll(availableTroops);
    autoAttackComboBox.getItems().addAll(Attack.noStrategy());
    autoAttackComboBox.getItems().addAll(Attack.getAvailableStrategies());
    autoAttackComboBox.setValue(autoAttackComboBox.getItems().get(0));
    final ChangeListener<String> intFieldListener =
        (observable, oldValue, newValue) -> {
          try {
            if (!newValue.isEmpty()) {
              Integer.parseInt(newValue);
            }
          } catch (final NumberFormatException e) {
            ((TextField) ((StringProperty) observable).getBean()).setText(oldValue);
          }
        };
    goldField.textProperty().addListener(intFieldListener);
    elixirField.textProperty().addListener(intFieldListener);
    deField.textProperty().addListener(intFieldListener);
    maxThField.textProperty().addListener(intFieldListener);
    logLevelComboBox
        .getItems()
        .addAll(
            Level.FINEST,
            Level.FINER,
            Level.FINE,
            Level.CONFIG,
            Level.INFO,
            Level.WARNING,
            Level.SEVERE);
    logLevelComboBox.setValue(logLevelComboBox.getItems().get(1));
    updateUI();
  }

  private void platformRunNow(final Runnable runnable) {
    final boolean[] done = new boolean[1];
    final Runnable sync =
        new Runnable() {

          @Override
          public void run() {
            logger.log(Level.FINE, "platformRunNow run start");
            runnable.run();
            done[0] = true;
            logger.log(Level.FINE, "platformRunNow run complete");
            synchronized (this) {
              this.notify();
            }
          }
        };
    javafx.application.Platform.runLater(sync);
    logger.log(Level.FINE, "platformRunNow wait start");
    synchronized (sync) {
      while (!done[0]) {
        try {
          sync.wait();
        } catch (final InterruptedException e) {
          logger.log(Level.WARNING, e.getMessage(), e);
        }
      }
    }
    logger.log(Level.FINE, "platformRunNow wait complete");
  }

  private String prompt(final String msg, final String value) {
    final String[] toReturn = new String[1];
    platformRunNow(
        () -> {
          final TextInputDialog dialog = new TextInputDialog(value == null ? "" : value);
          dialog.initOwner(application.getPrimaryStage());
          dialog.setHeaderText(msg);
          final Optional<String> result = dialog.showAndWait();
          toReturn[0] = result.isPresent() ? result.get() : null;
        });
    return toReturn[0];
  }

  private String select(final String str, final String[] options) {
    final String[] toReturn = new String[1];
    platformRunNow(
        () -> {
          final ChoiceDialog<String> dialog = new ChoiceDialog<>(null, options);
          dialog.initOwner(application.getPrimaryStage());
          dialog.setHeaderText(str);
          final Optional<String> result = dialog.showAndWait();
          toReturn[0] = result.isPresent() ? result.get() : null;
        });
    return toReturn[0];
  }

  @Override
  public void setApplication(final Application application) {
    this.application = application;
    showSettings(false);
  }

  private void showSettings(final boolean value) {
    setupPane.setVisible(value);
    controlPane.setVisible(!value);
  }

  private void updateUI() {
    final boolean running = model.isRunning();
    final boolean scriptRunning = model.isScriptRunning();
    startButton.setDisable(running || scriptRunning);
    stopButton.setDisable(!running && !scriptRunning);
    scriptsButton.setDisable(running || scriptRunning);
    final Settings settings = model.loadSettings();
    goldField.setText(settings.getGoldThreshold() + "");
    elixirField.setText(settings.getElixirThreshold() + "");
    deField.setText(settings.getDarkElixirThreshold() + "");
    maxThField.setText(settings.getMaxThThreshold() + "");
    detectEmptyCollectorsCheckBox.setSelected(settings.isDetectEmptyCollectors());
    isMatchAllConditionsCheckBox.setSelected(settings.isMatchAllConditions());
    collectResourcesCheckBox.setSelected(settings.isCollectResources());
    trainTroopsSlider.setValue(settings.getTrainMaxTroops());
    logLevelComboBox.getSelectionModel().select(settings.getLogLevel());
    autoAttackComboBox.getSelectionModel().select(settings.getAttackStrategy());
    rax1ComboBox.getSelectionModel().select(settings.getRaxInfo()[0]);
    rax2ComboBox.getSelectionModel().select(settings.getRaxInfo()[1]);
    rax3ComboBox.getSelectionModel().select(settings.getRaxInfo()[2]);
    rax4ComboBox.getSelectionModel().select(settings.getRaxInfo()[3]);
    rax5ComboBox.getSelectionModel().select(settings.getRaxInfo()[4]);
    rax6ComboBox.getSelectionModel().select(settings.getRaxInfo()[5]);
    extraFuncCheckBox.setSelected(settings.isExtraFunctions());
  }
}
Beispiel #10
0
  private void selectProducer(Human seller, int good) {
    double price = seller.expPrice[good];
    double quantity = budgetExp[good] / price;
    double otherQuantity = seller.budgetExp[good] / price; // seller.chokeQuant[good];
    String message;
    /*double quantity = chokeQuant[good];
      double otherQuantity = seller.chokeQuant[good];
    //How much is the buyer willing to buy at the price
    for(int i=0; i<Commodity.NUM_COMM; i++){
    if(i!=good){
    quantity -= demandSlope[i]*expPrice[i];
    }else{
    quantity -= demandSlope[good]*price;
    }
    }*/
    /*for(int k=0; k<Commodity.NUM_COMM; k++){
    otherQuantity -= seller.demandSlope[k]*seller.expPrice[k];
    }*/
    double firstQuantity = quantity;
    if (otherQuantity > (seller.commoditiesHeld[good] - quantity)) {
      quantity = (seller.commoditiesHeld[good] - quantity);
      // Remove seller from producer arrayList
      // cph Seller sold inventory, raises price to reflect scarcity of his good
      seller.expPrice[good] *= changeProp;
      if (good == GOOD) {
        message =
            "Producer of good "
                + Integer.toString(GOOD)
                + " ran out, price rises to "
                + Double.toString(seller.expPrice[good])
                + " wanted to hold quantity "
                + Double.toString(quantity)
                + " not "
                + Double.toString(firstQuantity);
        debug(message, PRICE);
      }
      Model.instance().removeFromProducers(seller.producedCommodity, seller);
      debug("removing", false);
    }
    double diff = price - expPrice[good];
    diff /= 10;
    double tempUnDiff = expPrice[good];
    // expPrice[good]+=diff;
    if (good == 2) {
      message =
          "2 price changed from "
              + Double.toString(tempUnDiff)
              + " to "
              + Double.toString(expPrice[good]);
      debug(message, TRADE);
      message = "2 price changed by " + Double.toString(diff);
      debug(message, TRADE);
      // System.out.printf("2 price changed from %f to %f\n", tempUnDiff, expPrice[good]);
      // System.out.printf("2 price changed by %f\n", diff);
    }
    // If they bought, raise seller's price
    if (quantity > 0) { // && money >= price*quantity){
      // System.out.printf("We bought %f at %f!\n",quantity, price);
      seller.commoditiesHeld[good] -= quantity;
      commoditiesHeld[good] += quantity;

      budgetExp[good] -= quantity * price;
      seller.money += quantity * price;
      money -= quantity * price;

      Commodity.getCommNum(good).reportSale(quantity);
      totalSpent += quantity * price;
      // seller.expPrice[good]*=1.01;
    } else {
      // System.out.printf("We didn't buy at %f!\n", price);
    }
  }
Beispiel #11
0
  /*Pobabilistically determine whether an agent will die and inter
  them and distribute their wealth*/
  public void considerDeath() {
    int BD = 0;
    int prob = Model.instance().generateLifeProb();
    // Death at end of model
    if (prob == 101) {

      // Death if black death is active
    } else if (Model.instance().getTick() > 80 && Model.instance().getTick() < 82 && BD != 0) {
      if (prob < 10) {
        Model.instance().inter(this);
        Model.instance().decrementPopulation();
        if (BEQ == 0) {
          omniBequeath(this);
        }
        if (BEQ == 1) {
          primoBequeath(this);
        }
      } else {
        Model.instance().schedule.scheduleOnceIn(.7, this);
      }
      // Normal death
    } else if (age >= 25 && age < 100) {
      int getAbove = 6;
      /*if(Model::instance()->getTick()>80 && Model::instance()->getTick()<85)
      {
      getAbove=90;
      }*/
      if (prob < getAbove) {
        Model.instance().inter(this);
        Model.instance().decrementPopulation();
        if (BEQ == 0) {
          omniBequeath(this);
        }
        if (BEQ == 1) {
          primoBequeath(this);
        }
      } else {
        Model.instance().schedule.scheduleOnceIn(.7, this);
      }
      // No one lives over 100 years
    } else if (age >= 100) {
      Model.instance().inter(this);
      Model.instance().decrementPopulation();
      if (BEQ == 0) {
        omniBequeath(this);
      }
      if (BEQ == 1) {
        primoBequeath(this);
      }
      // Person survived
    } else {
      Model.instance().schedule.scheduleOnceIn(.7, this);
    }
    age++;
  }
Beispiel #12
0
  // Talk to three producers for each good and select one to buy from
  // Lower the prices of the other two
  public void checkThreeProducers() { // TODO lots of things REALLY
    // makeBudget();
    String message;
    // Model.instance().showNumOfProducers();
    tradingPartners = new ArrayList<Human>();
    ArrayList<Integer> random = new ArrayList<Integer>();
    for (int l = 0; l < Commodity.NUM_COMM; l++) {
      random.add(l);
    }
    // Collections.shuffle(random);
    for (int p = 0; p < Commodity.NUM_COMM; p++) {
      int i = random.get(p);
      if (i == GOOD) {
        buyers++;
        // System.out.printf("%d agents have tried to buy the good\n", buyers);
      }
      int numTrades = 0;
      // System.out.printf("Human trade budget %f num prod %d numTrades %d\n", budgetExp[i],
      // Model.instance().getNumProducers(i),numTrades);
      while (Model.instance().getNumProducers(i) > 0 && budgetExp[i] > 0.01) { // && numTrades < 3){
        // System.out.printf("Human trade budget is %f and num prod is %d\n", budgetExp[i],
        // Model.instance().getNumProducers(i));
        numTrades++;
        tradingPartners.clear();
        // System.out.println("Maybe stuck in a loop\n");
        // System.out.printf("Budget for good %d is %f\n", i, budgetExp[i]);
        // int i = p;
        int numt = 3;
        int psize = Model.instance().getNumProducers(i);
        if (i == GOOD) {
          // System.out.printf("Num producers is %d\n",psize);
        }
        if (psize < 3) {
          numt = psize;
        }
        int cheapestProducer = 0;
        double lowestPrice = 0;
        double avgPrice = 0;
        double sumPrice = 0;
        // System.out.printf("psize is %d\n", psize);
        for (int k = 0; k < numt; k++) {
          Human toAdd = Model.instance().getProducerOfGood(i);
          if (tradingPartners.contains(toAdd)) {
            // k--;
          } else {
            tradingPartners.add(toAdd);
          }
        }
        // System.out.printf("tp size is %d\n",tradingPartners.size());
        lowestPrice = tradingPartners.get(0).expPrice[i];
        for (int k = 0; k < tradingPartners.size(); k++) {
          sumPrice += tradingPartners.get(k).expPrice[i];
          if (tradingPartners.get(k).expPrice[i] < lowestPrice) {
            cheapestProducer = k;
            lowestPrice = tradingPartners.get(k).expPrice[i];
          }
        }

        avgPrice = sumPrice / tradingPartners.size();
        double diff = avgPrice - expPrice[i];
        diff /= buyerChange;
        // cph change buyer's price to reflect prices they believe sellers are offering
        expPrice[i] += diff;

        for (int k = 0; k < tradingPartners.size(); k++) {
          if (k != cheapestProducer) {
            // tradingPartners.get(k).expPrice[i]*=.99;
            if (i == 2) {
              message = "no deal, price falls to " + Double.toString(expPrice[i]);
              debug(message, TRADE);
            }
          } else {
            selectProducer(tradingPartners.get(k), i);
          }
        }
      }
      // cph increase buyer's price by changeProp in the event of no producers to reflect scarcity
      // of the good
      // expPrice[i]*=changeProp;
      if (i == GOOD) {
        message =
            "no producers, price of good "
                + Integer.toString(GOOD)
                + " rises to "
                + Double.toString(expPrice[i]);
        // debug(message, PRICE);
      }
    }
  }