Exemplo n.º 1
2
  public void changeLAF(int iLAFIndex) {
    try {
      // Change LAF
      if (iLAFIndex >= marrLaf.length) iLAFIndex = marrLaf.length - 1;
      UIManager.setLookAndFeel(
          (LookAndFeel) Class.forName(marrLaf[iLAFIndex].getClassName()).newInstance());

      // Update UI
      ((JMenuItem) mvtLAFItem.elementAt(iLAFIndex)).setSelected(true);
      SwingUtilities.updateComponentTreeUI(this);
      SwingUtilities.updateComponentTreeUI(mnuMain);
      WindowManager.updateLookAndField();

      // Store config
      try {
        Hashtable prt = Global.loadHashtable(Global.FILE_CONFIG);
        prt.put("LAF", String.valueOf(iLAFIndex));
        Global.storeHashtable(prt, Global.FILE_CONFIG);
      } catch (Exception e) {
      }
    } catch (Exception e) {
      e.printStackTrace();
      MessageBox.showMessageDialog(this, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
    }
  }
Exemplo n.º 2
0
  public void changeDictionary(String strLanguage) {
    // Change dictionary
    MonitorDictionary.setCurrentLanguage(strLanguage);
    DefaultDictionary.setCurrentLanguage(strLanguage);
    ErrorDictionary.setCurrentLanguage(strLanguage);

    // Update UI
    updateLanguage();
    WindowManager.updateLanguage();
    int iIndex = mvtLanguage.indexOf(strLanguage);
    if (iIndex >= 0) {
      JRadioButtonMenuItem mnu = (JRadioButtonMenuItem) mvtLanguageItem.elementAt(iIndex);
      mnu.setSelected(true);
    }

    // Store config
    Hashtable prt = null;
    try {
      prt = Global.loadHashtable(Global.FILE_CONFIG);
    } catch (Exception e) {
      prt = new Hashtable();
    }
    prt.put("Language", strLanguage);
    try {
      Global.storeHashtable(prt, Global.FILE_CONFIG);
    } catch (Exception e) {
    }
  }
Exemplo n.º 3
0
  void waitForOtherPlayers() throws IOException {

    Global.log("Waiting for other players to register...");

    int n = Integer.parseInt(mainServer.readLine());
    playerNames = new String[n];

    for (int i = 0; i < n; ++i) {
      String info = mainServer.readLine();
      playerNames[i] = info;
    }

    // ping back to server for an OK
    mainServer.println();
    mainServer.flush();

    Global.log("List of Players:");
    for (int i = 0; i < n; ++i) Global.log("\t" + (i + 1) + ": " + playerNames[i]);

    // get player ID
    for (int i = 0; i < n; ++i) {
      if (name.equals(playerNames[i])) {
        playerID = i;
        break;
      }
    }

    Global.log("Player ID: " + (playerID + 1));
  }
Exemplo n.º 4
0
  void turnOnFadeLog() throws IOException {
    Global.log("Connecting to fade log...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.fadeLogPort() + "...");
      try {
        fadeLog = new ClientByteStream(ip, Global.fadeLogPort(), 12);
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                String s = null;
                byte[] data = null;
                try {
                  data = fadeLog.read();
                  if (data == null) return;
                  s = fadeLog.readLine();
                } catch (IOException ex) {
                  System.err.println("Error reading from fade log: " + ex);
                  Global.onException();
                  stop();
                  return;
                }
                if (s == null) return;
                ByteBuffer bb = ByteBuffer.wrap(data);
                float x = bb.getFloat();
                float y = bb.getFloat();
                Color color = Global.IntToColor(bb.getInt());

                // if fade color is same as ship color, play power-up sound

                if (color.equals(getPlayerShip().fill)) Sounds.powerUp.play();

                fadeLog(s, x, y, color);
              }
            }));
  }
