Package org.ggp.base.util.statemachine

Examples of org.ggp.base.util.statemachine.StateMachine


        frame.setPreferredSize(new Dimension(1200, 900));
        frame.getContentPane().add(theVisual);
        frame.pack();
        frame.setVisible(true);

        StateMachine theMachine = new CachedStateMachine(new ProverStateMachine());
        theMachine.initialize(theGame.getRules());
        try {
            MachineState theCurrentState = theMachine.getInitialState();
            do {
                theVisual.observe(new ServerNewGameStateEvent(theCurrentState));
                theCurrentState = theMachine.getRandomNextState(theCurrentState);
                Thread.sleep(250);
                System.out.println("State: " + theCurrentState);
            } while(!theMachine.isTerminal(theCurrentState));
            theVisual.observe(new ServerNewGameStateEvent(theCurrentState));
        } catch (Exception e) {
            e.printStackTrace();
        }
  }
View Full Code Here


   * </ol>
   */
  @Override
  public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException
  {
      StateMachine theMachine = getStateMachine();
    long start = System.currentTimeMillis();
    long finishBy = timeout - 1000;

    List<Move> moves = theMachine.getLegalMoves(getCurrentState(), getRole());
    Move selection = (moves.get(new Random().nextInt(moves.size())));

    // Shuffle the moves into a random order, so that when we find the first
    // move that doesn't give our opponent a forced win, we aren't always choosing
    // the first legal move over and over (which is visibly repetitive).
    List<Move> movesInRandomOrder = new ArrayList<Move>();
    while(!moves.isEmpty()) {
        Move aMove = moves.get(theRandom.nextInt(moves.size()));
        movesInRandomOrder.add(aMove);
        moves.remove(aMove);
    }

    // Go through all of the legal moves in a random over, and consider each one.
    // For each move, we want to determine whether taking that move will give our
    // opponent a one-move win. We're also interested in whether taking that move
    // will immediately cause us to win or lose.
    //
    // Our main goal is to find a move which won't give our opponent a one-move win.
    // We will also continue considering moves for two seconds, in case we can stumble
    // upon a move which would cause us to win: if we find such a move, we will just
    // immediately take it.
    boolean reasonableMoveFound = false;
    int maxGoal = 0;
    for(Move moveUnderConsideration : movesInRandomOrder) {
        // Check to see if there's time to continue.
        if(System.currentTimeMillis() > finishBy) break;

        // If we've found a reasonable move, only spend at most two seconds trying
        // to find a winning move.
        if(System.currentTimeMillis() > start + 2000 && reasonableMoveFound) break;

        // Get the next state of the game, if we take the move we're considering.
        // Since it's our turn, in an alternating-play game the opponent will only
        // have one legal move, and so calling "getRandomJointMove" with our move
        // fixed will always return the joint move consisting of our move and the
        // opponent's no-op. In a simultaneous-action game, however, the opponent
        // may have many moves, and so we will randomly pick one of our opponent's
        // possible actions and assume they do that.
        MachineState nextState = theMachine.getNextState(getCurrentState(), theMachine.getRandomJointMove(getCurrentState(), getRole(), moveUnderConsideration));

        // Does the move under consideration end the game? If it does, do we win
        // or lose? If we lose, don't bother considering it. If we win, then we
        // definitely want to take this move. If its goal is better than our current
        // best goal, go ahead and tentatively select it
        if(theMachine.isTerminal(nextState)) {
            if(theMachine.getGoal(nextState, getRole()) == 0) {
                continue;
            } else if(theMachine.getGoal(nextState, getRole()) == 100) {
                  selection = moveUnderConsideration;
                  break;
            } else {
              if (theMachine.getGoal(nextState, getRole()) > maxGoal)
              {
                selection = moveUnderConsideration;
                maxGoal = theMachine.getGoal(nextState, getRole());
              }
              continue;
            }
        }

        // Check whether any of the legal joint moves from this state lead to
        // a loss for us. Again, this only makes sense in the context of an alternating
        // play zero-sum game, in which this is the opponent's move and they are trying
        // to make us lose, and so if they are offered any move that will make us lose
        // they will take it.
        boolean forcedLoss = false;
        for(List<Move> jointMove : theMachine.getLegalJointMoves(nextState)) {
            MachineState nextNextState = theMachine.getNextState(nextState, jointMove);
            if(theMachine.isTerminal(nextNextState)) {
                if(theMachine.getGoal(nextNextState, getRole()) == 0) {
                    forcedLoss = true;
                    break;
                }
            }

View Full Code Here

   * Employs a simple sample "Monte Carlo" algorithm.
   */
  @Override
  public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException
  {
      StateMachine theMachine = getStateMachine();
    long start = System.currentTimeMillis();
    long finishBy = timeout - 1000;

    List<Move> moves = theMachine.getLegalMoves(getCurrentState(), getRole());
    Move selection = moves.get(0);
    if (moves.size() > 1) {
        int[] moveTotalPoints = new int[moves.size()];
        int[] moveTotalAttempts = new int[moves.size()];

View Full Code Here

    return selection;
  }

  private int[] depth = new int[1];
  int performDepthChargeFromMove(MachineState theState, Move myMove) {
      StateMachine theMachine = getStateMachine();
      try {
            MachineState finalState = theMachine.performDepthCharge(theMachine.getRandomNextState(theState, getRole(), myMove), depth);
            return theMachine.getGoal(finalState, getRole());
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
  }
View Full Code Here

      List<Gdl> description = new TestGameRepository().getGame("test_clean_not_distinct").getRules();
        description = GdlCleaner.run(description);

        StaticValidator.validateDescription(description);

        StateMachine sm = new ProverStateMachine();
        sm.initialize(description);
        MachineState state = sm.getInitialState();
        assertEquals(1, sm.getRoles().size());
        Role player = sm.getRoles().get(0);
        assertEquals(1, sm.getLegalMoves(state, player).size());
        state = sm.getNextStates(state).get(0);
        assertTrue(sm.isTerminal(state));
        assertEquals(100, sm.getGoal(state, player));
    }
View Full Code Here

  }

  @Override
  public List<ValidatorWarning> checkValidity(Game theGame) throws ValidatorException {
    try {
      StateMachine sm = new ProverStateMachine();
      sm.initialize(theGame.getRules());

      AimaProver prover = new AimaProver(theGame.getRules());
      GdlSentence basesQuery = GdlPool.getRelation(BASE, new GdlTerm[] {X});
      Set<GdlSentence> bases = prover.askAll(basesQuery, Collections.<GdlSentence>emptySet());
      GdlSentence inputsQuery = GdlPool.getRelation(INPUT, new GdlTerm[] {X, Y});
      Set<GdlSentence> inputs = prover.askAll(inputsQuery, Collections.<GdlSentence>emptySet());

      if (bases.size() == 0) {
        throw new ValidatorException("Could not find base propositions.");
      } else if (inputs.size() == 0) {
        throw new ValidatorException("Could not find input propositions.");
      }

      Set<GdlSentence> truesFromBases = new HashSet<GdlSentence>();
      for (GdlSentence base : bases) {
        truesFromBases.add(GdlPool.getRelation(TRUE, base.getBody()));
      }
      Set<GdlSentence> legalsFromInputs = new HashSet<GdlSentence>();
      for (GdlSentence input : inputs) {
        legalsFromInputs.add(GdlPool.getRelation(LEGAL, input.getBody()));
      }

      if (truesFromBases.isEmpty() && legalsFromInputs.isEmpty()) {
        return ImmutableList.of();
      }

      MachineState initialState = sm.getInitialState();
      MachineState state = initialState;
      long startTime = System.currentTimeMillis();
      while (System.currentTimeMillis() < startTime + millisecondsToTest) {
        //Check state against bases, inputs
        if (!truesFromBases.isEmpty()) {
          if (!truesFromBases.containsAll(state.getContents())) {
            Set<GdlSentence> missingBases = new HashSet<GdlSentence>();
            missingBases.addAll(state.getContents());
            missingBases.removeAll(truesFromBases);
            throw new ValidatorException("Found missing bases: " + missingBases);
          }
        }

        if (!legalsFromInputs.isEmpty()) {
          List<GdlSentence> legalSentences = new ArrayList<GdlSentence>();
          for (Role role : sm.getRoles()) {
            List<Move> legalMoves = sm.getLegalMoves(state, role);
            for (Move move : legalMoves) {
              legalSentences.add(GdlPool.getRelation(LEGAL, new GdlTerm[] {role.getName(), move.getContents()}));
            }
          }
          if (!legalsFromInputs.containsAll(legalSentences)) {
            Set<GdlSentence> missingInputs = new HashSet<GdlSentence>();
            missingInputs.addAll(legalSentences);
            missingInputs.removeAll(legalsFromInputs);
            throw new ValidatorException("Found missing inputs: " + missingInputs);
          }
        }

        state = sm.getRandomNextState(state);
        if (sm.isTerminal(state)) {
          state = initialState;
        }
      }
    } catch (MoveDefinitionException mde) {
      throw new ValidatorException("Could not find legal moves while simulating: " + mde);
View Full Code Here

  }

  @Override
  public List<ValidatorWarning> checkValidity(Game theGame) throws ValidatorException {
    for (int i = 0; i < numSimulations; i++) {
      StateMachine stateMachine = new ProverStateMachine();
      stateMachine.initialize(theGame.getRules());

      MachineState state = stateMachine.getInitialState();
      for (int depth = 0; !stateMachine.isTerminal(state); depth++) {
        if (depth == maxDepth) {
          throw new ValidatorException("Hit max depth while simulating: " + maxDepth);
        }
        try {
          state = stateMachine.getRandomNextState(state);
        } catch (MoveDefinitionException mde) {
          throw new ValidatorException("Could not find legal moves while simulating: " + mde);
        } catch (TransitionDefinitionException tde) {
          throw new ValidatorException("Could not find transition definition while simulating: " + tde);
        }
      }

      try {
        stateMachine.getGoals(state);
      } catch (GoalDefinitionException gde) {
        throw new ValidatorException("Could not find goals while simulating: " + gde);
      }
    }
    return ImmutableList.of();
View Full Code Here

            validate();
            runButton.setEnabled(false);
            if (theGame == null)
                return;

            StateMachine stateMachine = new ProverStateMachine();
            stateMachine.initialize(theGame.getRules());
            List<Role> roles = stateMachine.getRoles();

            int newRowCount = 11;
            for (int i = 0; i < roles.size(); i++) {
                roleLabels.add(new JLabel(roles.get(i).getName().toString() + ":"));
                playerFields.add(playerSelector.getPlayerSelectorBox());
View Full Code Here

TOP

Related Classes of org.ggp.base.util.statemachine.StateMachine

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.