diff --git a/android/build.gradle b/android/build.gradle index 245491c..e9a1990 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -19,7 +19,7 @@ android { } defaultConfig { applicationId "com.aqwsxlostfly.packandgo" - minSdkVersion 19 + minSdkVersion 24 targetSdkVersion 34 versionCode 1 versionName "1.0" diff --git a/android/src/com/aqwsxlostfly/packandgo/client/AndroidLauncher.java b/android/src/com/aqwsxlostfly/packandgo/client/AndroidLauncher.java index 7413d9b..ce8867f 100644 --- a/android/src/com/aqwsxlostfly/packandgo/client/AndroidLauncher.java +++ b/android/src/com/aqwsxlostfly/packandgo/client/AndroidLauncher.java @@ -104,7 +104,7 @@ public void onClose(int code, String reason) { @Override public void onError(Exception ex) { - Gdx.app.error("CONNECTION ERROR", "ERROR_MESSAGE: " + ex.getMessage()); +// Gdx.app.error("CONNECTION ERROR", "ERROR_MESSAGE: " + ex.getMessage()); WsEvent wsEvent = new WsEvent(); wsEvent.setData("ERROR_OCCURRED"); callback.onEvent(wsEvent); diff --git a/android/src/com/aqwsxlostfly/packandgo/client/MessageProcessor.java b/android/src/com/aqwsxlostfly/packandgo/client/MessageProcessor.java index 6e67a80..324a082 100644 --- a/android/src/com/aqwsxlostfly/packandgo/client/MessageProcessor.java +++ b/android/src/com/aqwsxlostfly/packandgo/client/MessageProcessor.java @@ -6,10 +6,16 @@ import com.badlogic.gdx.utils.JsonReader; import com.badlogic.gdx.utils.JsonValue; - public class MessageProcessor { private final Main main; + public static final String PLAYER_INTERACTION = "playerInteraction"; + public static final String PLAYER_STATE = "player"; + public static final String FURNITURE_STATE = "furniture"; + private static final String SESSION_KEY = "sessionKey"; + private static final String SESSION_ROOM = "sessionRoom"; + private static final String EVICT_MESSAGE = "evict"; + public MessageProcessor(Main main) { this.main = main; } @@ -23,9 +29,17 @@ public void processEvent(WsEvent event) { JsonValue parsed = jsonReader.parse(data); if (parsed.isArray()) { - processArray(parsed); + try { + processArray(parsed); + } catch (Exception e) { + // TODO + } } else if (parsed.isObject()) { - processObject(parsed); + try { + processObject(parsed); + } catch (Exception e) { + // TODO + } } } } @@ -41,33 +55,86 @@ private void processArray(JsonValue array) { private void processObject(JsonValue object) { String type = object.getString("class", null); + String interActionType = object.getString("type", null); + if (interActionType != null) { + if (interActionType.equals(PLAYER_INTERACTION)) { + Gdx.app.log("INTERACTION PLAYER", String.valueOf(object)); + String idInter = object.getString("id"); + float xInter = object.getFloat("x"); + float yInter = object.getFloat("y"); + float impulse = object.getFloat("impulse"); + try { + main.renderer.getCurrentScreen().updatePlayerInteraction(idInter, xInter, yInter, impulse); + } catch (Exception e) { + // TODO + } + } else { + throw new RuntimeException("Unknown message type " + type); + } + } if (type != null) { switch (type) { - case "sessionKey": + case SESSION_KEY: String meId = object.getString("id"); - main.setMeId(meId); + try { + main.setMeId(meId); + } catch (Exception e) { + // TODO + } break; - case "sessionRoom": + case SESSION_ROOM: String sessionId = object.getString("id"); String sessionPassword = object.getString("password"); String sessionMsg = object.getString("msg"); Gdx.app.log("SESSION STATE", "MSG " + sessionMsg); - main.gameSession.setConnected(true); - main.gameSession.setId(sessionId); - main.gameSession.setPassword(sessionPassword); - main.gameSession.setSessionMsg(sessionMsg); + try { + main.gameSession.setConnected(true); + main.gameSession.setId(sessionId); + main.gameSession.setPassword(sessionPassword); + main.gameSession.setSessionMsg(sessionMsg); + } catch (Exception e) { + // TODO + } break; - case "evict": + case EVICT_MESSAGE: String idToEvict = object.getString("id"); - main.evict(idToEvict); + try { + main.evict(idToEvict); + } catch (Exception e) { + // TODO + } break; - case "player": + case PLAYER_STATE: String id = object.getString("id"); float x = object.getFloat("x"); float y = object.getFloat("y"); + boolean isHolding = object.getBoolean("isHolding"); +// Gdx.app.log("UPD PLAYER FROM SERV", "ID " + id + " isHOLDING " + isHolding); + try { + Gdx.app.postRunnable( + new Runnable() { + @Override + public void run() { + main.renderer.getCurrentScreen().updatePlayerArray(id, x, y, isHolding); + } + }); + } catch (Exception e) { + // TODO + } + break; + case FURNITURE_STATE: + String furnId = object.getString("id"); + float furnX = object.getFloat("x"); + float furnY = object.getFloat("y"); + int holdersCount = object.getInt("holdersCount"); + boolean isTaken = object.getBoolean("isHolding"); - main.renderer.getCurrentScreen().updatePlayerArray(id, x, y); + try { + main.renderer.getCurrentScreen().updateFurnitureArray(furnId, furnX, furnY, holdersCount, isTaken); + } catch (Exception e) { + // TODO + } break; default: throw new RuntimeException("Unknown message type " + type); diff --git a/android/src/com/aqwsxlostfly/packandgo/client/dto/InputStateImpl.java b/android/src/com/aqwsxlostfly/packandgo/client/dto/InputStateImpl.java index dd23864..eb43f8f 100644 --- a/android/src/com/aqwsxlostfly/packandgo/client/dto/InputStateImpl.java +++ b/android/src/com/aqwsxlostfly/packandgo/client/dto/InputStateImpl.java @@ -1,7 +1,7 @@ package com.aqwsxlostfly.packandgo.client.dto; -import com.aqwsxlostfly.packandgo.session.InputState; +import com.aqwsxlostfly.packandgo.objectsdto.InputState; public class InputStateImpl implements InputState { @@ -11,6 +11,9 @@ public class InputStateImpl implements InputState { private float x; private float y; + private boolean holding; + private int holders; + public InputStateImpl() { } @@ -57,4 +60,24 @@ public float getY() { return this.y; } + @Override + public void setHolding(boolean isHolding) { + this.holding = isHolding; + } + + @Override + public boolean isHolding() { + return this.holding; + } + + @Override + public void setHolders(int holdersCount) { + this.holders = holdersCount; + } + + @Override + public int getHolders() { + return this.holders; + } + } diff --git a/assets/Clown.mp3 b/assets/Clown.mp3 new file mode 100644 index 0000000..49f5e5f Binary files /dev/null and b/assets/Clown.mp3 differ diff --git a/assets/HelloDarkness.mp3 b/assets/HelloDarkness.mp3 new file mode 100644 index 0000000..b951dc7 Binary files /dev/null and b/assets/HelloDarkness.mp3 differ diff --git a/assets/HelloTop.mp3 b/assets/HelloTop.mp3 new file mode 100644 index 0000000..c6f9e8d Binary files /dev/null and b/assets/HelloTop.mp3 differ diff --git a/assets/Map.tmx b/assets/Map.tmx index 3fcb189..4025878 100644 --- a/assets/Map.tmx +++ b/assets/Map.tmx @@ -1,5 +1,5 @@ - + @@ -23,9 +23,34 @@ + + + + + + + + + + + + + + + - eJztmVlsVFUYxz+S0lJpCy6Jxg4z05Z2KLglaiguD+IuSNIWWXyagi8u4BYB8cm6RMFXoLhO4gJlirGFoPiksmgMLl1mphSNCyq4vKiJ+4O/6703cz1zOnPPnUtsEx9++b77nTPn+8+535x7v3Zoqrw1CMMwNIl811ocqZbk1diFcBVMBh/N4nyPFLHUH5UiYZCbKkk19if8pfgjTk7dmB+f75IctEnhpzZViehoj4t0QCcsjevneMmyphrbDE8pfsbJqRvz47PnSfY+yT1IcT9S504TsWiIiTRCU8y+7kfzAOyBvXE75jI/KtIGCyAJXbClRpJnJ0TOSeTn1UNE8bNOTt2YH3+hrT3p1s8uYhYXoPtCuChmXxfjGvReC9fBGljr6F+P9g2J/Lw09Cl+zsmpG/Pjq/XTPUXkEbgc3VfAlTH72o3rbDt6O6ATNsJD0EI8h/bRhD3nUQX3syOenC+S66VYfu0e/O3wNDwDz8Jz8Dy8AKlYYf0U02liW3zOzXhyvoaefo/+l/FfgR2wE3qtWoA09MHuWGH9nCr9WxtFtkEPbG/Mx7MBc+5H+5ux8etHtU9QE0/CJtgcNdf/C5p/hd/gd4/+XJl75rd+tqB5K2yDHh/6rfPfG1vWJLIcVsDKJn39B7F+6+db9uw7+B5+aCy9dlbRvw/Nr8MbsN+jP1Omfr/1cyM5b4JFsLip9NoZRf94drzfeYXzO45h484ZWKE5C/3WTy+ad0Ea+nzoHylTv2vPQ/P5Rc5wv/VTPVvkNJgONbPN6z/o/i/AXlZk//3Wj6lV6z/o/od1/phav/Uf9Pw3rR9T67f+yz3/T1X9+K3/cs9/tX5Yz7r31n21NEgY191T8ji1Fdr6av2U6nc+dfoqkx5J3bNi663hfXVtQr/e3cTvSRTvv3Q9zvX0KzfEbf8Tp68y6ZFU/d4xdz03xwfo+zBhjy3iejHcDEvgI+IfJ+zPu/PV+tH1ODuYtzNu+8eYq/ZCvXN4tkEa+uYUft46I714x9z13BzesTTXfbAbXo3/O6c7X62fLO9mORiN5nucIfzhqO2PMVfthapbebbBdKhpLeyR1P33junWOzRX5PDcwp5LF1fr5zg6v4Kvo/l8n+F/7lwfZa6q53Y03wF3wl2tZmeIbr3medyneYXzdXHT59eoJl85tkUTfwyNj2v06+Jq/Yyxz8ec93tdz6TLF6b+rgaRVbAabmsoHVfr5wTaTzr6dT1T2Pqzyv18G23vwAE42FA6Xqx+dD1TJuT6KXe9Yu8/up5pJGT95a7n1g/fQY5U//N3UStmfS8J03dRnwXesSDrozllabcYdhj0XIflu6j6h0PKO79CpK3CzJrQNs46D/A8WgcP8l6wEfp5fgzAHtjbmo+X0vMuvGdog+hX18mgPQtH0TgGp+OfAWfCWZ54KT1B9n8i2SD7P5Hsf71/fm17s0hH8+Td/360DzRP3v3/v/4npu2qDM4qWK34h+tFLq4VuQQurTX33683y/9jGfwEPyu+pf8AOg7CoVpz39Jvkv/hquB0W39jsP5HHOFsg86Irb+zTmQp3FJn7lv6TfJ/w2dOwMm64P4X6P4SjkfCqR+T3OtmiKyHDTOC+/fOErkP7p8VTv2Y5K6cKVIF02aG44dRPyb5wqgfr7+MGloOK2BlAP/WiFm+vwFEpZ5j + eJztmEmMFFUYxz/iMMPIzIBLgnGa7llwmhE8oRG3g3hwvcAoi6cGvLhclAiIJ8clOngFBtdOQJnNBNSAeFJBIYbLLN0Ng8YFFVwuauIyevBXVlW68vp1db16NQjEwy/fV++9ft+/Xv37Vb8emykfjMI4jJ1HuR8djjVK7jbiMrgVzocczeLdR562/FS9yF/wN9jkpZmSm/LapkLGTVjW5F5yoy558nxfg8hWeBFs8iJz9nltfSHjCpY1WfMca5/jGeR5HvkrZ4m0Qgps8m1NkpuXFbki67ZXG1e0rLnM1Z7z/TNE2zCMgE3u6N+E9s1Zt73auJJlTdU/vTNEnoabMiI3wy0Z99pv18XlaZEV0ANb4Enoor2E9uNZd8wzCv5nJwI1d1Frd6Y8dz/5TngJXoZX4FV4DV6HfKbSP2E6TWJXxLGFQM296NkX0P8G+ZuwBwZgEIZgGEbgrUylf6ZL//YOkR3QDzs7yu3FmDUPov39THX/qPF5PPEC9MHWtLn+39D8O/wBfwb0lyzXLKp/tqF5O+yA/gj6nf0/2LayU2QVrIY1nXr/x4lR/fM9a/YD/Ag/ddSeu6jo34/mA/AeHAzoL1jqj+qfO6l5F9wN93TWnrug6K8Wq33P67zvcYbY5u2BdZq9MKp/BtE8BMMwEkH/hKV+Py5G8zUhe3hU/zQuELkYZkPTAnP/x13/G4g3hqx/VP+YRtX/cdc/qf3HNEb1f9z939Q/pjGq/233/+nyT1T/2+7/qn+Yz3n2znN1NEgS170zynjeSmx+1T+1zjufe+cqkzOSumZx59P1qf7RnXFubxO5o83NP/POVSZnJFV/sM9kPl2f6h/dGWcP2gfa3PwkY9Wz0OBC3m0wDCMLKz/v7JFBgn26+arluj7VP0V+m5XgeLp8xhkjH0+7+SRj1bNQYzfvNpgNTd2VZyR1/YN9uvmq5bo+1T+n0PkNfJsu1/uC/Evv+gRjVT0PovkheBge6TbbQ3TzXbWI57Socryu3fT91ZXQ/ho237NofE6jX9eu+meSdT7p/b7XnZmmW//adpF1sB4eaK/drvrnNNrPePp1Z6ak9RcV/3yIto/gEBxur90e5h/dmamg8atNtJ0v7PeP7sw0kbB+2/l8/3APcqzx3/9FnTbnviTJ3Ed9FwT74syP5ryj3WHcYzRwnVTuo+ofT6ju9XUiS+vMoglLq8zz+NUiG+GJrMgW2Mf74214B97tLrfX0nMEjhrGOPrVeQpoL8IJNE7CJeSXwmVweaB94KJw4qz/2Yq1tDvEWf+zFaPoPxfWOSz+v/7/vf/Dnod/n+fCel+o66/qDV6vrY/POliv5J+0iixpFrkWrms2zz9tNav/swW/wK9K7ug/hI7D8HGzee7oN6n/VEN8ep3/GGB5SmQF9KRc/T0tIvfCfS3muaPfpP53fOY0nGmJn3+F7q/hVCoZ/5jU3jhHZBNsnhM/f3S+yGOwYX4y/jGpXT9XpAFmzU0mT8I/JvWS8E8wX4mHVsFqWBMjvz9lVu8fyyufkg== + + + + + eJztzkERAAAEADCVFNA/llPAl8eWYBEAAAAAAAAAjMrrwe77D4AbDbkJAN8= + + + + + eJztl9lOwkAUhg8CwoXLvSshodf4BCbiEmXxFYzrg+iV+iJCi4kLvAcuPIV6r174T6BhUltmJi0w1fmSLzkz7Zz+GBYPkUEHPqeJvuB3X34dVPvteXsxqnmiWl4ux12S6B4+wEfYgu2k+NxlhugKlnNEFViFNXidCb7G9vjrrOZ7uWsH2ZuS+TdSRCW4CbfgNtxJic8tZIkWYQO5bOjAJlzKBl9je/x1VvO92LpSwOuFNbhfEOfoIOsTfIYv8BV2JfLXWT5o9+XXQbXf3q9eyOzAJryVyH+YJjqCx/AEnsKztPicy3lioMq9/Bm+nrGIZuEcnLf8+1wkeg7r6/ccXYh7fhVU88f9dZv80WUIc3Zc+aP+zE46v7sXZb9R8te+Lw0GgxjVuUqmVnlm2N78zCQzV8nUIti9u/ifeg+WYcUa9HjDd+Y7/EjI9eZnJpm5SqYWwe69QeY6bEDb6p1rFYmWp4hW4CpsF8W9VecqmVqEar9hvd0Zgp8jvGsvUf9OBvWIy29wmLlL9LceNaJZWrf8ludZYfPrQlyydtN0MOkMhvhSysmpK3HPHxXra/61DuicTQY+8394LxkMBoPBYBgPP0Jm8oo= @@ -41,15 +66,182 @@ - - - eJztl0lOw0AQRStKAiwY9sACRUoOQhg2EO7AeBBYAScBEiTGezDeBVjwLWzRarpdXbJD3FY96UnVrXT5x3JiFZFSBT6miD7hV6q59tWuPbtXwnaHaNAJy3HTJLqFd/AePsDHJn/udJroDJ6nmmtf7dqzeyUMkX0UmH+1RdSHa3AdbsDNFn9ucYZoCS6nmmtf7dqze211cf/hAO50+RxPyPoMX+ArfIPvAfkvcK1LeJVqrn21a+9PL2QewhG8Dsi/2ybag/vwAB7CozZ/LuO48avks+YZs57tEc3BebjQc/c5afyY19d1naoQe34J0vyxf2/NX16GImf/K3/Zv9lJ58/2yuw3Tur2f6koCo90rgqpJdcs2ls6V4XUHNJ+eb2lc1VIzSHtl9dbOleF1BzSfnm9sxnCnCPstU3Z70lfj1jewUXmLu5ejxtulq57/qoQS9b+yqQTKDGTPD8hVpXY8ytxEfvzFHt+RVEURakT3zUj56E= - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -60,16 +252,16 @@ - - - - - + + + + + - - - + + + @@ -78,6 +270,7 @@ + + - diff --git a/assets/Pedro.mp3 b/assets/Pedro.mp3 new file mode 100644 index 0000000..dd1d05e Binary files /dev/null and b/assets/Pedro.mp3 differ diff --git a/assets/RedBed.png b/assets/RedBed.png new file mode 100644 index 0000000..7fa34db Binary files /dev/null and b/assets/RedBed.png differ diff --git a/assets/RedBed.tsx b/assets/RedBed.tsx new file mode 100644 index 0000000..788df22 --- /dev/null +++ b/assets/RedBed.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/TopDownHouseFurnitureState2big.tsx b/assets/TopDownHouseFurnitureState2big.tsx new file mode 100644 index 0000000..447c886 --- /dev/null +++ b/assets/TopDownHouseFurnitureState2big.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/atlas16x.tsx b/assets/atlas16x.tsx new file mode 100644 index 0000000..e99f7ab --- /dev/null +++ b/assets/atlas16x.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/atlas16x16x32.tsx b/assets/atlas16x16x32.tsx new file mode 100644 index 0000000..567890c --- /dev/null +++ b/assets/atlas16x16x32.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/atlas16xsmall.tsx b/assets/atlas16xsmall.tsx new file mode 100644 index 0000000..cd7ff5a --- /dev/null +++ b/assets/atlas16xsmall.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/atlas32xbig.tsx b/assets/atlas32xbig.tsx new file mode 100644 index 0000000..63172b3 --- /dev/null +++ b/assets/atlas32xbig.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/atlas48xwork.tsx b/assets/atlas48xwork.tsx new file mode 100644 index 0000000..8c78ffe --- /dev/null +++ b/assets/atlas48xwork.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/bridge.png b/assets/bridge.png new file mode 100644 index 0000000..2aa7cf6 Binary files /dev/null and b/assets/bridge.png differ diff --git a/assets/bridge.tsx b/assets/bridge.tsx new file mode 100644 index 0000000..bfcf25b --- /dev/null +++ b/assets/bridge.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/env.properties b/assets/env.properties deleted file mode 100644 index 9413658..0000000 --- a/assets/env.properties +++ /dev/null @@ -1 +0,0 @@ -WS_URI=ws://192.168.2.176:8867/ws diff --git a/assets/heroHandsUp.png b/assets/heroHandsUp.png new file mode 100644 index 0000000..1bed5f9 Binary files /dev/null and b/assets/heroHandsUp.png differ diff --git a/assets/heroHandsUp_other.png b/assets/heroHandsUp_other.png new file mode 100644 index 0000000..1bed5f9 Binary files /dev/null and b/assets/heroHandsUp_other.png differ diff --git a/assets/longchair32x16.png b/assets/longchair32x16.png new file mode 100644 index 0000000..761fc16 Binary files /dev/null and b/assets/longchair32x16.png differ diff --git a/assets/longchair32x16.tsx b/assets/longchair32x16.tsx new file mode 100644 index 0000000..3cf9f22 --- /dev/null +++ b/assets/longchair32x16.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/menu.mp3 b/assets/menu.mp3 new file mode 100644 index 0000000..782ec91 Binary files /dev/null and b/assets/menu.mp3 differ diff --git a/assets/overbackground.png b/assets/overbackground.png new file mode 100644 index 0000000..6d78882 Binary files /dev/null and b/assets/overbackground.png differ diff --git a/assets/synk.png b/assets/synk.png new file mode 100644 index 0000000..83c2807 Binary files /dev/null and b/assets/synk.png differ diff --git a/assets/synk.tsx b/assets/synk.tsx new file mode 100644 index 0000000..f8deb47 --- /dev/null +++ b/assets/synk.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/tile_0456_other.png b/assets/tile_0456_other.png new file mode 100644 index 0000000..118dd3e Binary files /dev/null and b/assets/tile_0456_other.png differ diff --git a/assets/toilet.png b/assets/toilet.png new file mode 100644 index 0000000..fdc4e5a Binary files /dev/null and b/assets/toilet.png differ diff --git a/assets/toilet.tsx b/assets/toilet.tsx new file mode 100644 index 0000000..6bc17a7 --- /dev/null +++ b/assets/toilet.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/tree15x25.png b/assets/tree15x25.png new file mode 100644 index 0000000..6bb73b8 Binary files /dev/null and b/assets/tree15x25.png differ diff --git a/assets/tree15x25.tsx b/assets/tree15x25.tsx new file mode 100644 index 0000000..e84aa61 --- /dev/null +++ b/assets/tree15x25.tsx @@ -0,0 +1,4 @@ + + + + diff --git a/assets/winbackground.png b/assets/winbackground.png new file mode 100644 index 0000000..68ae587 Binary files /dev/null and b/assets/winbackground.png differ diff --git a/core/src/com/aqwsxlostfly/packandgo/Heroes/Furniture.java b/core/src/com/aqwsxlostfly/packandgo/Heroes/Furniture.java new file mode 100644 index 0000000..a4c9def --- /dev/null +++ b/core/src/com/aqwsxlostfly/packandgo/Heroes/Furniture.java @@ -0,0 +1,135 @@ +package com.aqwsxlostfly.packandgo.Heroes; +import static com.aqwsxlostfly.packandgo.Tools.maptools.TileMapHelper.worldHeight; +import static com.aqwsxlostfly.packandgo.Tools.maptools.TileMapHelper.worldWigth; +import com.aqwsxlostfly.packandgo.Tools.figures.Point2D; +import com.badlogic.gdx.graphics.g2d.SpriteBatch; +import com.badlogic.gdx.graphics.g2d.TextureRegion; +import com.badlogic.gdx.maps.objects.TextureMapObject; +import com.badlogic.gdx.math.Vector2; +import com.badlogic.gdx.physics.box2d.Body; + +public class Furniture extends Heroes{ + private float VELOCITY_SCALE_FURNITURE = 90.0f; + + private boolean isTaken; + + private int holdersCount; + + private int maxHolders; + + private float weight; + + public Furniture(Body body, TextureMapObject textureMapObject, int maxHolders, float weight) { + super(body, textureMapObject); + this.maxHolders = maxHolders; + this.weight = weight; + this.VELOCITY_SCALE_FURNITURE = this.VELOCITY_SCALE_FURNITURE - weight; + } + + public void setDirection(Point2D direction) { + this.direction = direction; + updateVelocity(); + } + + private void updateVelocity() { + // Задаем линейную скорость в соответствии с направлением. + // Если есть стена, Box2D автоматически обработает коллизию и остановит движение в этом направлении. + Vector2 newDir = new Vector2(direction.getX()*VELOCITY_SCALE_FURNITURE, direction.getY()*VELOCITY_SCALE_FURNITURE); + body.setLinearVelocity(newDir); + } + + public void testUpdate(float newX, float newY){ + body.setTransform(new Vector2(newX, newY), body.getLinearVelocity().x*10f + body.getLinearVelocity().y*10f); + } + + public void setAngle(float angle){ + body.setTransform(getX(), getY(), angle); + } + + public float getX(){ + return body.getPosition().x; + } + + public float getY(){ + return body.getPosition().y; + } + + public void setTransform(float x, float y, float angle){ + + body.setTransform(x, y, angle); + } + + public float getWidth(){ + return worldWigth; + } + + public float getHeight(){ + return worldHeight; + } + + @Override + public void draw(SpriteBatch batch) { + batch.draw(textureRegion, + body.getPosition().x-textureRegion.getRegionWidth()/ 2.0f, body.getPosition().y-textureRegion.getRegionHeight() / 2.0f, + textureRegion.getRegionWidth() / 2.0f, textureRegion.getRegionHeight() / 2.0f, + textureRegion.getRegionWidth(), textureRegion.getRegionHeight(), + textureMapObject.getScaleX(),textureMapObject.getScaleY(), 0); + } + + public void serverUpdate(float newX, float newY, int holdersCount, boolean isTaken){ +// body.setLinearVelocity(new Vector2(newX, newY)); + this.holdersCount = holdersCount; + this.isTaken = isTaken; + body.setTransform(new Vector2(newX, newY), 0); + } + + public boolean isTaken() { + return isTaken; + } + + public void setTaken(boolean taken) { + isTaken = taken; + } + + public int getHoldersCount() { + return holdersCount; + } + + public void setHoldersCount(int holdersCount) { + this.holdersCount = holdersCount; + } + + public int getMaxHolders() { + return maxHolders; + } + + public void setMaxHolders(int maxHolders) { + this.maxHolders = maxHolders; + } + + public void increaseHoldersCount() { + this.holdersCount++; + } + public void decreaseHoldersCount() { + if (holdersCount-1 >= 0) { + this.holdersCount--; + } + } + + public boolean availibleToTake() { + if (!isTaken) return true; + else return holdersCount < maxHolders; + } + + public float getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public void serverUpdateHolders(int holdersCount) { + this.holdersCount = holdersCount; + } +} \ No newline at end of file diff --git a/core/src/com/aqwsxlostfly/packandgo/Heroes/Heroes.java b/core/src/com/aqwsxlostfly/packandgo/Heroes/Heroes.java index e47c365..4d4927c 100644 --- a/core/src/com/aqwsxlostfly/packandgo/Heroes/Heroes.java +++ b/core/src/com/aqwsxlostfly/packandgo/Heroes/Heroes.java @@ -1,6 +1,8 @@ package com.aqwsxlostfly.packandgo.Heroes; import com.aqwsxlostfly.packandgo.Tools.figures.Point2D; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.maps.objects.TextureMapObject; @@ -12,11 +14,30 @@ public abstract class Heroes { public TextureMapObject textureMapObject; public TextureRegion textureRegion; + protected final Texture heroHandsUp; + protected final Texture hero; + protected final Texture heroHandsUp_other; + protected final Texture hero_other; + public Heroes(Body body, TextureMapObject textureMapObject) { this.body = body; this.direction = new Point2D(0, 0); this.textureMapObject = textureMapObject; this.textureRegion = textureMapObject.getTextureRegion(); + Gdx.app.log("Heroes", "Attempting to load textures"); + + try { + this.heroHandsUp = new Texture(Gdx.files.internal("heroHandsUp.png")); + this.heroHandsUp_other = new Texture(Gdx.files.internal("heroHandsUp_other.png")); + this.hero = new Texture(Gdx.files.internal("tile_0456.png")); + this.hero_other = new Texture(Gdx.files.internal("tile_0456_other.png")); + + Gdx.app.log("Heroes", "Textures loaded successfully"); + } catch (Exception e) { + Gdx.app.error("Heroes", "Error loading textures", e); + throw new RuntimeException("Could not load textures", e); + } + } public abstract void draw(SpriteBatch batch); diff --git a/core/src/com/aqwsxlostfly/packandgo/Heroes/Player.java b/core/src/com/aqwsxlostfly/packandgo/Heroes/Player.java index 14aad76..8483994 100644 --- a/core/src/com/aqwsxlostfly/packandgo/Heroes/Player.java +++ b/core/src/com/aqwsxlostfly/packandgo/Heroes/Player.java @@ -4,6 +4,8 @@ import static com.aqwsxlostfly.packandgo.Tools.maptools.TileMapHelper.worldWigth; import com.aqwsxlostfly.packandgo.Tools.figures.Point2D; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.maps.objects.TextureMapObject; import com.badlogic.gdx.math.Vector2; @@ -11,10 +13,23 @@ public class Player extends Heroes { - private static final float VELOCITY_SCALE = 80.0f; + private float VELOCITY_SCALE = 90.0f; + + public float CURRENT_VELOCITY_SCALE = 80.0f; + + public boolean isImpulsed; + + public Vector2 kickImpulse = new Vector2(0, 0); + private String contactFurnitureKey; + private boolean isHolding; + + private boolean statusContact; + + private boolean teamLead; public Player(Body body, TextureMapObject textureMapObject) { super(body, textureMapObject); + } public void setDirection(Point2D direction) { @@ -23,48 +38,115 @@ public void setDirection(Point2D direction) { } private void updateVelocity() { - Vector2 newDir = new Vector2(direction.getX()*VELOCITY_SCALE, direction.getY()*VELOCITY_SCALE); + Vector2 newDir = new Vector2(direction.getX() * CURRENT_VELOCITY_SCALE, direction.getY() * CURRENT_VELOCITY_SCALE); body.setLinearVelocity(newDir); } - public void serverUpdate(float newX, float newY){ + public void serverUpdate(float newX, float newY, boolean isHolding) { // body.setLinearVelocity(new Vector2(newX, newY)); + this.isHolding = isHolding; body.setTransform(new Vector2(newX, newY), 0); } - public void setAngle(float angle){ + public void applyImpulse(Vector2 impulse) { + this.kickImpulse = impulse; + + this.isImpulsed = true; + Gdx.app.log("IMPULSE APLY", " ME JBCJKBJBHJ KIIICKED"); + + body.applyLinearImpulse(kickImpulse, body.getWorldCenter(), true); + } + + public void decreaseSpeed(float minSpeed){ + if(this.VELOCITY_SCALE - minSpeed > 10){ + this.CURRENT_VELOCITY_SCALE = this.VELOCITY_SCALE - minSpeed; + } + + } + + + public void setAngle(float angle) { body.setTransform(getX(), getY(), angle); } - public float getX(){ + public float getX() { return body.getPosition().x; } - public float getY(){ + public float getY() { return body.getPosition().y; } - public void setTransform(float x, float y, float angle){ + public void setTransform(float x, float y, float angle) { body.setTransform(x, y, angle); } - public float getWidth(){ + public float getWidth() { return worldWigth; } - public float getHeight(){ + public float getHeight() { return worldHeight; } @Override public void draw(SpriteBatch batch) { + + if(isHolding) { + drawWithTexture(batch, heroHandsUp); + }else{ + drawWithTexture(batch, hero); + } + + } + private void drawWithTexture(SpriteBatch batch, Texture texture){ + textureRegion.setTexture(texture); + textureRegion.setRegion(texture); batch.draw(textureRegion, - body.getPosition().x-textureRegion.getRegionWidth()/ 2.0f, body.getPosition().y-textureRegion.getRegionHeight() / 2.0f, + body.getPosition().x - textureRegion.getRegionWidth() / 2.0f, body.getPosition().y - textureRegion.getRegionHeight() / 2.0f, textureRegion.getRegionWidth() / 2.0f, textureRegion.getRegionHeight() / 2.0f, textureRegion.getRegionWidth(), textureRegion.getRegionHeight(), - textureMapObject.getScaleX(),textureMapObject.getScaleY(), 0); + textureMapObject.getScaleX(), textureMapObject.getScaleY(), 0); + batch.flush(); + } + + public void resetImpulse() { + this.isImpulsed = false; + } + + public String getContactFurnitureKey() { + return contactFurnitureKey; + } + + public void setContactFurnitureKey(String contactFurnitureKey) { + this.contactFurnitureKey = contactFurnitureKey; + } + + public boolean isHolding() { + return isHolding; + } + + public void setHolding(boolean holding) { + isHolding = holding; + } + + public boolean isStatusContact() { + return statusContact; + } + + public void setStatusContact(boolean statusContact) { + this.statusContact = statusContact; + } + + public boolean isTeamLead() { + return teamLead; + } + + public void setTeamLead(boolean teamLead) { + this.teamLead = teamLead; } } + diff --git a/core/src/com/aqwsxlostfly/packandgo/Main.java b/core/src/com/aqwsxlostfly/packandgo/Main.java index 0a94bd6..b32c7d0 100644 --- a/core/src/com/aqwsxlostfly/packandgo/Main.java +++ b/core/src/com/aqwsxlostfly/packandgo/Main.java @@ -5,7 +5,7 @@ import com.aqwsxlostfly.packandgo.Screens.PlayScreen; import com.aqwsxlostfly.packandgo.render.Renderer; import com.aqwsxlostfly.packandgo.session.GameSession; -import com.aqwsxlostfly.packandgo.session.InputState; +import com.aqwsxlostfly.packandgo.objectsdto.InputState; import com.aqwsxlostfly.packandgo.session.MessageSender; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; @@ -18,13 +18,17 @@ public class Main extends Game { public GameSession gameSession; public static String meId = "666"; + public static boolean isHost; public static InputState inputState; public static MessageSender messageSender; + public Main(InputState inputState) { Main.inputState = inputState; + + this.gameSession = new GameSession(false); } @@ -43,6 +47,7 @@ public void create() { renderer = new Renderer(); renderer.setHomeScreen(new HomeSc(this)); + //renderer.setGameScreen(new PlayScreen()); } @Override diff --git a/core/src/com/aqwsxlostfly/packandgo/Screens/GameOverScreen.java b/core/src/com/aqwsxlostfly/packandgo/Screens/GameOverScreen.java new file mode 100644 index 0000000..9989e3e --- /dev/null +++ b/core/src/com/aqwsxlostfly/packandgo/Screens/GameOverScreen.java @@ -0,0 +1,234 @@ +package com.aqwsxlostfly.packandgo.Screens; + +import static com.aqwsxlostfly.packandgo.Main.screenHeight; +import static com.aqwsxlostfly.packandgo.Main.screenWidth; +import static com.aqwsxlostfly.packandgo.render.Renderer.changeToPlayScreen; +import static com.aqwsxlostfly.packandgo.render.Renderer.gameScreen; +import static com.aqwsxlostfly.packandgo.render.Renderer.homeScreen; +import static com.aqwsxlostfly.packandgo.render.Renderer.setCurrentScreen; + +import com.aqwsxlostfly.packandgo.Tools.MusicTools; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.graphics.GL20; +import com.badlogic.gdx.graphics.OrthographicCamera; +import com.badlogic.gdx.graphics.Texture; +import com.badlogic.gdx.graphics.g2d.BitmapFont; +import com.badlogic.gdx.graphics.g2d.GlyphLayout; +import com.badlogic.gdx.graphics.g2d.Sprite; +import com.badlogic.gdx.graphics.g2d.SpriteBatch; +import com.badlogic.gdx.graphics.glutils.ShapeRenderer; +import com.badlogic.gdx.scenes.scene2d.InputEvent; +import com.badlogic.gdx.scenes.scene2d.Stage; +import com.badlogic.gdx.scenes.scene2d.ui.Skin; +import com.badlogic.gdx.scenes.scene2d.ui.TextButton; +import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; +import com.badlogic.gdx.utils.viewport.ScreenViewport; + +public class GameOverScreen implements Screen { + private BitmapFont gameOverFont; + private TextButton playAgainButton; + + private TextButton backHomeButton; + + private String score; + private float timeTaken; + private float maxTime; + + private String maxItems; + + private Stage stage; + private Skin skin; + + private Texture overBackgroundTexture; + private Texture winBackgroundTexture; + private Sprite backgroundSprite; + + private ShapeRenderer shapeRenderer; + + private MusicTools musicTools; + + private final String WINMUSIC ="Pedro.mp3"; + private final String GAMEOVERMUSIC = "HelloTop.mp3"; + + + public GameOverScreen(String playersScore, float timeLeft, float maxTime, String maxItems) { + + + + this.maxItems = maxItems; + this.maxTime = maxTime; + this.score = playersScore; + this.timeTaken = timeLeft; + gameOverFont = new BitmapFont(); + stage = new Stage(new ScreenViewport()); + skin = new Skin(Gdx.files.internal("skin/uiskin.json")); + + playAgainButton = new TextButton("Play Again", skin); + backHomeButton = new TextButton("Home", skin); + + if (timeLeft < maxTime) { + musicTools = new MusicTools(WINMUSIC); + musicTools.startMusic(); + }else{ + musicTools = new MusicTools(GAMEOVERMUSIC); + musicTools.startMusic(); + } + + // Установить размеры кнопки + float buttonWidth = 600f; // ширина кнопки + float buttonHeight = 150f; // высота кнопки + + playAgainButton.getLabel().setFontScale(3.0f); + playAgainButton.setWidth(buttonWidth); + playAgainButton.setHeight(buttonHeight); + + backHomeButton.getLabel().setFontScale(3.0f); + backHomeButton.setWidth(buttonWidth); + backHomeButton.setHeight(buttonHeight); + + // Установить позицию кнопки по центру экрана + float buttonX = (screenWidth - buttonWidth) / 2; // центрирование по горизонтали + float buttonY = (screenHeight - buttonHeight) / 2; // центрирование по вертикали + playAgainButton.setPosition(buttonX, buttonY); + backHomeButton.setPosition(buttonX, buttonY - buttonHeight - 30); + + // Добавить слушателя нажатий + playAgainButton.addListener(new ClickListener() { + @Override + public void clicked(InputEvent event, float x, float y) { + try { +// gameScreen.resetFurniture(); + gameScreen.restart(); + changeToPlayScreen(); + musicTools.stopMusic(); + dispose(); + } catch (Exception e) { + // TODO + } + } + }); + + backHomeButton.addListener(new ClickListener() { + @Override + public void clicked(InputEvent event, float x, float y) { + try { + homeScreen.restart(); + setCurrentScreen(homeScreen); + musicTools.stopMusic(); + dispose(); + } catch (Exception e) { + // TODO + } + } + }); + + stage.addActor(playAgainButton); + stage.addActor(backHomeButton); + Gdx.input.setInputProcessor(stage); + + // Загрузка фонов + overBackgroundTexture = new Texture(Gdx.files.internal("overbackground.png")); + winBackgroundTexture = new Texture(Gdx.files.internal("winbackground.png")); + + shapeRenderer = new ShapeRenderer(); + } + + @Override + public void render(SpriteBatch batch, OrthographicCamera camera) { + + Gdx.gl.glClearColor(0, 0, 0, 1); + + + batch.begin(); + + if (timeTaken < maxTime) { + + backgroundSprite = new Sprite(winBackgroundTexture); + backgroundSprite.setSize(screenWidth, screenHeight); + backgroundSprite.draw(batch); +// drawTextCentered(batch, "NICE JOB!", screenWidth / 2, screenHeight / 2, gameOverFont); +// drawTextCentered(batch, "You win!\nYou took " + score + "/" + maxItems + " in " + timeTaken + "s", screenWidth / 2, screenHeight / 2 - 90, gameOverFont); + + drawTextWithBackground(batch, "NICE JOB!", screenWidth / 2, screenHeight / 2, gameOverFont); + drawTextWithBackground(batch, "You win! You took " + score + "/" + maxItems + " in " + timeTaken + "s", screenWidth / 2, screenHeight / 2 - 90, gameOverFont); + } else { + backgroundSprite = new Sprite(overBackgroundTexture); + backgroundSprite.setSize(screenWidth, screenHeight); + backgroundSprite.draw(batch); +// drawTextCentered(batch, "Game Over", screenWidth / 2, screenHeight / 2, gameOverFont); +// drawTextCentered(batch, "Your time left!\nYou took " + score + "/" + maxItems + " in " + maxTime + "s", screenWidth / 2, screenHeight / 2 - 90, gameOverFont); + + drawTextWithBackground(batch, "Game Over", screenWidth / 2, screenHeight / 2, gameOverFont); + drawTextWithBackground(batch, "Your time left! You took " + score + "/" + maxItems + " in " + maxTime + "s", screenWidth / 2, screenHeight / 2 - 90, gameOverFont); + } + + batch.end(); + + stage.act(); + stage.draw(); + + } + + @Override + public void dispose() { + stage.dispose(); + skin.dispose(); + gameOverFont.dispose(); + overBackgroundTexture.dispose(); + winBackgroundTexture.dispose(); + } + + @Override + public void updatePlayerArray(String id, float x, float y, boolean isHolding) { + + } + + + @Override + public void updatePlayerInteraction(String id, float x, float y, float impulse) { + + } + + @Override + public void updateFurnitureArray(String id, float x, float y, int holdersCount, boolean isTaken) { + + } + + + private void drawTextCentered(SpriteBatch batch, String text, float x, float y, BitmapFont font) { + font.getData().setScale(6.5f); // Если вы хотите увеличить текст, как показано выше + GlyphLayout layout = new GlyphLayout(font, text); + float textWidth = layout.width; + float verticalOffset = (float) screenHeight / 3; // Смещение текста вверх на 100 пикселей + font.draw(batch, text, x - textWidth / 2.0f, y + verticalOffset); // Используем смещение для `y` + font.getData().setScale(1.0f); // Сброс размера шрифта обратно + } + + + private void drawTextWithBackground(SpriteBatch batch, String text, float x, float y, BitmapFont font) { + font.getData().setScale(6.5f); // Если вы хотите увеличить текст, как показано выше + GlyphLayout layout = new GlyphLayout(font, text); + float textWidth = layout.width; + float textHeight = layout.height; + float verticalOffset = (float) screenHeight / 3; // Смещение текста вверх на 100 пикселей + + // Закончить работу с SpriteBatch, чтобы начать работу с ShapeRenderer + batch.end(); + + // Отрисовка черного фона за текстом + Gdx.gl.glEnable(GL20.GL_BLEND); + shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); + shapeRenderer.setColor(0, 0, 0, 0.5f); // Устанавливаем цвет (0,0,0,0.5) - черный с прозрачностью 50% + shapeRenderer.rect(x - textWidth / 2 - 10, y + verticalOffset - textHeight - 10, textWidth + 20, textHeight + 20); // Рисуем прямоугольник + shapeRenderer.end(); + Gdx.gl.glDisable(GL20.GL_BLEND); + + // Начинаем работу с SpriteBatch снова + batch.begin(); + + font.draw(batch, text, x - textWidth / 2.0f, y + verticalOffset); // Используем смещение для `y` + font.getData().setScale(1.0f); // Сброс размера шрифта обратно + } + + +} \ No newline at end of file diff --git a/core/src/com/aqwsxlostfly/packandgo/Screens/HomeSc.java b/core/src/com/aqwsxlostfly/packandgo/Screens/HomeSc.java index 7f36ae9..2b8fe1c 100644 --- a/core/src/com/aqwsxlostfly/packandgo/Screens/HomeSc.java +++ b/core/src/com/aqwsxlostfly/packandgo/Screens/HomeSc.java @@ -16,15 +16,21 @@ import static com.aqwsxlostfly.packandgo.constants.ScreensConstants.SOME_ERROR; import static com.aqwsxlostfly.packandgo.constants.ScreensConstants.SOME_ERROR_TEXT; import static com.aqwsxlostfly.packandgo.render.Renderer.changeToPlayScreen; +import static com.aqwsxlostfly.packandgo.render.Renderer.gameScreen; +import static com.aqwsxlostfly.packandgo.render.Renderer.setCurrentScreen; import static com.aqwsxlostfly.packandgo.render.Renderer.setGameScreen; +import com.badlogic.gdx.scenes.scene2d.ui.ImageButton; +import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.aqwsxlostfly.packandgo.Heroes.Player; import com.aqwsxlostfly.packandgo.Main; +import com.aqwsxlostfly.packandgo.Tools.MusicTools; import com.aqwsxlostfly.packandgo.Tools.hud.FlyingObject; import com.aqwsxlostfly.packandgo.session.SessionState; import com.aqwsxlostfly.packandgo.session.SessionStateToSend; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; +import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; @@ -42,6 +48,7 @@ import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; +import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.Timer; import com.badlogic.gdx.utils.viewport.ScreenViewport; @@ -57,6 +64,7 @@ public class HomeSc implements Screen { Timer timer = new Timer(); Texture backgroundTexture; + ImageButton exitButton; Label gameNameLabel; TextButton createRoomBtn; TextButton joinRoomBtn; @@ -67,6 +75,20 @@ public class HomeSc implements Screen { Dialog lobbyDialog; Dialog errorDialog; + private static MusicTools musicTools; + + private static final String SESSION_STATE_OK = "connected_ok"; + private static final String SESSION_STATE_NO_EXISTS = "does_not_exists"; + private static final String SESSION_STATE_WRONG_PASSWORD = "incorrect_password"; + private static final String SESSION_STATE_EXISTS = "session_exists"; + private static final String SESSION_STATE_MAX_PLAYERS = "players_limit"; + + public static final String CREATE_ROOM = "createRoom"; + public static final String JOIN_ROOM = "joinRoom"; + private static final String HOMESCREENNMUSIC = "menu.mp3"; + + private static Music music; + private ArrayList flyingObjects; private Texture chairTexture, bathTexture, wardrobeTexture, tableTexture, lampTexture; @@ -97,6 +119,18 @@ public HomeSc(Main main) { tableTexture = new Texture(Gdx.files.internal("table.png")); lampTexture = new Texture(Gdx.files.internal("sofa.png")); + musicTools = new MusicTools(HOMESCREENNMUSIC); + musicTools.startMusic(); + + Drawable exitDrawable = skin.getDrawable("button_cross"); + exitButton = new ImageButton(exitDrawable); + exitButton.setPosition(10, Gdx.graphics.getHeight() - exitButton.getHeight() - 70); + stage.addActor(exitButton); + + addExitButtonListener(); + + + flyingObjects = new ArrayList(); for (int i = 0; i < 12; i++) { @@ -110,6 +144,19 @@ public HomeSc(Main main) { addListeners(); } + private void addExitButtonListener() { + exitButton.setSize(100, 100); + exitButton.getImage().getDrawable().setMinWidth(100); + exitButton.getImage().getDrawable().setMinHeight(100); + exitButton.getImage().setSize(100, 100); + exitButton.addListener(new ClickListener() { + @Override + public void clicked(InputEvent event, float x, float y) { + Gdx.app.exit(); + } + }); + } + private Texture getRandomTexture() { int rand = MathUtils.random(0, 4); switch (rand) { @@ -283,10 +330,13 @@ public void clicked(InputEvent event, float x, float y) { } private void connectToServer(String password, String roomId, boolean isCreating) { - String action = isCreating ? "createRoom" : "joinRoom"; + String action = isCreating ? CREATE_ROOM : JOIN_ROOM; SessionState sessionState = new SessionStateToSend(action, roomId, password); try { Main.messageSender.sendMessage(sessionState); + if (isCreating){ + Main.isHost = true; + } startConnectionTimer(isCreating, roomId, password); } catch (Exception e) { showErrorDialog(CONNECTION_ERROR, FAILED_TO_CONNECT, 5); @@ -311,25 +361,34 @@ private void checkConnectionStatus(boolean isCreating, String roomId, String pas if (main.gameSession.getSessionMsg() != null) { resetButtons(); switch (main.gameSession.getSessionMsg()) { - case "connected_ok": + case SESSION_STATE_OK: Gdx.app.log(isCreating ? CREATE_ROOM : JOIN_ROOM, "Creating a room with ID: " + roomId + " and password: " + password + " response " + main.gameSession.getSessionMsg()); - setGameScreen(new PlayScreen()); - changeToPlayScreen(); + + if(gameScreen == null){ + setGameScreen(new PlayScreen()); + changeToPlayScreen(); + musicTools.stopMusic(); + + }else{ + gameScreen.restart(); + changeToPlayScreen(); + musicTools.stopMusic(); + } break; - case "session_exists": + case SESSION_STATE_EXISTS: resetSessionState(); showErrorDialog(SESSION_EXISTS, SESSION_EXIST_TEXT, 5); break; - case "does_not_exists": + case SESSION_STATE_NO_EXISTS: resetSessionState(); showErrorDialog(JOIN_ERROR, DOES_NOT_EXIST_TEXT, 5); break; - case "incorrect_password": + case SESSION_STATE_WRONG_PASSWORD: resetSessionState(); showErrorDialog(JOIN_ERROR, INCORRECT_PASSWORD_TEXT, 5); break; - case "players_limit": + case SESSION_STATE_MAX_PLAYERS: resetSessionState(); showErrorDialog(JOIN_ERROR, MAX_PLAYERS_TEXT, 5); break; @@ -421,7 +480,26 @@ public Player getPlayer(Player player) { } @Override - public void updatePlayerArray(String id, float x, float y) { + public void updatePlayerArray(String id, float x, float y, boolean isHolding) { + + } + + @Override + public void updatePlayerInteraction(String id, float x, float y, float impulse) { } + + @Override + public void updateFurnitureArray(String id, float x, float y, int holdersCount, boolean isTaken) { + + } + + + public void restart() { + Gdx.input.setInputProcessor(stage); + main.gameSession.setSessionMsg(""); + musicTools.startMusic(); +// layoutUi(); +// addListeners(); + } } \ No newline at end of file diff --git a/core/src/com/aqwsxlostfly/packandgo/Screens/PlayScreen.java b/core/src/com/aqwsxlostfly/packandgo/Screens/PlayScreen.java index 93d5d02..21e4835 100644 --- a/core/src/com/aqwsxlostfly/packandgo/Screens/PlayScreen.java +++ b/core/src/com/aqwsxlostfly/packandgo/Screens/PlayScreen.java @@ -5,24 +5,41 @@ import static com.aqwsxlostfly.packandgo.Main.messageSender; import static com.aqwsxlostfly.packandgo.Main.screenHeight; import static com.aqwsxlostfly.packandgo.Main.screenWidth; +import static com.aqwsxlostfly.packandgo.Tools.maptools.TileMapHelper.defaultPlayerPosition; import static com.aqwsxlostfly.packandgo.Tools.maptools.TileMapHelper.world; +import static com.aqwsxlostfly.packandgo.render.Renderer.gameOverScreen; +import static java.lang.Float.NaN; + +import com.aqwsxlostfly.packandgo.Heroes.Furniture; import com.aqwsxlostfly.packandgo.Heroes.Player; import com.aqwsxlostfly.packandgo.Main; +import com.aqwsxlostfly.packandgo.Tools.MusicTools; import com.aqwsxlostfly.packandgo.Tools.figures.Point2D; import com.aqwsxlostfly.packandgo.Tools.hud.GameHud; import com.aqwsxlostfly.packandgo.Tools.hud.Joystick; import com.aqwsxlostfly.packandgo.Tools.maptools.TileMapHelper; -import com.aqwsxlostfly.packandgo.session.InputState; +import com.aqwsxlostfly.packandgo.objectsdto.InputState; +import com.aqwsxlostfly.packandgo.render.Renderer; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; +import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; +import com.badlogic.gdx.graphics.g2d.BitmapFont; +import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.SpriteBatch; +import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; +import com.badlogic.gdx.math.Vector2; +import com.badlogic.gdx.physics.box2d.Body; +import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; +import com.badlogic.gdx.physics.box2d.Contact; +import com.badlogic.gdx.physics.box2d.Fixture; +import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.Timer; @@ -30,8 +47,30 @@ public class PlayScreen implements Screen { + + private static final float TOTAL_GAME_TIME_LVL_1 = 6f * 60f; + private boolean isWaitingForPlayers; + private boolean isGameCountdownRunning; + private boolean isGameStarted; + private float countdownTimer; + private float gameTimer; + + private ShapeRenderer shapeRenderer; + + private MusicTools musicTools; + + public static final String PLAYER_STATE = "playerState"; + + public static final String PLAYER_STATE_DELETE = "playerStateDelete"; + public static final String FURNITURE_STATE = "furnitureState"; + private static final String PLAYSCREENMUSIC = "Clown.mp3"; + + Timer timer = new Timer(); + + private BitmapFont font; + Joystick joy; - private final TileMapHelper tileMapHelper; + private TileMapHelper tileMapHelper; public GameHud gameHud; private static final float frameRateRender = 1 / 60f; @@ -42,28 +81,46 @@ public class PlayScreen implements Screen { private final int mapPixelHeight; public static ObjectMap players = new ObjectMap<>(); + public static ObjectMap furnitures = new ObjectMap<>(); private final OrthogonalTiledMapRenderer orthogonalTiledMapRenderer; private final OrthographicCamera hudCamera; private final Box2DDebugRenderer box2DDebugRenderer = new Box2DDebugRenderer(); + private InputMultiplexer inputMultiplexer = new InputMultiplexer(); + + + private final String HOW_TO_PLAY_INFO = "YOU HAVE TO MOVE ALL FURNITURE INTO TRUCK" + "\n" + + " UNTILE TIME IS GONE!" + "\n" + "CONTACT FURNITURE AND PRESS TAKE TO MOVE IT" + "\n" + + "PRESS KICK TO BYE BYE YOUR TEAMMATE"; + public PlayScreen() { + isWaitingForPlayers = true; + isGameCountdownRunning = false; + isGameStarted = false; + countdownTimer = 3f; // 3 секунды перед началом + gameTimer = TOTAL_GAME_TIME_LVL_1; // 5 минут обратный отсчет + font = new BitmapFont(); + shapeRenderer = new ShapeRenderer(); + hudCamera = new OrthographicCamera(screenWidth, screenHeight); hudCamera.viewportWidth = screenWidth; // Размеры для камеры HUD hudCamera.viewportHeight = screenHeight; hudCamera.position.set((float) screenWidth / 2, (float) screenHeight / 2, 0); hudCamera.update(); + musicTools = new MusicTools(PLAYSCREENMUSIC); + musicTools.startMusic(); + loadHeroes(); this.tileMapHelper = new TileMapHelper(); orthogonalTiledMapRenderer = tileMapHelper.setupMap(); - updatePlayerArray(meId, 0, 0); - InputMultiplexer inputMultiplexer = new InputMultiplexer(); + updatePlayerArray(meId, 0, 0, false); - gameHud = new GameHud(players.get(meId)); + gameHud = new GameHud(); inputMultiplexer.addProcessor(gameHud.stage); // Первый обработчик, чтобы убедиться, что UI имеет приоритет inputMultiplexer.addProcessor(new InputAdapter() { // Ваш текущий обработчик событий в PlayScreen @@ -133,37 +190,129 @@ public boolean scrolled(float amountX, float amountY) { } - public void updatePlayerArray(String id, float x_, float y_) { + public void updatePlayerArray(String id, float x_, float y_, boolean isHolding) { if (Objects.equals(id, meId)) { if (players.get(id) == null) { Gdx.app.log("ADD NEW PLAYER", "id " + id + " x " + x_ + " y " + y_); - players.put(id, tileMapHelper.getPlayer()); + players.put(id, tileMapHelper.getPlayer(id)); } } else { if (players.get(id) != null) { - players.get(id).serverUpdate(x_, y_); + players.get(id).serverUpdate(x_, y_, isHolding); } else { Gdx.app.log("ADD NEW PLAYER", "id " + id + " x " + x_ + " y " + y_); - players.put(id, tileMapHelper.getPlayer()); + players.put(id, tileMapHelper.getPlayer(id)); + } + + } + + } + + public void updateFurnitureArray(String id, float x_, float y_, int holdersCount, boolean isTaken) { + + if (furnitures.get(id) != null) { + if (Objects.equals(id, players.get(meId).getContactFurnitureKey())) { + // TODO +// Gdx.app.log("EQUAL FURN", "id " + id + " x " + x_ + " y " + y_); + if(players.get(meId).isTeamLead()){ + furnitures.get(id).serverUpdateHolders(holdersCount); + }else{ + furnitures.get(id).serverUpdate(x_, y_, holdersCount, isTaken); + } + } else { +// Gdx.app.log("OTHER FURN", "id " + id + " x " + x_ + " y " + y_); + furnitures.get(id).serverUpdate(x_, y_, holdersCount, isTaken); } + } else { + Gdx.app.log("FURN UPD ERROR", "id " + id + " x " + x_ + " y " + y_); } } + public void updateContactfurniture() { + + String currFurnKey = players.get(meId).getContactFurnitureKey(); + Body bodyA = players.get(meId).getBody(); + Body bodyB = furnitures.get(currFurnKey).getBody(); + + // Gdx.app.log("FURN INFO", "currID " + currFurnKey + " isTlid " + players.get(meId).isTeamLead() + " furnHoldersCount " + furnitures.get(currFurnKey).getHoldersCount() + " isTakenFurn " + + // furnitures.get(currFurnKey).isTaken() + " isHoldingPlayer " + players.get(meId).isHolding() + " currVelocity " + players.get(meId).CURRENT_VELOCITY_SCALE); + + if (countDistance(bodyA, bodyB)<30){ + if (players.get(meId).isTeamLead()) { + furnitures.get(currFurnKey).setDirection(joy.getDir()); + } + }else{ + + if (players.get(meId).isTeamLead()) { + furnitures.get(currFurnKey).getBody().setType(BodyDef.BodyType.StaticBody); + furnitures.get(currFurnKey).setTaken(false); + furnitures.get(currFurnKey).decreaseHoldersCount(); + updateAndGetFurnitureInputState(furnitures.get(currFurnKey), currFurnKey); + }else{ + furnitures.get(currFurnKey).decreaseHoldersCount(); + updateAndGetFurnitureInputState(furnitures.get(currFurnKey), currFurnKey); + } + + if (furnitures.get(currFurnKey).getHoldersCount()==0){ + furnitures.get(currFurnKey).getBody().setType(BodyDef.BodyType.StaticBody); + } + + + players.get(meId).setHolding(false); + players.get(meId).setTeamLead(false); + } + + } + public float countDistance(Body bodyA, Body bodyB){ + // Предположим, у вас уже есть два тела bodyA и bodyB + + + // Получаем позиции центров масс тел bodyA и bodyB + Vector2 positionA = bodyA.getPosition(); + Vector2 positionB = bodyB.getPosition(); + + // Вычисляем расстояние между центрами масс тел bodyA и bodyB + float currentDistance = positionA.dst(positionB); + + if (Float.isNaN(currentDistance)) currentDistance = 1000f; + +// Gdx.app.log("POSITION", String.valueOf(currentDistance)); + + return currentDistance; + } + + @Override + public void updatePlayerInteraction(String id, float x, float y, float impulse) { + if (id != null && players.get(id) != null) { + if (Objects.equals(id, meId)) { + Gdx.app.log("GET ME PUSH INTER", " x " + x + " y " + y + " imp " + impulse); + Vector2 directionToPlayer = new Vector2(x, y).nor(); // Нормирование вектора + Vector2 impulseVector = directionToPlayer.scl(impulse); // Масштабирование направления силой импульса + + players.get(id).applyImpulse(impulseVector); + + } + } + } + public void multitouch(float x, float y, boolean isDownTouch, int pointer) { for (int i = 0; i < 3; i++) { + joy.update(x, y, isDownTouch, pointer); } } public void render(SpriteBatch batch, OrthographicCamera camera) { - updatePlayers(); + if (players.get(meId) == null) return; + updatePlayers(); + updateGameTimers(frameRateRender); cameraUpdate(camera); world.step(frameRateRender, 8, 3); @@ -171,29 +320,235 @@ public void render(SpriteBatch batch, OrthographicCamera camera) { orthogonalTiledMapRenderer.setView(camera); // Устанавливаем камеру для рендерера карты orthogonalTiledMapRenderer.render(); // Рендерим карту - for (ObjectMap.Entry entry : players.entries()) { - entry.value.draw(batch); + if (players.get(meId).isHolding()) { + try { + + if(furnitures.get(players.get(meId).getContactFurnitureKey()).getHoldersCount()!=0) { + players.get(meId).decreaseSpeed(furnitures.get(players.get(meId).getContactFurnitureKey()).getWeight() / + furnitures.get(players.get(meId).getContactFurnitureKey()).getHoldersCount()); + }else{ + players.get(meId).decreaseSpeed(furnitures.get(players.get(meId).getContactFurnitureKey()).getWeight()); + } + + updateContactfurniture(); + + } catch (Exception e) { + // TODO + } + } else { + players.get(meId).decreaseSpeed(0f); } + furnitures.forEach(e -> e.value.draw(batch)); + + players.forEach(e -> e.value.draw(batch)); + // Начинаем рисовать элементы интерфейса с использованием камеры HUD batch.setProjectionMatrix(hudCamera.combined); + if (isWaitingForPlayers) { + drawWaitingForPlayers(batch); + drawTextWithBackground(batch, HOW_TO_PLAY_INFO, players.get(meId).getX() + 650, players.get(meId).getY() + 520, font); + } else if (isGameCountdownRunning) { + drawGameCountdown(batch); + } else if (isGameStarted) { + drawGameTimer(batch); + drawFurnitureCount(batch); + } + if (players.get(meId).isImpulsed) { + drawTextCenteredPlayer(batch, "AAAaaa", players.get(meId).getX(), players.get(meId).getY(), font); + } + joy.draw(batch); // Рисуем джойстик с использованием камеры HUD gameHud.update(frameRateRender); gameHud.draw(); -// box2DDebugRenderer.render(world, camera.combined.scl(1)); + //box2DDebugRenderer.render(world, camera.combined.scl(1)); + + } + + + private void drawFurnitureCount(SpriteBatch batch) { + String currentFurniture = getCurrentFurnitureCount(); + String maxFurniture = getMaxFurnitureCount(); + drawTextCentered(batch, "Furniture: " + currentFurniture + "/" + maxFurniture, screenWidth - 300, screenHeight / 2, font); + } + + private String getMaxFurnitureCount() { + + return String.valueOf(furnitures.size); + } + + private String getCurrentFurnitureCount() { + int currFurn = 0; + Array keysFurniture = new Array<>(furnitures.keys().toArray()); + for (String key : keysFurniture) { + float currY = furnitures.get(key).getBody().getPosition().y; + if (currY != 0f && currY < defaultPlayerPosition.y + 60) { + currFurn++; + } + } + return String.valueOf(currFurn); + } + + private void drawWaitingForPlayers(SpriteBatch batch) { + drawTextCentered(batch, "Waiting for other player...", screenWidth / 2, screenHeight / 2, font); + } + + private void drawGameCountdown(SpriteBatch batch) { + drawTextCentered(batch, "Game is starting: " + String.format("%.0f", countdownTimer) + "s", screenWidth / 2, screenHeight / 2, font); + } + + private void drawGameTimer(SpriteBatch batch) { + drawTextCentered(batch, "Time left: " + String.format("%.0f", gameTimer) + "s", screenWidth / 2, screenHeight / 2, font); + } + + private void drawTextCentered(SpriteBatch batch, String text, float x, float y, BitmapFont font) { + font.getData().setScale(5.5f); + GlyphLayout layout = new GlyphLayout(font, text); + float textWidth = layout.width; + float verticalOffset = (float) screenHeight / 2 - 20f; // Смещение текста вверх на 100 пикселей + font.draw(batch, text, x - textWidth / 2.0f, y + verticalOffset); // Используем смещение для `y` + font.getData().setScale(1.0f); // Сброс размера шрифта обратно + } + + private void drawTextCenteredPlayer(SpriteBatch batch, String text, float x, float y, BitmapFont font) { + font.getData().setScale(3.5f); + float verticalOffset = 580f; + font.draw(batch, text, x + verticalOffset, y + verticalOffset); + font.getData().setScale(1.0f); + } + + private void drawTextWithBackground(SpriteBatch batch, String text, float x, float y, BitmapFont font) { + font.getData().setScale(4.5f); // Если вы хотите увеличить текст, как показано выше + GlyphLayout layout = new GlyphLayout(font, text); + float textWidth = layout.width; + float textHeight = layout.height; + float verticalOffset = (float) screenHeight / 3; // Смещение текста вверх на 100 пикселей + + // Закончить работу с SpriteBatch, чтобы начать работу с ShapeRenderer + batch.end(); + + // Отрисовка черного фона за текстом + Gdx.gl.glEnable(GL20.GL_BLEND); + shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); + shapeRenderer.setColor(0, 0, 0, 0.5f); // Устанавливаем цвет (0,0,0,0.5) - черный с прозрачностью 50% + shapeRenderer.rect(x - textWidth / 2 - 10, y + verticalOffset - textHeight - 10, textWidth + 20, textHeight + 20); // Рисуем прямоугольник + shapeRenderer.end(); + Gdx.gl.glDisable(GL20.GL_BLEND); + + // Начинаем работу с SpriteBatch снова + batch.begin(); + + font.draw(batch, text, x - textWidth / 2.0f, y + verticalOffset); // Используем смещение для `y` + font.getData().setScale(1.0f); // Сброс размера шрифта обратно + } + + public void updateGameTimers(float delta) { + // Обновляем таймеры, если игра началась + if (isGameCountdownRunning) { + countdownTimer -= delta; + if (countdownTimer <= 0) { + isGameCountdownRunning = false; + isGameStarted = true; + } + } else if (isGameStarted) { + gameTimer -= delta; + if (gameTimer <= 0) { + // Игра закончилась, показываем экран game over + endGame(getCurrentFurnitureCount(), TOTAL_GAME_TIME_LVL_1); + } else if (Integer.valueOf(getCurrentFurnitureCount()).equals(Integer.valueOf(getMaxFurnitureCount()))) { + float takenTime = TOTAL_GAME_TIME_LVL_1 - gameTimer; + endGame(getCurrentFurnitureCount(), takenTime); + } + } + + // Проверяем, подключился ли второй игрок и обновляем состояния + if (isWaitingForPlayers && players.size >= 2) { + if (Main.isHost) { + timer.scheduleTask(new Timer.Task() { + @Override + public void run() { + isWaitingForPlayers = false; + isGameCountdownRunning = true; + movePlayersToStartPosition(); + } + }, 1); + } else { + isWaitingForPlayers = false; + isGameCountdownRunning = true; + movePlayersToStartPosition(); + } + } + } + + private void endGame(String playersScore, float timeLeft) { + + timer.stop(); + timer.clear(); + + clearPlayers(); + musicTools.stopMusic(); + + Renderer.setGameOverScreen(new GameOverScreen(playersScore, timeLeft, TOTAL_GAME_TIME_LVL_1, getMaxFurnitureCount())); + Renderer.setCurrentScreen(gameOverScreen); + + } + + private void clearPlayers() { + + InputState inputState = Main.inputState; + + inputState.setType(PLAYER_STATE_DELETE); + inputState.setId(meId); + + messageSender.sendMessage(inputState); + + players.forEach(el -> { + if (!Objects.equals(el.key, meId)) { + players.remove(el.key); + } + }); + + } + + private void movePlayersToStartPosition() { + players.get(meId).setDirection(new Point2D(0, 0)); + players.get(meId).getBody().setTransform(defaultPlayerPosition, 0); } public void updatePlayers() { + players.get(meId).setDirection(joy.getDir()); + + if (isGameCountdownRunning || isWaitingForPlayers) { + if (isWaitingForPlayers) { + //Gdx.app.log("PLAYER POS DEBUG", "PLAYER Y " + players.get(meId).getY() + " truck y " + (defaultPlayerPosition.y + 60)); + if (players.get(meId).getY() > defaultPlayerPosition.y + 60) { + players.get(meId).getBody().setTransform(defaultPlayerPosition, 0); + } else { + players.get(meId).setDirection(joy.getDir()); + } + } else { + + players.get(meId).setDirection(new Point2D(0, 0)); + } + } else { + if (players.get(meId).isImpulsed) { + players.get(meId).getBody().setLinearVelocity(players.get(meId).kickImpulse); + } else { + players.get(meId).setDirection(joy.getDir()); + } + } + } @Override public void dispose() { + orthogonalTiledMapRenderer.dispose(); gameHud.dispose(); } @@ -202,10 +557,13 @@ public void loadHeroes() { new Texture("circle.png"), new Point2D(((float) (screenHeight / 3) / 2 + (float) (screenHeight / 3) / 4), (float) (screenHeight / 3) / 2 + (float) (screenHeight / 3) / 4), (float) screenHeight / 3); + +// if (players.get(meId) == null) { +// players.put(meId, tileMapHelper.getPlayer(meId)); +// } } - private void startSendingState(){ - Timer timer = new Timer(); + private void startSendingState() { timer.scheduleTask(new Timer.Task() { @Override public void run() { @@ -239,20 +597,88 @@ private float clamp(float value, float min, float max) { public void handleTimer() { if (!players.isEmpty()) { - Player me = players.get(meId); - InputState playerState = updateAndGetInputState(me); - messageSender.sendMessage(playerState); + if (players.get(meId) != null) { + Player me = players.get(meId); + InputState playerState = updateAndGetPlayerInputState(me); + messageSender.sendMessage(playerState); + if (players.get(meId).isHolding()) { + if (players.get(meId).isTeamLead()) { + String currFurnitureKey = players.get(meId).getContactFurnitureKey(); + updateAndGetFurnitureInputState(furnitures.get(currFurnitureKey), currFurnitureKey); + } + } + } else { +// InputState inputState = Main.inputState; +// +// inputState.setType(PLAYER_STATE_DELETE); +// inputState.setId(meId); +// +// messageSender.sendMessage(inputState); + } } } - public InputState updateAndGetInputState(Player player) { + public InputState updateAndGetPlayerInputState(Player player) { InputState inputState = Main.inputState; - inputState.setType("playerState"); + inputState.setType(PLAYER_STATE); inputState.setId(meId); inputState.setX(player.getX()); inputState.setY(player.getY()); + inputState.setHolding(player.isHolding()); return inputState; } + + public static void updateAndGetFurnitureInputState(Furniture furniture, String furnId) { + InputState inputState = Main.inputState; + + inputState.setType(FURNITURE_STATE); + inputState.setId(furnId); + inputState.setX(furniture.getX()); + inputState.setY(furniture.getY()); + inputState.setHolding(furniture.isTaken()); + inputState.setHolders(furniture.getHoldersCount()); + +// Gdx.app.log("FURN UPD PS", String.valueOf(inputState)); + + messageSender.sendMessage(inputState); + + } + + public void restart() { + + Gdx.input.setInputProcessor(inputMultiplexer); + + musicTools = new MusicTools(PLAYSCREENMUSIC); + musicTools.startMusic(); + + tileMapHelper.setupMap(); + + players = new ObjectMap<>(); + + updatePlayerArray(meId, 0, 0, false); + + players.get(meId).setStatusContact(false); + players.get(meId).setHolding(false); + players.get(meId).setContactFurnitureKey(""); + players.get(meId).setDirection(new Point2D(0, 0)); + players.get(meId).setTeamLead(false); + + + isWaitingForPlayers = true; + isGameCountdownRunning = false; + isGameStarted = false; + countdownTimer = 3f; + gameTimer = TOTAL_GAME_TIME_LVL_1; + + timer.start(); + startSendingState(); + + } + + public void resetFurniture(){ + tileMapHelper.setupMap(); + } + } diff --git a/core/src/com/aqwsxlostfly/packandgo/Screens/Screen.java b/core/src/com/aqwsxlostfly/packandgo/Screens/Screen.java index e519882..998f9cc 100644 --- a/core/src/com/aqwsxlostfly/packandgo/Screens/Screen.java +++ b/core/src/com/aqwsxlostfly/packandgo/Screens/Screen.java @@ -19,5 +19,9 @@ default Player getPlayer(Player player){ return player; } - void updatePlayerArray(String id, float x, float y); + void updatePlayerArray(String id, float x, float y, boolean isHolding); + + void updatePlayerInteraction(String id, float x, float y, float impulse); + + void updateFurnitureArray(String id, float x, float y, int holdersCount, boolean isTaken); } \ No newline at end of file diff --git a/core/src/com/aqwsxlostfly/packandgo/Tools/MusicTools.java b/core/src/com/aqwsxlostfly/packandgo/Tools/MusicTools.java new file mode 100644 index 0000000..627f898 --- /dev/null +++ b/core/src/com/aqwsxlostfly/packandgo/Tools/MusicTools.java @@ -0,0 +1,31 @@ +package com.aqwsxlostfly.packandgo.Tools; + +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.audio.Music; + +public class MusicTools { + private Music music; + public MusicTools(String nameMusic){ + try { + this.music = Gdx.audio.newMusic(Gdx.files.internal(nameMusic)); + this.music.setLooping(true); // Устанавливаем музыку на повторение + this.music.setVolume(1f); // Устанавливает громкость + } catch (Exception e) { + Gdx.app.log("ERRORMusicInitial", String.valueOf(e)); // Выводим информацию об ошибке в консоль + } + } + public void startMusic(){ + try { + this.music.play(); // Начинаем воспроизведение музыки + } catch (Exception e) { + Gdx.app.log("ERRORMusicInitial", String.valueOf(e)); // Выводим информацию об ошибке в консоль + } + } + + public void stopMusic(){ + if (music != null) { + music.stop(); + music.dispose(); + } + } +} diff --git a/core/src/com/aqwsxlostfly/packandgo/Tools/hud/GameHud.java b/core/src/com/aqwsxlostfly/packandgo/Tools/hud/GameHud.java index fc15ba5..88f2908 100644 --- a/core/src/com/aqwsxlostfly/packandgo/Tools/hud/GameHud.java +++ b/core/src/com/aqwsxlostfly/packandgo/Tools/hud/GameHud.java @@ -1,9 +1,19 @@ package com.aqwsxlostfly.packandgo.Tools.hud; -import com.aqwsxlostfly.packandgo.Heroes.Player; +import static com.aqwsxlostfly.packandgo.Main.meId; +import static com.aqwsxlostfly.packandgo.Screens.PlayScreen.furnitures; +import static com.aqwsxlostfly.packandgo.Screens.PlayScreen.players; +import static com.aqwsxlostfly.packandgo.Screens.PlayScreen.updateAndGetFurnitureInputState; + + +import com.aqwsxlostfly.packandgo.Main; +import com.aqwsxlostfly.packandgo.objectsdto.InteractionPlayerImpl; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; +import com.badlogic.gdx.math.Vector2; +import com.badlogic.gdx.physics.box2d.Body; +import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Skin; @@ -11,19 +21,15 @@ import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.viewport.ScreenViewport; +import java.util.Objects; + public class GameHud { - Texture tabouret; - Texture hero; - public Stage stage; // Используется для управления и отображения UI - public Skin skin; // Скин для стилизации элементов UI - public TextButton takeBtn; // Кнопка в UI - public TextButton fightBtn; // Кнопка в UI - public Player player; - - - public GameHud(Player player) { - tabouret = new Texture("tabouret.png"); - hero = new Texture("tile_0456.png"); + public Stage stage; + public Skin skin; + public TextButton takeBtn; + public TextButton fightBtn; + + public GameHud() { // Инициализация скина и сцены skin = new Skin(Gdx.files.internal("skin/uiskin.json")); stage = new Stage(new ScreenViewport()); @@ -32,11 +38,9 @@ public GameHud(Player player) { takeBtn = new TextButton("Take", skin); fightBtn = new TextButton("Kick", skin); takeBtn.setSize(250, 150); // Установка размера кнопки - takeBtn.setPosition(Gdx.graphics.getWidth() -450, Gdx.graphics.getHeight() / 2 - 450); // Позиционирование кнопки + takeBtn.setPosition(Gdx.graphics.getWidth() - 450, Gdx.graphics.getHeight() / 2 - 450); // Позиционирование кнопки fightBtn.setSize(250, 150); // Установка размера кнопки - fightBtn.setPosition(Gdx.graphics.getWidth() -450, Gdx.graphics.getHeight() / 2 - 250); // Позиционирование кнопки - - this.player = player; + fightBtn.setPosition(Gdx.graphics.getWidth() - 450, Gdx.graphics.getHeight() / 2 - 250); // Позиционирование кнопки // Добавление кнопки на сцену stage.addActor(takeBtn); @@ -60,40 +64,127 @@ private void addListeners() { @Override public void clicked(InputEvent event, float x, float y) { - Texture currentTexture = player.textureMapObject.getTextureRegion().getTexture(); + // Обработка нажатия на кнопку Gdx.app.log("Button Clicked", "Take button was pressed"); - if (currentTexture != tabouret){ - Gdx.app.log("INFO","смена текстуры"); - player.textureMapObject.getTextureRegion().setTexture(tabouret); - } else{ - player.textureMapObject.getTextureRegion().setTexture(hero); + if (players.get(meId).isStatusContact()) { + String currFurnitureKey = players.get(meId).getContactFurnitureKey(); + + if (!players.get(meId).isHolding()) { + players.get(meId).setHolding(true); + if (furnitures.get(currFurnitureKey) != null) { + furnitures.get(currFurnitureKey).getBody().setType(BodyDef.BodyType.DynamicBody); + furnitures.get(currFurnitureKey).setTaken(true); + players.get(meId).setTeamLead(furnitures.get(currFurnitureKey).getHoldersCount() == 0); + furnitures.get(currFurnitureKey).increaseHoldersCount(); + updateAndGetFurnitureInputState(furnitures.get(currFurnitureKey), currFurnitureKey); + Gdx.app.log("(currFurnitureKey) != null", currFurnitureKey); + } + } else { + players.get(meId).setHolding(false); + players.get(meId).setContactFurnitureKey(""); + if (furnitures.get(currFurnitureKey) != null) { + if(players.get(meId).isTeamLead()){ + furnitures.get(currFurnitureKey).getBody().setType(BodyDef.BodyType.StaticBody); + furnitures.get(currFurnitureKey).setTaken(false); + furnitures.get(currFurnitureKey).decreaseHoldersCount(); + updateAndGetFurnitureInputState(furnitures.get(currFurnitureKey), currFurnitureKey); + players.get(meId).setTeamLead(false); + }else{ + players.get(meId).setTeamLead(false); + furnitures.get(currFurnitureKey).decreaseHoldersCount(); + updateAndGetFurnitureInputState(furnitures.get(currFurnitureKey), currFurnitureKey); + } + + if (furnitures.get(currFurnitureKey).getHoldersCount()==0){ + furnitures.get(currFurnitureKey).getBody().setType(BodyDef.BodyType.StaticBody); + } + } + } + } else if (players.get(meId).isHolding()) { + String currFurnitureKey = players.get(meId).getContactFurnitureKey(); + + players.get(meId).setHolding(false); + players.get(meId).setContactFurnitureKey(""); + if (furnitures.get(currFurnitureKey) != null) { + + + if(players.get(meId).isTeamLead()){ + furnitures.get(currFurnitureKey).getBody().setType(BodyDef.BodyType.StaticBody); + furnitures.get(currFurnitureKey).setTaken(false); + furnitures.get(currFurnitureKey).decreaseHoldersCount(); + updateAndGetFurnitureInputState(furnitures.get(currFurnitureKey), currFurnitureKey); + players.get(meId).setTeamLead(false); + }else{ + players.get(meId).setTeamLead(false); + furnitures.get(currFurnitureKey).decreaseHoldersCount(); + updateAndGetFurnitureInputState(furnitures.get(currFurnitureKey), currFurnitureKey); + } + + if (furnitures.get(currFurnitureKey).getHoldersCount()==0){ + furnitures.get(currFurnitureKey).getBody().setType(BodyDef.BodyType.StaticBody); + } + + + } } } }); fightBtn.addListener(new ClickListener() { - @Override public void clicked(InputEvent event, float x, float y) { - Texture currentTexture = player.textureMapObject.getTextureRegion().getTexture(); Gdx.app.log("Button Clicked", "Kick button was pressed"); - if (currentTexture != tabouret){ - Gdx.app.log("INFO","кнопка ударить"); - player.textureMapObject.getTextureRegion().setTexture(tabouret); + players.get(meId).resetImpulse(); + String nearestPlayerId = findNearestPlayer(); + if (nearestPlayerId != null) { + float impulseStrength = 100; // Значение нужно подобрать под вашу игру. + Vector2 directionToPlayer = new Vector2( + players.get(nearestPlayerId).getBody().getPosition()).sub(players.get(meId).getBody().getPosition()); + directionToPlayer.nor().scl(impulseStrength); + + // Send info to others + InteractionPlayerImpl stateToSend = new InteractionPlayerImpl(); + stateToSend.setType("playerInteraction"); + stateToSend.setId(nearestPlayerId); + stateToSend.setImpulse(impulseStrength); + stateToSend.setX(directionToPlayer.x); + stateToSend.setY(directionToPlayer.y); + Main.messageSender.sendMessage(stateToSend); - } else{ - player.textureMapObject.getTextureRegion().setTexture(hero); } } }); } + + + private String findNearestPlayer() { + String nearestPlayerId = null; + float minDistanceSquared = 250F; + + Vector2 playerPosition = players.get(meId).getBody().getPosition(); + + for (String otherPlayerId : players.keys()) { + if (!Objects.equals(otherPlayerId, meId)) { + float distanceSquared = playerPosition.dst2(players.get(otherPlayerId).getBody().getPosition()); + if (distanceSquared < minDistanceSquared) { + minDistanceSquared = distanceSquared; + nearestPlayerId = otherPlayerId; + } + } + } + + return nearestPlayerId; + } + + public void resize(int width, int height) { stage.getViewport().update(width, height, true); } + // Не забудьте освободить ресурсы public void dispose() { stage.dispose(); skin.dispose(); diff --git a/core/src/com/aqwsxlostfly/packandgo/Tools/maptools/BodyHelperService.java b/core/src/com/aqwsxlostfly/packandgo/Tools/maptools/BodyHelperService.java index 3ff09fb..4936605 100644 --- a/core/src/com/aqwsxlostfly/packandgo/Tools/maptools/BodyHelperService.java +++ b/core/src/com/aqwsxlostfly/packandgo/Tools/maptools/BodyHelperService.java @@ -14,6 +14,7 @@ public class BodyHelperService { public static final short CATEGORY_PLAYER = 0x0001; public static final short CATEGORY_WALL = 0x0002; + public static final short CATEGORY_FLOWERS = 0x0003; public static Body createBodyPlayer(TextureMapObject textureObject, World world, boolean isStatic) { TextureRegion textureRegion = textureObject.getTextureRegion(); @@ -37,7 +38,7 @@ public static Body createBodyPlayer(TextureMapObject textureObject, World world, FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape; - fixtureDef.density = 0F; + fixtureDef.density = 2.0F; fixtureDef.friction = 0.3f; fixtureDef.filter.categoryBits = CATEGORY_PLAYER; fixtureDef.filter.maskBits = CATEGORY_WALL; @@ -48,7 +49,38 @@ public static Body createBodyPlayer(TextureMapObject textureObject, World world, return body; } + public static Body createBodyFurniture(TextureMapObject textureObject, World world, boolean isStatic) { + TextureRegion textureRegion = textureObject.getTextureRegion(); + float width = textureRegion.getRegionWidth(); + float height = textureRegion.getRegionHeight(); + float x = textureObject.getX() + width /2 ; + float y = textureObject.getY() + height / 2; + BodyDef bodyDef = new BodyDef(); + bodyDef.type = BodyDef.BodyType.StaticBody; + bodyDef.position.set(x / 16.0f, y / 16.0f); + bodyDef.angularVelocity = 0f; + bodyDef.fixedRotation = true; + + Body body = world.createBody(bodyDef); + + PolygonShape shape = new PolygonShape(); + shape.setAsBox(width / 2 , height / 2 ); + + FixtureDef fixtureDef = new FixtureDef(); + fixtureDef.shape = shape; + fixtureDef.density = 2.0F; + fixtureDef.friction = 0.0f; + fixtureDef.filter.categoryBits = CATEGORY_FLOWERS; + fixtureDef.filter.maskBits = CATEGORY_PLAYER|CATEGORY_WALL|CATEGORY_FLOWERS; + + body.createFixture(fixtureDef); + + shape.dispose(); + + + return body; + } } \ No newline at end of file diff --git a/core/src/com/aqwsxlostfly/packandgo/Tools/maptools/TileMapHelper.java b/core/src/com/aqwsxlostfly/packandgo/Tools/maptools/TileMapHelper.java index 41db817..1c00954 100644 --- a/core/src/com/aqwsxlostfly/packandgo/Tools/maptools/TileMapHelper.java +++ b/core/src/com/aqwsxlostfly/packandgo/Tools/maptools/TileMapHelper.java @@ -1,9 +1,13 @@ package com.aqwsxlostfly.packandgo.Tools.maptools; - - +import static com.aqwsxlostfly.packandgo.Main.meId; +import static com.aqwsxlostfly.packandgo.Screens.PlayScreen.furnitures; +import static com.aqwsxlostfly.packandgo.Screens.PlayScreen.players; +import static com.aqwsxlostfly.packandgo.Screens.PlayScreen.updateAndGetFurnitureInputState; +import static com.aqwsxlostfly.packandgo.Tools.maptools.BodyHelperService.CATEGORY_FLOWERS; import static com.aqwsxlostfly.packandgo.Tools.maptools.BodyHelperService.CATEGORY_PLAYER; import static com.aqwsxlostfly.packandgo.Tools.maptools.BodyHelperService.CATEGORY_WALL; +import com.aqwsxlostfly.packandgo.Heroes.Furniture; import com.aqwsxlostfly.packandgo.Heroes.Player; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.maps.MapLayer; @@ -13,7 +17,6 @@ import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.objects.TextureMapObject; import com.badlogic.gdx.maps.tiled.TiledMap; -import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.math.Rectangle; @@ -28,6 +31,10 @@ import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; +import com.badlogic.gdx.physics.box2d.joints.DistanceJoint; +import com.badlogic.gdx.physics.box2d.joints.DistanceJointDef; +import com.badlogic.gdx.utils.Array; + import java.util.Objects; @@ -35,10 +42,15 @@ public class TileMapHelper { public TiledMap tiledMap; public static int worldHeight; public static int worldWigth; + private TextureMapObject textureMapObjectPlayer; + public static Vector2 defaultPlayerPosition; + public static World world; + + public TileMapHelper() { TileMapHelper.world = new World(new Vector2(0, 0), false); @@ -46,23 +58,51 @@ public TileMapHelper() { TileMapHelper.world.setContactListener(new ContactListener() { @Override public void beginContact(Contact contact) { - Fixture fixtureA = contact.getFixtureA(); - Fixture fixtureB = contact.getFixtureB(); - Gdx.app.log("Contact", "beginContact between " + fixtureA.getBody().getType() + " and " + fixtureB.getBody().getUserData()); + Gdx.app.log("Contact", "Контакт между объектами"); + Fixture fixtureA = contact.getFixtureA(); + Fixture fixtureB = contact.getFixtureB(); + + if ((Objects.equals(fixtureA.getFilterData().categoryBits, CATEGORY_FLOWERS) && Objects.equals(fixtureB.getBody().getUserData(), "PLAYER" + meId)) || + (Objects.equals(fixtureA.getBody().getUserData(), "PLAYER" + meId) && Objects.equals(fixtureB.getFilterData().categoryBits, CATEGORY_FLOWERS))){ + + if (Objects.equals(fixtureA.getFilterData().categoryBits, CATEGORY_FLOWERS)){ + + String currFurnKey = String.valueOf(fixtureA.getBody().getUserData()); + + if (furnitures.get(currFurnKey).availibleToTake() && !players.get(meId).isHolding()) { + players.get(meId).setStatusContact(true); + players.get(meId).setContactFurnitureKey(currFurnKey); + } + + + }else if (Objects.equals(fixtureB.getFilterData().categoryBits, CATEGORY_FLOWERS)){ + String currFurnKey = String.valueOf(fixtureB.getBody().getUserData()); + + if (furnitures.get(currFurnKey).availibleToTake() && !players.get(meId).isHolding()) { + players.get(meId).setStatusContact(true); + players.get(meId).setContactFurnitureKey(currFurnKey); + } + } + } } @Override public void endContact(Contact contact) { - + if (players.get(meId).isStatusContact()) { + players.get(meId).setStatusContact(false); + } } + @Override public void preSolve(Contact contact, Manifold oldManifold) { + } @Override public void postSolve(Contact contact, ContactImpulse impulse) { + } }); } @@ -76,6 +116,7 @@ public OrthogonalTiledMapRenderer setupMap() { parsePlayerTexture(tiledMap.getLayers().get("hero").getObjects()); parseWalls(); + parseMapObjectsLightFurniture(tiledMap.getLayers().get("objects").getObjects()); return new OrthogonalTiledMapRenderer(tiledMap); } @@ -88,9 +129,38 @@ private void parsePlayerTexture(MapObjects mapObjects) { if (textureMapObjectName != null && textureMapObjectName.equals("hero")) { this.textureMapObjectPlayer = textureMapObject; + defaultPlayerPosition = new Vector2(textureMapObjectPlayer.getX(), textureMapObjectPlayer.getY()); } } } + private void parseMapObjectsLightFurniture(MapObjects mapObjects) { + for (MapObject mapObject : mapObjects) { + + TextureMapObject textureMapObject = ((TextureMapObject) mapObject); + String textureMapObjectName = textureMapObject.getName(); + Gdx.app.log("NEW FURNITURE PROCESS","process"); + + //if (textureMapObjectName != null && textureMapObjectName.equals("flowers")) { +// this.textureMapObjectFurniture = textureMapObject; + String furnId = String.valueOf(mapObject.getProperties().get("id")); + if (furnitures.containsKey(furnId)){ + Gdx.app.log("FURNITURE PROCESS","CONTAIN KEY"); + furnitures.get(furnId).getBody().setTransform(textureMapObject.getX(), textureMapObject.getY(), 0); + furnitures.get(furnId).setTaken(false); + furnitures.get(furnId).setHoldersCount(0); + furnitures.get(furnId).getBody().setType(BodyDef.BodyType.StaticBody); + updateAndGetFurnitureInputState( furnitures.get(furnId), furnId); + }else{ + furnitures.put(furnId, getFurniture(textureMapObject, furnId)); + } + + Gdx.app.log("NEW FURNITURE", String.valueOf( furnitures.size)); + //} + + + } + + } private void parseWalls(){ for(MapLayer mapLayer : tiledMap.getLayers()){ @@ -173,9 +243,28 @@ private void createWall(float x, float y, float width, float height) { shape.dispose(); } + public Furniture getFurniture(TextureMapObject textureFurniture, String id) { + TextureMapObject textureMapObjectNew = new TextureMapObject(textureFurniture.getTextureRegion()); - public Player getPlayer() { + Body body = BodyHelperService.createBodyFurniture(textureMapObjectNew, + world, false); + + body.setTransform(textureFurniture.getX(), textureFurniture.getY(), 0); + body.setUserData(id); + + int maxHolders = (int) textureFurniture.getProperties().get("maxHolders"); + + float weight = (int) textureFurniture.getProperties().get("weight"); + +// if (maxHolders == 0) maxHolders =1; +// if (weight == 0) weight = 20; + + return new Furniture(body, textureMapObjectNew, maxHolders, weight); + + } + + public Player getPlayer(String id) { TextureMapObject textureMapObjectNew = new TextureMapObject(textureMapObjectPlayer.getTextureRegion()); @@ -184,6 +273,8 @@ public Player getPlayer() { body.setTransform(textureMapObjectPlayer.getX(), textureMapObjectPlayer.getY(), 0); + body.setUserData("PLAYER" + id); + return new Player(body, textureMapObjectNew); } diff --git a/core/src/com/aqwsxlostfly/packandgo/constants/ScreensConstants.java b/core/src/com/aqwsxlostfly/packandgo/constants/ScreensConstants.java index bea4963..ded241a 100644 --- a/core/src/com/aqwsxlostfly/packandgo/constants/ScreensConstants.java +++ b/core/src/com/aqwsxlostfly/packandgo/constants/ScreensConstants.java @@ -1,6 +1,8 @@ package com.aqwsxlostfly.packandgo.constants; public class ScreensConstants { + + // HomeSc connection lables public static final String CONNECTING = "CONNECTING"; public static final String CONNECTING_TEXT = "CONNECTING..."; public static final String CONNECTION_ERROR = "Connection Error"; diff --git a/core/src/com/aqwsxlostfly/packandgo/GraphicsObj/GraphicsObj.java b/core/src/com/aqwsxlostfly/packandgo/graphicsobj/GraphicsObj.java similarity index 85% rename from core/src/com/aqwsxlostfly/packandgo/GraphicsObj/GraphicsObj.java rename to core/src/com/aqwsxlostfly/packandgo/graphicsobj/GraphicsObj.java index 730390c..91e71e7 100644 --- a/core/src/com/aqwsxlostfly/packandgo/GraphicsObj/GraphicsObj.java +++ b/core/src/com/aqwsxlostfly/packandgo/graphicsobj/GraphicsObj.java @@ -1,4 +1,4 @@ -package com.aqwsxlostfly.packandgo.GraphicsObj; +package com.aqwsxlostfly.packandgo.graphicsobj; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; diff --git a/core/src/com/aqwsxlostfly/packandgo/objectsdto/InputState.java b/core/src/com/aqwsxlostfly/packandgo/objectsdto/InputState.java new file mode 100644 index 0000000..63b335f --- /dev/null +++ b/core/src/com/aqwsxlostfly/packandgo/objectsdto/InputState.java @@ -0,0 +1,23 @@ +package com.aqwsxlostfly.packandgo.objectsdto; + + +public interface InputState { + + void setType(String type); + String getType(); + + void setId(String id); + String getId(); + + void setX(float x); + float getX(); + + void setY(float y); + float getY(); + + void setHolding(boolean isHolding); + boolean isHolding(); + + void setHolders(int holdersCount); + int getHolders(); +} diff --git a/core/src/com/aqwsxlostfly/packandgo/objectsdto/InteractionPlayerImpl.java b/core/src/com/aqwsxlostfly/packandgo/objectsdto/InteractionPlayerImpl.java new file mode 100644 index 0000000..21fe67d --- /dev/null +++ b/core/src/com/aqwsxlostfly/packandgo/objectsdto/InteractionPlayerImpl.java @@ -0,0 +1,65 @@ +package com.aqwsxlostfly.packandgo.objectsdto; + +public class InteractionPlayerImpl implements InteractionPlayerState{ + + private String type; + + private String id; + private float x; + private float y; + + private float impulse; + + public InteractionPlayerImpl() { + } + + @Override + public void setType(String type) { + this.type = type; + } + + @Override + public String getType() { + return this.type; + } + + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public String getId() { + return this.id; + } + + @Override + public void setX(float x) { + this.x = x; + } + + @Override + public float getX() { + return this.x; + } + + @Override + public void setY(float y) { + this.y = y; + } + + @Override + public float getY() { + return this.y; + } + + @Override + public void setImpulse(float impulse) { + this.impulse = impulse; + } + + @Override + public float getImpulse() { + return this.impulse; + } +} diff --git a/core/src/com/aqwsxlostfly/packandgo/session/InputState.java b/core/src/com/aqwsxlostfly/packandgo/objectsdto/InteractionPlayerState.java similarity index 56% rename from core/src/com/aqwsxlostfly/packandgo/session/InputState.java rename to core/src/com/aqwsxlostfly/packandgo/objectsdto/InteractionPlayerState.java index bab45ec..b96c557 100644 --- a/core/src/com/aqwsxlostfly/packandgo/session/InputState.java +++ b/core/src/com/aqwsxlostfly/packandgo/objectsdto/InteractionPlayerState.java @@ -1,8 +1,6 @@ -package com.aqwsxlostfly.packandgo.session; - - -public interface InputState { +package com.aqwsxlostfly.packandgo.objectsdto; +public interface InteractionPlayerState { void setType(String type); String getType(); @@ -14,4 +12,7 @@ public interface InputState { void setY(float y); float getY(); + + void setImpulse(float impulse); + float getImpulse(); } diff --git a/core/src/com/aqwsxlostfly/packandgo/render/Renderer.java b/core/src/com/aqwsxlostfly/packandgo/render/Renderer.java index 0353b36..f561d96 100644 --- a/core/src/com/aqwsxlostfly/packandgo/render/Renderer.java +++ b/core/src/com/aqwsxlostfly/packandgo/render/Renderer.java @@ -1,15 +1,13 @@ package com.aqwsxlostfly.packandgo.render; +import com.aqwsxlostfly.packandgo.Screens.GameOverScreen; import com.aqwsxlostfly.packandgo.Screens.HomeSc; import com.aqwsxlostfly.packandgo.Screens.PlayScreen; import com.aqwsxlostfly.packandgo.Screens.Screen; import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; -import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; -import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; public class Renderer { @@ -17,9 +15,11 @@ public class Renderer { private final OrthographicCamera camera; - private static PlayScreen gameScreen; + public static PlayScreen gameScreen; - private HomeSc homeScreen; + public static HomeSc homeScreen; + + public static GameOverScreen gameOverScreen; private static Screen currentScreen; @@ -31,7 +31,7 @@ public void render() { if (currentScreen instanceof HomeSc){ homeScreen.render(batch, camera); - }else{ + }else if (currentScreen instanceof PlayScreen){ Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); @@ -41,6 +41,8 @@ public void render() { gameScreen.render(batch, camera); batch.end(); + } else if (currentScreen instanceof GameOverScreen){ + gameOverScreen.render(batch, camera); } } @@ -61,6 +63,10 @@ public static void setCurrentScreen(Screen screen) { currentScreen = screen; } + public static void setGameOverScreen(GameOverScreen screen) { + gameOverScreen = screen; + } + public void setHomeScreen(HomeSc screen) { homeScreen = screen; setCurrentScreen(homeScreen); diff --git a/core/src/com/aqwsxlostfly/packandgo/session/SessionStateToSend.java b/core/src/com/aqwsxlostfly/packandgo/session/SessionStateToSend.java index f10c157..0d33d0a 100644 --- a/core/src/com/aqwsxlostfly/packandgo/session/SessionStateToSend.java +++ b/core/src/com/aqwsxlostfly/packandgo/session/SessionStateToSend.java @@ -1,7 +1,5 @@ package com.aqwsxlostfly.packandgo.session; -import com.aqwsxlostfly.packandgo.session.SessionState; - public class SessionStateToSend implements SessionState { private String type; diff --git a/server/out/artifacts/packandgo_jar/packandgo.jar b/server/out/artifacts/packandgo_jar/packandgo.jar index b88983d..a86f1c1 100644 Binary files a/server/out/artifacts/packandgo_jar/packandgo.jar and b/server/out/artifacts/packandgo_jar/packandgo.jar differ diff --git a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Config/AppConfig.java b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Config/AppConfig.java index 24858b3..b813a1f 100644 --- a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Config/AppConfig.java +++ b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Config/AppConfig.java @@ -1,6 +1,7 @@ package com.aqwsxlostfly.packandgo.packandgo.Config; import com.aqwsxlostfly.packandgo.packandgo.GameLoop; +import com.aqwsxlostfly.packandgo.packandgo.GameStateTools.Furniture; import com.aqwsxlostfly.packandgo.packandgo.GameStateTools.Player; import com.aqwsxlostfly.packandgo.packandgo.Sessions.GameSessionToSend; import com.badlogic.gdx.backends.headless.HeadlessApplication; @@ -13,6 +14,10 @@ @Slf4j @Configuration public class AppConfig { + + public static final String PLAYER_STATE_SERVER = "player"; + public static final String FURNITURE_STATE_SERVER = "furniture"; + private static final String SESSION_ROOM_SERVER = "sessionRoom"; @Bean public HeadlessApplication getApplication(GameLoop gameLoop) { return new HeadlessApplication(gameLoop); @@ -22,8 +27,9 @@ public HeadlessApplication getApplication(GameLoop gameLoop) { public Json getJson() { Json json = new Json(); json.setOutputType(JsonWriter.OutputType.json); - json.addClassTag("player", Player.class); - json.addClassTag("sessionRoom", GameSessionToSend.class); + json.addClassTag(PLAYER_STATE_SERVER, Player.class); + json.addClassTag(FURNITURE_STATE_SERVER, Furniture.class); + json.addClassTag(SESSION_ROOM_SERVER, GameSessionToSend.class); return json; } } diff --git a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameLoop.java b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameLoop.java index c44a821..3d17073 100644 --- a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameLoop.java +++ b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameLoop.java @@ -1,5 +1,6 @@ package com.aqwsxlostfly.packandgo.packandgo; +import com.aqwsxlostfly.packandgo.packandgo.GameStateTools.Furniture; import com.aqwsxlostfly.packandgo.packandgo.GameStateTools.Player; import com.aqwsxlostfly.packandgo.packandgo.Sessions.GameSession; import com.aqwsxlostfly.packandgo.packandgo.Sessions.GameSessionManager; @@ -8,6 +9,7 @@ import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.Array; +import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.ObjectMap; import lombok.extern.slf4j.Slf4j; @@ -15,21 +17,24 @@ import org.springframework.stereotype.Component; import org.springframework.web.socket.adapter.standard.StandardWebSocketSession; - import java.io.IOException; import java.util.ArrayList; +import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; +import static com.aqwsxlostfly.packandgo.packandgo.Sessions.GameSessionManager.activeGameSessions; +import static com.aqwsxlostfly.packandgo.packandgo.Sessions.GameSessionManager.getAllUsersInSessionByUserId; + @Slf4j @Component public class GameLoop extends ApplicationAdapter { - private final MyWebSocketHandler socketHandler; + public static MyWebSocketHandler socketHandler; private final Json json; - private static final float frameRate = 1/50f; + private static final Object sendLock = new Object(); + private static final float frameRate = 1 / 50f; private float lastRender = 0; public static final ExecutorService threadPool = @@ -45,7 +50,7 @@ public class GameLoop extends ApplicationAdapter { private MessageDispatcher messageDispatcher; public GameLoop(MyWebSocketHandler socketHandler, Json json) { - this.socketHandler = socketHandler; + GameLoop.socketHandler = socketHandler; this.json = json; } @@ -58,7 +63,7 @@ public void create() { sendToEverybodyInSession( String.format(EVICT_MESSAGE, session.getId()), - gameSessionManager.getAllUsersInSessionByUserId(session.getId()) + getAllUsersInSessionByUserId(session.getId()) ); gameSessionManager.disconnectGameSession(session.getId()); @@ -78,7 +83,7 @@ public void render() { lastRender += currentTime; if (lastRender >= frameRate) { - ObjectMap sessionsCopy = new ObjectMap<>(gameSessionManager.getActiveGameSessions()); + ObjectMap sessionsCopy = new ObjectMap<>(activeGameSessions); for (ObjectMap.Entry gameSessionEntry : sessionsCopy.entries()) { GameSession gameSession = gameSessionEntry.value; @@ -93,17 +98,46 @@ public void render() { private void processGameSession(GameSession gameSession) { + processPlayers(gameSession); + processFurniture(gameSession); + } + + private void processFurniture(GameSession gameSession) { + Array stateToSend = new Array<>(); + for (Furniture furniture : gameSession.getGameState().getFurnitureObjectMap().values()) { + furniture.setId(furniture.getId()); + furniture.setY(furniture.getY()); + furniture.setX(furniture.getX()); + furniture.setHolding(furniture.isHolding()); + furniture.setHoldersCount(furniture.getHoldersCount()); + stateToSend.add(furniture); + } + try { + String stateJson = json.toJson(stateToSend); + ArrayList usersInSession = new ArrayList<>(gameSession.getActiveUserSessions().keySet()); + sendToEverybodyInSession(stateJson, usersInSession); + }catch (NullPointerException | GdxRuntimeException | IllegalStateException | NoSuchElementException e){ + // TODO + } + } + + private void processPlayers(GameSession gameSession) { Array stateToSend = new Array<>(); for (Player player : gameSession.getGameState().getPlayersObjectMap().values()) { player.setId(player.getId()); player.setY(player.getY()); player.setX(player.getX()); + player.setHolding(player.isHolding()); stateToSend.add(player); } - String stateJson = json.toJson(stateToSend); - ArrayList usersInSession = new ArrayList<>(gameSession.getActiveUserSessions().keySet()); - sendToEverybodyInSession(stateJson, usersInSession); + try { + String stateJson = json.toJson(stateToSend); + ArrayList usersInSession = new ArrayList<>(gameSession.getActiveUserSessions().keySet()); + sendToEverybodyInSession(stateJson, usersInSession); + }catch (NullPointerException | IllegalStateException | NoSuchElementException | GdxRuntimeException e){ + // TODO + } } private void sendToEverybody(String json) { @@ -123,27 +157,30 @@ private void sendToEverybody(String json) { private void sendMessage(String json, StandardWebSocketSession session) { threadPool.execute(() -> { - try { - if (session.isOpen()) { - session.getNativeSession().getBasicRemote().sendText(json); + synchronized (sendLock) { + try { + if (session.isOpen()) { + session.getNativeSession().getBasicRemote().sendText(json); + } + } catch (IOException e) { + e.printStackTrace(); } - } catch (IOException e) { - e.printStackTrace(); } - }); } - private void sendToEverybodyInSession(String json, ArrayList sessionIdsToSend) { + public static void sendToEverybodyInSession(String json, ArrayList sessionIdsToSend) { threadPool.execute(() -> { Array sessionsCopy = new Array<>(socketHandler.getSessions()); for (StandardWebSocketSession session : sessionsCopy) { - try { - if (session.isOpen() && sessionIdsToSend.contains(session.getId())) { - session.getNativeSession().getBasicRemote().sendText(json); + synchronized (sendLock) { + try { + if (session.isOpen() && sessionIdsToSend.contains(session.getId())) { + session.getNativeSession().getBasicRemote().sendText(json); + } + } catch (IOException e) { + e.printStackTrace(); } - } catch (IOException e) { - e.printStackTrace(); } } }); diff --git a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/Furniture.java b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/Furniture.java new file mode 100644 index 0000000..69e4f19 --- /dev/null +++ b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/Furniture.java @@ -0,0 +1,85 @@ +package com.aqwsxlostfly.packandgo.packandgo.GameStateTools; + +import com.badlogic.gdx.utils.Json; +import com.badlogic.gdx.utils.JsonValue; + +public class Furniture implements Json.Serializable { + private String id; + private float x; + private float y; + + private boolean isHolding; + + private int holdersCount; + + public void update(Float new_x, Float new_y, int holdersCount, boolean isHolding) { + this.isHolding = isHolding; + this.holdersCount = holdersCount; + this.x = new_x; + this.y = new_y; + } + + @Override + public void write(Json json) { + try { + json.writeValue("id", id); + json.writeValue("x", x); + json.writeValue("y", y); + json.writeValue("y", y); + json.writeValue("isHolding", isHolding); + json.writeValue("holdersCount", holdersCount); + }catch (IllegalStateException e) { + // Обработка исключения IllegalStateException + // TODO + } catch (NullPointerException e) { + // Обработка исключения NullPointerException + // TODO + } + + } + + @Override + public void read(Json json, JsonValue jsonData) { + + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public float getX() { + return x; + } + + public void setX(float x) { + this.x = x; + } + + public float getY() { + return y; + } + + public void setY(float y) { + this.y = y; + } + + public boolean isHolding() { + return isHolding; + } + + public void setHolding(boolean holding) { + isHolding = holding; + } + + public int getHoldersCount() { + return holdersCount; + } + + public void setHoldersCount(int holdersCount) { + this.holdersCount = holdersCount; + } +} diff --git a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/GameState.java b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/GameState.java index 1900063..cdfd14e 100644 --- a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/GameState.java +++ b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/GameState.java @@ -2,34 +2,67 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.ObjectMap; - import com.fasterxml.jackson.databind.JsonNode; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; +import static com.aqwsxlostfly.packandgo.packandgo.GameLoop.sendToEverybodyInSession; +import static com.aqwsxlostfly.packandgo.packandgo.Sessions.GameSessionManager.getAllUsersInSessionByUserId; +import static com.aqwsxlostfly.packandgo.packandgo.Sessions.MessageDispatcher.*; + @Slf4j @Component @Getter public class GameState { - private final ObjectMap playersObjectMap = new ObjectMap<>(); -// TODO -// public final ObjectMap furnitureObjectMap = new ObjectMap<>(); + private final ObjectMap playersObjectMap = new ObjectMap<>(); + public final ObjectMap furnitureObjectMap = new ObjectMap<>(); public void updateState(JsonNode state) { String type = state.get("type").asText(); switch (type) { - case "playerState": + case PLAYER_STATE -> { + String playerId = state.get("id").asText(); - float new_x = state.get("x").asLong(); - float new_y = state.get("y").asLong(); - updatePlayer(playerId, new_x, new_y); - break; - case "furnitureState": - // TODO - break; + float new_x_player = state.get("x").asLong(); + float new_y_player = state.get("y").asLong(); + boolean isHolding = state.get("holding").asBoolean(); + updatePlayer(playerId, new_x_player, new_y_player, isHolding); + } + case PLAYER_INTERACTION -> { + + String playerIdInter = state.get("id").asText(); + sendToEverybodyInSession(String.valueOf(state), getAllUsersInSessionByUserId(playerIdInter)); + } + case FURNITURE_STATE -> { + String furnitureId = state.get("id").asText(); + float new_x_furn = state.get("x").asLong(); + float new_y_furn = state.get("y").asLong(); + int holdersCount = state.get("holders").asInt(); + boolean isTaken = state.get("holding").asBoolean(); + + updateFurniture(furnitureId, new_x_furn, new_y_furn, holdersCount, isTaken); + + } + case PLAYER_STATE_DELETE -> { + String playerIdDelete = state.get("id").asText(); + if (playersObjectMap.containsKey(playerIdDelete)) { + playersObjectMap.remove(playerIdDelete); + } + } + } + } + + private void updateFurniture(String furnitureId, float new_x_furn, float new_y_furn, int holdersCount, boolean isHolding) { + if (this.furnitureObjectMap.containsKey(furnitureId)) { + this.furnitureObjectMap.get(furnitureId).update(new_x_furn, new_y_furn, holdersCount, isHolding); + } else { + addFurniture(furnitureId); + // TODO + Gdx.app.log("GAME STATE", "ADD NEW FURNITURE " + furnitureId); + } } @@ -56,6 +89,19 @@ public void addPlayer(String playerId) { } } + public void addFurniture(String furnId) { +// TODO +// check if input playerId is correct + if (!this.furnitureObjectMap.containsKey(furnId)) { + Furniture furniture = new Furniture(); + furniture.setId(furnId); + this.furnitureObjectMap.put(furnId, furniture); + } else { + // TODO + Gdx.app.log("GAME STATE", "ERROR ADDING PLAYER - PLAYER " + furnId + " EXISTS"); + } + } + public void evictPLayer(String playerId) { // TODO // check if input playerId is correct @@ -67,14 +113,16 @@ public void evictPLayer(String playerId) { } } - public void updatePlayer(String playerId, Float new_x, Float new_y) { + public void updatePlayer(String playerId, Float new_x, Float new_y, boolean isHolding) { // TODO // check if input playerId is correct if (this.playersObjectMap.containsKey(playerId)) { - this.playersObjectMap.get(playerId).update(new_x, new_y); + this.playersObjectMap.get(playerId).update(new_x, new_y, isHolding); } else { + + addPlayer(playerId); // TODO - Gdx.app.log("GAME STATE", "ERROR UPDATING PLAYER - PLAYER " + playerId + " DOES NOT EXISTS"); + Gdx.app.log("GAME STATE", "ADD PLAYER - PLAYER " + playerId + " DOES NOT EXISTS"); } } diff --git a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/Player.java b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/Player.java index 5447a65..5b2f928 100644 --- a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/Player.java +++ b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/GameStateTools/Player.java @@ -8,16 +8,28 @@ public class Player implements Json.Serializable { private float x; private float y; - public void update(Float new_x, Float new_y) { + private boolean isHolding; + + public void update(Float new_x, Float new_y, boolean isHolding) { + this.isHolding = isHolding; this.x = new_x; this.y = new_y; } @Override public void write(Json json) { - json.writeValue("id", id); - json.writeValue("x", x); - json.writeValue("y", y); + try { + json.writeValue("id", id); + json.writeValue("x", x); + json.writeValue("y", y); + json.writeValue("isHolding", isHolding); + }catch (IllegalStateException e) { + // Обработка исключения IllegalStateException + // TODO + } catch (NullPointerException e) { + // Обработка исключения NullPointerException + // TODO + } } @Override @@ -49,4 +61,11 @@ public void setY(float y) { this.y = y; } + public boolean isHolding() { + return isHolding; + } + + public void setHolding(boolean holding) { + isHolding = holding; + } } diff --git a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Sessions/GameSessionManager.java b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Sessions/GameSessionManager.java index 18467b8..80ff360 100644 --- a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Sessions/GameSessionManager.java +++ b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Sessions/GameSessionManager.java @@ -25,9 +25,9 @@ @Getter public class GameSessionManager { - private final ConcurrentHashMap userToSession = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap userToSession = new ConcurrentHashMap<>(); - private final ObjectMap activeGameSessions = new ObjectMap<>(); + public static final ObjectMap activeGameSessions = new ObjectMap<>(); private final Json json; @@ -42,11 +42,12 @@ public GameSessionManager(Json json) { this.json = json; } - public String getSessionIdByUserId(String userSessionId) { + public static String getSessionIdByUserId(String userSessionId) { return userToSession.getOrDefault(userSessionId, null); } + public void updateGameSession(String userId, JsonNode state) { String sessionId = getSessionIdByUserId(userId); @@ -101,9 +102,25 @@ public void createGameSession(String userId, String sessionId, String sessionPas sendSessionState(sessionPassword, sessionId, SESSION_STATE_OK, session); } else { - // TODO - Gdx.app.log("ADD SESSION", "ERROR ADDING SESSION - SESSION " + sessionId + " EXISTS"); - sendSessionState(sessionPassword, sessionId, SESSION_STATE_EXISTS, session); + if (userToSession.containsKey(userId) && !activeGameSessions.containsKey(sessionId)) { + + disconnectGameSession(userId); + + GameState gameState = new GameState(); + GameSession gameSession = new GameSession(sessionId, sessionPassword, userLimit, gameState); + gameSession.addUserSession(userId); + + activeGameSessions.put(sessionId, gameSession); + userToSession.put(userId, sessionId); + + Gdx.app.log("CREATED_GAME_SESSION", gameSession.toString()); + + sendSessionState(sessionPassword, sessionId, SESSION_STATE_OK, session); + }else{ + // TODO + Gdx.app.log("ADD SESSION", "ERROR ADDING SESSION - SESSION " + sessionId + " EXISTS"); + sendSessionState(sessionPassword, sessionId, SESSION_STATE_EXISTS, session); + } } } @@ -137,6 +154,7 @@ public void disconnectGameSession(String userId) { activeGameSessions.get(sessionId).removeUserSession(userId); activeGameSessions.remove(sessionId); userToSession.remove(userId); + Gdx.app.log("DELETED_GAME_SESSION", sessionId); } else { activeGameSessions.get(sessionId).removeUserSession(userId); } @@ -147,7 +165,7 @@ public void disconnectGameSession(String userId) { } } - public ArrayList getAllUsersInSessionByUserId(String userId) { + public static ArrayList getAllUsersInSessionByUserId(String userId) { String sessionId = getSessionIdByUserId(userId); GameSession session = activeGameSessions.get(sessionId); @@ -160,5 +178,4 @@ public ArrayList getAllUsersInSessionByUserId(String userId) { return new ArrayList<>(usersInSession.keySet()); } - } diff --git a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Sessions/MessageDispatcher.java b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Sessions/MessageDispatcher.java index d913926..17e5cc7 100644 --- a/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Sessions/MessageDispatcher.java +++ b/server/src/main/java/com/aqwsxlostfly/packandgo/packandgo/Sessions/MessageDispatcher.java @@ -13,6 +13,15 @@ @Getter public class MessageDispatcher { + public static final String CREATE_ROOM = "createRoom"; + public static final String JOIN_ROOM = "joinRoom"; + public static final String PLAYER_STATE = "playerState"; + public static final String PLAYER_STATE_DELETE = "playerStateDelete"; + public static final String FURNITURE_STATE = "furnitureState"; + public static final String PLAYER_INTERACTION = "playerInteraction"; + public static final String SESSION_PASSWORD = "sessionPassword"; + public static final String SESSION_ID = "sessionId"; + @Autowired private GameSessionManager gameSessionManager; @@ -21,17 +30,18 @@ public void processMessage(StandardWebSocketSession session, JsonNode message) { String userId = session.getId(); String type = message.get("type").asText(); switch (type) { - case "createRoom" -> { - String sessionId = message.get("sessionId").asText(); - String sessionPassword = message.get("sessionPassword").asText(); + case CREATE_ROOM -> { + String sessionId = message.get(SESSION_ID).asText(); + String sessionPassword = message.get(SESSION_PASSWORD).asText(); gameSessionManager.createGameSession(userId, sessionId, sessionPassword, 2, session); } - case "joinRoom" -> { - String sessionJoinId = message.get("sessionId").asText(); - String sessionJoinPassword = message.get("sessionPassword").asText(); + case JOIN_ROOM -> { + String sessionJoinId = message.get(SESSION_ID).asText(); + String sessionJoinPassword = message.get(SESSION_PASSWORD).asText(); gameSessionManager.joinGameSession(userId, sessionJoinId, sessionJoinPassword, session); } - case "playerState", "furnitureState" -> gameSessionManager.updateGameSession(userId, message); + case PLAYER_STATE, FURNITURE_STATE, PLAYER_INTERACTION, PLAYER_STATE_DELETE -> + gameSessionManager.updateGameSession(userId, message); default -> throw new RuntimeException("Unknown WS object type: " + type); }