Exemplo n.º 5
0
  void turnOnBulletReceiver() throws IOException {
    Global.log("Turning on bullet receiver...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + (Global.bulletPort()) + "...");
      try {
        bulletStream = new ClientByteStream(ip, Global.bulletPort(), Bullet.bufferSize());
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return true;
              }

              public float FPS() {
                return Global.ReceiveFPS * 20;
              }

              public void run() {
                byte[] data = null;
                try {
                  data = bulletStream.read();
                } catch (IOException ex) {
                  System.err.println("Bullet receiver error: " + ex);
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                Bullet toSpawn = Bullet.fromBytes(data);
                Ship find = cShip.get(toSpawn.getFill());
                if (find == null) {
                  for (Ship s : turrets) {
                    if (s.fill.equals(toSpawn.getFill())) {
                      find = s;
                      break;
                    }
                  }
                }
                if (find == null) return;
                find.getBulletSet().add(toSpawn);
              }
            }));
  }
Exemplo n.º 6
0
  void connectToMainServer() throws IOException {

    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to main server...");
      try {
        mainServer = new ClientStream(ip, Global.PORT);
        break;
      } catch (UnknownHostException ex) {
        throw ex;
      } catch (IOException ex) {
      }
    }

    Global.log("Connected to server [" + ip + " : " + Global.PORT + "]");
  }
Exemplo n.º 7
0
  public ClientGame(String name, String ip) throws ClientNameException, IOException {

    super();
    this.name = name;
    this.ip = ip;

    // try {
    connectToMainServer();
    registerName();
    waitForOtherPlayers();
    createBytePorts();
    createShips();
    turnOnBulletReceiver();
    turnOnTurretReceiver();
    turnOnPowerReceiver();
    turnOnChatLog();
    turnOnFadeLog();
    turnOnServerTime();
    // turnOnEndGameReceiver();
    Global.log("Successfully created client game.");
    // }
    // catch (IOException ex) {
    // System.err.println("Exception occured: " + ex.toString());
    // Global.onException();
    // }

  }
Exemplo n.º 8
0
  void registerName() throws IOException, ClientNameException {

    // send name of player to main server
    Global.log("Sending player information [" + name + "]...");
    mainServer.out.println(name);
    mainServer.out.flush();
    Global.log("Checking if name already exists...");

    // check if registered
    String s = mainServer.readLine();
    if (!s.equals("OK")) {
      Global.log("Error! Name already exists. ClientNameException thrown.");
      throw new ClientNameException("Client name [" + name + "] already exists in server");
    }

    Global.log("Successfully registered as [" + name + "]");
  }
Exemplo n.º 9
0
  void turnOnTurretReceiver() throws IOException {
    Global.log("Turning on turret receiver...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.turretPort() + "...");
      try {
        turretStream = new ClientByteStream(ip, Global.turretPort(), Ship.bufferSize());
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                byte[] data = null;
                String name = null;
                try {
                  data = turretStream.read();
                  name = turretStream.readLine();
                } catch (IOException ex) {
                  System.err.println("Cannot read info from turret stream");
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                Ship s = new Ship(name, Global.transparent);
                s.setDesign(new Design.Turret(s));
                s.fromBytes(data, false);
                addShip(s);
              }
            }));
  }
Exemplo n.º 10
0
  void turnOnServerTime() throws IOException {
    Global.log("Turning on server time...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.serverTimePort() + "...");
      try {
        serverTime = new ClientByteStream(ip, Global.serverTimePort(), 2);
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                byte[] data = null;
                try {
                  data = serverTime.read();
                } catch (IOException ex) {
                  System.err.println("Error reading from server time: " + ex);
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                ByteBuffer bb = ByteBuffer.wrap(data);
                short time = bb.getShort();
                Game.activeGame().getHud().setTime(time);
              }
            }));
  }
Exemplo n.º 11
0
  @Override
  public void startTheGame() {

    gameType = "";

    try {
      // receive ping from server
      gameType = mainServer.readLine();
    } catch (IOException ex) {
      System.err.println("Could not communicate with server: " + ex);
      Global.onException();
    }

    super.startTheGame();

    for (FixedTimer timer : timers) timer.start();

    startMarquee(getGameType(), 1000);
    startMarquee("3");
    startMarquee("2");
    startMarquee("1");

    // receive ping that the game is starting

    try {
      // ping back that client is ready
      mainServer.println();
      mainServer.flush();
      // wait for if server is ready
      mainServer.readLine();
    } catch (IOException ex) {
      System.err.println("Could not communicate with server: " + ex);
      Global.onException();
    }

    turnOnEndGameReceiver();
    startMarquee("START!");
  }
