public static void main(String[] args) {
    startUpRoleChooser();
    int night = 1;
    Collections.sort(game.getPlayers(), new PriorityComp());
    CardHash hash = new CardHash(game.getPlayers());
    System.out.println();
    System.out.println("These cards represent the different roles for the people.");
    System.out.println(hash);
    while (game.checkWinConditions() == 0) { // loop
      // game.tick();
      System.out.println();
      System.out.println("Night " + night + "\nEverybody go to sleep!");

      night++;
      loopThroughPlayers();
      queryPlayers("");
      System.out.println();
      System.out.println("Everybody wake up!");

      System.out.println();
      printAll(); // test
      System.out.println();

      System.out.println(game.processMarks());

      System.out.println();
      printAll(); // test
      System.out.println();

      if (game.checkWinConditions() != 0) {
        break;
      }
      dayTime();
    }
  }
Exemple #2
0
 public BoardPanel(
     final JFrame frame,
     Game game,
     UnitTypeConfiguration unitTypeConfiguration,
     TileTypeConfiguration tileTypeConfiguration,
     TileStateConfiguration tileStateConfiguration,
     ChessMovementStrategy movementStrategy,
     UnitSelectorMode unitSelectorMode,
     BattleStrategyConfiguration battleStrategyConfiguration) {
   this.frame = frame;
   this.battleStrategyConfiguration = battleStrategyConfiguration;
   thisPanel = this;
   this.game = game;
   game.addGameObserver(this);
   this.board = game.getBoard();
   this.movementStrategy = movementStrategy;
   int rows = board.getDimension().getHeight();
   int columns = board.getDimension().getWidth();
   setLayout(new GridLayout(rows, columns));
   for (Tile tile : board.getTiles()) {
     final TilePanel tilePanel =
         new TilePanel(tileTypeConfiguration, unitTypeConfiguration, tileStateConfiguration, tile);
     if (UnitSelectorMode.MULTIPLE.equals(unitSelectorMode)) {
       tilePanel.addMouseListener(
           new MultipleUnitSelectorMouseListener(tilePanel, frame, thisPanel));
     }
     if (UnitSelectorMode.SINGLE.equals(unitSelectorMode)) {
       tilePanel.addMouseListener(
           new SingleUnitSelectorMouseListener(tilePanel, frame, thisPanel));
     }
     map.put(tile, tilePanel);
     add(tilePanel);
   }
   resetPositions();
 }
  public static void dayTime() { // daytime phase
    Scanner s = new Scanner(System.in);

    System.out.println("It's daytime! Discuss who you wanna lynch, if anyone.");
    System.out.print("Do you want to lynch someone? (Y/N) ");

    String in = s.nextLine();
    in = in.toLowerCase();
    while (!(in.equals("y") || in.equals("n") || in.equals("no") || in.equals("yes"))) {
      System.out.print("Please input Y/N/Yes/No: ");
      in = s.nextLine();
    }

    if (in.equals("no") || in.equals("n")) {
      return;
    } else { // yes
      System.out.print("Who do you wanna lynch? ");
      printAll();
      in = s.nextLine();
      while (!(playerExists(in, game.getPlayers()))) {
        System.out.print("Please choose someone in the game: ");
        in = s.nextLine();
      }
      game.removePlayer(in);
    }
  }
