From ffcda75a9b417cdc8b6c1c3f7046edb62b9c30a5 Mon Sep 17 00:00:00 2001 From: cirakg Date: Wed, 4 Jan 2023 17:49:53 +0100 Subject: Omocueno ukolko igrac izadje iz aplikacije u toku igre da se igra prekine i drugi korisnik se obavesti o tome. --- src/main/java/pokemon/Server.java | 42 +++++++++++++++++++++++++++++++++++++++ src/main/java/ui/MainFrame.java | 5 +++++ 2 files changed, 47 insertions(+) (limited to 'src/main/java') diff --git a/src/main/java/pokemon/Server.java b/src/main/java/pokemon/Server.java index 77b7fad..09ced57 100644 --- a/src/main/java/pokemon/Server.java +++ b/src/main/java/pokemon/Server.java @@ -88,6 +88,46 @@ public class Server implements Runnable { e.printStackTrace(); } + } + private void leftGame(SocketChannel sc)throws Exception { + long id=players.get(sc); + Game game=null; + for(Game tempGame :games) { + if(tempGame.player1Id==id || tempGame.player2Id==id) { + game=tempGame; + break; + } + } + if(game==null) + return; + long notifyId=-1; + if(game.player1Id==id) + notifyId=game.player2Id; + else if(game.player2Id==id) + notifyId=game.player1Id; + + if(notifyId==-1) + return; + + SocketChannel notifySocket=null; + for(Entry player : players.entrySet()) { + if(player.getValue()==notifyId) { + notifySocket=player.getKey(); + break; + } + } + if(notifySocket==null) + return; + + inGame.remove(sc); + inGame.remove(notifySocket); + games.remove(game); + ByteBuffer buff = ByteBuffer.wrap("OPPONENTLEFT".getBytes()); + notifySocket.write(buff); + + + + } private void readMessage(SelectionKey key)throws Exception { SocketChannel sc = (SocketChannel) key.channel(); @@ -105,6 +145,7 @@ public class Server implements Runnable { } catch (Exception e) { Long closedId=players.get(sc); + leftGame(sc); players.remove(sc); System.out.println("Client dissconnected: "+closedId ); System.out.println("Remaining clients: "+players.size() ); @@ -115,6 +156,7 @@ public class Server implements Runnable { if(read==-1) { Long closedId=players.get(sc); + leftGame(sc); players.remove(sc); System.out.println("Client dissconnected: "+closedId ); System.out.println("Remaining clients: "+players.size() ); diff --git a/src/main/java/ui/MainFrame.java b/src/main/java/ui/MainFrame.java index ef5f304..dc4b7f5 100644 --- a/src/main/java/ui/MainFrame.java +++ b/src/main/java/ui/MainFrame.java @@ -135,6 +135,11 @@ public class MainFrame extends JFrame implements Runnable { String msg=response[1]+":"+response[2]+"\n"; this.gamePanel.chat+=msg; this.gamePanel.refreshChat(); + }else if(response[0].trim().equals("OPPONENTLEFT")){ + System.out.println("OPPONENTLEFT"); + this.getContentPane().removeAll(); + this.getContentPane().add(this.chooseOpponentPanel,BorderLayout.CENTER); + SwingUtilities.updateComponentTreeUI(this); }else { //XML OBJECTS XMLDecoder decoder = null; -- cgit v1.2.3