Exemplo n.º 12
0
  void turnOnChatLog() throws IOException {
    Global.log("Connecting to chat log...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.chatLogPort() + "...");
      try {
        chatLog = new ClientByteStream(ip, Global.chatLogPort(), 1);
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                String s = null;
                try {
                  s = chatLog.readLine();
                } catch (IOException ex) {
                  System.err.println("Error reading from chat log: " + ex);
                  Global.onException();
                  stop();
                  return;
                }
                if (s == null) return;
                log(s);
              }
            }));
  }
Exemplo n.º 13
0
  void createBytePorts() throws IOException {

    Global.log("Creating byte ports...");

    int n = numPlayers();
    playerByteStreams = new ClientByteStream[n];

    for (int i = 0; i < n; ++i) {

      ClientByteStream stream = null;

      while (true) {

        if (isDisposed()) throw new IOException("Client game disposed");
        Global.log("Connecting to port " + Global.playerPort(i) + "...");
        try {
          stream =
              playerByteStreams[i] =
                  new ClientByteStream(ip, Global.playerPort(i), Ship.bufferSize());
          break;
        } catch (IOException ex) {
        }
      }

      Global.log("Connected!");
      Global.log("Sending client information...");

      // first byte is player ID

      stream.out.write((byte) playerID);
      stream.out.flush();
      Global.log("Done!");
    }

    Global.log("Done creating byte ports!");
  }
