Package org.ggp.base.util.match

Examples of org.ggp.base.util.match.Match


  @Override
  public void observe(Event genericEvent) {
    if (!(genericEvent instanceof ServerMatchUpdatedEvent)) return;
    ServerMatchUpdatedEvent event = (ServerMatchUpdatedEvent)genericEvent;
    Match match = event.getMatch();

    DefaultTableModel model = (DefaultTableModel) queueTable.getModel();
    for (int i = 0; i < model.getRowCount(); i++) {
      String rowMatchId = model.getValueAt(i, 0).toString();
      if (rowMatchId.equals(match.getMatchId())) {
        String status = "active";
        if (match.isAborted()) status = "aborted";
        if (match.isCompleted()) status = "done";
        model.setValueAt(status, i, 3);
        if (match.isCompleted()) {
          model.setValueAt(getLinebreakString(match.getGoalValues()), i, 5);
        }
        List<Integer> errorCounts = new ArrayList<Integer>();
        List<String> errorCountStrings = new ArrayList<String>();
        for (int j = 0; j < match.getPlayerNamesFromHost().size(); j++) {
          errorCounts.add(0);
        }
        for (List<String> errors : match.getErrorHistory()) {
          for (int j = 0; j < errors.size(); j++) {
            if (!errors.get(j).isEmpty()) {
              errorCounts.set(j, errorCounts.get(j) + 1);
            }
          }
        }
        for (int errorCount : errorCounts) {
          if (errorCount > 0) {
            errorCountStrings.add("<font color=red>" + errorCount + "</font>");
          } else {
            errorCountStrings.add("0");
          }
        }
        model.setValueAt(getLinebreakString(errorCountStrings), i, 6);
        model.setValueAt(match.getStateHistory().size()-1, i, 7);

        if (event.getExternalPublicationKey() != null) {
          matchIdToURL.put(match.getMatchId(), "http://www.ggp.org/view/all/matches/" + event.getExternalPublicationKey() + "/");
        }
        if (event.getExternalFilename() != null) {
          matchIdToFilename.put(match.getMatchId(), event.getExternalFilename());
        }

        return;
      }
    }

    // Couldn't find the match in the existing list -- add it.
    model.addRow(new Object[]{match.getMatchId(),match.getGame().getKey(),match.getStartClock() + "," + match.getPlayClock(),"starting",getLinebreakString(match.getPlayerNamesFromHost()),"","",0});
    queueTable.setRowHeight(model.getRowCount()-1, match.getPlayerNamesFromHost().size()*20);
  }
 