Exemple #4
0
  public void startNGameCycles(Runnable finalAction, int nrOfRuns) {
    Class currWhitePlayer = whitePlayer.getClass();
    Class currBlackPlayer = blackPlayer.getClass();

    new Thread(
            () -> {
              for (int i = 0; i < nrOfRuns; i++) {
                progressOfNGames = OptionalDouble.of((double) i / nrOfRuns);

                GipfBoardState gipfBoardStateCopy =
                    new GipfBoardState(
                        getGipfBoardState(), gipfBoardState.getPieceMap(), gipfBoardState.players);
                Game copyOfGame = new BasicGame();
                try {
                  copyOfGame.whitePlayer = (ComputerPlayer) currWhitePlayer.newInstance();
                  copyOfGame.blackPlayer = (ComputerPlayer) currBlackPlayer.newInstance();
                } catch (InstantiationException | IllegalAccessException e) {
                  e.printStackTrace();
                }
                copyOfGame.loadState(gipfBoardStateCopy);

                GameLoopThread gameLoopThread = new GameLoopThread(copyOfGame, finalAction);
                gameLoopThread.start();
                try {
                  gameLoopThread.join();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
              }

              progressOfNGames = OptionalDouble.empty();
            })
        .start();
  }
 public void hitResponse(String response) {
   StringTokenizer st = new StringTokenizer(response);
   int k = 0;
   String side = null;
   int x = -1;
   int y = -1;
   while (st.hasMoreTokens()) {
     if (k == 0) st.nextToken();
     if (k == 1) side = st.nextToken();
     if (k == 2) x = Integer.parseInt(st.nextToken());
     if (k == 3) y = Integer.parseInt(st.nextToken());
     k++;
   }
   System.out.println(gameData.getPlayerSide());
   System.out.println(side);
   if (gameData.getPlayerSide().equals(side)) {
     System.out.println("player field hit");
     gameData.shootAtField(side, x, y, 3, false, null, null, -1, -1);
     mw.v.enqueEvent(new CustomEvent(CustomEvent.PLAYER_FIELD_HIT, x, y));
   } else {
     System.out.println("enemy field hit");
     gameData.shootAtField(side, x, y, 3, false, null, null, -1, -1);
     mw.v.enqueEvent(new CustomEvent(CustomEvent.OPPONENT_FIELD_HIT, x, y));
   }
 }
Exemple #6
0
 private void watchLastRound(Game g) {
   if (true) return;
   int rounds = g.rounds();
   Game.Round lastRound = g.round(rounds - 1);
   if (attacking) processRnd(myTeam, opposingTeam, lastRound);
   else processRnd(opposingTeam, myTeam, lastRound);
 }
 private void removePlayer(Player player) {
   int index = players.indexOf(player);
   if (index < 0) return;
   players.remove(index);
   Game game = games.remove(index);
   removeController(player, index);
   game.destroy();
 }
  @Override
  public void nextStepForAllGames() {
    lock.writeLock().lock();
    try {
      for (Game game : games) {
        if (game.isGameOver()) {
          game.newGame();
        }
        game.tick();
      }

      HashMap<Player, PlayerData> map = new HashMap<Player, PlayerData>();
      for (int i = 0; i < games.size(); i++) {
        Game game = games.get(i);

        Player player = players.get(i);

        map.put(
            player,
            new PlayerData(
                gameType.getBoardSize(),
                decoder.encode(game.getBoardAsString()),
                player.getScore(),
                game.getMaxScore(),
                game.getCurrentScore(),
                player.getCurrentLevel() + 1,
                player.getMessage()));
      }

      screenSender.sendUpdates(map);

      for (int index = 0; index < players.size(); index++) {
        Player player = players.get(index);
        Game game = games.get(index);
        try {
          String board = game.getBoardAsString().replace("\n", "");

          if (logger.isDebugEnabled()) {
            logger.debug(String.format("Sent for player '%s' board \n%s", player, board));
          }

          controllers.get(index).requestControl(player, board);
        } catch (IOException e) {
          logger.error(
              "Unable to send control request to player "
                  + player.getName()
                  + " URL: "
                  + player.getCallbackUrl(),
              e);
        }
      }
    } catch (Error e) {
      e.printStackTrace();
      logger.error("nextStepForAllGames throws", e);
    } finally {
      lock.writeLock().unlock();
    }
  }
Exemple #9
0
  public Game create(String name, int nValue, int dropNumber, EndPoint ep) {
    GameInfo gi = new GameInfo(name, nValue, dropNumber, ep);
    Game g = gi.game;

    map.put(g.getId(), gi);
    epMap.put(ep, gi);
    onGameListUpdate();
    return g;
  }
Exemple #10
0
  @Before
  public void setup() {
    Fixtures.deleteAll();

    Fixtures.load("data.yml");

    duckRunnerGame = Game.find("byName", "Duck Runner").first();
    parkingLotGame = Game.find("byName", "Parking Lot").first();
  }
Exemple #11
0
  // get all quests currenty active
  public static ArrayList getQuests() {
    ArrayList qs = (ArrayList) Game.hero().get("Quests");
    if (qs == null) {
      qs = new ArrayList();
      Game.hero().set("Quests", qs);
    }

    return qs;
  }
  @Override
  protected void onStart() {
    super.onStart();

    em = new EntityManager();
    MetaEntity.defaultEntityManager = em;
    Game game = new Game(em);

    /** create the surface + thread */
    SurfaceViewThePit surfaceView = new SurfaceViewThePit(this, game);
    RenderSystemSimpleDrawable renderSystem = new RenderSystemSimpleDrawable(em, surfaceView, game);
    MainRunThread runGameThread = new MainRunThread(this, em, surfaceView, renderSystem);
    runGameThread.loadAllCoreSubSystems();

    // runGameThread.setGameResult( gameToStart );
    SubsystemTouchHandler systemTh = new SubsystemTouchHandler(em);
    runGameThread.orderedSubSystems.addLast(systemTh); // MUST be before the Collision Subsystem
    TouchListenerPlayerMovement thv = new TouchListenerPlayerMovement(systemTh);

    SubsystemGhosts systemGhosts = new SubsystemGhosts(em, game);
    runGameThread.orderedSubSystems.addLast(systemGhosts);

    SubsystemMovementAndCollision systemCollision =
        new SubsystemMovementAndCollision(em, renderSystem);
    runGameThread.orderedSubSystems.addLast(systemCollision);

    SubsystemLighting systemLighting = new SubsystemLighting(em, game);
    runGameThread.orderedSubSystems.addLast(systemLighting);

    SubsystemTriggers systemTriggers = new SubsystemTriggers(this, em, game);
    runGameThread.orderedSubSystems.addLast(systemTriggers);

    surfaceView.setOnTouchListener(thv);
    surfaceView.thread = runGameThread;
    Log.i(getClass().getSimpleName(), "initialized thread and surface");

    /**
     * Finally ... tell the game that the ES is now valid, it's ship reference is OK, and it can do
     * game-setup
     */
    game.preSetupGame();
    renderSystem.shiftCanvasToKeepPositionOnScreen(
        new CPosition(
            game.initialPlayerLocation.x,
            game.initialPlayerLocation.y,
            game.mazeCellWidth,
            game.mazeCellHeight));

    // turn off the window's title bar
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow()
        .setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(surfaceView);
  }
Exemple #13
0
 public void removeGame(Game g) {
   GameInfo gi = map.get(g.getId());
   gi.epArr[0].close();
   epMap.remove(gi.epArr[0]);
   if (gi.epArr[1] != null) {
     gi.epArr[1].close();
     epMap.remove(gi.epArr[1]);
   }
   map.remove(g.getId());
   onGameListUpdate();
 }
Exemple #14
0
  public static Thing createHero(String name, String race, String profession) {

    Thing h = createBaseHero(race);
    Game.instance().initialize(h);

    if ((name == null) || (name.equals(""))) name = "Tester";
    setHeroName(h, name);

    // Debug mode modifications
    if (Game.isDebug()) {
      addDebugModifications(h);
    }

    // Race Modifications
    applyRace(h, race);

    // Professions
    applyProfession(h, profession);

    // Bonus items based on skills
    applyBonusItems(h);

    // set up HPS and MPS
    h.set(RPG.ST_HPSMAX, h.getBaseStat(RPG.ST_TG) + RPG.d(6));
    h.set(RPG.ST_MPSMAX, h.getBaseStat(RPG.ST_WP) + RPG.d(6));

    h.set(RPG.ST_HPS, h.getStat(RPG.ST_HPSMAX));
    h.set(RPG.ST_MPS, h.getStat(RPG.ST_MPSMAX));

    Being.utiliseItems(h);

    Wish.makeWish("id", 100);

    // score starts at zero
    h.set("Score", 0);

    // religion
    ArrayList gods = Gods.getPossibleGods(h);
    int gl = gods.size();
    if (gl > 0) {
      h.set("Religion", gods.get(RPG.r(gl)));
    } else {
      Game.warn("No religion available for " + race + " " + profession);
    }

    createHeroHistory(h);

    // performance improvement with flattened properties
    h.flattenProperties();

    return h;
  }
  /**
   * Test load simple gnugo.
   *
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public void testLoadSimpleGnugo() throws IOException {

    Game game = Game.loadFromFile(new File("sgf/testing/simpleGnuGo.sgf"));
    Iterator<Move> i = game.getMoves();
    Move move = null;
    BoardI board = new SmallerBoard(game.getSize());
    while (i.hasNext()) {
      move = i.next();
      assertNotNull(move);
      board = board.newBoard(move);
    }
    // System.err.println(g);
  }
  /**
   * Test load all sg ffiles.
   *
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public void testLoadAllSGFfiles() throws IOException {
    Stack<String> files = new Stack<String>();
    files.push("sgf/2004-12");
    int count = 0;

    while (files.size() > 0 && count <= 10) {
      String filename = files.pop();
      File file = new File(filename);
      count++;
      if (DEBUG) System.err.println("examining \"" + filename + "\"");
      if (file.exists()) {
        if (!file.isDirectory()) {
          // System.err.println("\"" + filename + "\" is not a
          // directory, parsing as an SGF file");

          Game game = Game.loadFromFile(file);
          if (game.getSize() == 19) {
            Iterator<Move> i = game.getMoves();
            Move move = null;
            BoardI board = new SmallerBoard(game.getSize());
            // System.err.println("board size is: \"" +
            // goGame.getSize()
            // + "\"");
            while (i.hasNext()) {
              move = i.next();
              assertNotNull(move);
              // System.err.print("move: \"" + move + "\"");
              // assertTrue("" + board + "\n" +
              // move.toString(),board.isLegalMove(move));
              board = board.newBoard(move);
              // System.err.println(" board size is: \"" +
              // board.getSize() + "\"");
            }
            // System.err.println();

          }
        } else {
          if (DEBUG) System.err.println("\"" + filename + "\" is a directory");
          if (!file.getName().contains(".svn")) {
            String[] children = file.list();
            for (int i = 0; i < children.length; i++) {
              // System.err.println("pushing \"" + children[i] +
              // "\"");
              files.push(filename + "/" + children[i]);
            }
          }
        }
      }
    }
  }
Exemple #17
0
  public void play(int lv) {
    jl.setText("Level " + level);
    Game game = new Game(lv); // An object representing the game
    View view = new View(game); // An object representing the view of the game
    game.newGame();
    view.print();
    gameBoardPanel = view.mainPanel;
    ButtonPanel buttonPanel = new ButtonPanel(game);
    container.add(buttonPanel, BorderLayout.EAST);
    container.add(gameBoardPanel, BorderLayout.WEST);
    mainFrame.pack();

    // Main game loop
    while (true) {

      view.print();
      gameBoardPanel = view.mainPanel;

      // Win/lose conditions
      if (game.isWin()) {
        view.print();
        gameBoardPanel = view.mainPanel;
        int choice;
        choice = JOptionPane.showConfirmDialog(null, "You win!", "", JOptionPane.OK_OPTION);
        if (choice == JOptionPane.OK_OPTION) {
          level++;
          mainFrame.remove(buttonPanel);
          mainFrame.remove(gameBoardPanel);
          play(level);
        }
      }
      if (game.isLose()) {
        view.print();
        gameBoardPanel = view.mainPanel;
        int choice;
        choice =
            JOptionPane.showConfirmDialog(
                null, "You lose!", "Would you like to play again?", JOptionPane.YES_NO_OPTION);
        if (choice == JOptionPane.YES_OPTION) {
          level = 1;
          mainFrame.remove(buttonPanel);
          mainFrame.remove(gameBoardPanel);
          play(level);
        } else {
          System.exit(0);
        }
      }
    }
  }
Exemple #18
0
  // enter a world map square
  //  - if there is a portal to a special location then use it
  //  - else create the appropraite outdoor area map
  //
  public static void exitWorldMap(Map m, int tx, int ty) {
    Thing h = Game.hero();

    // record movement time
    Time.logTime(Movement.moveCost(m, h, tx, ty));

    Thing p = m.getFlaggedObject(tx, ty, "IsPortal");
    if (p != null) {
      Portal.travel(p, h);
    } else {
      // put hero into a local area map
      Map nm = WorldMap.createArea(m, tx, ty);

      // phantom Portal
      p = Portal.create();
      Thing t = nm.getEntrance();
      Portal.setDestination(p, nm, t.x, t.y);

      // could build a portal here so we can return to exact location map
      // Don't think we really want this though
      //   addThing(p,tx,ty);

      Portal.travel(p, h);
    }
  }
Exemple #19
0
  @Test
  public void evenlyRandomlySelectsGame() {
    boolean duckRunnerGameFetched = false;
    boolean parkingLotGameFetched = false;

    // two games should be fetched by random chance

    for (int i = 0; i < 25; i++) {
      String aRandomGameName = Game.random().name;
      assertNotNull(aRandomGameName);

      if (aRandomGameName == duckRunnerGame.name) {
        duckRunnerGameFetched = true;
      } else if (aRandomGameName == parkingLotGame.name) {
        parkingLotGameFetched = true;
      } else {
        fail("should select existing games only...");
      }
    }

    if (!duckRunnerGameFetched) {
      fail("duck runner game should've been selected...");
    }

    if (!parkingLotGameFetched) {
      fail("parking lot game should've been selected...");
    }
  }
Exemple #20
0
	public static void blinkDeathmatchScoreboard( Player client )
	{
		// if during intermission, we must blink our header if we're the winning team (or tie)
		//if ( inIntermission && ((int)Game.getGameTime()%2 == 0 ) )	// blink every second
		if ( (int)Game.getGameTime()%2 == 0 )	// blink every second
		{
			if ( TEAM1.getCaptures() > TEAM2.getCaptures() )
				client.fEntity.setPlayerStat( STAT_CTF_TEAM1_HEADER, (short)0 );
			else if ( TEAM2.getCaptures() > TEAM1.getCaptures() )
				client.fEntity.setPlayerStat( STAT_CTF_TEAM2_HEADER, (short)0 );
			// Capture tie, check total frags
			else if ( TEAM1.getScore() > TEAM2.getScore() )
				client.fEntity.setPlayerStat( STAT_CTF_TEAM1_HEADER, (short)0 );
			else if ( TEAM2.getScore() > TEAM1.getScore() )
				client.fEntity.setPlayerStat( STAT_CTF_TEAM2_HEADER, (short)0 );
			else
			{	// tie game
				client.fEntity.setPlayerStat( STAT_CTF_TEAM1_HEADER, (short)0 );
				client.fEntity.setPlayerStat( STAT_CTF_TEAM2_HEADER, (short)0 );
			}
		}
		else
		{
			// show both if not blinked
			client.fEntity.setPlayerStat( STAT_CTF_TEAM1_HEADER, (short)Engine.getImageIndex("ctfsb1") );
			client.fEntity.setPlayerStat( STAT_CTF_TEAM2_HEADER, (short)Engine.getImageIndex("ctfsb2") );
		}
	}
Exemple #21
0
	public void addPlayer( Player p )
	{
		if (fPlayers.contains(p))
			return; // already joined this team
			
		fPlayers.addElement( p );

		// make sure we find out if the team member disconnects
		p.addPlayerStateListener(this);

		// act as a damage filter for this member
		p.addDamageListener(this);

		// assign new skin
		assignSkinTo( p );
		Object[] args = {p.getName(), fTeamIndex};
		Game.localecast("q2java.ctf.CTFMessages", "join_team", args, Engine.PRINT_HIGH);	
		
		//update players stats that he joined this team (the yellow line around team-icon)
		int index1 = ( this == Team.TEAM1 ? STAT_CTF_JOINED_TEAM1_PIC : STAT_CTF_JOINED_TEAM2_PIC );
		int index2 = ( this == Team.TEAM1 ? STAT_CTF_JOINED_TEAM2_PIC : STAT_CTF_JOINED_TEAM1_PIC );
		int picnum = Engine.getImageIndex("i_ctfj");
		p.fEntity.setPlayerStat( index1, (short)picnum );
		p.fEntity.setPlayerStat( index2, (short)0      );
	}
  public void loseGame() {
    final GameBoard boardView = (GameBoard) this.findViewById(R.id.gameBoard);

    game.reInitGame();

    boardView.setGame(game);
    boardView.invalidate();
  }
Exemple #23
0
 private void repaintPanels(Iterable<TilePanel> panels) {
   long start = System.currentTimeMillis();
   for (TilePanel panel : panels) {
     game.notifyGameObservers(panel.getTile().getPosition());
   }
   long stop = System.currentTimeMillis();
   Logger.getLogger(BoardPanel.class).debug("Repaint time: " + (stop - start) / 1000.0);
 }
 public static boolean validateName(String name) { // to make sure nobody has the same name
   for (Player p : game.getPlayers()) {
     if (name.equals(p.getName())) { // muy mal
       return false;
     }
   }
   return true;
 }
Exemple #25
0
 private static HashMap getKillHashMap() {
   Thing h = Game.hero();
   HashMap hm = (HashMap) h.get("Kills");
   if (hm == null) {
     hm = new HashMap();
     h.set("Kills", hm);
   }
   return hm;
 }
 public static void loopThroughPlayers() {
   String playersstr = ""; // contains all playernames
   ArrayList<Player> players = game.getPlayers(); // assuming this is sorted
   for (Player currentP : players) {
     playersstr += currentP.getName() + " ";
   }
   playersstr = playersstr.substring(0, playersstr.length() - 1); // just to remove the last space
   System.out.println(playersstr);
 }
Exemple #27
0
  public Hand deal(Game game) {

    // always shuffle before dealing!
    shuffle();

    // create a new hand
    Hand hand = game.newHand();

    // deal five cards to each player
    for (Team.Player player : game.getPlayers()) {
      hand.setCards(player, useNextCards(5));
    }

    // set the up card
    hand.setUpCard(useNextCard());

    return hand;
  }
Exemple #28
0
  public boolean addEndPoint(Game g, EndPoint ep) {
    if (epMap.containsKey(ep)) return false;
    GameInfo gi = map.get(g.getId());

    if (gi == null) return false;

    gi.epArr[1] = ep;
    epMap.put(ep, gi);
    return true;
  }
 public void shipPlacedResponse(String response) {
   int i = 0;
   StringTokenizer st = new StringTokenizer(response);
   String field = null;
   String alignment = null;
   String shipName = null;
   int xStartCoordinate = -1;
   int yStartCoordinate = -1;
   while (st.hasMoreTokens()) {
     if (i == 0) st.nextToken();
     if (i == 1) field = st.nextToken();
     if (i == 2) alignment = st.nextToken();
     if (i == 3) shipName = st.nextToken();
     if (i == 4) xStartCoordinate = Integer.parseInt(st.nextToken());
     if (i == 5) yStartCoordinate = Integer.parseInt(st.nextToken());
     i++;
   }
   if (field.equals(gameData.getPlayerSide()))
     gameData.placeShipsOnField(alignment, shipName, xStartCoordinate, yStartCoordinate);
 }
 public void shoot(int x, int y) {
   if (!isServer)
     requestToServer.println(
         "fire "
             + gameData.getPlayerSide()
             + " "
             + new Integer(x).toString()
             + " "
             + new Integer(y).toString());
   if (isServer) elaborateShootRequest(x, y, "host");
 }