Exemplo n.º 14
0
 private void jbInit() throws Exception {
   ////////////////////////////////////////////////////////
   // Init LAF
   ////////////////////////////////////////////////////////
   ButtonGroup grpLAF = new ButtonGroup();
   ActionListener lsnLAF =
       new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
           int iIndex = mvtLAFItem.indexOf(evt.getSource());
           if (iIndex >= 0) changeLAF(iIndex);
         }
       };
   ////////////////////////////////////////////////////////
   UIManager.LookAndFeelInfo laf =
       new UIManager.LookAndFeelInfo(
           "Kunststoff", "com.incors.plaf.kunststoff.KunststoffLookAndFeel");
   marrLaf = UIManager.getInstalledLookAndFeels();
   int iIndex = 0;
   while (iIndex < marrLaf.length && !marrLaf[iIndex].getName().equals(laf.getName())) iIndex++;
   if (iIndex >= marrLaf.length) {
     UIManager.installLookAndFeel(laf);
     marrLaf = UIManager.getInstalledLookAndFeels();
   }
   for (iIndex = 0; iIndex < marrLaf.length; iIndex++) {
     JMenuItem mnu = new JRadioButtonMenuItem(marrLaf[iIndex].getName());
     mnu.addActionListener(lsnLAF);
     mvtLAFItem.addElement(mnu);
     mnuUI.add(mnu);
     grpLAF.add(mnu);
   }
   mnuUI.addSeparator();
   ////////////////////////////////////////////////////////
   // Init language
   ////////////////////////////////////////////////////////
   ButtonGroup grpLanguage = new ButtonGroup();
   ActionListener lsnLanguage =
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           int iIndex = mvtLanguageItem.indexOf(e.getSource());
           if (iIndex >= 0) changeDictionary((String) mvtLanguage.elementAt(iIndex));
         }
       };
   ////////////////////////////////////////////////////////
   String[] str = MonitorDictionary.getSupportedLanguage();
   for (iIndex = 0; iIndex < str.length; iIndex++) {
     JMenuItem mnu =
         new JRadioButtonMenuItem(MonitorDictionary.getDictionary(str[iIndex]).getLanguage());
     mnu.addActionListener(lsnLanguage);
     mvtLanguage.addElement(str[iIndex]);
     mvtLanguageItem.addElement(mnu);
     mnuUI.add(mnu);
     grpLanguage.add(mnu);
   }
   ////////////////////////////////////////////////////////
   // Add to main menu
   ////////////////////////////////////////////////////////
   mnuMain.removeAll();
   mnuMain.add(mnuSystem);
   mnuSystem.add(mnuSystem_Login);
   mnuSystem.add(mnuSystem_ChangePassword);
   mnuSystem.addSeparator();
   mnuSystem.add(mnuSystem_StopServer);
   mnuSystem.add(mnuSystem_EnableThreads);
   mnuMain.add(mnuUI);
   mnuMain.add(mnuHelp);
   mnuHelp.add(mnuHelp_About);
   ////////////////////////////////////////////////////////
   mnuMain.add(chkVietnamese);
   mnuMain.add(lblStatus);
   ////////////////////////////////////////////////////////
   pnlThread.setTabPlacement(JTabbedPane.LEFT);
   pnlThread.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
   ////////////////////////////////////////////////////////
   tblUser.addColumn("", 1, false);
   tblUser.addColumn("", 2, false, Global.FORMAT_DATE_TIME);
   tblUser.addColumn("", 3, false);
   ////////////////////////////////////////////////////////
   JPanel pnlMessage = new JPanel();
   pnlMessage.setLayout(new GridBagLayout());
   pnlMessage.add(
       new JScrollPane(txtBoard),
       new GridBagConstraints(
           0,
           0,
           2,
           1,
           1.0,
           1.0,
           GridBagConstraints.CENTER,
           GridBagConstraints.BOTH,
           new Insets(2, 2, 2, 2),
           0,
           0));
   pnlMessage.add(
       txtMessage,
       new GridBagConstraints(
           0,
           1,
           1,
           1,
           1.0,
           0.0,
           GridBagConstraints.CENTER,
           GridBagConstraints.BOTH,
           new Insets(2, 2, 2, 2),
           0,
           0));
   pnlMessage.add(
       btnSend,
       new GridBagConstraints(
           1,
           1,
           1,
           1,
           0.0,
           0.0,
           GridBagConstraints.CENTER,
           GridBagConstraints.NONE,
           new Insets(2, 2, 2, 2),
           0,
           0));
   txtBoard.setEditable(false);
   txtBoard.setAutoscrolls(true);
   txtBoard.setContentType("text/html");
   clearAll(txtBoard);
   ////////////////////////////////////////////////////////
   JPanel pnlUserButton = new JPanel(new GridLayout(1, 2, 4, 4));
   pnlUserButton.add(btnKick);
   pnlUserButton.add(btnRefresh);
   ////////////////////////////////////////////////////////
   JPanel pnlManager = new JPanel(new GridBagLayout());
   pnlManager.add(
       new JScrollPane(tblUser),
       new GridBagConstraints(
           0,
           0,
           1,
           1,
           1.0,
           1.0,
           GridBagConstraints.CENTER,
           GridBagConstraints.BOTH,
           new Insets(2, 2, 2, 2),
           0,
           0));
   pnlManager.add(
       pnlUserButton,
       new GridBagConstraints(
           0,
           1,
           1,
           1,
           0.0,
           0.0,
           GridBagConstraints.CENTER,
           GridBagConstraints.NONE,
           new Insets(4, 2, 4, 2),
           0,
           0));
   ////////////////////////////////////////////////////////
   pnlUser.setDividerLocation(320);
   pnlUser.setLeftComponent(pnlManager);
   pnlUser.setRightComponent(pnlMessage);
   pnlUser.setOneTouchExpandable(true);
   ////////////////////////////////////////////////////////
   setOrientation(JSplitPane.VERTICAL_SPLIT);
   setOneTouchExpandable(true);
   pnlThread.setVisible(false);
   pnlUser.setVisible(false);
   setTopComponent(pnlThread);
   setBottomComponent(pnlUser);
   ////////////////////////////////////////////////////////
   pmn.add(mnuSelectAll);
   pmn.addSeparator();
   pmn.add(mnuClearSelected);
   pmn.add(mnuClearAll);
   ////////////////////////////////////////////////////////
   setBorder(BorderFactory.createEmptyBorder());
   pnlUser.setBorder(BorderFactory.createEmptyBorder());
   pnlManager.setBorder(
       BorderFactory.createBevelBorder(
           javax.swing.border.BevelBorder.RAISED,
           Color.white,
           UIManager.getColor("Panel.background"),
           UIManager.getColor("Panel.background"),
           UIManager.getColor("Panel.background")));
   pnlMessage.setBorder(
       BorderFactory.createBevelBorder(
           javax.swing.border.BevelBorder.RAISED,
           Color.white,
           UIManager.getColor("Panel.background"),
           UIManager.getColor("Panel.background"),
           UIManager.getColor("Panel.background")));
   ////////////////////////////////////////////////////////
   Skin.applySkin(mnuMain);
   Skin.applySkin(tblUser);
   Skin.applySkin(pmn);
   Skin.applySkin(this);
   ////////////////////////////////////////////////////////
   // Default setting
   ////////////////////////////////////////////////////////
   Hashtable prt = null;
   try {
     prt = Global.loadHashtable(Global.FILE_CONFIG);
   } catch (Exception e) {
     prt = new Hashtable();
   }
   changeLAF(Integer.parseInt(StringUtil.nvl(prt.get("LAF"), "0")));
   changeDictionary(StringUtil.nvl(prt.get("Language"), "VN"));
   Skin.LANGUAGE_CHANGE_LISTENER = this;
   MonitorProcessor.setRootObject(this);
   updateKeyboardUI();
   ////////////////////////////////////////////////////////
   // Event handler
   ////////////////////////////////////////////////////////
   tblUser.addMouseListener(
       new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
           if (e.getClickCount() > 1) btnKick.doClick();
         }
       });
   ////////////////////////////////////////////////////////
   btnRefresh.addActionListener(
       new java.awt.event.ActionListener() {
         public void actionPerformed(ActionEvent evt) {
           try {
             DDTP request = new DDTP();
             request.setRequestID(String.valueOf(System.currentTimeMillis()));
             DDTP response = channel.sendRequest("ThreadProcessor", "queryUserList", request);
             if (response != null) {
               tblUser.setData((Vector) response.getReturn());
               if (mstrChannel != null) removeUser(mstrChannel);
             }
           } catch (Exception e) {
             e.printStackTrace();
             MessageBox.showMessageDialog(pnlThread, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
           }
         }
       });
   ////////////////////////////////////////////////////////
   btnKick.addActionListener(
       new java.awt.event.ActionListener() {
         public void actionPerformed(ActionEvent evt) {
           int iSelected = tblUser.getSelectedRow();
           if (iSelected < 0) return;
           int iResult =
               MessageBox.showConfirmDialog(
                   pnlThread,
                   mdic.getString("ConfirmKick"),
                   Global.APP_NAME,
                   MessageBox.YES_NO_OPTION);
           if (iResult == MessageBox.NO_OPTION) return;
           try {
             String strChannel = (String) tblUser.getRow(iSelected).elementAt(0);
             DDTP request = new DDTP();
             request.setRequestID(String.valueOf(System.currentTimeMillis()));
             request.setString("strChannel", strChannel);
             DDTP response = channel.sendRequest("ThreadProcessor", "kickUser", request);
           } catch (Exception e) {
             e.printStackTrace();
             MessageBox.showMessageDialog(pnlThread, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
           }
         }
       });
   ////////////////////////////////////////////////////////
   txtMessage.addActionListener(
       new java.awt.event.ActionListener() {
         public void actionPerformed(ActionEvent evt) {
           btnSend.doClick();
         }
       });
   ////////////////////////////////////////////////////////
   btnSend.addActionListener(
       new java.awt.event.ActionListener() {
         public void actionPerformed(ActionEvent evt) {
           if (txtMessage.getText().length() == 0) return;
           try {
             DDTP request = new DDTP();
             request.setString("strMessage", txtMessage.getText());
             channel.sendRequest("ThreadProcessor", "sendMessage", request);
             txtMessage.setText("");
           } catch (Exception e) {
             e.printStackTrace();
             MessageBox.showMessageDialog(pnlThread, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
           }
         }
       });
   ////////////////////////////////////////////////////////
   mnuClearAll.addActionListener(
       new java.awt.event.ActionListener() {
         public void actionPerformed(ActionEvent e) {
           clearAll(txtBoard);
         }
       });
   ////////////////////////////////////////////////////////
   mnuClearSelected.addActionListener(
       new java.awt.event.ActionListener() {
         public void actionPerformed(ActionEvent e) {
           txtBoard.setEditable(true);
           txtBoard.replaceSelection("");
           txtBoard.setEditable(false);
         }
       });
   ////////////////////////////////////////////////////////
   mnuSelectAll.addActionListener(
       new java.awt.event.ActionListener() {
         public void actionPerformed(ActionEvent e) {
           txtBoard.requestFocus();
           txtBoard.selectAll();
         }
       });
   ////////////////////////////////////////////////////////
   txtBoard.addMouseListener(
       new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
           if (e.getButton() == e.BUTTON3) pmn.show(txtBoard, e.getX(), e.getY());
         }
       });
   ////////////////////////////////////////////////////////
   mnuSystem_Login.addActionListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           login();
         }
       });
   ////////////////////////////////////////////////////////
   mnuSystem_ChangePassword.addActionListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           changePassword();
         }
       });
   ////////////////////////////////////////////////////////
   mnuSystem_StopServer.addActionListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           stopServer();
         }
       });
   ////////////////////////////////////////////////////////
   mnuSystem_EnableThreads.addActionListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           manageThreads();
         }
       });
   ////////////////////////////////////////////////////////
   mnuHelp_About.addActionListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           WindowManager.centeredWindow(new DialogAbout(PanelThreadManager.this));
         }
       });
   ////////////////////////////////////////////////////////
   chkVietnamese.addActionListener(
       new java.awt.event.ActionListener() {
         public void actionPerformed(ActionEvent e) {
           switchKeyboard();
         }
       });
 }
