private synchronized void render(Graphics g) {
    if (level != null) {
      int xScroll = (int) (player.pos.x - screen.w / 2);
      int yScroll = (int) (player.pos.y - (screen.h - 24) / 2);
      soundPlayer.setListenerPosition((float) player.pos.x, (float) player.pos.y);
      level.render(screen, xScroll, yScroll);
    }
    if (!menuStack.isEmpty()) {
      menuStack.peek().render(screen);
    }

    if (Options.getAsBoolean(Options.DRAW_FPS, Options.VALUE_FALSE)) {
      Font.draw(screen, texts.FPS(fps), 10, 10);
    }

    if (player != null && menuStack.size() == 0) {
      if (isMultiplayer) {
        Font.draw(screen, texts.latency(latencyCacheReady() ? "" + avgLatency() : "-"), 10, 20);
      }

      Font.draw(screen, texts.health(player.health, player.maxHealth), 340, screen.h - 16);
      Font.draw(screen, texts.money(player.score), 340, screen.h - 27);
      Font.draw(screen, texts.nextLevel((int) player.getNextLevel()), 340, screen.h - 38);
      Font.draw(screen, texts.playerExp((int) player.pexp), 340, screen.h - 49);
      Font.draw(screen, texts.playerLevel(player.plevel), 340, screen.h - 60);
    }

    if (isMultiplayer && menuStack.isEmpty()) {
      chat.render(screen);
    }

    g.setColor(Color.BLACK);

    g.fillRect(0, 0, getWidth(), getHeight());
    g.translate((getWidth() - GAME_WIDTH * SCALE) / 2, (getHeight() - GAME_HEIGHT * SCALE) / 2);
    g.clipRect(0, 0, GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE);

    if (!menuStack.isEmpty() || level != null) {

      // render mouse
      renderMouse(screen, mouseButtons);

      g.drawImage(screen.image, 0, 0, GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE, null);
    }
  }
  private void init() {
    soundPlayer = new SoundPlayer();
    soundPlayer.startTitleMusic();

    try {
      emptyCursor =
          Toolkit.getDefaultToolkit()
              .createCustomCursor(
                  new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB), new Point(0, 0), "empty");
    } catch (RuntimeException e) {
      e.printStackTrace();
    }
    setFocusTraversalKeysEnabled(false);
    requestFocus();

    // hide cursor, since we're drawing our own one
    setCursor(emptyCursor);
  }
  private synchronized void render(Graphics g) {
    if (level != null) {
      int xScroll = (int) (player.pos.x - screen.w / 2);
      int yScroll = (int) (player.pos.y - (screen.h - 24) / 2);
      soundPlayer.setListenerPosition((float) player.pos.x, (float) player.pos.y);
      level.render(screen, xScroll, yScroll);
    }
    if (!menuStack.isEmpty()) {
      menuStack.peek().render(screen);
    }

    Font.draw(screen, "FPS: " + fps, 10, 10);
    // for (int p = 0; p < players.length; p++) {
    // if (players[p] != null) {
    // String msg = "P" + (p + 1) + ": " + players[p].getScore();
    // Font.draw(screen, msg, 320, screen.h - 24 + p * 8);
    // }
    // }
    if (player != null && menuStack.size() == 0) {
      Font.draw(screen, player.health + " / 10", 340, screen.h - 19);
      Font.draw(screen, "" + player.score, 340, screen.h - 33);
    }

    g.setColor(Color.BLACK);

    g.fillRect(0, 0, getWidth(), getHeight());
    g.translate((getWidth() - GAME_WIDTH * SCALE) / 2, (getHeight() - GAME_HEIGHT * SCALE) / 2);
    g.clipRect(0, 0, GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE);

    if (!menuStack.isEmpty() || level != null) {

      // render mouse
      renderMouse(screen, mouseButtons);

      g.drawImage(screen.image, 0, 0, GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE, null);
    }

    // String msg = "FPS: " + fps;
    // g.setColor(Color.LIGHT_GRAY);
    // g.drawString(msg, 11, 11);
    // g.setColor(Color.WHITE);
    // g.drawString(msg, 10, 10);

  }
  private synchronized void render(Graphics g) {
    if (level != null) {
      int xScroll = (int) (player.pos.x - screen.w / 2);
      int yScroll = (int) (player.pos.y - (screen.h - 24) / 2);
      soundPlayer.setListenerPosition((float) player.pos.x, (float) player.pos.y);
      level.render(screen, xScroll, yScroll);
    }
    if (!menuStack.isEmpty()) {
      menuStack.peek().render(screen);
    }

    boolean drawFPS = Options.get("drawFPS") != null && Options.get("drawFPS").equals("true");
    if (drawFPS) {
      Font.draw(screen, texts.FPS(fps), 10, 10);
    }

    if (player != null && menuStack.size() == 0) {
      Font.draw(screen, texts.health(player.health, player.maxHealth), 340, screen.h - 16);
      Font.draw(screen, texts.money(player.score), 340, screen.h - 27);
      Font.draw(screen, texts.nextLevel((int) player.getNextLevel()), 340, screen.h - 38);
      Font.draw(screen, texts.playerExp((int) player.pexp), 340, screen.h - 49);
      Font.draw(screen, texts.playerLevel(player.plevel), 340, screen.h - 60);
    }

    g.setColor(Color.BLACK);

    g.fillRect(0, 0, getWidth(), getHeight());
    g.translate((getWidth() - GAME_WIDTH * SCALE) / 2, (getHeight() - GAME_HEIGHT * SCALE) / 2);
    g.clipRect(0, 0, GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE);

    if (!menuStack.isEmpty() || level != null) {

      // render mouse
      renderMouse(screen, mouseButtons);

      g.drawImage(screen.image, 0, 0, GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE, null);
    }
  }
  public void handleAction(int id) {
    if (id == TitleMenu.RETURN_TO_TITLESCREEN) {
      clearMenus();
      TitleMenu menu = new TitleMenu(GAME_WIDTH, GAME_HEIGHT);
      addMenu(menu);

    } else if (id == TitleMenu.START_GAME_ID) {
      clearMenus();
      isMultiplayer = false;
      chat.clear();

      localId = 0;
      localTeam = Team.Team1;
      synchronizer = new TurnSynchronizer(this, null, 0, 1);
      synchronizer.setStarted(true);

      createLevel(TitleMenu.level, TitleMenu.defaultGameMode);
      soundPlayer.stopBackgroundMusic();
    } else if (id == TitleMenu.SELECT_LEVEL_ID) {
      addMenu(new LevelSelect(false, localTeam));
    } else if (id == TitleMenu.SELECT_HOST_LEVEL_ID) {
      addMenu(new LevelSelect(true, localTeam));
    } else if (id == TitleMenu.UPDATE_LEVELS) {
      GuiMenu menu = menuStack.pop();
      if (menu instanceof LevelSelect) {
        addMenu(new LevelSelect(((LevelSelect) menu).bHosting, localTeam));
      } else {
        addMenu(new LevelSelect(false, localTeam));
      }
    } else if (id == TitleMenu.HOST_GAME_ID) {
      addMenu(new HostingWaitMenu());
      isMultiplayer = true;
      isServer = true;
      chat.clear();
      try {
        if (isServer) {
          localId = 0;
          localTeam = Team.Team1;
          serverSocket = new ServerSocket(3000);
          serverSocket.setSoTimeout(1000);

          hostThread =
              new Thread() {

                @Override
                public void run() {
                  boolean fail = true;
                  try {
                    while (!isInterrupted()) {
                      Socket socket = null;
                      try {
                        socket = serverSocket.accept();
                      } catch (SocketTimeoutException e) {

                      }
                      if (socket == null) {
                        System.out.println("Waiting for player to connect");
                        continue;
                      }
                      fail = false;

                      packetLink = new NetworkPacketLink(socket);

                      createServerState = 1;
                      break;
                    }
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                  if (fail) {
                    try {
                      serverSocket.close();
                    } catch (IOException e) {
                    }
                  }
                };
              };
          hostThread.start();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (id == TitleMenu.JOIN_GAME_ID) {
      addMenu(new JoinGameMenu());
    } else if (id == TitleMenu.CANCEL_JOIN_ID) {
      popMenu();
      if (hostThread != null) {
        hostThread.interrupt();
        hostThread = null;
      }
    } else if (id == TitleMenu.PERFORM_JOIN_ID) {
      menuStack.clear();
      isMultiplayer = true;
      isServer = false;
      chat.clear();

      try {
        localId = 1;
        localTeam = Team.Team2;
        packetLink = new ClientSidePacketLink(TitleMenu.ip, 3000);
        synchronizer = new TurnSynchronizer(this, packetLink, localId, 2);
        packetLink.setPacketListener(this);
      } catch (Exception e) {
        e.printStackTrace();
        // System.exit(1);
        addMenu(new TitleMenu(GAME_WIDTH, GAME_HEIGHT));
      }
    } else if (id == TitleMenu.HOW_TO_PLAY) {
      addMenu(new HowToPlayMenu());
    } else if (id == TitleMenu.OPTIONS_ID) {
      addMenu(new OptionsMenu());
    } else if (id == TitleMenu.SELECT_DIFFICULTY_ID) {
      addMenu(new DifficultySelect(false));
    } else if (id == TitleMenu.SELECT_DIFFICULTY_HOSTING_ID) {
      addMenu(new DifficultySelect(true));
    } else if (id == TitleMenu.KEY_BINDINGS_ID) {
      addMenu(new KeyBindingsMenu(keys, inputHandler));
    } else if (id == TitleMenu.EXIT_GAME_ID) {
      System.exit(0);
    } else if (id == TitleMenu.RETURN_ID) {
      synchronizer.addCommand(new PauseCommand(false));
      keys.tick();
    } else if (id == TitleMenu.BACK_ID) {
      popMenu();
    }
  }
  private void tick() {
    // Not-In-Focus-Pause
    if (this.isFocusOwner() && level != null) {
      paused2 = false;
    }

    if (!this.isFocusOwner() && level != null) {
      keys.release();
      mouseButtons.releaseAll();
      if (!paused && !paused2) {
        PauseCommand pauseCommand = new PauseCommand(true);
        synchronizer.addCommand(pauseCommand);
        paused2 = true;
      }
    }
    if (isMultiplayer) {
      tickChat();
    }

    if (requestToggleFullscreen || keys.fullscreen.wasPressed()) {
      requestToggleFullscreen = false;
      setFullscreen(!fullscreen);
    }

    if (level != null && level.victoryConditions != null) {
      if (level.victoryConditions.isVictoryConditionAchieved()) {
        addMenu(new WinMenu(GAME_WIDTH, GAME_HEIGHT, level.victoryConditions.playerVictorious()));
        level = null;
        return;
      }
    }

    if (packetLink != null) {
      packetLink.tick();
    }

    mouseButtons.setPosition(getMousePosition());
    if (!menuStack.isEmpty()) {
      menuStack.peek().tick(mouseButtons);
    }
    if (mouseMoved) {
      mouseMoved = false;
      mouseHideTime = 0;
      if (mouseButtons.mouseHidden) {
        mouseButtons.mouseHidden = false;
      }
    }
    if (mouseHideTime < 60) {
      mouseHideTime++;
      if (mouseHideTime == 60) {
        mouseButtons.mouseHidden = true;
      }
    }

    if (level == null) {
      mouseButtons.tick();
    } else if (level != null) {
      if (synchronizer.preTurn()) {
        synchronizer.postTurn();

        for (int index = 0; index < mouseButtons.currentState.length; index++) {
          boolean nextState = mouseButtons.nextState[index];
          if (mouseButtons.isDown(index) != nextState) {
            synchronizer.addCommand(new ChangeMouseButtonCommand(index, nextState));
          }
        }

        synchronizer.addCommand(
            new ChangeMouseCoordinateCommand(
                mouseButtons.getX(), mouseButtons.getY(), mouseButtons.mouseHidden));

        mouseButtons.tick();
        for (MouseButtons sMouseButtons : synchedMouseButtons) {
          sMouseButtons.tick();
        }

        if (!paused) {
          for (int index = 0; index < keys.getAll().size(); index++) {
            Keys.Key key = keys.getAll().get(index);
            boolean nextState = key.nextState;
            if (key.isDown != nextState) {
              synchronizer.addCommand(new ChangeKeyCommand(index, nextState));
            }
          }

          keys.tick();
          for (Keys skeys : synchedKeys) {
            skeys.tick();
          }

          if (keys.pause.wasPressed()) {
            keys.release();
            mouseButtons.releaseAll();
            synchronizer.addCommand(new PauseCommand(true));
          }

          level.tick();
        }

        // every 4 minutes, start new background music :)
        if (System.currentTimeMillis() / 1000 > nextMusicInterval) {
          nextMusicInterval = (System.currentTimeMillis() / 1000) + 4 * 60;
          soundPlayer.startBackgroundMusic();
        }

        if (keys.screenShot.isDown) {
          takeScreenShot();
        }
      }
    }

    if (createServerState == 1) {
      createServerState = 2;

      synchronizer = new TurnSynchronizer(MojamComponent.this, packetLink, localId, 2);

      clearMenus();
      createLevel(TitleMenu.level, TitleMenu.defaultGameMode);

      synchronizer.setStarted(true);
      if (TitleMenu.level.vanilla) {
        packetLink.sendPacket(
            new StartGamePacket(
                TurnSynchronizer.synchedSeed,
                TitleMenu.level.getUniversalPath(),
                DifficultyList.getDifficultyID(TitleMenu.difficulty)));
      } else {
        packetLink.sendPacket(
            new StartGamePacketCustom(
                TurnSynchronizer.synchedSeed,
                level,
                DifficultyList.getDifficultyID(TitleMenu.difficulty)));
      }
      packetLink.setPacketListener(MojamComponent.this);
    }
  }
 public void stop() {
   running = false;
   soundPlayer.shutdown();
 }
  private void tick() {

    if (packetLink != null) {
      packetLink.tick();
    }

    mouseButtons.setPosition(getMousePosition());
    if (!menuStack.isEmpty()) {
      menuStack.peek().tick(mouseButtons);
    }
    if (mouseMoved) {
      mouseMoved = false;
      mouseHideTime = 0;
      if (mouseHidden) {
        mouseHidden = false;
      }
    }
    if (mouseHideTime < 60) {
      mouseHideTime++;
      if (mouseHideTime == 60) {
        mouseHidden = true;
      }
    }
    mouseButtons.tick();

    if (level != null) {
      if (synchronizer.preTurn()) {
        synchronizer.postTurn();

        if (!paused) {
          for (int index = 0; index < keys.getAll().size(); index++) {
            Keys.Key key = keys.getAll().get(index);
            boolean nextState = key.nextState;
            if (key.isDown != nextState) {
              synchronizer.addCommand(new ChangeKeyCommand(index, nextState));
            }
          }

          keys.tick();
          for (Keys skeys : synchedKeys) {
            skeys.tick();
          }

          if (keys.pause.wasPressed()) {
            keys.release();
            synchronizer.addCommand(new PauseCommand(true));
          }

          if (keys.fullscreen.wasPressed()) {
            setFullscreen(!fullscreen);
          }

          // if mouse is in use, update player orientation before level tick
          if (!mouseHidden) {

            // update player mouse, in world pixels relative to
            // player
            player.setAimByMouse(
                ((mouseButtons.getX() / SCALE) - (screen.w / 2)),
                (((mouseButtons.getY() / SCALE) + 24) - (screen.h / 2)));
          } else {
            player.setAimByKeyboard();
          }

          level.tick();
        }

        // every 4 minutes, start new background music :)
        if (System.currentTimeMillis() / 1000 > nextMusicInterval) {
          nextMusicInterval = (System.currentTimeMillis() / 1000) + 4 * 60;
          soundPlayer.startBackgroundMusic();
        }

        if (keys.screenShot.isDown) {
          takeScreenShot();
        }
      }
    }

    if (createServerState == 1) {
      createServerState = 2;

      synchronizer = new TurnSynchronizer(MojamComponent.this, packetLink, localId, 2);

      clearMenus();
      createLevel(TitleMenu.level);

      synchronizer.setStarted(true);
      if (TitleMenu.level.vanilla) {
        packetLink.sendPacket(
            new StartGamePacket(
                TurnSynchronizer.synchedSeed,
                TitleMenu.level.getUniversalPath(),
                DifficultyList.getDifficultyID(TitleMenu.difficulty)));
      } else {
        packetLink.sendPacket(
            new StartGamePacketCustom(
                TurnSynchronizer.synchedSeed,
                level,
                DifficultyList.getDifficultyID(TitleMenu.difficulty)));
      }
      packetLink.setPacketListener(MojamComponent.this);
    }
  }