View Full Code Here


    }
  }

  private synchronized void doSchedule(PendingMatch spec) {
    try {
      Match match = new Match(spec.matchID, spec.previewClock, spec.startClock, spec.playClock, spec.theGame);

      List<String> hosts = new ArrayList<String>(spec.thePlayers.size());
      List<Integer> ports = new ArrayList<Integer>(spec.thePlayers.size());
      List<String> playerNames = new ArrayList<String>(spec.thePlayers.size());
      for (PlayerPresence player : spec.thePlayers) {
                hosts.add(player.getHost());
                ports.add(player.getPort());
                playerNames.add(player.getName());
      }

      HistoryPanel historyPanel = new HistoryPanel();
      ErrorPanel errorPanel = new ErrorPanel();
      VisualizationPanel visualizationPanel = new VisualizationPanel(spec.theGame);
      StatesPanel statesPanel = new StatesPanel();

      if (spec.shouldDetail) {
        JTabbedPane tab = new JTabbedPane();
        tab.addTab("History", historyPanel);
        tab.addTab("Error", errorPanel);
        tab.addTab("Visualization", visualizationPanel);
        tab.addTab("States", statesPanel);
        CloseableTabs.addClosableTab(matchesTabbedPane, tab, spec.matchID, addTabCloseButton(tab));
      }

      match.setCryptographicKeys(signingKeys);
      match.setPlayerNamesFromHost(playerNames);
      if (spec.shouldScramble) {
        match.enableScrambling();
      }

      GameServer gameServer = new GameServer(match, hosts, ports);
      if (spec.shouldDetail) {
        gameServer.addObserver(errorPanel);
        gameServer.addObserver(historyPanel);
        gameServer.addObserver(visualizationPanel);
        gameServer.addObserver(statesPanel);
      }
      gameServer.addObserver(schedulingPanel);
      gameServer.addObserver(leaderboardPanel);
      gameServer.addObserver(this);
      gameServer.start();

      activePlayers.addAll(playerNames);

      if (spec.shouldSave) {
        File matchesDir = new File(System.getProperty("user.home"), "ggp-saved-matches");
        if (!matchesDir.exists()) {
          matchesDir.mkdir();
        }
        File matchFile = new File(matchesDir, match.getMatchId() + ".json");
        gameServer.startSavingToFilename(matchFile.getAbsolutePath());
      }
      if (spec.shouldPublish) {
        if (!match.getGame().getRepositoryURL().contains("127.0.0.1")) {
          gameServer.startPublishingToSpectatorServer("http://matches.ggp.org/");
          gameServer.setForceUsingEntireClock();
        }
      }
View Full Code Here

  @Override
  public void observe(Event genericEvent) {
    if (!(genericEvent instanceof ServerMatchUpdatedEvent)) return;
    ServerMatchUpdatedEvent event = (ServerMatchUpdatedEvent)genericEvent;
    Match match = event.getMatch();
    if (!match.isAborted() && !match.isCompleted()) return;
    activePlayers.removeAll(match.getPlayerNamesFromHost());
  }
View Full Code Here

    public void testClojureGamer() {
        try {
            Gamer g = new SampleClojureGamerStub();
            assertEquals("SampleClojureGamer", g.getName());

            Match m = new Match("", -1, 1000, 1000, GameRepository.getDefaultRepository().getGame("ticTacToe"));
            g.setMatch(m);
            g.setRoleName(GdlPool.getConstant("xplayer"));
            g.metaGame(1000);
            assertTrue(g.selectMove(1000) != null);
        } catch(Exception e) {
View Full Code Here

            return "busy";
        }

        // Create the new match, and handle all of the associated logistics
        // in the gamer to indicate that we're starting a new match.
    Match match = new Match(matchId, -1, startClock, playClock, game);
    gamer.setMatch(match);
    gamer.setRoleName(roleName);
    gamer.notifyObservers(new GamerNewMatchEvent(match, roleName));

    // Finally, have the gamer begin metagaming.
View Full Code Here

    public static final boolean hideControlProposition = true;
    public static final boolean showCurrentState = false;

    public static void main(String[] args) throws InterruptedException {
        final Game theGame = GameRepository.getDefaultRepository().getGame("nineBoardTicTacToe");
        final Match theMatch = new Match("simpleGameSim." + Match.getRandomString(5), -1, 0, 0, theGame);
        try {
            // Load a sample set of cryptographic keys. These sample keys are not secure,
            // since they're checked into the public GGP Base SVN repository. They are provided
            // merely to illustrate how the crypto key API in Match works. If you want to prove
            // that you ran a match, you need to generate your own pair of cryptographic keys,
            // keep them secure and hidden, and pass them to "setCryptographicKeys" in Match.
            // The match will then be signed using those keys. Do not use the sample keys if you
            // want to actually prove anything.
            theMatch.setCryptographicKeys(new EncodedKeyPair(FileUtils.readFileAsString(new File("src/org/ggp/base/apps/utilities/SampleKeys.json"))));
        } catch (JSONException e) {
            System.err.println("Could not load sample cryptograhic keys: " + e);
        }

        // Set up fake players to pretend to play the game
        List<String> fakeHosts = new ArrayList<String>();
        List<Integer> fakePorts = new ArrayList<Integer>();
        for (int i = 0; i < Role.computeRoles(theGame.getRules()).size(); i++) {
          fakeHosts.add("SamplePlayer" + i);
          fakePorts.add(9147+i);
        }

        // Set up a game server to play through the game, with all players playing randomly.
        final GameServer theServer = new GameServer(theMatch, fakeHosts, fakePorts);
        for (int i = 0; i < fakeHosts.size(); i++) {
          theServer.makePlayerPlayRandomly(i);
        }

        // TODO: Allow a custom state machine to be plugged into the GameServer so that we can
        // simulate games using this tool with custom state machines, to verify they're sane.

        final Set<GdlSentence> oldContents = new HashSet<GdlSentence>();
        final int[] nState = new int[1];
        theServer.addObserver(new Observer() {
      @Override
      public void observe(Event event) {
        if (event instanceof ServerNewGameStateEvent) {
          MachineState theCurrentState = ((ServerNewGameStateEvent)event).getState();
                  if(nState[0] > 0) System.out.print("State[" + nState[0] + "]: ");
                  Set<GdlSentence> newContents = theCurrentState.getContents();
                  for(GdlSentence newSentence : newContents) {
                      if(hideStepCounter && newSentence.toString().contains("step")) continue;
                      if(hideControlProposition && newSentence.toString().contains("control")) continue;
                      if(!oldContents.contains(newSentence)) {
                          System.out.print("+" + newSentence + ", ");
                      }
                  }
                  for(GdlSentence oldSentence : oldContents) {
                      if(hideStepCounter && oldSentence.toString().contains("step")) continue;
                      if(hideControlProposition && oldSentence.toString().contains("control")) continue;
                      if(!newContents.contains(oldSentence)) {
                          System.out.print("-" + oldSentence + ", ");
                      }
                  }
                  System.out.println();
                  oldContents.clear();
                  oldContents.addAll(newContents);

                  if(showCurrentState) System.out.println("State[" + nState[0] + "] Full: " + theCurrentState);
                  nState[0]++;
        } else if (event instanceof ServerNewMovesEvent) {
          System.out.println("Move taken: " + ((ServerNewMovesEvent)event).getMoves());
        } else if (event instanceof ServerCompletedMatchEvent) {
              System.out.println("State[" + nState[0] + "] Full (Terminal): " + oldContents);
              System.out.println("Match information: " + theMatch);
              System.out.println("Goals: " + ((ServerCompletedMatchEvent)event).getGoals());
              try {
                System.out.println("Match information cryptographically signed? " + SignableJSON.isSignedJSON(new JSONObject(theMatch.toJSON())));
                System.out.println("Match information cryptographic signature valid? " + SignableJSON.verifySignedJSON(new JSONObject(theMatch.toJSON())));
              } catch (JSONException je) {
                je.printStackTrace();
              }
              System.out.println("Game over.");
        }
View Full Code Here

    }
    int expectedRoles = Role.computeRoles(game.getRules()).size();
    if (hostNames.size() != expectedRoles) {
      throw new RuntimeException("Invalid number of players for game " + gameKey + ": " + hostNames.size() + " vs " + expectedRoles);
    }
    Match match = new Match(matchName, -1, startClock, playClock, game);
    match.setPlayerNamesFromHost(playerNames);

    // Actually run the match, using the desired configuration.
    GameServer server = new GameServer(match, hostNames, portNumbers);
    server.start();
    server.join();

    // Open up the directory for this tournament.
    // Create a "scores" file if none exists.
    File f = new File(tourneyName);
    if (!f.exists()) {
      f.mkdir();
      f = new File(tourneyName + "/scores");
      f.createNewFile();
    }

    // Open up the XML file for this match, and save the match there.
    f = new File(tourneyName + "/" + matchName + ".xml");
    if (f.exists()) f.delete();
    BufferedWriter bw = new BufferedWriter(new FileWriter(f));
    bw.write(match.toXML());
    bw.flush();
    bw.close();

    // Open up the JSON file for this match, and save the match there.
    f = new File(tourneyName + "/" + matchName + ".json");
    if (f.exists()) f.delete();
    bw = new BufferedWriter(new FileWriter(f));
    bw.write(match.toJSON());
    bw.flush();
    bw.close();

    // Save the goals in the "/scores" file for the tournament.
    bw = new BufferedWriter(new FileWriter(tourneyName + "/scores", true));
View Full Code Here

  @Override
  public void observe(Event event)
  {
    if (!(event instanceof ServerMatchUpdatedEvent)) return;
    Match match = ((ServerMatchUpdatedEvent) event).getMatch();

    if (!match.isCompleted()) return;
    if (match.getMatchId().startsWith("Test")) return;

    List<Integer> goals = match.getGoalValues();
    List<Integer> errors = getErrorCounts(match.getErrorHistory());
    List<String> players = match.getPlayerNamesFromHost();
    for (int i = 0; i < players.size(); i++) { if (players.get(i)==null) { players.set(i, "?"); } }

    Set<String> playersToAdd = new HashSet<String>(players);
    DefaultTableModel model = (DefaultTableModel) leaderTable.getModel();
    for (int i = 0; i < model.getRowCount(); i++) {
View Full Code Here

                }

                String matchId = "kiosk." + theGame.kifFile + "-" + System.currentTimeMillis();
                int startClock = Integer.valueOf(startClockTextField.getText());
                int playClock = Integer.valueOf(playClockTextField.getText());
                Match match = new Match(matchId, -1, startClock, playClock, game);
                theHumanGamer.setCanvas(theGame.getCanvas());

                // Stop old player if it's not the right type
                String computerPlayerName = (String) playerComboBox.getSelectedItem();
                if(theComputerPlayer != null && !theComputerPlayer.getGamer().getName().equals(computerPlayerName)) {
                    theComputerPlayer.interrupt();
                    Thread.sleep(100);
                    theComputerPlayer = null;
                }

                // Start a new player if necessary
                if(theComputerPlayer == null) {
                    Gamer gamer = null;
                    if(!playerComboBox.getSelectedItem().equals(remotePlayerString)) {
                        Class<?> gamerClass = gamers.get(playerComboBox.getSelectedIndex());
                        try {
                            gamer = (Gamer) gamerClass.newInstance();
                        } catch(Exception ex) { throw new RuntimeException(ex); }
                        theComputerPlayer = new GamePlayer(DEFAULT_COMPUTER_PORT, gamer);
                        theComputerPlayer.start();
                        System.out.println("Kiosk has started a gamer named " + theComputerPlayer.getGamer().getName() + ".");
                    }
                }

                List<String> hosts = new ArrayList<String>();
                List<Integer> ports = new ArrayList<Integer>();
                List<String> playerNames = new ArrayList<String>();

                if(!flipRoles.isSelected()) {
                    hosts.add("127.0.0.1");
                    ports.add(theHumanPlayer.getGamerPort());
                    playerNames.add("Human");
                }

                if(playerComboBox.getSelectedItem().equals(remotePlayerString)) {
                    try {
                        String[] splitAddress = computerAddress.getText().split(":");
                        String hostname = splitAddress[0];
                        int port = Integer.parseInt(splitAddress[1]);

                        hosts.add(hostname);
                        ports.add(port);
                        playerNames.add("Computer");
                    } catch(Exception ex) {
                        ex.printStackTrace();
                        return;
                    }
                } else {
                    hosts.add("127.0.0.1");
                    ports.add(theComputerPlayer.getGamerPort());
                    playerNames.add("Computer");
                }

                if(flipRoles.isSelected()) {
                    hosts.add("127.0.0.1");
                    ports.add(theHumanPlayer.getGamerPort());
                    playerNames.add("Human");
                }

                match.setPlayerNamesFromHost(playerNames);

                GamerLogger.startFileLogging(match, "kiosk");
                kioskServer = new GameServer(match, hosts, ports);
                kioskServer.givePlayerUnlimitedTime((flipRoles.isSelected()? 1 : 0));
                kioskServer.addObserver(theHumanGamer);
View Full Code Here

    public void testPythonGamer() {
        try {
            Gamer g = new SamplePythonGamerStub();
            assertEquals("SamplePythonGamer", g.getName());

            Match m = new Match("", -1, 1000, 1000, GameRepository.getDefaultRepository().getGame("ticTacToe"));
            g.setMatch(m);
            g.setRoleName(GdlPool.getConstant("xplayer"));
            g.metaGame(1000);
            assertTrue(g.selectMove(1000) != null);
        } catch(Exception e) {
View Full Code Here

TOP

Related Classes of org.ggp.base.util.match.Match

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.