Exemplo n.º 15
0
  void turnOnPowerReceiver() throws IOException {
    Global.log("Turning on power receiver...");
    while (true) {

      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + (Global.powerPort()) + "...");
      try {
        powerStream = new ClientByteStream(ip, Global.powerPort(), Power.bufferSize());
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                byte[] data = null;
                try {
                  data = powerStream.read();
                } catch (IOException ex) {
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                addPower(Power.fromBytes(data));
              }
            }));
    Global.log("Turning on power remover...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.powerRemoverPort() + "...");
      try {
        powerRemover = new ClientByteStream(ip, Global.powerRemoverPort(), 2);
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                byte[] data = null;
                try {
                  data = powerRemover.read();
                } catch (IOException ex) {
                  System.err.println("Cannot read info from power remover");
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                ByteBuffer bb = ByteBuffer.wrap(data);
                short id = bb.getShort();
                for (Power power : powers) {
                  if (power.ID == id) {
                    removePower(power);
                    break;
                  }
                }
              }
            }));
  }
Exemplo n.º 16
0
  void createShips() {

    Global.log("Creating ships...");
    int n = numPlayers();

    for (int i = 0; i < n; ++i) {

      Global.log("Creating ship for Player " + (i + 1) + " [" + playerNames[i] + "]...");

      final int I = i;

      if (i == playerID) {
        final PlayerShip ship = new PlayerShip(name, nextColor(), this, new Controls());
        ship.getControls().enabled = false;
        timers.add(
            new FixedTimer(
                new FixedTask() {
                  public boolean fixedRate() {
                    return true;
                  }

                  public float FPS() {
                    return Global.SendFPS;
                  }

                  public void run() {
                    try {
                      sendMessage(ship.getControlBytes());
                    } catch (IOException ex) {
                      System.err.println(
                          "An exception occured via the ship of Player "
                              + (I + 1)
                              + " ["
                              + playerNames[I]
                              + "]: "
                              + ex.toString());
                      Global.onException();
                      stop();
                    }
                  }
                }));
        timers.add(
            new FixedTimer(
                new FixedTask() {
                  public boolean fixedRate() {
                    return true;
                  }

                  public float FPS() {
                    return Global.ReceiveFPS;
                  }

                  public void run() {
                    byte[] data = null;
                    try {
                      data = playerByteStreams[I].read();
                    } catch (IOException ex) {
                      System.err.println("Error reading ship from server: " + ex);
                      Global.onException();
                      stop();
                      return;
                    }
                    if (data == null) return;
                    ship.fromBytes(data);
                  }
                }));
        addShip(ship);
      } else {
        final Ship ship = new Ship(playerNames[i], nextColor());
        timers.add(
            new FixedTimer(
                new FixedTask() {
                  public boolean fixedRate() {
                    return true;
                  }

                  public float FPS() {
                    return Global.ReceiveFPS;
                  }

                  public void run() {
                    byte[] data = null;
                    try {
                      data = playerByteStreams[I].read();
                    } catch (IOException ex) {
                      System.err.println("Error reading ship from server: " + ex);
                      Global.onException();
                      stop();
                      return;
                    }
                    if (data == null) return;
                    ship.fromBytes(data);
                  }
                }));
        addShip(ship);
      }

      Global.log("Done!");
    }

    Global.log("Done creating ships!");
  }