Package de.creepsmash.client.panel

Source Code of de.creepsmash.client.panel.GameLobby

/**
   Creep Smash, a multiplayer towerdefence game
   created as a project at the Hochschule fuer
   Technik Stuttgart (University of Applied Science)
   http://www.hft-stuttgart.de
  
   Copyright (C) 2008 by     
    * Andreas Wittig
    * Bernd Hietler
    * Christoph Fritz
    * Fabian Kessel
    * Levin Fritz
    * Nikolaj Langner
    * Philipp Schulte-Hubbert
    * Robert Rapczynski
    * Ron Trautsch
    * Sven Supper
    http://creepsmash.sf.net/

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/


package de.creepsmash.client.panel;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TreeSet;
import java.util.Vector;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.text.html.HTMLEditorKit;

import org.apache.tools.ant.taskdefs.optional.junit.Enumerations;

import de.creepsmash.client.network.MessageListener;
import de.creepsmash.client.sound.SoundManagement;
import de.creepsmash.client.util.LobbyTimerTask;
import de.creepsmash.common.IConstants;
import de.creepsmash.common.messages.client.JoinGameRequestMessage;
import de.creepsmash.common.messages.client.LogoutMessage;
import de.creepsmash.common.messages.client.RefreshMessage;
import de.creepsmash.common.messages.client.SendMessageMessage;
import de.creepsmash.common.messages.server.GameDescription;
import de.creepsmash.common.messages.server.GamesMessage;
import de.creepsmash.common.messages.server.JoinGameResponseMessage;
import de.creepsmash.common.messages.server.MessageMessage;
import de.creepsmash.common.messages.server.PlayersMessage;
import de.creepsmash.common.messages.server.ServerMessage;

/**
* The GameLobby screen.
*
* @author nikolaj
*
*/
public class GameLobby extends GameScreen implements MessageListener {

  private final Logger logger = Logger.getLogger(GameLobby.class.getName());
  private static final long serialVersionUID = -2767071218252528630L;
  protected static final String URI = null;
  private final JButton lobby;
  private final JLabel help;
  private JLabel LabelPlayerListCount;
  private JEditorPane  GameInfoEditorPane;
  private final JTextField message;
  private PlayerChat chatdialog;
  private JScrollPane chatScrollPane;
  private JList playerlist;
  private JScrollPane playersScrollPane;
  private JTabbedPane gamesTabbedPane;
  private JTable gameinfoWaiting;
  private JScrollPane gamesScrollPaneWaiting;
  private JTable gameinfoRunning;
  private JScrollPane gamesScrollPaneRunning;
  private final JButton highscore;
  private final JButton join;
  private final JButton create;
  private final JButton profil;
  private final JButton refresh;
  private final JButton site;
  private final JButton forum;
  private final JButton wiki;
  private JButton quit;
  private final JButton chat;
  private SoundManagement managementSound;
  private int joinGameId;
  private GameDescription joinGame;
  private ArrayList<GameDescription> games;
  private int Player_Online_gameinfo;
  private int Player_Online_player_list;
 
