public void summarizePlayer(int playerID) { Player p = players.get(playerID); Map<Integer, Playing> playersGames = p.games; Set<Integer> gamesKeys = playersGames.keySet(); Integer[] gameIDs = gamesKeys.toArray(new Integer[gamesKeys.size()]); System.out.println("Player: " + p); System.out.println("Total Gamerscore: " + p.getGamerScore()); System.out.printf( "%4s %-20s %-16s %-16s %-16s \n", " ", "Game", "Achievements", "Gamerscore", "IGN"); System.out.println( "--------------------------------------------------------------------------------"); for (int i = 0; i < gameIDs.length; i++) { Game g = games.get(gameIDs[i]); Playing playerInfo = p.games.get(gameIDs[i]); int nPlayerAchieve = playerInfo.achievements.size(); int nTotalAchieve = g.achievements.size(); System.out.printf( "%4s %-20s %-16s %-16s %-16s \n", (i + 1 + "."), g, (nPlayerAchieve + "/" + nTotalAchieve), (playerInfo.getPoints() + " pts"), playerInfo.ign); } System.out.printf("\n%4s %-16s %-16s \n", " ", "Friend", "Gamerscore"); System.out.println( "--------------------------------------------------------------------------------"); printSortedPlayers(p.friends); }
public void count_bip_exits(String hostname) { int[] pos; pos = (int[]) mbips.get(hostname); if (pos == null) { pos = make_int_array(MBIPS_NUM_POS); mbips.put(hostname, pos); } ++pos[MBIPS_BIPS_EXITTED_POS]; return; }
public void count_account_stat(String hostname, AccountStatisticReturnVal acstat) { double[] pos; pos = (double[]) mtimes.get(hostname); if (pos == null) { pos = make_double_array(MTIMES_NUM_POS); mtimes.put(hostname, pos); } pos[MTIMES_CPU_TIME_POS] += acstat.get_cpu_time(); pos[MTIMES_WALL_TIME_POS] += acstat.get_wall_time(); return; }
private static void fdCallbackHandler(int fd) { FD_HANDLER_TYPE handler = (FD_HANDLER_TYPE) fdHashTable.get(Integer.toString(fd)); if (handler != null) { handler.handle(fd); } else System.out.println("Ooops -- no handler for fd"); }
public static ZigBee findRemote(long address64) { ZigBee zb; synchronized (knownNodes) { zb = knownNodes.get(new Long(address64)); } return zb; }
private static void timerCallbackHandler(int handlerNum, long currentTime, long scheduledTime) { TIMER_HANDLER_TYPE handler = (TIMER_HANDLER_TYPE) timerHashTable.get(Integer.toString(handlerNum)); if (handler != null) { handler.handle(currentTime, scheduledTime); } else System.out.println("Ooops -- no handler for timer"); }
public static Map<String, String[]> fillMap() { // HashMap to keep track of each notes intervals and neighboring notes Map<String, String[]> intervals = new HashMap<String, String[]>(); // Array of all possible notes String[] allNotes = {"A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "G", "G#"}; // Loop through every note and populate our hash map for (String i : allNotes) { intervals.put(i, new String[4]); } ; // Update the map so all notes are covered intervals.put("A", new String[] {"1", "1", "B", "G"}); intervals.put("B", new String[] {"0.5", "1", "C", "A"}); intervals.put("C", new String[] {"1", "0.5", "D", "B"}); intervals.put("D", new String[] {"1", "1", "E", "C"}); intervals.put("E", new String[] {"0.5", "1", "F", "D"}); intervals.put("F", new String[] {"1", "0.5", "G", "E"}); intervals.put("G", new String[] {"1", "1", "A", "F"}); return intervals; }
/** ** Gets the SMSoutboubdGateway for the specified name */ public static SMSOutboundGateway GetSMSGateway(String name) { /* get handler */ if (StringTools.isBlank(name)) { return null; } else { return SmsGatewayHandlerMap.get(name.toLowerCase()); } }
void updateAddress64(long address64) { synchronized (this) { if (serialNumber != null && serialNumber.longValue() == address64) { return; } if (serialNumber != null) { knownNodes.remove(serialNumber); } if (address64 != -1 && address64 != 0) { serialNumber = new Long(address64); knownNodes.put(serialNumber, this); sendMessage("SERIALNO"); sendStaticMessage("SERIALNO"); } } }
public static void onPortChanged() { close(); synchronized (knownNodes) { knownNodes.clear(); } connectedAddress = new Long(0); synchronized (getLocalLock) { local = null; } }
private static void queryNotifyCallbackHandler(int handlerNum, int msgInstance, int byteArray) { String hashKey = Integer.toString(handlerNum); handlerHashData handlerData = (handlerHashData) msgHashTable.get(hashKey); msgHashTable.remove(hashKey); if (handlerData != null) { Object object; try { object = unmarshallMsgData( IPC_msgInstanceFormatter(msgInstance), byteArray, handlerData.dataClass); handlerData.handler.handle(new MSG_INSTANCE(msgInstance), object); } catch (Exception e) { handleException("queryNotifyCallbackHandler", IPC_msgInstanceName(msgInstance), e); } } else System.out.println( "Ooops -- no query notification handler for " + IPC_msgInstanceName(msgInstance)); }
private void startUpload(int index) { if (NavigineApp.Navigation == null) return; String userHash = NavigineApp.Settings.getString("user_hash", ""); if (userHash.length() == 0) return; LocationInfo info = mInfoList.get(index); String location = new String(info.title); Log.d(TAG, String.format(Locale.ENGLISH, "Start upload: %s", location)); synchronized (mLoaderMap) { if (!mLoaderMap.containsKey(location)) { LoaderState loader = new LoaderState(); loader.location = location; loader.type = UPLOAD; loader.id = LocationLoader.startLocationUploader(location, info.archiveFile, true); mLoaderMap.put(location, loader); } } mAdapter.updateList(); }
private static void changeCallbackHandler(String msgName, int numHandlers) { List handlerList = (List) handlerChangeHashTable.get(msgName); if (handlerList == null) { System.out.println("Ooops -- no change handlers for message " + msgName); return; } Iterator iter = handlerList.iterator(); while (iter.hasNext()) { ((CHANGE_HANDLE_TYPE) iter.next()).handle(msgName, numHandlers); } }
static ZigBee findOrCreateRemote(long address64, short address16) { ZigBee zb; synchronized (knownNodes) { zb = knownNodes.get(new Long(address64)); if (zb == null) { zb = new ZigBee(); zb.updateAddress64(address64); } } zb.updateAddress16(address16); return zb; }
/** ** Returns an OrderedMap of defined primary keys ** @return map of defined primary keys */ public Map<DBField, Object> getKeyMap() { Map<DBField, Object> keyMap = new OrderedMap<DBField, Object>(); // ordered key list if (this.dbFactory != null) { DBField keyField[] = this.dbFactory.getKeyFields(); for (int i = 0; i < keyField.length; i++) { String key = keyField[i].getName(); Object val = null; if (this.dbRecord != null) { // all key values will be defined val = this.dbRecord.getFieldValue(key); } else { // use parent keys DBFactoryTree parent = this.getParentNode(); for (; (parent != null) && (val == null); parent = parent.getParentNode()) { DBRecord dbr = parent.getDBRecord(); if (dbr == null) { // stop at the first undefined ancestor break; } else if (dbr.hasField(key)) { // try getting key value from ancestor DBField parFld = dbr.getField(key); if ((parFld != null) && parFld.isPrimaryKey()) { // primary key fields only val = dbr.getFieldValue(key); } } } } // save key DBField and value if (val != null) { keyMap.put(keyField[i], val); } else { keyMap.put(keyField[i], null); } } } return keyMap; }
@Scheduled(fixedDelay = SCHEDULED_CHECK) public void checkActiveClients() { Set<String> users = user_vidNameMap.keySet(); Iterator<String> it = users.iterator(); long time = System.currentTimeMillis(); int count = 0; while (it.hasNext()) { count++; String user = it.next(); if (user == null) continue; if (userAliveMap.containsKey(user)) { if (userAliveMap.get(user).longValue() < time) { removeUser(user); userAliveMap.remove(user); } } else { throw new RuntimeException("user in user-vid map but not in user-alive map"); } } // System.out.println("Debug: Scheduled Check count:"+count+" user // count:"+user_vidNameMap.size()); System.gc(); }
private static void msgCallbackHandler(int handlerNum, int msgInstance, int byteArray) { handlerHashData handlerData = (handlerHashData) msgHashTable.get(Integer.toString(handlerNum)); if (handlerData != null) { Object object; try { int formatter = IPC_msgInstanceFormatter(msgInstance); object = unmarshallMsgData(formatter, byteArray, handlerData.dataClass); handlerData.handler.handle(new MSG_INSTANCE(msgInstance), object); } catch (Exception e) { handleException("msgCallbackHandler", IPC_msgInstanceName(msgInstance), e); } } else System.out.println("Ooops -- no handler for " + IPC_msgInstanceName(msgInstance)); }
/** * When scanning a robot we need to add it to the collection of scanned objects so it can be used * later for updates to the bots movement. */ public void onScannedRobot(ScannedRobotEvent e) { double targetBearing = getHeading() + e.getBearing(); double tmpX = getX() + e.getDistance() * Math.sin(Math.toRadians(targetBearing)); double tmpY = getY() + e.getDistance() * Math.cos(Math.toRadians(targetBearing)); String name = e.getName(); if (name.equals(GOAL_NAME)) { foundGoal = true; } obstacles.put(name, new Enemy(tmpX, tmpY, e.getBearing())); setTurnRadarRight(getRadarTurnRemaining()); }
@RequestMapping(value = CLIENT_HEARTBEAT_PATH) public @ResponseBody int heartBeat( @RequestParam(value = "username") String uName, HttpServletResponse response) { try { if (!user_vidNameMap.containsKey(uName)) { response.setStatus(402); // client not connected return 0; } userAliveMap.put(uName, new Long(System.currentTimeMillis() + TTL)); return TTL; } catch (Exception e) { System.err.println(e.getMessage()); return FAILED; } }
@RequestMapping(value = CLIENT_CONNECT_PATH, method = RequestMethod.POST) public @ResponseBody int connectClient(@RequestBody String allVid) { try { int reply = FAILED; String[] videos = allVid.split(","); String uName = videos[0].trim(); videos = java.util.Arrays.copyOfRange(videos, 1, videos.length); // System.out.println("Client connect"+hostAdder+" "+uName+" "+ Arrays.asList(videos)); int ans = masterService.psConnectClient(hostAdder, uName, videos); // System.out.println("ans =" +ans +" "+FAILED); while (ans == PS_NOT_CONNECTED) { reconnectToMS(); ans = masterService.psConnectClient(hostAdder, uName, videos); } if (ans == FAILED) return FAILED; // System.out.println("Clinet "+ uName + " connected"); if (user_vidNameMap.containsKey(uName)) { reply = CLIENT_ALREADY_CONNECTED; } else { reply = CLIENT_CONNECTED; user_vidNameMap.put(uName, new HashSet<String>()); } // System.out.println("Clinet "+ uName + " connected"); Set<String> vidSet = user_vidNameMap.get(uName); for (int i = 0; i < videos.length; i++) { String temp = videos[i].trim(); // System.out.println("add video"); if (!temp.equals("")) { vidSet.add(temp); addTovidName_UserMap(uName, temp); } } // System.out.println("Clinet "+ uName + " connected"); userAliveMap.put(uName, new Long(System.currentTimeMillis() + TTL)); // System.out.println("Clinet "+ uName + " connected"); activeUsers.add(uName); System.out.println("Clinet " + uName + " connected"); return reply; } catch (Exception e) { System.out.println("Error: " + e.getMessage()); return FAILED; } }
@RequestMapping(value = CLIENT_DISCONNECT_PATH, method = RequestMethod.DELETE) public @ResponseBody int removeClient( @RequestParam(value = "username") String uName, HttpServletResponse response) { try { if (!user_vidNameMap.containsKey(uName)) { response.setStatus(402); // client not connected return 0; } System.out.println("Disconnecting " + uName); removeUser(uName); userAliveMap.remove(uName); return ACK; } catch (Exception e) { System.err.println(e.getMessage()); return FAILED; } }
private void updateLocationLoaders() { if (NavigineApp.Navigation == null) return; long timeNow = DateTimeUtils.currentTimeMillis(); mUpdateLocationLoadersTime = timeNow; synchronized (mLoaderMap) { Iterator<Map.Entry<String, LoaderState>> iter = mLoaderMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, LoaderState> entry = iter.next(); LoaderState loader = entry.getValue(); if (loader.state < 100) { loader.timeLabel = timeNow; if (loader.type == DOWNLOAD) loader.state = LocationLoader.checkLocationLoader(loader.id); if (loader.type == UPLOAD) loader.state = LocationLoader.checkLocationUploader(loader.id); } else if (loader.state == 100) { String archivePath = NavigineApp.Navigation.getArchivePath(); String locationFile = LocationLoader.getLocationFile(NavigineApp.AppContext, loader.location); if (archivePath != null && archivePath.equals(locationFile)) { Log.d(TAG, "Reloading archive " + archivePath); if (NavigineApp.Navigation.loadArchive(archivePath)) { SharedPreferences.Editor editor = NavigineApp.Settings.edit(); editor.putString("map_file", archivePath); editor.commit(); } } if (loader.type == DOWNLOAD) LocationLoader.stopLocationLoader(loader.id); if (loader.type == UPLOAD) LocationLoader.stopLocationUploader(loader.id); iter.remove(); } else { // Load failed if (Math.abs(timeNow - loader.timeLabel) > 5000) { if (loader.type == DOWNLOAD) LocationLoader.stopLocationLoader(loader.id); if (loader.type == UPLOAD) LocationLoader.stopLocationUploader(loader.id); iter.remove(); } } } } updateLocalVersions(); mAdapter.updateList(); }
// Doesn't check the argument is appropriate for the command. // Using Number won't handle -0 properly. // Also won't handle packets longer than 32k properly. public byte[] buildLocalCommand(Command c, byte api, String command, Object argument) throws ZigBeeException { int length = getArgumentLength(argument) + 6 + command.length(); byte[] packet = new byte[length]; packet[0] = 0x7e; packet[1] = intToByte((length - 4) >> 8); packet[2] = intToByte(length - 4); packet[3] = api; packet[4] = ++currentId; synchronized (outstandingCommands) { outstandingCommands.put(currentId, c); } for (int i = 0; i < command.length(); ++i) { packet[5 + i] = (byte) command.charAt(i); } putArgumentBytes(packet, 5 + command.length(), argument); computeChecksum(packet); return packet; }
/** ** Add SMS Gateway support provider */ public static void AddSMSGateway(String name, SMSOutboundGateway smsGW) { /* validate name */ if (StringTools.isBlank(name)) { Print.logWarn("SMS Gateway name is blank"); return; } else if (smsGW == null) { Print.logWarn("SMS Gateway handler is null"); return; } /* initialize map? */ if (SmsGatewayHandlerMap == null) { SmsGatewayHandlerMap = new HashMap<String, SMSOutboundGateway>(); } /* save handler */ SmsGatewayHandlerMap.put(name.toLowerCase(), smsGW); Print.logDebug("Added SMS Gateway Handler: " + name); }
// Doesn't check the argument is appropriate for the command. // Using Number won't handle -0 properly. // Also won't handle packets longer than 32k properly. public byte[] buildRemoteCommand(Command c, byte api, String command, Object argument) throws ZigBeeException { synchronized (this) { // don't want something to change while we are building the command. int length = getArgumentLength(argument) + 17 + command.length(); // Address is 10 bytes byte[] packet = new byte[length]; packet[0] = 0x7e; packet[1] = intToByte((length - 4) >> 8); packet[2] = intToByte(length - 4); packet[3] = api; packet[4] = ++currentId; synchronized (outstandingCommands) { outstandingCommands.put(currentId, c); } if (currentId == -1) { // never assing id 0 to a packet. it means no id. currentId = 0; } putAddress64(packet, 5, serialNumber); if (address == null) { putAddress16(packet, 13, (short) -2); } else { putAddress16(packet, 13, address); } if (c.command == ZigBeeCommands.AC) { packet[15] = 0x2; // apply changes. } else { packet[15] = 0x0; } for (int i = 0; i < command.length(); ++i) { packet[16 + i] = (byte) command.charAt(i); } putArgumentBytes(packet, 16 + command.length(), argument); computeChecksum(packet); return packet; } }
public boolean convalida() { boolean tuttoOk = true; Map<String, String> errori = new HashMap<String, String>(); if ((nome == null) || nome.equals("")) { tuttoOk = false; request.setAttribute("nome", nome); errori.put("nome", "campo obbligatorio"); } if ((descrizione == null) || descrizione.equals("")) { tuttoOk = false; request.setAttribute("descrizione", descrizione); errori.put("descrizione", "campo obbligatorio"); } if ((codice == null) || codice.equals("")) { tuttoOk = false; request.setAttribute("codice", codice); errori.put("codice", "campo obbligatorio"); } if (!isInteger(disponibilita)) { tuttoOk = false; request.setAttribute("disponibilita", disponibilita); errori.put("disponibilita", "formato non valido"); } if (!isInteger(prezzo)) { tuttoOk = false; request.setAttribute("prezzo", prezzo); errori.put("prezzo", "formato non valido"); } if (!tuttoOk) request.setAttribute("errori", errori); HttpSession sess = request.getSession(); sess.setAttribute("errori", errori); return tuttoOk; }
// Constructor connection receiving a socket number public ClientGUI(String host, int port, int udpPort) { super("Clash of Clans"); defaultPort = port; defaultUDPPort = udpPort; defaultHost = host; // the server name and the port number JPanel serverAndPort = new JPanel(new GridLayout(1, 5, 1, 3)); tfServer = new JTextField(host); tfPort = new JTextField("" + port); tfPort.setHorizontalAlignment(SwingConstants.RIGHT); // CHAT COMPONENTS chatStatus = new JLabel("Please login first", SwingConstants.LEFT); chatField = new JTextField(18); chatField.setBackground(Color.WHITE); JPanel chatControls = new JPanel(); chatControls.add(chatStatus); chatControls.add(chatField); chatControls.setBounds(0, 0, 200, 50); chatArea = new JTextArea("Welcome to the Chat room\n", 80, 80); chatArea.setEditable(false); JScrollPane jsp = new JScrollPane(chatArea); jsp.setBounds(0, 50, 200, 550); JPanel chatPanel = new JPanel(null); chatPanel.setSize(1000, 600); chatPanel.add(chatControls); chatPanel.add(jsp); // LOGIN COMPONENTS mainLogin = new MainPanel(); mainLogin.add(new JLabel("Main Login")); usernameField = new JTextField("user", 15); passwordField = new JTextField("password", 15); login = new CButton("Login"); login.addActionListener(this); sideLogin = new SidePanel(new FlowLayout(FlowLayout.LEFT)); sideLogin.add(usernameField); sideLogin.add(passwordField); sideLogin.add(login); // MAIN MENU COMPONENTS mainMenu = new MainPanel(); mmLabel = new JLabel("Main Menu"); timer = new javax.swing.Timer(1000, this); mainMenu.add(mmLabel); sideMenu = new SidePanel(new FlowLayout(FlowLayout.LEFT)); cmButton = new CButton("Customize Map"); tmButton = new CButton("Troop Movement"); gsButton = new CButton("Game Start"); logout = new CButton("Logout"); cmButton.addActionListener(this); tmButton.addActionListener(this); gsButton.addActionListener(this); logout.addActionListener(this); sideMenu.add(cmButton); // sideMenu.add(tmButton); sideMenu.add(gsButton); sideMenu.add(logout); // CM COMPONENTS mainCM = new MainPanel(new GridLayout(mapSize, mapSize)); tiles = new Tile[mapSize][mapSize]; int tileSize = mainCM.getWidth() / mapSize; for (int i = 0; i < mapSize; i++) { tiles[i] = new Tile[mapSize]; for (int j = 0; j < mapSize; j++) { tiles[i][j] = new Tile(i, j); tiles[i][j].setPreferredSize(new Dimension(tileSize, tileSize)); tiles[i][j].setSize(tileSize, tileSize); tiles[i][j].addActionListener(this); if ((i + j) % 2 == 0) tiles[i][j].setBackground(new Color(102, 255, 51)); else tiles[i][j].setBackground(new Color(51, 204, 51)); mainCM.add(tiles[i][j]); } } sideCM = new SidePanel(new FlowLayout(FlowLayout.LEFT)); cmBack = new CButton("Main Menu"); cmBack.setSize(150, 30); cmBack.setPreferredSize(new Dimension(150, 30)); cmBack.addActionListener(this); sideCM.add(cmBack); // TM COMPONENTS mainTM = new MainPanel(null); mapTM = new Map(600); mapTM.setPreferredSize(new Dimension(600, 600)); mapTM.setSize(600, 600); mapTM.setBounds(0, 0, 600, 600); mainTM.add(mapTM); sideTM = new SidePanel(new FlowLayout(FlowLayout.LEFT)); tmBack = new CButton("Main Menu"); tmBack.setSize(150, 30); tmBack.setPreferredSize(new Dimension(150, 30)); tmBack.addActionListener(this); sideTM.add(tmBack); JRadioButton button; ButtonGroup group; ub = new ArrayList<JRadioButton>(); group = new ButtonGroup(); button = new JRadioButton("Barbarian"); button.addActionListener(this); ub.add(button); sideTM.add(button); group.add(button); button = new JRadioButton("Archer"); button.addActionListener(this); ub.add(button); sideTM.add(button); group.add(button); createBuildings(); bb = new ArrayList<JRadioButton>(); group = new ButtonGroup(); JRadioButton removeButton = new JRadioButton("Remove Building"); bb.add(removeButton); sideCM.add(removeButton); group.add(removeButton); for (int i = 0; i < bList.size(); i++) { button = new JRadioButton(bList.get(i).getName() + '-' + bList.get(i).getQuantity()); bb.add(button); sideCM.add(button); group.add(button); } mainPanels = new MainPanel(new CardLayout()); mainPanels.add(mainLogin, "Login"); mainPanels.add(mainMenu, "Menu"); mainPanels.add(mainCM, "CM"); mainPanels.add(mainTM, "TM"); sidePanels = new SidePanel(new CardLayout()); sidePanels.add(sideLogin, "Login"); sidePanels.add(sideMenu, "Menu"); sidePanels.add(sideCM, "CM"); sidePanels.add(sideTM, "TM"); JPanel mainPanel = new JPanel(null); mainPanel.setSize(1000, 600); mainPanel.add(sidePanels); mainPanel.add(mainPanels); mainPanel.add(chatPanel); add(mainPanel, BorderLayout.CENTER); try { setIconImage(ImageIO.read(new File("images/logo.png"))); } catch (IOException exc) { exc.printStackTrace(); } setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(1000, 600); setVisible(true); setResizable(false); chatField.requestFocus(); }
public void actionPerformed(ActionEvent e) { Object o = e.getSource(); for (JRadioButton u : ub) { if (o == u) { mapTM.setUnitType(u.getText()); System.out.println("Set unit type - " + u.getText()); return; } } if (o == timer) { /* mmLabel.setText("Main Menu ("+(cdTime--)+")"); if(cdTime == 0){ timer.stop(); gsButton.setText("Game Start"); mmLabel.setText("Main Menu"); ArrayList<Building> bArr = new ArrayList<Building>(); String temp = "Elixir Collector-24,8-960|Elixir Collector-31,8-960|Gold Mine-17,10-960|Elixir Collector-25,21-960|Elixir Collector-11,22-960"; String[] bs = temp.split("\\|"); for(String b : bs){ String[] bParts = b.split("-"); String[] cParts = bParts[1].split(","); int x = Integer.parseInt(cParts[0].trim()); int y = Integer.parseInt(cParts[1].trim()); Building tb = new Building(bParts[0], new Coordinate(x,y)); tb.setHp(Integer.parseInt(bParts[2].trim())); bArr.add(tb); } mapTM.setBuildings(bArr); switchCards("TM"); } */ return; } if (o == gsButton) { if (timer.isRunning()) { // timer.stop(); gsButton.setText("Game Start"); mmLabel.setText("Main Menu"); // sends the leave command client.sendUDP("leave~" + unameUDP); return; } // sends the joinlobby command client.sendUDP("joinlobby~" + unameUDP); // gsButton.setText("Game Stop"); String serverResp = client.receiveUDP(); if (serverResp.trim().equals("false")) { // place false handler here } else { String[] enemies = serverResp.trim().split(","); ArrayList<Building> bArr = new ArrayList<Building>(); String mapConfig = getBaseConfig(enemies[0]); String[] bs = mapConfig.split("\\|"); for (String b : bs) { String[] bParts = b.split("-"); String[] cParts = bParts[1].split(","); int x = Integer.parseInt(cParts[0].trim()); int y = Integer.parseInt(cParts[1].trim()); Building tb = new Building(bParts[0], new Coordinate(x, y)); tb.setHp(Integer.parseInt(bParts[2].trim())); bArr.add(tb); } mapTM.setBuildings(bArr); switchCards("TM"); } // System.out.println(serverResp); // cdTime = 10; // timer.start(); return; } if (o == logout) { client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, "")); chatArea.setText(""); switchCards("Login"); return; } if (o == cmButton) { String baseConfig = getBaseConfig(); System.out.println("base config: " + baseConfig); for (int i = 0; i < mapSize; i++) { for (int j = 0; j < mapSize; j++) { tiles[i][j].setValue(""); } } if (!baseConfig.equals("")) { String[] bs = baseConfig.split("\\|"); for (String b : bs) { String[] bParts = b.split("-"); String[] cParts = bParts[1].split(","); int x = Integer.parseInt(cParts[0].trim()); int y = Integer.parseInt(cParts[1].trim()); int index = 0; for (int i = 0; i < bb.size(); i++) { if (bb.get(i).getText().split("-")[0].trim().equals(bParts[0])) { index = i; break; } } insertBuilding(y, x, index); } } switchCards("CM"); return; } if (o == tmButton) { ArrayList<Building> bArr = new ArrayList<Building>(); for (int i = 0; i < 40; i++) { for (int j = 0; j < 40; j++) { if (tiles[i][j].getValue().equals("") || tiles[i][j].getValue().contains("-")) { continue; } // weird part here bArr.add(new Building(tiles[i][j].getValue(), new Coordinate(j, i))); } } mapTM.setBuildings(bArr); switchCards("TM"); return; } // if it the who is in button if (o == whoIsIn) { client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, "")); return; } if (o == cmBack) { ArrayList<Building> bArr = new ArrayList<Building>(); for (int i = 0; i < 40; i++) { for (int j = 0; j < 40; j++) { if (tiles[i][j].getValue().equals("") || tiles[i][j].getValue().contains("-")) { continue; } // weird part here bArr.add(new Building(tiles[i][j].getValue(), new Coordinate(j, i))); } } String temp = "mapdata~" + unameUDP + "~"; int tileCount = 40; int dim = 600; int tileDim = (int) (dim / tileCount); int counter = 0; for (Building b : bArr) { int x, y, hp; x = b.getPos().getX() / tileDim; y = b.getPos().getY() / tileDim; hp = b.getHp(); temp += b.getName() + "-" + x + "," + y + "-" + hp + "|"; counter += 1; } if (counter > 0) { temp = temp.substring(0, temp.length() - 1); // removes the last '|' } else { temp += "none"; } client.sendUDP(temp); // allows saving of the current state of the map into the user's account switchCards("Menu"); return; } if (o == tmBack) { switchCards("Menu"); return; } for (int i = 0; i < 40; i++) { for (int j = 0; j < 40; j++) { if (o == tiles[i][j]) { for (int k = 0; k < bb.size(); k++) { if (bb.get(k).isSelected()) { if (bb.get(k).getText().equals("Remove Building")) { removeBuilding(i, j); return; } insertBuilding(i, j, k); // JOptionPane.showMessageDialog(null, bb.get(k).getText()); return; } } // JOptionPane.showMessageDialog(null, "i-"+i+" j-"+j); return; } } } // ok it is coming from the JTextField if (connected) { // just have to send the message client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, chatField.getText())); chatField.setText(""); return; } if (o == login) { // ok it is a connection request String username = usernameField.getText().trim(); String password = passwordField.getText().trim(); // empty username ignore it if (username.length() == 0) return; // empty serverAddress ignore it String server = tfServer.getText().trim(); if (server.length() == 0) return; // empty or invalid port numer, ignore it String portNumber = tfPort.getText().trim(); if (portNumber.length() == 0) return; int port = 0; try { port = Integer.parseInt(portNumber); } catch (Exception en) { return; // nothing I can do if port number is not valid } // try creating a new Client with GUI client = new Client(server, port, username, password, this); // test if we can start the Client if (!client.start()) return; unameUDP = username; switchCards("Menu"); // fetching of the base_config string from the database chatField.setText(""); chatArea.setText(""); } }
public void run() { setAllColors(Color.GREEN); setTurnRadarRight(Double.POSITIVE_INFINITY); double robotX, robotY; double robotHeading, angleToGoal, angleToObs; double adjustment; double obsAngle, obsAdjustment; double angleDiff; double speedToGoal, speedFromObs; Enemy temp; obstacles = new HashMap<String, Enemy>(10); while (true) { if (foundGoal) { robotX = getX(); robotY = getY(); goalX = obstacles.get(GOAL_NAME).x; goalY = obstacles.get(GOAL_NAME).y; // Adjust robocode's returned heading so that 0 aligns with the positive x-axis instead of // the positive y-axis. // Also make it so that positive angle indicates a counter clockwise rotation instead of the // clockwise style // returned by robocode. robotHeading = 360 - (getHeading() - 90); angleToGoal = Math.toDegrees(Math.atan2(goalY - robotY, goalX - robotX)); if (angleToGoal < 0) { angleToGoal += 360; } adjustment = angleToGoal - robotHeading; adjustment = normalizeAngle(adjustment); speedToGoal = calcRobotSpeedLinear(robotX, robotY, goalX, goalY); // Calculate how the robot's heading and speed should be affected by objects that it has // located // as it explores the world. Iterator it = obstacles.entrySet().iterator(); while (it.hasNext()) { System.out.println("Iterating through objects."); Map.Entry pairs = (Map.Entry) it.next(); // If the current item in the Iterator isn't the goal. if (!pairs.getKey().equals(GOAL_NAME)) { temp = (Enemy) pairs.getValue(); speedFromObs = calcObjRepulseSpeed(robotX, robotY, temp.x, temp.y); // If the robot is in range of the object to be affected by it's repulsion. if (speedFromObs != 0) { obsAngle = Math.toDegrees(Math.atan2(robotY - temp.y, robotX - temp.x)); if (obsAngle < 0) obsAngle += 360; angleDiff = obsAngle - angleToGoal; angleDiff = normalizeAngle(angleDiff); adjustment += (angleDiff * (speedFromObs / speedToGoal)); speedToGoal -= speedFromObs; } } // Was getting a null pointer exception when using this. The internet lied about its // usefulness. // it.remove(); // avoids a ConcurrentModificationException } adjustment = normalizeAngle(adjustment); setTurnLeft(adjustment); // ahead(speedToGoal); setAhead(speedToGoal); } execute(); } }
public static String[] lookUp(String key) { Map<String, String[]> intervals = fillMap(); return intervals.get(key); }