  private Timer inactiveTimer;
  private LobbyTimerTask inactiveTimerTask = new LobbyTimerTask(this);
  /**
   * The GameLobby screen.
   */
  public GameLobby() {
   
    this.inactiveTimer = new Timer();
   
    this.setLayout(null);
    this.setBackground(Color.BLACK);
   
    UIManager.put("ToolTip.background", Color.BLACK );
    UIManager.put("ToolTip.foreground", Color.green );
   
    this.lobby = new JButton("CreepSmash.de Game Lobby");
    this.lobby.setBounds(100, 10, 500, 30);
    this.lobby.setBorder(null);
    this.lobby.setForeground(Color.green);
    this.lobby.setBackground(Color.BLACK);
    this.lobby.setFont(new Font("Arial", Font.BOLD, 28));
   
    this.help = new JLabel("Press F1 for help...");
    this.help.setBounds(833, 0, 100, 10);
    this.help.setForeground(Color.green);
    this.help.setFont(new Font("Arial", Font.BOLD, 9));
   
    this.LabelPlayerListCount = new JLabel("0 Player Online", SwingConstants.RIGHT);
    this.LabelPlayerListCount.setBounds(640, 39, 270, 10);
    this.LabelPlayerListCount.setForeground(Color.green);
    this.LabelPlayerListCount.setFont(new Font("Arial", Font.BOLD, 9));
   
    this.GameInfoEditorPane = new JEditorPane ();
    this.GameInfoEditorPane.setBounds(640, 50, 270, 200);
    this.GameInfoEditorPane.setEditable(false);
    this.GameInfoEditorPane.setFont(new Font("Arial", Font.PLAIN, 10));
    this.GameInfoEditorPane.setEditorKit(new HTMLEditorKit());
    this.GameInfoEditorPane.setAutoscrolls(true);
    this.GameInfoEditorPane.setFocusable(false);
    this.GameInfoEditorPane.setDoubleBuffered(true);
    this.GameInfoEditorPane.setBorder(BorderFactory.createLoweredBevelBorder());
       
    this.playersScrollPane = this.initPlayersList();
    this.playersScrollPane.setBounds(640, 254, 270, 342);
   
    this.playerlist.setBackground(Color.BLACK);
    this.playerlist.setForeground(Color.GREEN);
   
    this.gamesTabbedPane = new JTabbedPane();
    this.gamesTabbedPane.setBounds(20, 50, 600, 300);
    this.gamesTabbedPane.setForeground(Color.black);
   
    UIManager.put("TabbedPane.contentBorderInsets", new InsetsUIResource(0,
                0, 0, 0));
   
    UIManager.put("TabbedPane.background", Color.lightGray);
    UIManager.put("TabbedPane.darkShadow", Color.lightGray);
    UIManager.put("TabbedPane.focus", Color.lightGray);
    UIManager.put("TabbedPane.highlight", Color.lightGray);
    UIManager.put("TabbedPane.shadow", Color.lightGray);
    UIManager.put("TabbedPane.selected", Color.white);
    UIManager.put("TabbedPane.tabAreaBackground", Color.black);
    SwingUtilities.updateComponentTreeUI(this.gamesTabbedPane);
   
    this.gamesTabbedPane.setOpaque(true);
   
    this.gamesScrollPaneWaiting = new JScrollPane();
    this.gamesScrollPaneWaiting = this.initGamesTableWaiting();
    this.gamesTabbedPane.addTab("Games Waiting",null,this.gamesScrollPaneWaiting, "Waiting Games");
   
    this.gamesScrollPaneRunning = new JScrollPane();
    this.gamesScrollPaneRunning = this.initGamesTableRunning();
    this.gamesTabbedPane.addTab("Games Running",null,this.gamesScrollPaneRunning, "Running Games");
   
    this.chatdialog = new PlayerChat();
     
    this.chatScrollPane = new JScrollPane(this.chatdialog,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    this.chatScrollPane.setPreferredSize(new Dimension(500,180));
    this.chatScrollPane.setBounds(20, 370, 600, 200);
   
    // Welcome Chat MSG
    chatdialog.sendChatText("System", "Welcome to CreepSmash Chat. :)", null);
    chatdialog.sendChatText("System", "Please no Flaming, Abusing or Spam.", null);
   
    this.message = new JTextField();
    this.message.setBounds(20, 570, 550, 25);
    this.message.setEditable(true);
    this.setGameScreenFocus(message);
   
    this.add(this.GameInfoEditorPane);
    this.add(this.playersScrollPane);
    this.add(this.gamesTabbedPane);
    this.add(this.chatScrollPane);
    this.add(this.message);
    this.add(this.lobby);
    this.add(this.LabelPlayerListCount);
   
 
    this.create = new JButton("Create game");
    this.create.setBounds(20, 620, 110, 25);
    this.create.setBackground(Color.BLACK);
    this.create.setForeground(Color.GREEN);
   
    this.join = new JButton("Join game");
    this.join.setBounds(135, 620, 110, 25);
    this.join.setBackground(Color.BLACK);
    this.join.setForeground(Color.GREEN);
    this.join.setEnabled(false);
   
    this.refresh = new JButton("Refresh");
    this.refresh.setBounds(250, 620, 110, 25);
    this.refresh.setBackground(Color.BLACK);
    this.refresh.setForeground(Color.GREEN);
   
    this.highscore = new JButton("Highscores");
    this.highscore.setBounds(365, 620, 110, 25);
    this.highscore.setBackground(Color.BLACK);
    this.highscore.setForeground(Color.GREEN);
     
    this.profil = new JButton("Profile");
    this.profil.setBounds(480, 620, 110, 25);
    this.profil.setBackground(Color.BLACK);
    this.profil.setForeground(Color.GREEN);
   
    this.forum = new JButton("Forum");
    this.forum.setBounds(20, 655, 110, 25);
    this.forum.setBackground(Color.BLACK);
    this.forum.setForeground(Color.getHSBColor(255, 255, 255));
   
   
    this.wiki = new JButton("Wiki");
    this.wiki.setBounds(135, 655, 110, 25);
    this.wiki.setBackground(Color.BLACK);
    this.wiki.setForeground(Color.getHSBColor(255, 255, 255));
   
   
    this.site = new JButton("Blog");
    this.site.setBounds(250, 655, 110, 25);
    this.site.setBackground(Color.BLACK);
    this.site.setForeground(Color.getHSBColor(255, 255, 255));
   
    this.quit = new JButton("Quit");
    this.quit.setBounds(800, 620, 110, 25);
    this.quit.setBackground(Color.BLACK);
    this.quit.setForeground(Color.GREEN);
   
    this.chat = new JButton(">");
    this.chat.setBounds(570, 570, 50, 25);
    this.chat.setBackground(Color.BLACK);
    this.chat.setForeground(Color.GREEN);
   
    this.add(this.site);
    this.add(this.wiki);
    this.add(this.forum);
    this.add(this.join);
    this.add(this.refresh);
    this.add(this.create);
    this.add(this.highscore);
    this.add(this.quit);
    this.add(this.chat);
    this.add(this.profil);
    this.add(this.help);
   
    ActionListener a1 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JoinGameRequestMessage grm = new JoinGameRequestMessage();
        String pw = null;
        if (GameLobby.this.joinGame == null) {
          GameLobby.this.logger.info("Could not select the game");
          return;
        }
        if ( GameLobby.this.joinGame.getMinEloPoints() > getCore().getPlayerEloScore() && GameLobby.this.joinGame.getMinEloPoints() != 0){
          errorDialog(GameLobby.this.joinGame.getMinEloPoints() + " Score-Points required for this Game.");
          return;
        }
        if ( GameLobby.this.joinGame.getMaxEloPoints() < getCore().getPlayerEloScore() && GameLobby.this.joinGame.getMaxEloPoints() != 0){
          errorDialog("max." + GameLobby.this.joinGame.getMaxEloPoints() + " Score-Points required for this Game.");
          return;
        }
        if (!GameLobby.this.joinGame.getState().equals("waiting")){
          errorDialog("they can join only waiting game...");
          return;
        }
        if (GameLobby.this.joinGame.getPasswort().equals("yes")){
         
          UIManager.put("OptionPane.background", Color.BLACK);
          UIManager.put("Panel.background", Color.BLACK);
          UIManager.put("OptionPane.messageForeground", Color.GREEN);
          pw = JOptionPane.showInputDialog(null,"please enter a valid password for this game:")
          if (pw != null){
            if (pw.equals("")) return;
          }else{
            return;
          }
        } 
        GameLobby.this.joinGameId = GameLobby.this.joinGame.getGameId();

        grm.setGameId(GameLobby.this.joinGameId);
        grm.setPasswort(pw);
        GameLobby.this.getCore().getNetwork().sendMessage(grm);
        GameLobby.this.join.setEnabled(false);
      }
    };
    this.join.addActionListener(a1);

    join.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        JoinGameRequestMessage grm = new JoinGameRequestMessage();
        String pw = null;
        if (GameLobby.this.joinGame == null) {
          GameLobby.this.logger.info("Could not select the game");
          return;
        }
        if ( GameLobby.this.joinGame.getMinEloPoints() > getCore().getPlayerEloScore() && GameLobby.this.joinGame.getMinEloPoints() != 0){
          errorDialog(GameLobby.this.joinGame.getMinEloPoints() + " Score-Points required for this Game.");
          return;
        }
        if ( GameLobby.this.joinGame.getMaxEloPoints() < getCore().getPlayerEloScore() && GameLobby.this.joinGame.getMaxEloPoints() != 0){
          errorDialog("max." + GameLobby.this.joinGame.getMaxEloPoints() + " Score-Points required for this Game.");
          return;
        }
        if (!GameLobby.this.joinGame.getState().equals("waiting")){
          errorDialog("they can join only waiting game...");
          return;
        }
        if (GameLobby.this.joinGame.getPasswort().equals("yes")){
         
          UIManager.put("OptionPane.background", Color.BLACK);
          UIManager.put("Panel.background", Color.BLACK);
          UIManager.put("OptionPane.messageForeground", Color.GREEN);
          pw = JOptionPane.showInputDialog(null,"please enter a valid password for this game:")
          if (pw.equals("")) return;
       
        GameLobby.this.joinGameId = GameLobby.this.joinGame.getGameId();

        grm.setGameId(GameLobby.this.joinGameId);
        grm.setPasswort(pw);
        GameLobby.this.getCore().getNetwork().sendMessage(grm);
        GameLobby.this.join.setEnabled(false);
      }
    });

    ActionListener a2 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        GameLobby.this.getCore().pushScreen(new CreateGamePanel());
      }
    };
    this.create.addActionListener(a2);

    create.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        getCore().pushScreen(new CreateGamePanel());
      }
    });

    ActionListener a3 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        GameLobby.this.getCore().pushScreen(new HighscorePanel());
      }
    };
    this.highscore.addActionListener(a3);

    highscore.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        getCore().pushScreen(new HighscorePanel());
      }
    });

    ActionListener a4 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if ((GameLobby.this.message.getText() != null)
            && (!GameLobby.this.message.getText().equals(""))) {
          if (GameLobby.this.message.getText().length() > 180){
            GameLobby.this.errorDialog("Please don't enter more then 180 keystrokes.");
            return;
          }else{
          SendMessageMessage m = new SendMessageMessage();
          m.setMessage(GameLobby.this.message.getText());
          GameLobby.this.message.setText("");
          m.setClientId(GameLobby.this.getCore().getPlayerId());
          GameLobby.this.getCore().getNetwork().sendMessage(m);
          }
        }
      }
    };
    this.chat.addActionListener(a4);
    this.message.addActionListener(a4);

    // Quitbutton
    ActionListener a5 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        LogoutMessage gm = new LogoutMessage();
        getCore().getNetwork().sendMessage(gm);
        getCore().getNetwork().shutdown();
        getCore().popScreen();
      }
    };
    this.quit.addActionListener(a5);
   
    quit.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        LogoutMessage gm = new LogoutMessage();
        getCore().getNetwork().sendMessage(gm);
        getCore().getNetwork().shutdown();
        getCore().popScreen();
      }
      });
   
    ActionListener a6 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        getCore().pushScreen(new ProfilPanel());
      }
    };
    this.profil.addActionListener(a6);

    profil.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        getCore().pushScreen(new ProfilPanel());
      }
    });
   
   
   
    this.message.addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(KeyEvent evt) {
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
          GameLobby.this.message.postActionEvent();
        }
      }
    });
   
   
    ActionListener a7 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        getCore().getNetwork().sendMessage(new RefreshMessage());
      }
    };
   
    this.refresh.addActionListener(a7);
   
    this.refresh.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        getCore().getNetwork().sendMessage(new RefreshMessage());
      }
    });
   
   
    //Button
    ActionListener a8 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
       
        openURL("http://www.creepsmash.de/");
      }
    };
   
    this.lobby.addActionListener(a8);
   
    this.lobby.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        openURL("http://www.creepsmash.de/");
      }
    });
   
   
    //Button Site
    ActionListener a9 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
       
        openURL("http://www.creepsmash.de/");
      }
    };
   
    this.site.addActionListener(a9);
   
    this.site.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        openURL("http://www.creepsmash.de/");
      }
    });
   
    //Button Forum
    ActionListener a10 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
       
        openURL("http://www.creepsmash.de/forum/");
      }
    };
   
    this.forum.addActionListener(a10);
   
    //Button WIKI
    ActionListener a11 = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
       
        openURL("http://wiki.creepsmash.de/");
      }
    };
    this.wiki.addActionListener(a11);
   
    this.forum.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        openURL("http://www.creepsmash.de/forum/");
      }
    });
   
  }
  /**
   * Open URL
   *
   */
  private void openURL(String URL){
   
    try {
        java.net.URI url = new java.net.URI(URL);
      Desktop.getDesktop().browse(url);
      } catch(Exception e1) {
         System.out.println(e1.getMessage());
      }
  }
 
  /**
   * Creates the games table Wating.
   *
   * @return a scrollpane with the table
   */
  private JScrollPane initGamesTableWaiting() {

    if (this.gameinfoWaiting == null) {
      this.gameinfoWaiting = new JTable() {
        private static final long serialVersionUID = -5995847295484708948L;
      };
      this.gameinfoWaiting.setBackground(Color.BLACK);
      this.gameinfoWaiting.setForeground(Color.GREEN);
      this.gameinfoWaiting.setSelectionBackground(Color.GREEN);
      this.gameinfoWaiting.setSelectionForeground(Color.BLACK);
      this.gameinfoWaiting.setModel(new DefaultTableModel() {
        private static final long serialVersionUID = -5995847295484708948L;

        @Override
        public boolean isCellEditable(int row, int column) {
          return false;
        }
      });

      this.gameinfoWaiting.setDoubleBuffered(true);
      this.gameinfoWaiting.setIntercellSpacing(new Dimension(0, 0));
      this.gameinfoWaiting.setShowVerticalLines(false);
      this.gameinfoWaiting.setShowHorizontalLines(false);

      this.gameinfoWaiting
          .setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      this.gameinfoWaiting.getSelectionModel().addListSelectionListener(
          new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {

              int index = GameLobby.this.gameinfoWaiting
                  .getSelectedRow();

              if (index < 0) {
                GameLobby.this.join.setEnabled(false);
              } else {
               
                int indeX = GameLobby.this.gameinfoRunning .getSelectedRow();

                 if (indeX != -1){
                 GameLobby.this.gameinfoRunning.removeRowSelectionInterval(indeX, indeX);
                 }
                
                int GameID = Integer
                    .parseInt(GameLobby.this.gameinfoWaiting
                        .getValueAt(index, 6)
                        .toString());

                GameLobby.this.joinGame = GameLobby.this.games
                    .get(GameID);
                GameLobby.this.join.setEnabled(true);

                // Set Game info label
                GameLobby.this
                    .setGameInfoEditorPaneSelectGame(GameID);
              }
            }
          });
      this.gameinfoWaiting.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {

          if (e.getClickCount() >= 2) {
            if (GameLobby.this.join.isEnabled()
                && GameLobby.this.joinGame != null) {
              GameLobby.this.join.doClick();
            }
          }
        }
      });
    }

    this.gamesScrollPaneWaiting.setViewportView(this.gameinfoWaiting);
    return this.gamesScrollPaneWaiting;
  }
  /**
   * Creates the games table Running.
   *
   * @return a scrollpane with the table
   */
  private JScrollPane initGamesTableRunning() {

    if (this.gameinfoRunning == null) {
      this.gameinfoRunning = new JTable() {
        private static final long serialVersionUID = -5995847295484708948L;
      };
      this.gameinfoRunning.setBackground(Color.BLACK);
      this.gameinfoRunning.setForeground(Color.GREEN);
      this.gameinfoRunning.setSelectionBackground(Color.GREEN);
      this.gameinfoRunning.setSelectionForeground(Color.BLACK);
      this.gameinfoRunning.setModel(new DefaultTableModel() {
        private static final long serialVersionUID = -5995847295484708948L;

        @Override
        public boolean isCellEditable(int row, int column) {
          return false;
        }
      });

      this.gameinfoRunning.setDoubleBuffered(true);
      this.gameinfoRunning.setIntercellSpacing(new Dimension(0, 0));
      this.gameinfoRunning.setShowVerticalLines(false);
      this.gameinfoRunning.setShowHorizontalLines(false);

      this.gameinfoRunning
          .setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      this.gameinfoRunning.getSelectionModel().addListSelectionListener(
          new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
             
                          
              int index = GameLobby.this.gameinfoRunning
                  .getSelectedRow();

              if (index < 0) {
                GameLobby.this.join.setEnabled(false);
              } else {
               
                int indeX = GameLobby.this.gameinfoWaiting.getSelectedRow();

                 if (indeX != -1){
                 GameLobby.this.gameinfoWaiting.removeRowSelectionInterval(indeX, indeX);
                 }
                
                int GameID = Integer
                    .parseInt(GameLobby.this.gameinfoRunning
                        .getValueAt(index, 6)
                        .toString());

                GameLobby.this.join.setEnabled(false);

                // Set Game info label
                GameLobby.this
                    .setGameInfoEditorPaneSelectGame(GameID);

              }
            }

          });

    }

    this.gamesScrollPaneRunning.setViewportView(this.gameinfoRunning);
    return this.gamesScrollPaneRunning;
  }

  /**
   * Gets all available games and add them to the gameslist textarea.
   *
   * @param g
   *            the gamesMessage
   */
  private synchronized void setGameList(GamesMessage g) {
   
    int oldSelectionWaiting = this.gameinfoWaiting.getSelectedRow();
    int oldSelectionRunning = this.gameinfoRunning.getSelectedRow();
   
    final Object[] headerNames = new Object[] { "Name", "Players", "Map",
        "Min/Max","PW","State","GameID" };
   
    final Vector<Vector<String>> rowsWaiting = new Vector<Vector<String>>();
    final Vector<Vector<String>> rowsRunning = new Vector<Vector<String>>();

    final DefaultTableModel modelWaiting = (DefaultTableModel) this.gameinfoWaiting
        .getModel();
   
    final DefaultTableModel modelRunning = (DefaultTableModel) this.gameinfoRunning
    .getModel();
   
    if (g != null) {
      this.games = new ArrayList<GameDescription>(g.getGames());
      Collections.sort(this.games, new Comparator<GameDescription>() {
        public int compare(GameDescription a, GameDescription b) {
          return a.getState().compareToIgnoreCase(b.getState()) * -1;
        }
      });
      this.Player_Online_gameinfo = 0;
      int count = 0;
      for (GameDescription gd : this.games) {
       
        final int fullCount = gd.getMaxPlayers();
        final int playerCount = gd.getCurrentPlayers();
        this.Player_Online_gameinfo = this.Player_Online_gameinfo + playerCount;
        final Vector<String> rowsData = new Vector<String>();

        rowsData.add(gd.getGameName());
        rowsData.add(String.valueOf(playerCount) + "/"
            + String.valueOf(fullCount));
        rowsData.add(IConstants.Map.getMapById(gd.getMapId())
            .toString());
       
        rowsData.add(((gd.getMinEloPoints() == 0) ? "all" : gd.getMinEloPoints()) + "/" + ((gd.getMaxEloPoints() == 0) ? "all" : gd.getMaxEloPoints()));
        rowsData.add((gd.getPasswort().equals("yes") ? "<html><DIV style=\"color:red;\"><b>" + gd.getPasswort() + "</DIV></HTML>" : gd.getPasswort()));
             
        String State = gd.getState();
        String StateMSG = "";
               
        if (State.compareToIgnoreCase("waiting") == 0){
          StateMSG = "<html><DIV style=\"color:red;\"><b>" + State + "</DIV></HTML>";
        }else if (State.compareToIgnoreCase("ended") == 0){
          StateMSG = "<html><DIV style=\"color:yellow;\">" + State + "</DIV></HTML>"
        }else {
          StateMSG = State;
        }
        rowsData.add(StateMSG);
       
        rowsData.add(""+count);
       
        if (State.equals("waiting")){
          rowsWaiting.add(rowsData);
        }else{
          rowsRunning.add(rowsData);
        }
       
        count++;
      }
    }
   
   
    TableColumn col = null;
    if (rowsWaiting.size() == 0){
     
      int selectedRow = this.gameinfoWaiting.getSelectedRow();
      if (selectedRow != -1) {
        this.gameinfoWaiting.removeRowSelectionInterval(selectedRow, selectedRow);
        oldSelectionWaiting = -1;
      }
     
      final Object[] Info = new Object[] { "information" };
      final Vector<String> rowsData = new Vector<String>();
      rowsData.add("<html><DIV style='color:red;'><h3>No game waits for players.<br>Please provide a new. (Create Game)</h3></div></html>");
      rowsWaiting.add(rowsData);
      modelWaiting.setDataVector(rowsWaiting, new Vector<Object>(Arrays.asList(Info)));
      modelWaiting.fireTableDataChanged();
      this.gameinfoWaiting.setEnabled(false);
     
      col = gameinfoWaiting.getColumnModel().getColumn(0);
      col.setPreferredWidth(gamesTabbedPane.getWidth());
      col.setMinWidth(gamesTabbedPane.getWidth());
      col.setMaxWidth(gamesTabbedPane.getWidth());
      gameinfoWaiting.setRowHeight(50);     
     
    }else{
      modelWaiting.setDataVector(rowsWaiting, new Vector<Object>(Arrays.asList(headerNames)));
      modelWaiting.fireTableDataChanged();
      gameinfoWaiting.setRowHeight(gameinfoRunning.getRowHeight());
      this.gameinfoWaiting.setEnabled(true);
      col = gameinfoWaiting.getColumnModel().getColumn(0);
      col.setPreferredWidth(300);
      col.setMinWidth(200);
      col.setMaxWidth(350);
     
      col = gameinfoWaiting.getColumnModel().getColumn(1);
      col.setPreferredWidth(55);
      col.setMinWidth(45);
      col.setMaxWidth(150);
     
      col = gameinfoWaiting.getColumnModel().getColumn(2);
      col.setPreferredWidth(100);
      col.setMinWidth(120);
      col.setMaxWidth(200);
     
      col = gameinfoWaiting.getColumnModel().getColumn(3);
      col.setPreferredWidth(60);
      col.setMinWidth(70);
      col.setMaxWidth(70);
     
      col = gameinfoWaiting.getColumnModel().getColumn(4);
      col.setPreferredWidth(30);
      col.setMinWidth(30);
      col.setMaxWidth(30);
     
      col = gameinfoWaiting.getColumnModel().getColumn(5);
      col.setPreferredWidth(50);
      col.setMinWidth(50);
      col.setMaxWidth(150);
     
      col = gameinfoWaiting.getColumnModel().getColumn(6);
      col.setPreferredWidth(0);
      col.setMinWidth(0);
      col.setMaxWidth(0);
      col.setWidth(0);
    }
   
   
    modelRunning.setDataVector(rowsRunning, new Vector<Object>(Arrays.asList(headerNames)));
    modelRunning.fireTableDataChanged();
   
   
    col = gameinfoRunning.getColumnModel().getColumn(0);
    col.setPreferredWidth(300);
    col.setMinWidth(200);
    col.setMaxWidth(350);
   
    col = gameinfoRunning.getColumnModel().getColumn(1);
    col.setPreferredWidth(55);
    col.setMinWidth(45);
    col.setMaxWidth(150);
   
    col = gameinfoRunning.getColumnModel().getColumn(2);
    col.setPreferredWidth(100);
    col.setMinWidth(120);
    col.setMaxWidth(200);
   
    col = gameinfoRunning.getColumnModel().getColumn(3);
    col.setPreferredWidth(60);
    col.setMinWidth(70);
    col.setMaxWidth(70);
   
    col = gameinfoRunning.getColumnModel().getColumn(4);
    col.setPreferredWidth(30);
    col.setMinWidth(30);
    col.setMaxWidth(30);
   
    col = gameinfoRunning.getColumnModel().getColumn(5);
    col.setPreferredWidth(50);
    col.setMinWidth(50);
    col.setMaxWidth(150);
   
    col = gameinfoRunning.getColumnModel().getColumn(6);
    col.setPreferredWidth(0);
    col.setMinWidth(0);
    col.setMaxWidth(0);
    col.setWidth(0);
   
    if (oldSelectionWaiting != -1) {
      try {
       
        this.gameinfoWaiting.setRowSelectionInterval(oldSelectionWaiting,oldSelectionWaiting);

      } catch (IllegalArgumentException e) {
        GameLobby.this.logger.info("setRowSelectionInterval illegal argument");
        this.setGameInfoEditorPaneHTML(null);
      }
    }else if (oldSelectionRunning != -1) {
      try {
       
        this.gameinfoRunning.setRowSelectionInterval(oldSelectionRunning,oldSelectionRunning);

      } catch (IllegalArgumentException e) {
        GameLobby.this.logger.info("setRowSelectionInterval illegal argument");
        this.setGameInfoEditorPaneHTML(null);
      }
    }else{
      this.setGameInfoEditorPaneHTML(null);
    }
  }

  /**
   * Creates the player list.
   *
   * @return a scrollpane with the playerlist
   */
  private JScrollPane initPlayersList() {
    this.playerlist = new JList();
    this.playerlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    this.playerlist.setLayoutOrientation(JList.VERTICAL);
    this.playerlist.setVisibleRowCount(-1);

    if (this.playersScrollPane == null) {
      this.playersScrollPane = new JScrollPane(this.playerlist);
      //this.playersScrollPane.setPreferredSize(new Dimension(150, 80));
     
    }
    return this.playersScrollPane;

  }

  /**
   * Gets the playerlist and adds the players to the textarea.
   *
   * @param p
   *            the playersMessage
   */
  private void setPlayersList(PlayersMessage p) {
    if (p != null) {
     
      Player_Online_player_list = 0;
      DefaultListModel listModel = new DefaultListModel();
      Enumeration<String> e = Collections.enumeration( new TreeSet<String>( Collections.list( p.getPlayerNames().keys() ) ) );  ;
     
      while (e.hasMoreElements()) {
       
        Player_Online_player_list++;
          String key = (String) e.nextElement();
          if (GameLobby.this.getCore().getPlayerName().equals(key)) {
            listModel.addElement("<html><font color=\"red\">" + key + ""
                +" [" + p.getPlayerNames().get(key) + "]"
                + "</font></html>");
          GameLobby.this.getCore().setPlayerEloScore(
              Integer.valueOf(p.getPlayerNames().get(key)
                  .toString()));
        }else{
            listModel.addElement("" + key + ""
                +" [" + p.getPlayerNames().get(key) + "]"
                + "");
           
        }
      }

      this.playerlist.setModel(listModel);
    }
  }

 
  /**
   * Set the Game Info Label, NULL = Start Screen
   *
   * @param txt Set the Label info
   *           
   */
  public void setGameInfoEditorPaneHTML(String HTML){
   
    String inhalt = "<html><body text=\"#00FF00\" bgcolor=\"#000000\">";
   
    if (HTML == null){
      inhalt = inhalt+"<center><br>" +
              "<h1>Welcome to <br>" +
              "<b>CreepSmash Lobby</b></h1>" +
              "Multiplayer TowerDefence<br><br>" +
              "<small>Press F1 for Help...</small><br>" +
              "</center>";
    }else{
      inhalt = inhalt+HTML;
    }
   
    inhalt = inhalt+"</body></html>";
   
    if (inhalt != this.GameInfoEditorPane.getText()){
      this.GameInfoEditorPane.setText(inhalt);
    }
     
  }
  /**
   * Set the LabelGameInfo with Slected Game Info
   *
   * @param selectedRow
   *
   *
   */
  public synchronized void setGameInfoEditorPaneSelectGame(int selectedRow) {

    GameDescription GameRow = this.games.get(selectedRow);
    java.net.URL imageURL = getClass().getClassLoader().getResource(
        IConstants.Map.getPictureThumbnailPath(IConstants.Map
            .getMapById(GameRow.getMapId()).toString()));

    String txt = "<div align=\"center\">" + "<small>"
        + GameRow.getGameName() +"<br>("
        + IConstants.Map.getMapById(GameRow.getMapId()).toString()
        + ")</small><hr>"
        + "<table border='0' style='border-collapse: collapse' width='270' height='102' cellpadding='3'>"
        + "<tr>" + "<td width='122' valign='top' height='102'>"
        + "<center>"
        + "  <img border='1' src='" + imageURL
        + "' width='100' height='100'></center></td>"
        + "  <td valign='top' width='150' height='102'>"
        + "  Player: "
        + GameRow.getCurrentPlayers() + " of "
        + GameRow.getMaxPlayers() + "<br>" + "  Status: "
        + GameRow.getState() + "<br>" + "  Min/Max: "
        + GameRow.getMinEloPoints() + " / " + GameRow.getMaxEloPoints()
        + "<br>" + "  PW: " + GameRow.getPasswort() + "<br>" + "  </td>"
        + "</tr>" + "</table>" + "</div>" + "<hr><b>Player in Game:</b> "
        + GameRow.getPlayer1() + " " + GameRow.getPlayer2() + " "
        + GameRow.getPlayer3() + " " + GameRow.getPlayer4() + "<br>"
        + "</font>";

    this.setGameInfoEditorPaneHTML(txt);
   
  }
  /**
   * {@inheritDoc}
   */
  @Override
  public void end() {
    this.getCore().getNetwork().removeListener(this);
    this.endLobbyTimer();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void start() {
    managementSound = this.getCore().getCoreManagementSound();
    this.getCore().getNetwork().addListener(this);
    this.repaint();
    resetLobbyTimer();
    // refresh gamelist
    getCore().getNetwork().sendMessage(new RefreshMessage());
    this.setGameInfoEditorPaneHTML(null);
       
  }

  /**
   * {@inheritDoc}
   */
  public void update(ServerMessage m) {
       
    if (m instanceof GamesMessage) {
      this.setGameList((GamesMessage) m);
      this.setPlayerCountLabel();
    }
    if (m instanceof PlayersMessage) {
      PlayersMessage pm = (PlayersMessage) m;
      int size = this.playerlist.getModel().getSize();
      ArrayList<String> alist = new ArrayList<String>();
      for (int i = 0; i < size; i++) {
        alist.add((String) playerlist.getModel().getElementAt(i));
      }
      ArrayList<String> newPlayers = new ArrayList<String>();
      Enumeration<String> e = pm.getPlayerNames().keys();
      while (e.hasMoreElements()) {
        String nick = (String) e.nextElement().toString();
        nick += " [" + (String) pm.getPlayerNames().get(nick).toString() + "]";
        newPlayers.add(nick);
      }
//      int newSize = newPlayers.size();
//      if (size > newSize && size - newSize == 1) {
//        for (int j = 0; j < size; j++) {
//          if (!newPlayers.contains((String) (alist.get(j)))) {
//            String leftPlayer = alist.get(j);
//            //this.sendChatTextArea("System",leftPlayer + " left...");
//            //
//            //if (managementSound != null) {
//            //  managementSound.hornbeepSound();
//            //}
//          }
//        }
//      }
//
//      if (size < newSize && newSize - size == 1) {
//        for (int i = 0; i < newSize; i++) {
//
//          if (!alist.contains(newPlayers.get(i))) {
//            String joinedPlayer = newPlayers.get(i);
//            //this.sendChatTextArea("System",joinedPlayer + " joined!");
//            //if (managementSound != null) {
//            //  managementSound.hornbeepSound();
//            //}
//          }
//        }
//      }
      this.setPlayersList((PlayersMessage) m);
      this.setPlayerCountLabel();
    }
   
    if (m instanceof MessageMessage) {
      MessageMessage mm = (MessageMessage) m;
     
      this.chatdialog.sendChatText(mm.getPlayerName(),mm.getMessage(), getCore());
     
      if (managementSound != null) {
        managementSound.clapSound();
      }
    }

    if (m instanceof JoinGameResponseMessage) {
      if (((JoinGameResponseMessage) m).getResponseType().equals(
          IConstants.ResponseType.ok)) {

        WaitingGamePanel wgp = new WaitingGamePanel();
        if (this.joinGame == null) {
          this.logger.severe("The game to join was null!");
        }
        wgp.setMapId(this.joinGame.getMapId());
        this.getCore().setActiveGame(this.joinGame);
        this.getCore().pushScreen(wgp);
        } else {
          errorDialog("Cannot join the game!");
      }
      this.join.setEnabled(true);
     
    }
    resetLobbyTimer();
  }
  /**
   * Schreibt das Player Count Label neu
   */
  public void setPlayerCountLabel(){
   
    LabelPlayerListCount.setText(Player_Online_gameinfo
                  +Player_Online_player_list
                  + " player online");
  }
  /**
   * @param msg
   *            msg
   */
  public void errorDialog(String msg) {
    UIManager.put("OptionPane.background", Color.BLACK);
    UIManager.put("Panel.background", Color.BLACK);
    UIManager.put("OptionPane.messageForeground", Color.GREEN);
    JOptionPane.showMessageDialog(this, msg, "error",
        JOptionPane.ERROR_MESSAGE);
  }
  /**
   * Resets the inactive timer to 30 minutes.
   */
  public void resetLobbyTimer() {
    this.inactiveTimerTask.cancel();
    this.inactiveTimer.purge();
    this.inactiveTimerTask = new LobbyTimerTask(this);

    this.inactiveTimer.schedule(this.inactiveTimerTask,
        1000 * 60 * 30);
  }
  /**
   * stops the lobby timer.
   */
  public void endLobbyTimer() {
    this.inactiveTimerTask.cancel();
    this.inactiveTimer.purge();
   
  }
}
TOP

Related Classes of de.creepsmash.client.panel.GameLobby

TOP
Copyright © 2018 www.massapi.com. 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.