From 2bc268b05389add788d3a5669f3eff954526d465 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Mon, 20 Feb 2023 15:41:13 +0100 Subject: [PATCH 01/50] refactor(utils): :recycle: refactor utility classes such as GameMode, EntityType, Settings, ... This is a refactoring of the classes in Utils : - EntityType - GameMode - GameVariableNames - Settings The other files are refactored for calling the new classes in Utils package. --- .../Component/AlienComponent.java | 30 +++---- .../Component/BulletComponent.java | 10 +-- .../Component/LifeComponent.java | 14 ++-- .../Component/PlayerComponent.java | 24 +++--- .../Component/ShootingSmokeComponent.java | 10 +-- .../Component/ShootingStartComponent.java | 6 +- .../Component/SpaceInvadersFactory.java | 29 +++---- .../Core/AlienBulletCollision.java | 3 +- .../Core/AlienPlayerCollision.java | 3 +- .../Core/BulletBulletCollision.java | 2 +- .../Core/BulletPlayerCollision.java | 3 +- .../Core/EnemyShootBulletCollision.java | 2 +- .../Core/EnemyShootPlayerCollision.java | 3 +- .../org/enstabretagne/Game/GameLauncher.java | 79 ++++++++++--------- .../org/enstabretagne/Game/NewMainMenu.java | 11 +-- .../{Component => Utils}/EntityType.java | 2 +- .../{Game => Utils}/GameMode.java | 2 +- .../{Core => Utils}/GameVariableNames.java | 2 +- .../Constant.java => Utils/Settings.java} | 4 +- .../org/enstabretagne/Utils/assetNames.java | 8 +- .../Component/AlienComponentTest.java | 5 +- .../Component/BulletComponentTest.java | 2 + .../Component/PlayerComponentTest.java | 5 +- .../Core/AlienBulletCollisionTest.java | 1 + .../Core/AlienPlayerCollisionTest.java | 2 +- 25 files changed, 136 insertions(+), 126 deletions(-) rename duelinvaders/src/main/java/org/enstabretagne/{Component => Utils}/EntityType.java (83%) rename duelinvaders/src/main/java/org/enstabretagne/{Game => Utils}/GameMode.java (83%) rename duelinvaders/src/main/java/org/enstabretagne/{Core => Utils}/GameVariableNames.java (95%) rename duelinvaders/src/main/java/org/enstabretagne/{Core/Constant.java => Utils/Settings.java} (97%) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java index 36e740c..519aaa8 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java @@ -1,8 +1,8 @@ package org.enstabretagne.Component; -import org.enstabretagne.Core.Constant; -import org.enstabretagne.Core.Constant.Direction; +import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.entityNames; +import org.enstabretagne.Utils.Settings.Direction; import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.entity.Entity; @@ -22,7 +22,7 @@ public class AlienComponent extends Component { private Direction movementDirection; private Direction globalDirection; private Double last_shot = 0.0; - private double limit_right = Constant.GAME_WIDTH; + private double limit_right = Settings.GAME_WIDTH; private double limit_left = 0.0; /** @@ -54,12 +54,12 @@ public AlienComponent() { * Initialise l'alien * */ - public void initialize(Constant.Direction direction) { + public void initialize(Settings.Direction direction) { this.globalDirection = direction; - if (direction == Constant.Direction.UP) { + if (direction == Settings.Direction.UP) { entity.rotateBy(180); this.movementDirection = Direction.RIGHT; - } else if (direction == Constant.Direction.DOWN) { + } else if (direction == Settings.Direction.DOWN) { this.movementDirection = Direction.LEFT; } @@ -72,7 +72,7 @@ public void initialize(Constant.Direction direction) { */ @Override public void onUpdate(double tpf) { - dx = tpf * Constant.SPEED_ALIEN; + dx = tpf * Settings.SPEED_ALIEN; dy = entity.getHeight(); this.move(dx); } @@ -99,9 +99,9 @@ public void moveRight(Double dx) { if (this.entity.getRightX() + dx <= limit_right) { this.entity.translateX(dx); } else { - if (this.globalDirection == Constant.Direction.DOWN) { + if (this.globalDirection == Settings.Direction.DOWN) { this.entity.translateY(dy); - } else if (this.globalDirection == Constant.Direction.UP) { + } else if (this.globalDirection == Settings.Direction.UP) { this.entity.translateY(-dy); } this.movementDirection = Direction.LEFT; @@ -117,9 +117,9 @@ public void moveLeft(Double dx) { if (this.entity.getX() - dx >= limit_left) { this.entity.translateX(-dx); } else { - if (this.globalDirection == Constant.Direction.DOWN) { + if (this.globalDirection == Settings.Direction.DOWN) { this.entity.translateY(dy); - } else if (this.globalDirection == Constant.Direction.UP) { + } else if (this.globalDirection == Settings.Direction.UP) { this.entity.translateY(-dy); } this.movementDirection = Direction.RIGHT; @@ -127,8 +127,8 @@ public void moveLeft(Double dx) { } public void setAlienNumber(int AlienNumber) { - limit_right = Constant.GAME_WIDTH - (Constant.ALIEN_WIDTH * (Constant.ALIENS_NUMBER - AlienNumber - 1)); - limit_left = 0.0 + (Constant.ALIEN_WIDTH * AlienNumber); + limit_right = Settings.GAME_WIDTH - (Settings.ALIEN_WIDTH * (Settings.ALIENS_NUMBER - AlienNumber - 1)); + limit_left = 0.0 + (Settings.ALIEN_WIDTH * AlienNumber); } /** @@ -146,13 +146,13 @@ public void randomShoot(double chance) { * L'alien tire un projectile à une cadence définie dans {@code}Constant{@code}. */ public void shoot() { - Boolean canShoot = getGameTimer().getNow() - last_shot.doubleValue() >= Constant.RATE_ALIEN_SHOOT.doubleValue(); + Boolean canShoot = getGameTimer().getNow() - last_shot.doubleValue() >= Settings.RATE_ALIEN_SHOOT.doubleValue(); if (!canShoot) return; double x = this.entity.getX() + this.entity.getWidth() / 2; double y = this.entity.getY(); - if (this.globalDirection == Constant.Direction.DOWN) + if (this.globalDirection == Settings.Direction.DOWN) y += this.entity.getHeight(); spawn(entityNames.ECLAT, x, y); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/BulletComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/BulletComponent.java index 8661d25..ef900ac 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/BulletComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/BulletComponent.java @@ -1,6 +1,6 @@ package org.enstabretagne.Component; -import org.enstabretagne.Core.Constant; +import org.enstabretagne.Utils.Settings; import com.almasb.fxgl.dsl.components.ExpireCleanComponent; import com.almasb.fxgl.dsl.components.ProjectileComponent; @@ -17,8 +17,8 @@ * @since 0.1.0 */ public class BulletComponent extends Component { - private Double speed = Constant.SPEED_SHOOT; - private Duration duration = Constant.BULLET_DURATION; + private Double speed = Settings.SPEED_SHOOT; + private Duration duration = Settings.BULLET_DURATION; private Point2D direction = new Point2D(0, -1); private int playerId; @@ -41,8 +41,8 @@ public BulletComponent() { * Ce sont des composants prédéfinis dans la librairie FXGL qui facilite la * création de projectiles */ - public void initialize(Constant.Direction UporDown) { - this.direction = new Point2D(0, UporDown == Constant.Direction.UP ? -1 : 1); + public void initialize(Settings.Direction UporDown) { + this.direction = new Point2D(0, UporDown == Settings.Direction.UP ? -1 : 1); this.entity.addComponent(new ProjectileComponent(direction, speed)); this.entity.addComponent(new ExpireCleanComponent(duration)); } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/LifeComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/LifeComponent.java index 56e7aea..a599d1f 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/LifeComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/LifeComponent.java @@ -1,6 +1,6 @@ package org.enstabretagne.Component; -import org.enstabretagne.Core.Constant; +import org.enstabretagne.Utils.Settings; import com.almasb.fxgl.entity.component.Component; @@ -15,13 +15,13 @@ public class LifeComponent extends Component { /** * Initialise le composant affichage de vie */ - public void initialize(Constant.Direction direction) { - if (direction == Constant.Direction.UP) { - entity.setX(Constant.GAME_WIDTH - Constant.LIFE_DISPLAY_WIDTH); + public void initialize(Settings.Direction direction) { + if (direction == Settings.Direction.UP) { + entity.setX(Settings.GAME_WIDTH - Settings.LIFE_DISPLAY_WIDTH); entity.setY(0); - } else if (direction == Constant.Direction.DOWN) { - entity.setX(Constant.GAME_WIDTH - Constant.LIFE_DISPLAY_WIDTH); - entity.setY(Constant.GAME_HEIGHT - Constant.LIFE_DISPLAY_HEIGHT); + } else if (direction == Settings.Direction.DOWN) { + entity.setX(Settings.GAME_WIDTH - Settings.LIFE_DISPLAY_WIDTH); + entity.setY(Settings.GAME_HEIGHT - Settings.LIFE_DISPLAY_HEIGHT); } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java index 21456f6..eed370d 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java @@ -5,15 +5,15 @@ import static com.almasb.fxgl.dsl.FXGL.runOnce; import static com.almasb.fxgl.dsl.FXGL.set; import static com.almasb.fxgl.dsl.FXGL.spawn; -import static org.enstabretagne.Core.Constant.DELAY_BETWEEN_SHOOT; -import static org.enstabretagne.Core.Constant.GAME_WIDTH; -import static org.enstabretagne.Core.Constant.PLAYER_HEIGHT; -import static org.enstabretagne.Core.Constant.SPEED_SPACESHIP; +import static org.enstabretagne.Utils.Settings.DELAY_BETWEEN_SHOOT; +import static org.enstabretagne.Utils.Settings.GAME_WIDTH; +import static org.enstabretagne.Utils.Settings.PLAYER_HEIGHT; +import static org.enstabretagne.Utils.Settings.SPEED_SPACESHIP; -import org.enstabretagne.Core.Constant; -import org.enstabretagne.Core.Constant.Direction; -import org.enstabretagne.Core.GameVariableNames; +import org.enstabretagne.Utils.GameVariableNames; +import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.entityNames; +import org.enstabretagne.Utils.Settings.Direction; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.entity.component.Component; @@ -31,7 +31,7 @@ public class PlayerComponent extends Component { private Double dx; private Double last_shot = 0.0; private Direction side_shoot = Direction.LEFT; - private Constant.Direction direction = Constant.Direction.UP; + private Settings.Direction direction = Settings.Direction.UP; private int id; private static int counter; @@ -51,8 +51,8 @@ public PlayerComponent() { * * @param direction */ - public void setDirection(Constant.Direction direction) { - if (direction == Constant.Direction.LEFT || direction == Constant.Direction.RIGHT) + public void setDirection(Settings.Direction direction) { + if (direction == Settings.Direction.LEFT || direction == Settings.Direction.RIGHT) return; if (this.direction == direction) return; @@ -109,7 +109,7 @@ private Point2D calculateShootPosition() { int decalage = 20; int shift_x; int shift_y; - if (this.direction == Constant.Direction.UP) { + if (this.direction == Settings.Direction.UP) { shift_y = -decalage; } else { shift_y = PLAYER_HEIGHT.intValue() + decalage; @@ -140,7 +140,7 @@ private void createBullet(Point2D position) { * Simule le recul du vaisseau lors du tir */ private void shootingRecoil() { - if (this.direction == Constant.Direction.DOWN) { + if (this.direction == Settings.Direction.DOWN) { this.entity.translateY(-10); runOnce(() -> this.entity.translateY(10), Duration.seconds(0.1)); } else if (this.direction == Direction.UP) { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/ShootingSmokeComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/ShootingSmokeComponent.java index 38db5bc..d0215d0 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/ShootingSmokeComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/ShootingSmokeComponent.java @@ -1,8 +1,8 @@ package org.enstabretagne.Component; -import static org.enstabretagne.Core.Constant.SMOKE_DURATION; +import static org.enstabretagne.Utils.Settings.SMOKE_DURATION; -import org.enstabretagne.Core.Constant; +import org.enstabretagne.Utils.Settings; import com.almasb.fxgl.dsl.components.ExpireCleanComponent; import com.almasb.fxgl.entity.component.Component; @@ -20,11 +20,11 @@ public class ShootingSmokeComponent extends Component { * * @param direction */ - public void initialize(Constant.Direction direction) { + public void initialize(Settings.Direction direction) { this.entity.addComponent(new ExpireCleanComponent(SMOKE_DURATION)); - double dx = Constant.SHOOTING_SMOKE_WIDTH / 2; + double dx = Settings.SHOOTING_SMOKE_WIDTH / 2; double dy = 30; - if (direction == Constant.Direction.DOWN) { + if (direction == Settings.Direction.DOWN) { this.entity.rotateBy(180); this.entity.translate(dx, dy); } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/ShootingStartComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/ShootingStartComponent.java index 6665f1f..76abf5b 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/ShootingStartComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/ShootingStartComponent.java @@ -1,9 +1,9 @@ package org.enstabretagne.Component; -import static org.enstabretagne.Core.Constant.FIRE_DURATION; -import static org.enstabretagne.Core.Constant.SHOOTING_START_WIDTH; +import static org.enstabretagne.Utils.Settings.FIRE_DURATION; +import static org.enstabretagne.Utils.Settings.SHOOTING_START_WIDTH; -import org.enstabretagne.Core.Constant.Direction; +import org.enstabretagne.Utils.Settings.Direction; import com.almasb.fxgl.dsl.components.ExpireCleanComponent; import com.almasb.fxgl.entity.component.Component; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/SpaceInvadersFactory.java b/duelinvaders/src/main/java/org/enstabretagne/Component/SpaceInvadersFactory.java index b018c3f..7b00368 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/SpaceInvadersFactory.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/SpaceInvadersFactory.java @@ -5,7 +5,8 @@ import static com.almasb.fxgl.dsl.FXGL.spawn; import static com.almasb.fxgl.dsl.FXGL.texture; -import org.enstabretagne.Core.Constant; +import org.enstabretagne.Utils.EntityType; +import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.assetNames; import org.enstabretagne.Utils.entityNames; @@ -37,7 +38,7 @@ public class SpaceInvadersFactory implements EntityFactory { */ @Spawns(entityNames.PLAYER) public Entity newPlayer(SpawnData data) { - Texture texture = texture(assetNames.textures.SPACESHIP, Constant.PLAYER_WIDTH, Constant.PLAYER_HEIGHT); + Texture texture = texture(assetNames.textures.SPACESHIP, Settings.PLAYER_WIDTH, Settings.PLAYER_HEIGHT); return entityBuilder() .type(EntityType.PLAYER) @@ -56,11 +57,11 @@ public Entity newPlayer(SpawnData data) { */ @Spawns(entityNames.ALIEN) public Entity newAlien(SpawnData data) { - int randomIndex = Constant.random.nextInt(Constant.AlienColor.values().length); - Constant.AlienColor randomColor = Constant.AlienColor.values()[randomIndex]; + int randomIndex = Settings.random.nextInt(Settings.AlienColor.values().length); + Settings.AlienColor randomColor = Settings.AlienColor.values()[randomIndex]; Color color = Color.valueOf(randomColor.name()); - Texture texture = texture(assetNames.textures.ALIEN, Constant.ALIEN_WIDTH, Constant.ALIEN_HEIGHT) + Texture texture = texture(assetNames.textures.ALIEN, Settings.ALIEN_WIDTH, Settings.ALIEN_HEIGHT) .multiplyColor(color); return entityBuilder() .type(EntityType.ALIEN) @@ -109,7 +110,7 @@ public Entity newAlienBullet(SpawnData data) { int laserHeight = 20; Texture texture = texture(assetNames.textures.LASER, laserWidth, laserHeight); String randomLaserSound = assetNames.sounds.LASER_SOUNDS - .get(FXGLMath.random(0, Constant.NUMBER_OF_LASER_SOUNDS - 1)); + .get(FXGLMath.random(0, Settings.NUMBER_OF_LASER_SOUNDS - 1)); play(randomLaserSound); return entityBuilder() @@ -152,7 +153,7 @@ public Entity newEclat(SpawnData data) { public Entity newBackground(SpawnData data) { return entityBuilder() .at(-10, -10) - .view(texture(assetNames.textures.GAME_BACKGROUND, Constant.GAME_WIDTH + 20, Constant.GAME_HEIGHT + 20)) + .view(texture(assetNames.textures.GAME_BACKGROUND, Settings.GAME_WIDTH + 20, Settings.GAME_HEIGHT + 20)) .zIndex(-500) .build(); } @@ -166,8 +167,8 @@ public Entity newBackground(SpawnData data) { */ @Spawns(entityNames.SHOOTING_START) public Entity shooting_start(SpawnData data) { - Texture texture = texture(assetNames.textures.FIRE, Constant.SHOOTING_START_WIDTH, - Constant.SHOOTING_START_HEIGHT); + Texture texture = texture(assetNames.textures.FIRE, Settings.SHOOTING_START_WIDTH, + Settings.SHOOTING_START_HEIGHT); texture.setRotate(180); return entityBuilder() @@ -186,8 +187,8 @@ public Entity shooting_start(SpawnData data) { */ @Spawns(entityNames.SHOOTING_SMOKE) public Entity shooting_smoke(SpawnData data) { - Texture texture = texture(assetNames.textures.SMOKE, Constant.SHOOTING_SMOKE_WIDTH, - Constant.SHOOTING_SMOKE_HEIGHT); + Texture texture = texture(assetNames.textures.SMOKE, Settings.SHOOTING_SMOKE_WIDTH, + Settings.SHOOTING_SMOKE_HEIGHT); return entityBuilder() .at(data.getX(), data.getY()) .view(texture) @@ -207,7 +208,7 @@ public Entity explosion_alien(SpawnData data) { int explosion_width = 60; int explosion_height = 60; String randomTexture = assetNames.textures.EXPLOSIONS - .get(FXGLMath.random(0, Constant.NUMBER_OF_EXPLOSIONS - 1)); + .get(FXGLMath.random(0, Settings.NUMBER_OF_EXPLOSIONS - 1)); Texture texture = texture(randomTexture, explosion_width, explosion_height); return entityBuilder() .at(data.getX(), data.getY()) @@ -271,8 +272,8 @@ public Entity explosion_player_death(SpawnData data) { @Spawns(entityNames.LIFE) public Entity life(SpawnData data) { int x = (int) data.getX(); - Texture texture = texture(assetNames.textures.LIFES.get(x - 1), Constant.LIFE_DISPLAY_WIDTH, - Constant.LIFE_DISPLAY_HEIGHT); + Texture texture = texture(assetNames.textures.LIFES.get(x - 1), Settings.LIFE_DISPLAY_WIDTH, + Settings.LIFE_DISPLAY_HEIGHT); return entityBuilder() .at(data.getX(), data.getY()) .view(texture) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/AlienBulletCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Core/AlienBulletCollision.java index 67d16c9..ffb1997 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/AlienBulletCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Core/AlienBulletCollision.java @@ -6,8 +6,9 @@ import static com.almasb.fxgl.dsl.FXGL.spawn; import org.enstabretagne.Component.BulletComponent; -import org.enstabretagne.Component.EntityType; import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.EntityType; +import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.assetNames; import org.enstabretagne.Utils.entityNames; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/AlienPlayerCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Core/AlienPlayerCollision.java index 178a50b..5dbbbdc 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/AlienPlayerCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Core/AlienPlayerCollision.java @@ -4,7 +4,8 @@ import static com.almasb.fxgl.dsl.FXGL.set; import static com.almasb.fxgl.dsl.FXGL.spawn; -import org.enstabretagne.Component.EntityType; +import org.enstabretagne.Utils.EntityType; +import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.assetNames; import org.enstabretagne.Utils.entityNames; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/BulletBulletCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Core/BulletBulletCollision.java index 90ad40a..f9a528c 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/BulletBulletCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Core/BulletBulletCollision.java @@ -3,7 +3,7 @@ import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.spawn; -import org.enstabretagne.Component.EntityType; +import org.enstabretagne.Utils.EntityType; import org.enstabretagne.Utils.assetNames; import org.enstabretagne.Utils.entityNames; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/BulletPlayerCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Core/BulletPlayerCollision.java index 1ea4c44..8c6449a 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/BulletPlayerCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Core/BulletPlayerCollision.java @@ -6,8 +6,9 @@ import static com.almasb.fxgl.dsl.FXGL.set; import static com.almasb.fxgl.dsl.FXGL.spawn; -import org.enstabretagne.Component.EntityType; import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.EntityType; +import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.assetNames; import org.enstabretagne.Utils.entityNames; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootBulletCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootBulletCollision.java index b0c9534..9ef37a3 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootBulletCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootBulletCollision.java @@ -3,7 +3,7 @@ import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.spawn; -import org.enstabretagne.Component.EntityType; +import org.enstabretagne.Utils.EntityType; import org.enstabretagne.Utils.assetNames; import org.enstabretagne.Utils.entityNames; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootPlayerCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootPlayerCollision.java index 431770b..5a717cb 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootPlayerCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootPlayerCollision.java @@ -5,8 +5,9 @@ import static com.almasb.fxgl.dsl.FXGL.set; import static com.almasb.fxgl.dsl.FXGL.spawn; -import org.enstabretagne.Component.EntityType; import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.EntityType; +import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.assetNames; import org.enstabretagne.Utils.entityNames; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index c5dd3d5..683eed0 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -13,9 +13,9 @@ import static com.almasb.fxgl.dsl.FXGL.run; import static com.almasb.fxgl.dsl.FXGL.spawn; import static com.almasb.fxgl.dsl.FXGL.texture; -import static org.enstabretagne.Game.GameMode.CLASSIQUE; -import static org.enstabretagne.Game.GameMode.INFINITY_MODE; -import static org.enstabretagne.Game.GameMode.SOLO; +import static org.enstabretagne.Utils.GameMode.CLASSIQUE; +import static org.enstabretagne.Utils.GameMode.INFINITY_MODE; +import static org.enstabretagne.Utils.GameMode.SOLO; import java.util.ArrayList; import java.util.Arrays; @@ -25,17 +25,18 @@ import java.util.stream.Collectors; import org.enstabretagne.Component.AlienComponent; -import org.enstabretagne.Component.EntityType; import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Component.SpaceInvadersFactory; import org.enstabretagne.Core.AlienBulletCollision; import org.enstabretagne.Core.AlienPlayerCollision; import org.enstabretagne.Core.BulletBulletCollision; import org.enstabretagne.Core.BulletPlayerCollision; -import org.enstabretagne.Core.Constant; import org.enstabretagne.Core.EnemyShootBulletCollision; import org.enstabretagne.Core.EnemyShootPlayerCollision; -import org.enstabretagne.Core.GameVariableNames; +import org.enstabretagne.Utils.EntityType; +import org.enstabretagne.Utils.GameMode; +import org.enstabretagne.Utils.GameVariableNames; +import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.assetNames; import org.enstabretagne.Utils.entityNames; @@ -69,8 +70,8 @@ public class GameLauncher extends GameApplication { private Entity player1; private Entity player2; private long last_ambient_sound = System.currentTimeMillis(); - private int delay_ambient_sound = FXGLMath.random(Constant.AMBIENT_SOUND_DELAY_MIN, - Constant.AMBIENT_SOUND_DELAY_MAX); + private int delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, + Settings.AMBIENT_SOUND_DELAY_MAX); private static GameMode GameMode = CLASSIQUE; VBox playersUI = new VBox(); @@ -85,8 +86,8 @@ public static void setGameMode(GameMode gameMode) { */ @Override protected void initSettings(GameSettings settings) { - settings.setWidth(Constant.GAME_WIDTH.intValue()); - settings.setHeight(Constant.GAME_HEIGHT.intValue()); + settings.setWidth(Settings.GAME_WIDTH.intValue()); + settings.setHeight(Settings.GAME_HEIGHT.intValue()); settings.setTitle("Duel Invaders"); settings.setAppIcon(assetNames.textures.APP_ICON); settings.setVersion("0.2.0"); @@ -184,36 +185,36 @@ protected void initGame() { getGameWorld().addEntityFactory(new SpaceInvadersFactory()); player1 = spawn(entityNames.PLAYER); - player1.setX(Constant.GAME_WIDTH / 2); - player1.setY(Constant.GAME_HEIGHT - player1.getHeight()); + player1.setX(Settings.GAME_WIDTH / 2); + player1.setY(Settings.GAME_HEIGHT - player1.getHeight()); playerComponent1 = player1.getComponent(PlayerComponent.class); - playerComponent1.setDirection(Constant.Direction.UP); + playerComponent1.setDirection(Settings.Direction.UP); playerComponent1.initializeScore(); playerComponent1.initializeLife(); if (GameMode != SOLO) { player2 = spawn(entityNames.PLAYER); - player2.setX(Constant.GAME_WIDTH / 2); + player2.setX(Settings.GAME_WIDTH / 2); player2.setY(0); playerComponent2 = player2.getComponent(PlayerComponent.class); - playerComponent2.setDirection(Constant.Direction.DOWN); + playerComponent2.setDirection(Settings.Direction.DOWN); playerComponent2.initializeScore(); playerComponent2.initializeLife(); } if (GameMode == INFINITY_MODE) { // spawn Aliens pour infinity mode - Entity alien1 = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); - alien1.getComponent(AlienComponent.class).initialize(Constant.Direction.UP); - Entity alien2 = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); - alien2.getComponent(AlienComponent.class).initialize(Constant.Direction.DOWN); + Entity alien1 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); + alien1.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); + Entity alien2 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); + alien2.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); run(() -> { - Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Constant.Direction.UP); + Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); }, Duration.seconds(1.4)); run(() -> { - Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Constant.Direction.DOWN); + Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); }, Duration.seconds(1.5)); } else if (GameMode == CLASSIQUE) { @@ -228,21 +229,21 @@ protected void initGame() { private void makeAlienBlock() { for (int i = 0; i < 2; i++) { - makeAlienLine(i, Constant.Direction.DOWN); - makeAlienLine(i, Constant.Direction.UP); + makeAlienLine(i, Settings.Direction.DOWN); + makeAlienLine(i, Settings.Direction.UP); } } - private void makeAlienLine(int line, Constant.Direction direction) { - for (int i = 0; i < Constant.ALIENS_NUMBER; i++) { - if (direction == Constant.Direction.DOWN) { - Entity alien = spawn(entityNames.ALIEN, i * Constant.ALIEN_WIDTH, - Constant.GAME_HEIGHT / 2 + (line - 1) * Constant.ALIEN_HEIGHT); + private void makeAlienLine(int line, Settings.Direction direction) { + for (int i = 0; i < Settings.ALIENS_NUMBER; i++) { + if (direction == Settings.Direction.DOWN) { + Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, + Settings.GAME_HEIGHT / 2 + (line - 1) * Settings.ALIEN_HEIGHT); alien.getComponent(AlienComponent.class).initialize(direction); alien.getComponent(AlienComponent.class).setAlienNumber(i); } else { - Entity alien = spawn(entityNames.ALIEN, i * Constant.ALIEN_WIDTH, - Constant.GAME_HEIGHT / 2 + (line - 2) * Constant.ALIEN_HEIGHT); + Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, + Settings.GAME_HEIGHT / 2 + (line - 2) * Settings.ALIEN_HEIGHT); alien.getComponent(AlienComponent.class).initialize(direction); alien.getComponent(AlienComponent.class).setAlienNumber(i); } @@ -251,9 +252,9 @@ private void makeAlienLine(int line, Constant.Direction direction) { private void makeAlienBlockSolo() { for (int line = 0; line < 4; line++) { - for (int k = 0; k < Constant.ALIENS_NUMBER; k++) { - Entity alien = spawn(entityNames.ALIEN, k * Constant.ALIEN_WIDTH, (line - 1) * Constant.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Constant.Direction.DOWN); + for (int k = 0; k < Settings.ALIENS_NUMBER; k++) { + Entity alien = spawn(entityNames.ALIEN, k * Settings.ALIEN_WIDTH, (line - 1) * Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); alien.getComponent(AlienComponent.class).setAlienNumber(k); } } @@ -331,16 +332,16 @@ protected void onUpdate(double tpf) { if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { ambientSound(); last_ambient_sound = System.currentTimeMillis(); - delay_ambient_sound = FXGLMath.random(Constant.AMBIENT_SOUND_DELAY_MIN, Constant.AMBIENT_SOUND_DELAY_MAX); + delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); } if (getGameScene().getContentRoot().getChildren().contains(playersUI)) showPlayersLivesAndScores(); run(() -> { getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { if (FXGLMath.randomBoolean(0.01)) - alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); + alien.getComponent(AlienComponent.class).randomShoot(Settings.ALIEN_SHOOT_CHANCE); }); - }, Duration.seconds(Constant.random.nextDouble() * 10)); + }, Duration.seconds(Settings.random.nextDouble() * 10)); } /** @@ -390,7 +391,7 @@ private void winScreen() { */ private void ambientSound() { String ambientMusic = assetNames.sounds.AMBIENT_SOUNDS - .get(FXGLMath.random(0, Constant.NUMBER_OF_AMBIENT_SOUND - 1)); + .get(FXGLMath.random(0, Settings.NUMBER_OF_AMBIENT_SOUND - 1)); play(ambientMusic); } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java index b9e5f3c..88f12dd 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java @@ -5,7 +5,8 @@ import static com.almasb.fxgl.dsl.FXGL.getWindowService; import static com.almasb.fxgl.dsl.FXGL.texture; -import org.enstabretagne.Core.Constant; +import org.enstabretagne.Utils.GameMode; +import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.assetNames; import com.almasb.fxgl.app.scene.FXGLMenu; @@ -44,7 +45,7 @@ public NewMainMenu() { var titleBox = new HBox(title); titleBox.setAlignment(Pos.CENTER); titleBox.setTranslateY(100); - titleBox.setTranslateX(Constant.GAME_WIDTH / 2 - title.getLayoutBounds().getWidth() / 2); + titleBox.setTranslateX(Settings.GAME_WIDTH / 2 - title.getLayoutBounds().getWidth() / 2); var pauseText = getUIFactoryService().newText("PAUSE", Color.WHITE, 20); var pauseKey = new KeyView(KeyCode.ESCAPE, Color.BLUE, 20.0); @@ -113,7 +114,7 @@ private VBox createMenu() { new Separator(Orientation.HORIZONTAL), getUIFactoryService().newText("Select Game Mode", Color.WHITE, 22)); box.setTranslateX(100); - box.setTranslateY(Constant.GAME_HEIGHT / 2); + box.setTranslateY(Settings.GAME_HEIGHT / 2); box.setAlignment(Pos.CENTER); return box; } @@ -138,7 +139,7 @@ private VBox createOptions() { var soundBox = new HBox(10, soundText, soundSlider); var box = new VBox(10, musicBox, soundBox); box.setTranslateX(getAppHeight() / 2 + 100); - box.setTranslateY(Constant.GAME_HEIGHT / 2); + box.setTranslateY(Settings.GAME_HEIGHT / 2); musicBox.setAlignment(Pos.CENTER); soundBox.setAlignment(Pos.CENTER); box.setAlignment(Pos.CENTER); @@ -163,7 +164,7 @@ private FXGLTextFlow createCredits() { FXGLTextFlow creditsText = getUIFactoryService().newTextFlow(); creditsText.append(creditsString, Color.GRAY, 16); creditsText.setTranslateX(getAppHeight() / 2 + 100); - creditsText.setTranslateY(Constant.GAME_HEIGHT / 2); + creditsText.setTranslateY(Settings.GAME_HEIGHT / 2); return creditsText; } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/EntityType.java b/duelinvaders/src/main/java/org/enstabretagne/Utils/EntityType.java similarity index 83% rename from duelinvaders/src/main/java/org/enstabretagne/Component/EntityType.java rename to duelinvaders/src/main/java/org/enstabretagne/Utils/EntityType.java index 7dcad8c..8196817 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/EntityType.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Utils/EntityType.java @@ -1,4 +1,4 @@ -package org.enstabretagne.Component; +package org.enstabretagne.Utils; /** * Définition des types d'entités disponibles dans le jeu diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameMode.java similarity index 83% rename from duelinvaders/src/main/java/org/enstabretagne/Game/GameMode.java rename to duelinvaders/src/main/java/org/enstabretagne/Utils/GameMode.java index 057c3cf..35a321f 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameMode.java @@ -1,4 +1,4 @@ -package org.enstabretagne.Game; +package org.enstabretagne.Utils; /** * Modes de jeu disponibles diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/GameVariableNames.java b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java similarity index 95% rename from duelinvaders/src/main/java/org/enstabretagne/Core/GameVariableNames.java rename to duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java index 6b48aac..7c9091f 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/GameVariableNames.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java @@ -1,4 +1,4 @@ -package org.enstabretagne.Core; +package org.enstabretagne.Utils; /** * Classe contenant les noms des variables de jeu diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/Constant.java b/duelinvaders/src/main/java/org/enstabretagne/Utils/Settings.java similarity index 97% rename from duelinvaders/src/main/java/org/enstabretagne/Core/Constant.java rename to duelinvaders/src/main/java/org/enstabretagne/Utils/Settings.java index 2c9e7ef..e46bfb0 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/Constant.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Utils/Settings.java @@ -1,4 +1,4 @@ -package org.enstabretagne.Core; +package org.enstabretagne.Utils; import javafx.util.Duration; import java.util.Random; @@ -11,7 +11,7 @@ * @author jufch, LBF38, MathieuDFS * @since 0.1.0 */ -public class Constant { +public class Settings { public static final Double GAME_WIDTH = 1366.0; public static final Double GAME_HEIGHT = 768.0; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Utils/assetNames.java b/duelinvaders/src/main/java/org/enstabretagne/Utils/assetNames.java index a2f3344..123da82 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Utils/assetNames.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Utils/assetNames.java @@ -2,8 +2,6 @@ import java.util.ArrayList; -import org.enstabretagne.Core.Constant; - /** * Classe contenant les noms des assets du jeu * Cela permet d'éviter les risques de fautes de frappe et centralise l'ensemble @@ -27,7 +25,7 @@ public static class textures { public static final String EXPLOSION_FINAL = "explosion_final.png"; public static final ArrayList EXPLOSIONS = new ArrayList() { { - for (int i = 1; i <= Constant.NUMBER_OF_EXPLOSIONS; i++) { + for (int i = 1; i <= Settings.NUMBER_OF_EXPLOSIONS; i++) { add("explosion" + i + ".png"); } } @@ -62,7 +60,7 @@ public static class sounds { public static final String VICTORY_CLAIRON = "autre/claironVictory.wav"; public static final ArrayList AMBIENT_SOUNDS = new ArrayList() { { - for (int i = 1; i < Constant.NUMBER_OF_AMBIENT_SOUND + 1; i++) { + for (int i = 1; i < Settings.NUMBER_OF_AMBIENT_SOUND + 1; i++) { add("ambiance/ambientSound" + i + ".wav"); } } @@ -70,7 +68,7 @@ public static class sounds { public static final String CANNON_SHOT = "Tir/canon.wav"; public static final ArrayList LASER_SOUNDS = new ArrayList<>() { { - for (int i = 1; i <= Constant.NUMBER_OF_LASER_SOUNDS; i++) { + for (int i = 1; i <= Settings.NUMBER_OF_LASER_SOUNDS; i++) { add("Tir/laser" + i + ".wav"); } } diff --git a/duelinvaders/src/test/java/org/enstabretagne/Component/AlienComponentTest.java b/duelinvaders/src/test/java/org/enstabretagne/Component/AlienComponentTest.java index 337873f..a3055ed 100644 --- a/duelinvaders/src/test/java/org/enstabretagne/Component/AlienComponentTest.java +++ b/duelinvaders/src/test/java/org/enstabretagne/Component/AlienComponentTest.java @@ -1,6 +1,7 @@ package org.enstabretagne.Component; -import org.enstabretagne.Core.Constant; +import org.enstabretagne.Utils.EntityType; +import org.enstabretagne.Utils.Settings; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; @@ -12,7 +13,7 @@ public class AlienComponentTest { @BeforeEach public void setup() { - alienComponent = new AlienComponent(Constant.Direction.DOWN); + alienComponent = new AlienComponent(Settings.Direction.DOWN); entityBuilder() .type(EntityType.ALIEN) .at(0, 0) diff --git a/duelinvaders/src/test/java/org/enstabretagne/Component/BulletComponentTest.java b/duelinvaders/src/test/java/org/enstabretagne/Component/BulletComponentTest.java index b058855..afd9a50 100644 --- a/duelinvaders/src/test/java/org/enstabretagne/Component/BulletComponentTest.java +++ b/duelinvaders/src/test/java/org/enstabretagne/Component/BulletComponentTest.java @@ -5,6 +5,8 @@ import static com.almasb.fxgl.dsl.FXGL.entityBuilder; import static org.junit.jupiter.api.Assertions.*; +import org.enstabretagne.Utils.EntityType; + public class BulletComponentTest { private BulletComponent bulletComponent; // private Double dy = 1.0; diff --git a/duelinvaders/src/test/java/org/enstabretagne/Component/PlayerComponentTest.java b/duelinvaders/src/test/java/org/enstabretagne/Component/PlayerComponentTest.java index 9e4de69..db1c048 100644 --- a/duelinvaders/src/test/java/org/enstabretagne/Component/PlayerComponentTest.java +++ b/duelinvaders/src/test/java/org/enstabretagne/Component/PlayerComponentTest.java @@ -1,6 +1,7 @@ package org.enstabretagne.Component; -import org.enstabretagne.Core.Constant; +import org.enstabretagne.Utils.EntityType; +import org.enstabretagne.Utils.Settings; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; @@ -8,7 +9,7 @@ public class PlayerComponentTest { private PlayerComponent playerComponent; - private Double dx = Constant.SPEED_SPACESHIP; + private Double dx = Settings.SPEED_SPACESHIP; @BeforeEach public void setup() { diff --git a/duelinvaders/src/test/java/org/enstabretagne/Core/AlienBulletCollisionTest.java b/duelinvaders/src/test/java/org/enstabretagne/Core/AlienBulletCollisionTest.java index 9961e77..ae36042 100644 --- a/duelinvaders/src/test/java/org/enstabretagne/Core/AlienBulletCollisionTest.java +++ b/duelinvaders/src/test/java/org/enstabretagne/Core/AlienBulletCollisionTest.java @@ -8,6 +8,7 @@ // import static org.junit.jupiter.api.Assertions.*; import org.enstabretagne.Component.*; +import org.enstabretagne.Utils.EntityType; // import static com.almasb.fxgl.dsl.FXGL.*; diff --git a/duelinvaders/src/test/java/org/enstabretagne/Core/AlienPlayerCollisionTest.java b/duelinvaders/src/test/java/org/enstabretagne/Core/AlienPlayerCollisionTest.java index dec722e..7bb38f7 100644 --- a/duelinvaders/src/test/java/org/enstabretagne/Core/AlienPlayerCollisionTest.java +++ b/duelinvaders/src/test/java/org/enstabretagne/Core/AlienPlayerCollisionTest.java @@ -1,8 +1,8 @@ package org.enstabretagne.Core; import org.enstabretagne.Component.AlienComponent; -import org.enstabretagne.Component.EntityType; import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.EntityType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; From 937040f6b14b64706823542b356d0a5e321f0c78 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Mon, 20 Feb 2023 17:12:31 +0100 Subject: [PATCH 02/50] refactor(collision): :recycle: refactor core package to collisions as it only have collisions It is only a refactor, no logic change. Only the package name is changed. --- .../enstabretagne/{Core => Collision}/AlienBulletCollision.java | 2 +- .../enstabretagne/{Core => Collision}/AlienPlayerCollision.java | 2 +- .../{Core => Collision}/BulletBulletCollision.java | 2 +- .../{Core => Collision}/BulletPlayerCollision.java | 2 +- .../{Core => Collision}/EnemyShootBulletCollision.java | 2 +- .../{Core => Collision}/EnemyShootPlayerCollision.java | 2 +- .../java/org/enstabretagne/Core/AlienBulletCollisionTest.java | 1 + .../java/org/enstabretagne/Core/AlienPlayerCollisionTest.java | 1 + 8 files changed, 8 insertions(+), 6 deletions(-) rename duelinvaders/src/main/java/org/enstabretagne/{Core => Collision}/AlienBulletCollision.java (98%) rename duelinvaders/src/main/java/org/enstabretagne/{Core => Collision}/AlienPlayerCollision.java (97%) rename duelinvaders/src/main/java/org/enstabretagne/{Core => Collision}/BulletBulletCollision.java (96%) rename duelinvaders/src/main/java/org/enstabretagne/{Core => Collision}/BulletPlayerCollision.java (98%) rename duelinvaders/src/main/java/org/enstabretagne/{Core => Collision}/EnemyShootBulletCollision.java (96%) rename duelinvaders/src/main/java/org/enstabretagne/{Core => Collision}/EnemyShootPlayerCollision.java (97%) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/AlienBulletCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Collision/AlienBulletCollision.java similarity index 98% rename from duelinvaders/src/main/java/org/enstabretagne/Core/AlienBulletCollision.java rename to duelinvaders/src/main/java/org/enstabretagne/Collision/AlienBulletCollision.java index ffb1997..2a03a03 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/AlienBulletCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Collision/AlienBulletCollision.java @@ -1,4 +1,4 @@ -package org.enstabretagne.Core; +package org.enstabretagne.Collision; import static com.almasb.fxgl.dsl.FXGL.getGameWorld; import static com.almasb.fxgl.dsl.FXGL.play; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/AlienPlayerCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Collision/AlienPlayerCollision.java similarity index 97% rename from duelinvaders/src/main/java/org/enstabretagne/Core/AlienPlayerCollision.java rename to duelinvaders/src/main/java/org/enstabretagne/Collision/AlienPlayerCollision.java index 5dbbbdc..e9a826b 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/AlienPlayerCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Collision/AlienPlayerCollision.java @@ -1,4 +1,4 @@ -package org.enstabretagne.Core; +package org.enstabretagne.Collision; import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.set; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/BulletBulletCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Collision/BulletBulletCollision.java similarity index 96% rename from duelinvaders/src/main/java/org/enstabretagne/Core/BulletBulletCollision.java rename to duelinvaders/src/main/java/org/enstabretagne/Collision/BulletBulletCollision.java index f9a528c..c565c20 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/BulletBulletCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Collision/BulletBulletCollision.java @@ -1,4 +1,4 @@ -package org.enstabretagne.Core; +package org.enstabretagne.Collision; import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.spawn; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/BulletPlayerCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Collision/BulletPlayerCollision.java similarity index 98% rename from duelinvaders/src/main/java/org/enstabretagne/Core/BulletPlayerCollision.java rename to duelinvaders/src/main/java/org/enstabretagne/Collision/BulletPlayerCollision.java index 8c6449a..861f51d 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/BulletPlayerCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Collision/BulletPlayerCollision.java @@ -1,5 +1,5 @@ -package org.enstabretagne.Core; +package org.enstabretagne.Collision; import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.runOnce; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootBulletCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootBulletCollision.java similarity index 96% rename from duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootBulletCollision.java rename to duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootBulletCollision.java index 9ef37a3..10b0d2f 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootBulletCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootBulletCollision.java @@ -1,4 +1,4 @@ -package org.enstabretagne.Core; +package org.enstabretagne.Collision; import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.spawn; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootPlayerCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootPlayerCollision.java similarity index 97% rename from duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootPlayerCollision.java rename to duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootPlayerCollision.java index 5a717cb..43dd1c6 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/EnemyShootPlayerCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootPlayerCollision.java @@ -1,5 +1,5 @@ -package org.enstabretagne.Core; +package org.enstabretagne.Collision; import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.set; diff --git a/duelinvaders/src/test/java/org/enstabretagne/Core/AlienBulletCollisionTest.java b/duelinvaders/src/test/java/org/enstabretagne/Core/AlienBulletCollisionTest.java index ae36042..10d8669 100644 --- a/duelinvaders/src/test/java/org/enstabretagne/Core/AlienBulletCollisionTest.java +++ b/duelinvaders/src/test/java/org/enstabretagne/Core/AlienBulletCollisionTest.java @@ -6,6 +6,7 @@ import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.entity.GameWorld; +import org.enstabretagne.Collision.AlienBulletCollision; // import static org.junit.jupiter.api.Assertions.*; import org.enstabretagne.Component.*; import org.enstabretagne.Utils.EntityType; diff --git a/duelinvaders/src/test/java/org/enstabretagne/Core/AlienPlayerCollisionTest.java b/duelinvaders/src/test/java/org/enstabretagne/Core/AlienPlayerCollisionTest.java index 7bb38f7..3acb28d 100644 --- a/duelinvaders/src/test/java/org/enstabretagne/Core/AlienPlayerCollisionTest.java +++ b/duelinvaders/src/test/java/org/enstabretagne/Core/AlienPlayerCollisionTest.java @@ -1,5 +1,6 @@ package org.enstabretagne.Core; +import org.enstabretagne.Collision.AlienPlayerCollision; import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.EntityType; From f36d7bf5393246367ebda6915cba356bb0eadfcf Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Mon, 20 Feb 2023 17:25:39 +0100 Subject: [PATCH 03/50] Added a TCP connection between two instances of the game Added a MULTI game mode Added a button to launch the Multi game mode in the main menu Added a pop-up to select your role (server or client) Added a connection between servers and clients (fixed port) --- .../org/enstabretagne/Game/GameLauncher.java | 57 +++++++++++++------ .../java/org/enstabretagne/Game/GameMode.java | 2 +- .../org/enstabretagne/Game/NewMainMenu.java | 10 +++- 3 files changed, 48 insertions(+), 21 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index c5dd3d5..570d202 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -1,21 +1,8 @@ package org.enstabretagne.Game; -import static com.almasb.fxgl.dsl.FXGL.getDialogService; -import static com.almasb.fxgl.dsl.FXGL.getGameController; -import static com.almasb.fxgl.dsl.FXGL.getGameScene; -import static com.almasb.fxgl.dsl.FXGL.getGameWorld; -import static com.almasb.fxgl.dsl.FXGL.getPhysicsWorld; -import static com.almasb.fxgl.dsl.FXGL.getUIFactoryService; -import static com.almasb.fxgl.dsl.FXGL.getb; -import static com.almasb.fxgl.dsl.FXGL.loopBGM; -import static com.almasb.fxgl.dsl.FXGL.onKey; -import static com.almasb.fxgl.dsl.FXGL.play; -import static com.almasb.fxgl.dsl.FXGL.run; -import static com.almasb.fxgl.dsl.FXGL.spawn; -import static com.almasb.fxgl.dsl.FXGL.texture; -import static org.enstabretagne.Game.GameMode.CLASSIQUE; -import static org.enstabretagne.Game.GameMode.INFINITY_MODE; -import static org.enstabretagne.Game.GameMode.SOLO; +import static com.almasb.fxgl.dsl.FXGL.*; +import static com.almasb.fxgl.dsl.FXGLForKtKt.runOnce; +import static org.enstabretagne.Game.GameMode.*; import java.util.ArrayList; import java.util.Arrays; @@ -24,6 +11,8 @@ import java.util.Map; import java.util.stream.Collectors; +import com.almasb.fxgl.core.serialization.Bundle; +import com.almasb.fxgl.net.Server; import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.EntityType; import org.enstabretagne.Component.PlayerComponent; @@ -77,6 +66,8 @@ public class GameLauncher extends GameApplication { public static void setGameMode(GameMode gameMode) { GameMode = gameMode; } + private boolean isServer; + private Server server; /** * Initialisation des paramètres du jeu @@ -93,7 +84,7 @@ protected void initSettings(GameSettings settings) { settings.setMainMenuEnabled(true); settings.setGameMenuEnabled(true); settings.setFullScreenAllowed(true); - settings.setFullScreenFromStart(true); +// settings.setFullScreenFromStart(true); settings.setCredits(Arrays.asList( "Duel Invaders project by:", "@MathieuDFS", @@ -180,6 +171,10 @@ protected void initGameVars(Map vars) { */ @Override protected void initGame() { + serverLogic(); + if(GameMode == MULTI) { + isServer(); + } play(assetNames.sounds.START_CLAIRON); getGameWorld().addEntityFactory(new SpaceInvadersFactory()); @@ -226,6 +221,34 @@ protected void initGame() { loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); } + private void isServer(){ + runOnce(() -> { + getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { + if (yes) { + isServer = true; + server = getNetService().newTCPServer(55555); // todo -> selection du port + server.startAsync(); + } else { + isServer = false; + var client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port + + // todo -> logique du client + + client.connectAsync(); + } + }); + return null; + },Duration.seconds(0.1)); + } + + private void serverLogic(){ //todo -> logique du serveur + var data = new Bundle("Player1"); + data.put("message", "value"); + + if(isServer) + server.broadcast(data); + } + private void makeAlienBlock() { for (int i = 0; i < 2; i++) { makeAlienLine(i, Constant.Direction.DOWN); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameMode.java index 057c3cf..07828c5 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameMode.java @@ -7,5 +7,5 @@ * @since 0.2.0 */ public enum GameMode { - CLASSIQUE, INFINITY_MODE, SOLO, MUSIC_DEMO + CLASSIQUE, INFINITY_MODE, SOLO, MUSIC_DEMO,MULTI } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java index b9e5f3c..e88a07e 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java @@ -80,6 +80,11 @@ private VBox createMenu() { fireNewGame(); }); + SpaceButton buttonMultiMode = new SpaceButton("Play multi", () -> { + GameLauncher.setGameMode(GameMode.MULTI); + fireNewGame(); + }); + SpaceButton buttonMusicDemo = new SpaceButton("Play Music Demo", () -> { GameLauncher.setGameMode(GameMode.MUSIC_DEMO); fireNewGame(); @@ -105,6 +110,7 @@ private VBox createMenu() { buttonClassicMode, buttonInfinityMode, buttonSoloMode, + buttonMultiMode, buttonMusicDemo, buttonOption, buttonCredit, @@ -169,9 +175,7 @@ private FXGLTextFlow createCredits() { /** * Define the button - * - * @param name - * @param action + * * @return SpaceButton * @see SpaceButton * @see StackPane From cdca91e7f491b64d88a174fe5523520e604533bc Mon Sep 17 00:00:00 2001 From: LBF38 Date: Mon, 20 Feb 2023 20:06:08 +0100 Subject: [PATCH 04/50] refactor(GameMode): :recycle: refactor code for easier game mode implementation I refactored the game modes in a simple class. Also created an interface for the game modes. The GameLauncher now uses the GameMode class to launch the game. It only depends on the GameMode interface. WIP : the game isn't working yet. Some important fixes need to be made. The inputs aren't correctly working for now. --- .../org/enstabretagne/Game/GameLauncher.java | 157 +++++++----------- .../Game/GameModes/ClassicGameMode.java | 116 +++++++++++++ .../Game/GameModes/GameMode.java | 9 + .../org/enstabretagne/Game/NewMainMenu.java | 10 +- .../{GameMode.java => GameModeTypes.java} | 4 +- 5 files changed, 188 insertions(+), 108 deletions(-) create mode 100644 duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java create mode 100644 duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java rename duelinvaders/src/main/java/org/enstabretagne/Utils/{GameMode.java => GameModeTypes.java} (60%) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 683eed0..92cae57 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -8,14 +8,10 @@ import static com.almasb.fxgl.dsl.FXGL.getUIFactoryService; import static com.almasb.fxgl.dsl.FXGL.getb; import static com.almasb.fxgl.dsl.FXGL.loopBGM; -import static com.almasb.fxgl.dsl.FXGL.onKey; import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.run; import static com.almasb.fxgl.dsl.FXGL.spawn; import static com.almasb.fxgl.dsl.FXGL.texture; -import static org.enstabretagne.Utils.GameMode.CLASSIQUE; -import static org.enstabretagne.Utils.GameMode.INFINITY_MODE; -import static org.enstabretagne.Utils.GameMode.SOLO; import java.util.ArrayList; import java.util.Arrays; @@ -24,17 +20,19 @@ import java.util.Map; import java.util.stream.Collectors; +import org.enstabretagne.Collision.AlienBulletCollision; +import org.enstabretagne.Collision.AlienPlayerCollision; +import org.enstabretagne.Collision.BulletBulletCollision; +import org.enstabretagne.Collision.BulletPlayerCollision; +import org.enstabretagne.Collision.EnemyShootBulletCollision; +import org.enstabretagne.Collision.EnemyShootPlayerCollision; import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Component.SpaceInvadersFactory; -import org.enstabretagne.Core.AlienBulletCollision; -import org.enstabretagne.Core.AlienPlayerCollision; -import org.enstabretagne.Core.BulletBulletCollision; -import org.enstabretagne.Core.BulletPlayerCollision; -import org.enstabretagne.Core.EnemyShootBulletCollision; -import org.enstabretagne.Core.EnemyShootPlayerCollision; +import org.enstabretagne.Game.GameModes.ClassicGameMode; +import org.enstabretagne.Game.GameModes.GameMode; import org.enstabretagne.Utils.EntityType; -import org.enstabretagne.Utils.GameMode; +import org.enstabretagne.Utils.GameModeTypes; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.assetNames; @@ -50,7 +48,6 @@ import com.almasb.fxgl.entity.Entity; import javafx.geometry.Pos; -import javafx.scene.input.KeyCode; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; @@ -65,18 +62,18 @@ * @since 0.1.0 */ public class GameLauncher extends GameApplication { - private PlayerComponent playerComponent1; - private PlayerComponent playerComponent2; - private Entity player1; - private Entity player2; + private static GameMode game_mode = new ClassicGameMode(); private long last_ambient_sound = System.currentTimeMillis(); private int delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); - private static GameMode GameMode = CLASSIQUE; VBox playersUI = new VBox(); public static void setGameMode(GameMode gameMode) { - GameMode = gameMode; + game_mode = gameMode; + } + + public static GameModeTypes getGameModeType() { + return game_mode.getGameModeType(); } /** @@ -94,7 +91,7 @@ protected void initSettings(GameSettings settings) { settings.setMainMenuEnabled(true); settings.setGameMenuEnabled(true); settings.setFullScreenAllowed(true); - settings.setFullScreenFromStart(true); + // settings.setFullScreenFromStart(true); settings.setCredits(Arrays.asList( "Duel Invaders project by:", "@MathieuDFS", @@ -126,42 +123,7 @@ public FXGLMenu newMainMenu() { */ @Override protected void initInput() { - onKey(KeyCode.ENTER, () -> { - playerComponent1.shoot(); - }); - - onKey(KeyCode.RIGHT, () -> { - playerComponent1.moveRight(); - }); - - onKey(KeyCode.LEFT, () -> { - playerComponent1.moveLeft(); - }); - - onKey(KeyCode.SPACE, () -> { - if (GameMode == SOLO) { - playerComponent1.shoot(); - } else { - playerComponent2.shoot(); - } - }); - - onKey(KeyCode.D, () -> { - if (GameMode == SOLO) { - playerComponent1.moveRight(); - } else { - playerComponent2.moveRight(); - } - }); - - onKey(KeyCode.Q, () -> { - if (GameMode == SOLO) { - playerComponent1.moveLeft(); - } else { - playerComponent2.moveLeft(); - } - }); - + super.initInput(); } /** @@ -184,44 +146,37 @@ protected void initGame() { play(assetNames.sounds.START_CLAIRON); getGameWorld().addEntityFactory(new SpaceInvadersFactory()); - player1 = spawn(entityNames.PLAYER); - player1.setX(Settings.GAME_WIDTH / 2); - player1.setY(Settings.GAME_HEIGHT - player1.getHeight()); - playerComponent1 = player1.getComponent(PlayerComponent.class); - playerComponent1.setDirection(Settings.Direction.UP); - playerComponent1.initializeScore(); - playerComponent1.initializeLife(); - - if (GameMode != SOLO) { - player2 = spawn(entityNames.PLAYER); - player2.setX(Settings.GAME_WIDTH / 2); - player2.setY(0); - playerComponent2 = player2.getComponent(PlayerComponent.class); - playerComponent2.setDirection(Settings.Direction.DOWN); - playerComponent2.initializeScore(); - playerComponent2.initializeLife(); + game_mode.initGameMode(); + try { + game_mode.initInput(); + } catch (Exception exception) { + System.out.println("Erreur lors de l'initialisation des inputs : " + exception.getMessage()); } - if (GameMode == INFINITY_MODE) { - // spawn Aliens pour infinity mode - Entity alien1 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); - alien1.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); - Entity alien2 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); - alien2.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); - run(() -> { - Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); - }, Duration.seconds(1.4)); - run(() -> { - Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); - }, Duration.seconds(1.5)); - - } else if (GameMode == CLASSIQUE) { - makeAlienBlock(); - } else if (GameMode == SOLO) { - makeAlienBlockSolo(); - } + // if (GameModeType == INFINITY_MODE) { + // // spawn Aliens pour infinity mode + // Entity alien1 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - + // Settings.ALIEN_HEIGHT); + // alien1.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); + // Entity alien2 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - + // Settings.ALIEN_HEIGHT); + // alien2.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); + // run(() -> { + // Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - + // Settings.ALIEN_HEIGHT); + // alien.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); + // }, Duration.seconds(1.4)); + // run(() -> { + // Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - + // Settings.ALIEN_HEIGHT); + // alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); + // }, Duration.seconds(1.5)); + + // } else if (GameModeType == CLASSIQUE) { + // makeAlienBlock(); + // } else if (GameModeType == SOLO) { + // makeAlienBlockSolo(); + // } spawn(entityNames.BACKGROUND); loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); @@ -325,9 +280,9 @@ private HBox createLifeUI(int life) { @Override protected void onUpdate(double tpf) { if (getb(GameVariableNames.isGameOver)) - gameOverScreen(); + gameOverScreen("to refactor", "to refactor"); // TODO : refactor if (getb(GameVariableNames.isGameWon)) - winScreen(); + winScreen("to refactor", "to refactor"); // TODO : refactor if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { ambientSound(); @@ -347,12 +302,12 @@ protected void onUpdate(double tpf) { /** * Affichage de l'écran de fin de partie */ - private void gameOverScreen() { + private void gameOverScreen(String score_player1, String score_player2) { play(assetNames.sounds.DEFEAT_CLAIRON); String message = "Game Over ! \n Scores are as follows : \n" + - "Player 1 : " + playerComponent1.getScore() + "\n"; - if (playerComponent2 != null) { - String player2 = "Player 2 : " + playerComponent2.getScore(); + "Player 1 : " + score_player1 + "\n"; + if (score_player2 != null) { + String player2 = "Player 2 : " + score_player2; message += player2; } getDialogService().showMessageBox(message, () -> { @@ -373,12 +328,12 @@ private void playAgain(Boolean yes) { /** * Affichage de l'écran de victoire */ - private void winScreen() { + private void winScreen(String score_player1, String score_player2) { play(assetNames.sounds.VICTORY_CLAIRON); String message = "You won ! \n Scores are as follows : \n" + - "Player 1 : " + playerComponent1.getScore() + "\n"; - if (playerComponent2 != null) { - String player2 = "Player 2 : " + playerComponent2.getScore(); + "Player 1 : " + score_player1 + "\n"; + if (score_player2 != null) { + String player2 = "Player 2 : " + score_player2; message += player2; } getDialogService().showMessageBox(message, () -> { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java new file mode 100644 index 0000000..ebb1fdf --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java @@ -0,0 +1,116 @@ +package org.enstabretagne.Game.GameModes; + +import org.enstabretagne.Component.AlienComponent; +import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.GameModeTypes; +import org.enstabretagne.Utils.Settings; +import org.enstabretagne.Utils.entityNames; + +import com.almasb.fxgl.entity.Entity; + +import javafx.scene.input.KeyCode; + +import static com.almasb.fxgl.dsl.FXGL.*; + +public class ClassicGameMode implements GameMode { + private PlayerComponent playerComponent1; + private PlayerComponent playerComponent2; + private Entity player1; + private Entity player2; + private GameModeTypes gameModeType = GameModeTypes.CLASSIQUE; + + @Override + public void initGameMode() { + initPlayer1(); + initPlayer2(); + makeAlienBlock(); + } + + private void initPlayer1() { + player1 = spawn(entityNames.PLAYER); + player1.setX(Settings.GAME_WIDTH / 2); + player1.setY(Settings.GAME_HEIGHT - player1.getHeight()); + playerComponent1 = player1.getComponent(PlayerComponent.class); + playerComponent1.setDirection(Settings.Direction.UP); + playerComponent1.initializeScore(); + playerComponent1.initializeLife(); + } + + private void initPlayer2() { + player2 = spawn(entityNames.PLAYER); + player2.setX(Settings.GAME_WIDTH / 2); + player2.setY(0); + playerComponent2 = player2.getComponent(PlayerComponent.class); + playerComponent2.setDirection(Settings.Direction.DOWN); + playerComponent2.initializeScore(); + playerComponent2.initializeLife(); + } + + @Override + public void initInput() { + // TODO: Implementer les touches de jeu avec getInput. + // getInput().addAction(game_mode.getMoveLeft(), game_mode.getMoveLeftAction()); + // getInput().addAction(() -> playerComponent1.moveLeft(), KeyCode.LEFT); + if (playerComponent1 == null || playerComponent2 == null) { + System.out.println("No PlayerComponent"); + return; + } else { + System.out.println("PlayerComponent OK"); + } + + onKey(KeyCode.ENTER, () -> { + playerComponent1.shoot(); + }); + + onKey(KeyCode.RIGHT, () -> { + playerComponent1.moveRight(); + }); + + onKey(KeyCode.LEFT, () -> { + playerComponent1.moveLeft(); + }); + + onKey(KeyCode.SPACE, () -> { + playerComponent2.shoot(); + }); + + onKey(KeyCode.D, () -> { + playerComponent2.moveRight(); + }); + + onKey(KeyCode.Q, () -> { + playerComponent2.moveLeft(); + }); + + } + + // Getters and Setters + @Override + public GameModeTypes getGameModeType() { + return gameModeType; + } + + // Methods + private void makeAlienBlock() { + for (int i = 0; i < 2; i++) { + makeAlienLine(i, Settings.Direction.DOWN); + makeAlienLine(i, Settings.Direction.UP); + } + } + + private void makeAlienLine(int line, Settings.Direction direction) { + for (int i = 0; i < Settings.ALIENS_NUMBER; i++) { + if (direction == Settings.Direction.DOWN) { + Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, + Settings.GAME_HEIGHT / 2 + (line - 1) * Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(direction); + alien.getComponent(AlienComponent.class).setAlienNumber(i); + } else { + Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, + Settings.GAME_HEIGHT / 2 + (line - 2) * Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(direction); + alien.getComponent(AlienComponent.class).setAlienNumber(i); + } + } + } +} diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java new file mode 100644 index 0000000..b051830 --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java @@ -0,0 +1,9 @@ +package org.enstabretagne.Game.GameModes; + +import org.enstabretagne.Utils.GameModeTypes; + +public interface GameMode { + public void initGameMode(); + public void initInput(); + public GameModeTypes getGameModeType(); +} \ No newline at end of file diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java index 88f12dd..86f0064 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java @@ -5,7 +5,7 @@ import static com.almasb.fxgl.dsl.FXGL.getWindowService; import static com.almasb.fxgl.dsl.FXGL.texture; -import org.enstabretagne.Utils.GameMode; +import org.enstabretagne.Game.GameModes.ClassicGameMode; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.assetNames; @@ -67,22 +67,22 @@ private VBox createMenu() { FXGLTextFlow creditsText = createCredits(); SpaceButton buttonClassicMode = new SpaceButton("Play Classique", () -> { - GameLauncher.setGameMode(GameMode.CLASSIQUE); + GameLauncher.setGameMode(new ClassicGameMode()); fireNewGame(); }); SpaceButton buttonInfinityMode = new SpaceButton("Play Infinity", () -> { - GameLauncher.setGameMode(GameMode.INFINITY_MODE); + GameLauncher.setGameMode(new ClassicGameMode()); // TODO: change for infinity mode fireNewGame(); }); SpaceButton buttonSoloMode = new SpaceButton("Play Solo", () -> { - GameLauncher.setGameMode(GameMode.SOLO); + GameLauncher.setGameMode(new ClassicGameMode()); // TODO: change for solo mode fireNewGame(); }); SpaceButton buttonMusicDemo = new SpaceButton("Play Music Demo", () -> { - GameLauncher.setGameMode(GameMode.MUSIC_DEMO); + GameLauncher.setGameMode(new ClassicGameMode()); // TODO: change for music demo mode fireNewGame(); }); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java similarity index 60% rename from duelinvaders/src/main/java/org/enstabretagne/Utils/GameMode.java rename to duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java index 35a321f..0ebecec 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java @@ -6,6 +6,6 @@ * @author LBF38, MathieuDFS, jufch * @since 0.2.0 */ -public enum GameMode { - CLASSIQUE, INFINITY_MODE, SOLO, MUSIC_DEMO +public enum GameModeTypes { + CLASSIQUE, INFINITY_MODE, SOLO, MUSIC_DEMO, MULTI } From 00f2801ed3efc63a4d17d391eed8205dcc397201 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Mon, 27 Feb 2023 14:13:28 +0100 Subject: [PATCH 05/50] refactor(GameMode): :recycle: refactor inputs in GameMode The inputs are working but we have a lack of performance. --- .../org/enstabretagne/Game/GameLauncher.java | 6 +- .../Game/GameModes/ClassicGameMode.java | 79 +++++++++++++------ .../Game/GameModes/GameMode.java | 5 +- 3 files changed, 61 insertions(+), 29 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 92cae57..8f1a82b 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -124,6 +124,7 @@ public FXGLMenu newMainMenu() { @Override protected void initInput() { super.initInput(); + game_mode.initInput(getGameScene().getInput()); } /** @@ -148,9 +149,10 @@ protected void initGame() { game_mode.initGameMode(); try { - game_mode.initInput(); + game_mode.rebindInput(getGameScene().getInput()); } catch (Exception exception) { - System.out.println("Erreur lors de l'initialisation des inputs : " + exception.getMessage()); + System.out.println("Erreur lors de l'initialisation des inputs : " + + exception.getMessage()); } // if (GameModeType == INFINITY_MODE) { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java index ebb1fdf..fe6181f 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java @@ -7,6 +7,8 @@ import org.enstabretagne.Utils.entityNames; import com.almasb.fxgl.entity.Entity; +import com.almasb.fxgl.input.Input; +import com.almasb.fxgl.input.UserAction; import javafx.scene.input.KeyCode; @@ -47,7 +49,7 @@ private void initPlayer2() { } @Override - public void initInput() { + public void rebindInput(Input input) { // TODO: Implementer les touches de jeu avec getInput. // getInput().addAction(game_mode.getMoveLeft(), game_mode.getMoveLeftAction()); // getInput().addAction(() -> playerComponent1.moveLeft(), KeyCode.LEFT); @@ -57,31 +59,50 @@ public void initInput() { } else { System.out.println("PlayerComponent OK"); } - - onKey(KeyCode.ENTER, () -> { - playerComponent1.shoot(); - }); - - onKey(KeyCode.RIGHT, () -> { - playerComponent1.moveRight(); - }); - - onKey(KeyCode.LEFT, () -> { - playerComponent1.moveLeft(); - }); - - onKey(KeyCode.SPACE, () -> { - playerComponent2.shoot(); - }); - - onKey(KeyCode.D, () -> { - playerComponent2.moveRight(); - }); - - onKey(KeyCode.Q, () -> { - playerComponent2.moveLeft(); - }); - + UserAction player1_shoot = new UserAction("player1_shoot") { + @Override + protected void onAction() { + playerComponent1.shoot(); + } + }; + getInput().rebind(player1_shoot, KeyCode.ENTER); + UserAction player1_moveLeft = new UserAction("player1_moveLeft") { + @Override + protected void onAction() { + playerComponent1.moveLeft(); + } + }; + UserAction player1_moveRight = new UserAction("player1_moveRight") { + @Override + protected void onAction() { + playerComponent1.moveRight(); + } + }; + UserAction player2_shoot = new UserAction("player2_shoot") { + @Override + protected void onAction() { + playerComponent2.shoot(); + } + }; + UserAction player2_moveLeft = new UserAction("player2_moveLeft") { + @Override + protected void onAction() { + playerComponent2.moveLeft(); + } + }; + UserAction player2_moveRight = new UserAction("player2_moveRight") { + @Override + protected void onAction() { + playerComponent2.moveRight(); + } + }; + + input.addAction(player1_shoot, KeyCode.ENTER); + input.addAction(player1_moveLeft, KeyCode.LEFT); + input.addAction(player1_moveRight, KeyCode.RIGHT); + input.addAction(player2_shoot, KeyCode.SPACE); + input.addAction(player2_moveLeft, KeyCode.Q); + input.addAction(player2_moveRight, KeyCode.D); } // Getters and Setters @@ -113,4 +134,10 @@ private void makeAlienLine(int line, Settings.Direction direction) { } } } + + @Override + public void initInput(Input input) { + // TODO Auto-generated method stub + throw new UnsupportedOperationException("Unimplemented method 'initInput'"); + } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java index b051830..756497c 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java @@ -2,8 +2,11 @@ import org.enstabretagne.Utils.GameModeTypes; +import com.almasb.fxgl.input.Input; + public interface GameMode { public void initGameMode(); - public void initInput(); + public void initInput(Input input); + public void rebindInput(Input input); public GameModeTypes getGameModeType(); } \ No newline at end of file From 52ab9da9cc9543e27b434b9a77af2aa64f16fee4 Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Mon, 27 Feb 2023 15:54:05 +0100 Subject: [PATCH 06/50] First data exchange Server -> Client (player_1: X and Y position) --- .../org/enstabretagne/Game/GameLauncher.java | 43 +++++++++++++++---- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 570d202..42e9b3b 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -171,7 +171,6 @@ protected void initGameVars(Map vars) { */ @Override protected void initGame() { - serverLogic(); if(GameMode == MULTI) { isServer(); } @@ -219,6 +218,7 @@ protected void initGame() { spawn(entityNames.BACKGROUND); loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); + serverLogic(); } private void isServer(){ @@ -226,27 +226,53 @@ private void isServer(){ getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { if (yes) { isServer = true; + System.out.println("server"); server = getNetService().newTCPServer(55555); // todo -> selection du port + server.setOnConnected(connection -> { + connection.addMessageHandlerFX((conn, message) -> { + System.out.println("message from client"); + // do something with message when received from client + // FX means this callback runs on JavaFX thread + }); + }); server.startAsync(); } else { isServer = false; + System.out.println("client"); var client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port - + client.setOnConnected(connection -> { + connection.addMessageHandlerFX((conn, message) -> { + System.out.println("message from server"); + player1.setX(message.get("x")); + player1.setY(message.get("y")); + // do something with message when received from server + // FX means this callback runs on JavaFX thread + }); + }); // todo -> logique du client - client.connectAsync(); } }); return null; - },Duration.seconds(0.1)); + },Duration.seconds(0)); } private void serverLogic(){ //todo -> logique du serveur - var data = new Bundle("Player1"); - data.put("message", "value"); + System.out.println("server logic"); + //Broadcast player 1 Tcp + if (GameMode == MULTI) { + System.out.println("isServer : " + isServer); + Bundle bundle = new Bundle("Player1"); + bundle.put("type", "Player1"); + bundle.put("x", player1.getX()); + bundle.put("y", player1.getY()); + if (isServer) { + System.out.println("server broadcast"); + server.broadcast(bundle); + } + } + //Broadcast player 1 Udp - if(isServer) - server.broadcast(data); } private void makeAlienBlock() { @@ -346,6 +372,7 @@ private HBox createLifeUI(int life) { */ @Override protected void onUpdate(double tpf) { + serverLogic(); if (getb(GameVariableNames.isGameOver)) gameOverScreen(); if (getb(GameVariableNames.isGameWon)) From 203acf7ee8e4d6747a02e47c5d524d44508cc1b9 Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Mon, 27 Feb 2023 16:07:50 +0100 Subject: [PATCH 07/50] bi-directional connection Client -> Server (Player_2: x and y Position) --- .../org/enstabretagne/Game/GameLauncher.java | 57 ++++++++++++------- 1 file changed, 36 insertions(+), 21 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 42e9b3b..4e96564 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -12,6 +12,7 @@ import java.util.stream.Collectors; import com.almasb.fxgl.core.serialization.Bundle; +import com.almasb.fxgl.net.Client; import com.almasb.fxgl.net.Server; import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.EntityType; @@ -68,6 +69,8 @@ public static void setGameMode(GameMode gameMode) { } private boolean isServer; private Server server; + private Client client; + private boolean multiplayerGameInProgress = false; /** * Initialisation des paramètres du jeu @@ -218,7 +221,6 @@ protected void initGame() { spawn(entityNames.BACKGROUND); loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); - serverLogic(); } private void isServer(){ @@ -231,48 +233,55 @@ private void isServer(){ server.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { System.out.println("message from client"); - // do something with message when received from client - // FX means this callback runs on JavaFX thread + player2.setX(message.get("x")); + player2.setY(message.get("y")); }); }); server.startAsync(); + multiplayerGameInProgress = true; } else { isServer = false; System.out.println("client"); - var client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port + client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port client.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { System.out.println("message from server"); player1.setX(message.get("x")); player1.setY(message.get("y")); - // do something with message when received from server - // FX means this callback runs on JavaFX thread }); }); // todo -> logique du client client.connectAsync(); + multiplayerGameInProgress = true; } }); return null; },Duration.seconds(0)); } - private void serverLogic(){ //todo -> logique du serveur - System.out.println("server logic"); - //Broadcast player 1 Tcp - if (GameMode == MULTI) { - System.out.println("isServer : " + isServer); - Bundle bundle = new Bundle("Player1"); - bundle.put("type", "Player1"); - bundle.put("x", player1.getX()); - bundle.put("y", player1.getY()); - if (isServer) { - System.out.println("server broadcast"); - server.broadcast(bundle); - } + private void onUpdateServerLogic(){ //todo -> logique du serveur + //Broadcast player 1 + System.out.println("isServer : " + isServer); + Bundle bundle = new Bundle("Player1"); + bundle.put("type", "Player1"); + bundle.put("x", player1.getX()); + bundle.put("y", player1.getY()); + if (isServer) { + System.out.println("server broadcast"); + server.broadcast(bundle); } - //Broadcast player 1 Udp + } + private void onUpdateClientLogic(){ + //Broadcast player 2 + Bundle bundle = new Bundle("Player2"); + bundle.put("type", "Player2"); + bundle.put("x", player2.getX()); + bundle.put("y", player2.getY()); + if (!isServer) { + System.out.println("client broadcast"); + client.broadcast(bundle); + } } private void makeAlienBlock() { @@ -372,7 +381,13 @@ private HBox createLifeUI(int life) { */ @Override protected void onUpdate(double tpf) { - serverLogic(); + if (multiplayerGameInProgress) { + if (isServer) { + onUpdateServerLogic(); + } else { + onUpdateClientLogic(); + } + } if (getb(GameVariableNames.isGameOver)) gameOverScreen(); if (getb(GameVariableNames.isGameWon)) From bd8033e92d6368aa2558d287ee53add82d01484d Mon Sep 17 00:00:00 2001 From: LBF38 Date: Mon, 27 Feb 2023 16:09:39 +0100 Subject: [PATCH 08/50] refactor(UI): :recycle: refactor UI methods Refactored UI methods into a separate file for easier maintainability. It is responsible for UI components such as the player informations and the win/lose screen. --- .../org/enstabretagne/Game/GameLauncher.java | 130 +----------------- .../java/org/enstabretagne/UI/UI_Factory.java | 110 +++++++++++++++ 2 files changed, 116 insertions(+), 124 deletions(-) create mode 100644 duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 8f1a82b..c27e32e 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -1,24 +1,21 @@ package org.enstabretagne.Game; -import static com.almasb.fxgl.dsl.FXGL.getDialogService; -import static com.almasb.fxgl.dsl.FXGL.getGameController; import static com.almasb.fxgl.dsl.FXGL.getGameScene; import static com.almasb.fxgl.dsl.FXGL.getGameWorld; import static com.almasb.fxgl.dsl.FXGL.getPhysicsWorld; -import static com.almasb.fxgl.dsl.FXGL.getUIFactoryService; import static com.almasb.fxgl.dsl.FXGL.getb; import static com.almasb.fxgl.dsl.FXGL.loopBGM; import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.run; import static com.almasb.fxgl.dsl.FXGL.spawn; -import static com.almasb.fxgl.dsl.FXGL.texture; +import static org.enstabretagne.UI.UI_Factory.ambientSound; +import static org.enstabretagne.UI.UI_Factory.gameOverScreen; +import static org.enstabretagne.UI.UI_Factory.showPlayersLivesAndScores; +import static org.enstabretagne.UI.UI_Factory.winScreen; -import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; -import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import org.enstabretagne.Collision.AlienBulletCollision; import org.enstabretagne.Collision.AlienPlayerCollision; @@ -27,7 +24,6 @@ import org.enstabretagne.Collision.EnemyShootBulletCollision; import org.enstabretagne.Collision.EnemyShootPlayerCollision; import org.enstabretagne.Component.AlienComponent; -import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Component.SpaceInvadersFactory; import org.enstabretagne.Game.GameModes.ClassicGameMode; import org.enstabretagne.Game.GameModes.GameMode; @@ -47,11 +43,7 @@ import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.entity.Entity; -import javafx.geometry.Pos; -import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; -import javafx.scene.paint.Color; -import javafx.scene.text.Text; import javafx.util.Duration; /** @@ -184,29 +176,6 @@ protected void initGame() { loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); } - private void makeAlienBlock() { - for (int i = 0; i < 2; i++) { - makeAlienLine(i, Settings.Direction.DOWN); - makeAlienLine(i, Settings.Direction.UP); - } - } - - private void makeAlienLine(int line, Settings.Direction direction) { - for (int i = 0; i < Settings.ALIENS_NUMBER; i++) { - if (direction == Settings.Direction.DOWN) { - Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, - Settings.GAME_HEIGHT / 2 + (line - 1) * Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(direction); - alien.getComponent(AlienComponent.class).setAlienNumber(i); - } else { - Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, - Settings.GAME_HEIGHT / 2 + (line - 2) * Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(direction); - alien.getComponent(AlienComponent.class).setAlienNumber(i); - } - } - } - private void makeAlienBlockSolo() { for (int line = 0; line < 4; line++) { for (int k = 0; k < Settings.ALIENS_NUMBER; k++) { @@ -235,43 +204,7 @@ protected void initPhysics() { */ @Override protected void initUI() { - showPlayersLivesAndScores(); - } - - private void showPlayersLivesAndScores() { - getGameScene().removeChild(playersUI); - - List playersViews = new ArrayList<>(); - List players = getGameWorld().getEntitiesByType(EntityType.PLAYER).stream() - .map(player -> player.getComponent(PlayerComponent.class)).collect(Collectors.toList()); - for (PlayerComponent playerComponent : players) { - HBox scoreUI = createScoreUI(playerComponent.getScore(), playerComponent.getId()); - scoreUI.setTranslateY(scoreUI.getHeight() * playerComponent.getId()); - HBox lifeUI = createLifeUI(playerComponent.getLife()); - var playerUI = new HBox(30, scoreUI, lifeUI); - playersViews.add(playerUI); - } - playersUI = new VBox(20, playersViews.toArray(new HBox[0])); - getGameScene().addChild(playersUI); - } - - private HBox createScoreUI(int score, int player_id) { - Text scoreText = getUIFactoryService().newText(Integer.toString(score), Color.WHITE, 24.0); - Text playerText = getUIFactoryService().newText("Player " + Integer.toString(player_id % 2 + 1), Color.WHITE, - 24.0); - var scoreView = new HBox(10, playerText, scoreText); - scoreView.setAlignment(Pos.CENTER); - return scoreView; - } - - private HBox createLifeUI(int life) { - var lifeTexture = texture(assetNames.textures.LIFE, 30, 30); - var lifeView = new HBox(10); - for (int i = 0; i < life; i++) { - lifeView.getChildren().add(lifeTexture.copy()); - } - lifeView.setAlignment(Pos.CENTER); - return lifeView; + showPlayersLivesAndScores(playersUI); } /** @@ -292,7 +225,7 @@ protected void onUpdate(double tpf) { delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); } if (getGameScene().getContentRoot().getChildren().contains(playersUI)) - showPlayersLivesAndScores(); + showPlayersLivesAndScores(playersUI); run(() -> { getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { if (FXGLMath.randomBoolean(0.01)) @@ -301,57 +234,6 @@ protected void onUpdate(double tpf) { }, Duration.seconds(Settings.random.nextDouble() * 10)); } - /** - * Affichage de l'écran de fin de partie - */ - private void gameOverScreen(String score_player1, String score_player2) { - play(assetNames.sounds.DEFEAT_CLAIRON); - String message = "Game Over ! \n Scores are as follows : \n" + - "Player 1 : " + score_player1 + "\n"; - if (score_player2 != null) { - String player2 = "Player 2 : " + score_player2; - message += player2; - } - getDialogService().showMessageBox(message, () -> { - getDialogService().showConfirmationBox("Do you want to play again?", (yes) -> playAgain(yes)); - }); - } - - /** - * Affichage de l'écran pour jouer une nouvelle partie - */ - private void playAgain(Boolean yes) { - if (yes) - getGameController().startNewGame(); - else - getGameController().gotoMainMenu(); - } - - /** - * Affichage de l'écran de victoire - */ - private void winScreen(String score_player1, String score_player2) { - play(assetNames.sounds.VICTORY_CLAIRON); - String message = "You won ! \n Scores are as follows : \n" + - "Player 1 : " + score_player1 + "\n"; - if (score_player2 != null) { - String player2 = "Player 2 : " + score_player2; - message += player2; - } - getDialogService().showMessageBox(message, () -> { - getDialogService().showConfirmationBox("Do you want to play again?", (yes) -> playAgain(yes)); - }); - } - - /** - * Joue un son d'ambiance aléatoire parmi ceux disponibles - */ - private void ambientSound() { - String ambientMusic = assetNames.sounds.AMBIENT_SOUNDS - .get(FXGLMath.random(0, Settings.NUMBER_OF_AMBIENT_SOUND - 1)); - play(ambientMusic); - } - public static void main(String[] args) { launch(args); } diff --git a/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java b/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java new file mode 100644 index 0000000..25d5e7a --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java @@ -0,0 +1,110 @@ +package org.enstabretagne.UI; + +import static com.almasb.fxgl.dsl.FXGL.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.EntityType; +import org.enstabretagne.Utils.Settings; +import org.enstabretagne.Utils.assetNames; + +import com.almasb.fxgl.core.math.FXGLMath; + +import javafx.geometry.Pos; +import javafx.scene.layout.HBox; +import javafx.scene.layout.VBox; +import javafx.scene.paint.Color; +import javafx.scene.text.Text; + +public class UI_Factory { + + public static void showPlayersLivesAndScores(VBox playersUI) { + getGameScene().removeChild(playersUI); + + List playersViews = new ArrayList<>(); + List players = getGameWorld().getEntitiesByType(EntityType.PLAYER).stream() + .map(player -> player.getComponent(PlayerComponent.class)).collect(Collectors.toList()); + for (PlayerComponent playerComponent : players) { + HBox scoreUI = createScoreUI(playerComponent.getScore(), playerComponent.getId()); + scoreUI.setTranslateY(scoreUI.getHeight() * playerComponent.getId()); + HBox lifeUI = createLifeUI(playerComponent.getLife()); + var playerUI = new HBox(30, scoreUI, lifeUI); + playersViews.add(playerUI); + } + playersUI = new VBox(20, playersViews.toArray(new HBox[0])); + getGameScene().addChild(playersUI); + } + + public static HBox createScoreUI(int score, int player_id) { + Text scoreText = getUIFactoryService().newText(Integer.toString(score), Color.WHITE, 24.0); + Text playerText = getUIFactoryService().newText("Player " + Integer.toString(player_id % 2 + 1), Color.WHITE, + 24.0); + var scoreView = new HBox(10, playerText, scoreText); + scoreView.setAlignment(Pos.CENTER); + return scoreView; + } + + public static HBox createLifeUI(int life) { + var lifeTexture = texture(assetNames.textures.LIFE, 30, 30); + var lifeView = new HBox(10); + for (int i = 0; i < life; i++) { + lifeView.getChildren().add(lifeTexture.copy()); + } + lifeView.setAlignment(Pos.CENTER); + return lifeView; + } + + /** + * Affichage de l'écran pour jouer une nouvelle partie + */ + public static void playAgain(Boolean yes) { + if (yes) + getGameController().startNewGame(); + else + getGameController().gotoMainMenu(); + } + + /** + * Affichage de l'écran de victoire + */ + public static void winScreen(String score_player1, String score_player2) { + play(assetNames.sounds.VICTORY_CLAIRON); + String message = "You won ! \n Scores are as follows : \n" + + "Player 1 : " + score_player1 + "\n"; + if (score_player2 != null) { + String player2 = "Player 2 : " + score_player2; + message += player2; + } + getDialogService().showMessageBox(message, () -> { + getDialogService().showConfirmationBox("Do you want to play again?", (yes) -> playAgain(yes)); + }); + } + + /** + * Affichage de l'écran de fin de partie + */ + public static void gameOverScreen(String score_player1, String score_player2) { + play(assetNames.sounds.DEFEAT_CLAIRON); + String message = "Game Over ! \n Scores are as follows : \n" + + "Player 1 : " + score_player1 + "\n"; + if (score_player2 != null) { + String player2 = "Player 2 : " + score_player2; + message += player2; + } + getDialogService().showMessageBox(message, () -> { + getDialogService().showConfirmationBox("Do you want to play again?", (yes) -> playAgain(yes)); + }); + } + + /** + * Joue un son d'ambiance aléatoire parmi ceux disponibles + */ + public static void ambientSound() { + String ambientMusic = assetNames.sounds.AMBIENT_SOUNDS + .get(FXGLMath.random(0, Settings.NUMBER_OF_AMBIENT_SOUND - 1)); + play(ambientMusic); + } +} From d8221db440aa86936721863b10e8aa2de9a95957 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Mon, 27 Feb 2023 16:11:10 +0100 Subject: [PATCH 09/50] fix(input): :poop: WIP: fixing input bug trying to fix input bug --- .../Game/GameModes/ClassicGameMode.java | 113 ++++++++++-------- 1 file changed, 62 insertions(+), 51 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java index fe6181f..192b8a7 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java @@ -1,5 +1,11 @@ package org.enstabretagne.Game.GameModes; +import static com.almasb.fxgl.dsl.FXGL.spawn; +import static com.almasb.fxgl.dsl.FXGL.*; + +import java.util.HashMap; +import java.util.Map; + import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.GameModeTypes; @@ -8,18 +14,64 @@ import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.input.Input; +import com.almasb.fxgl.input.KeyTrigger; +import com.almasb.fxgl.input.Trigger; import com.almasb.fxgl.input.UserAction; import javafx.scene.input.KeyCode; -import static com.almasb.fxgl.dsl.FXGL.*; - public class ClassicGameMode implements GameMode { private PlayerComponent playerComponent1; private PlayerComponent playerComponent2; private Entity player1; private Entity player2; private GameModeTypes gameModeType = GameModeTypes.CLASSIQUE; + UserAction player1_shoot = new UserAction("player1_shoot") { + @Override + protected void onAction() { + playerComponent1.shoot(); + } + }; + UserAction player1_moveLeft = new UserAction("player1_moveLeft") { + @Override + protected void onAction() { + playerComponent1.moveLeft(); + } + }; + UserAction player1_moveRight = new UserAction("player1_moveRight") { + @Override + protected void onAction() { + playerComponent1.moveRight(); + } + }; + UserAction player2_shoot = new UserAction("player2_shoot") { + @Override + protected void onAction() { + playerComponent2.shoot(); + } + }; + UserAction player2_moveLeft = new UserAction("player2_moveLeft") { + @Override + protected void onAction() { + playerComponent2.moveLeft(); + } + }; + UserAction player2_moveRight = new UserAction("player2_moveRight") { + @Override + protected void onAction() { + playerComponent2.moveRight(); + } + }; + Map inputMap = new HashMap() { + { + put(player1_shoot, new KeyTrigger(KeyCode.ENTER)); + put(player1_moveLeft, new KeyTrigger(KeyCode.RIGHT)); + put(player1_moveRight, new KeyTrigger(KeyCode.LEFT)); + put(player2_shoot, new KeyTrigger(KeyCode.SPACE)); + put(player2_moveLeft, new KeyTrigger(KeyCode.Q)); + put(player2_moveRight, new KeyTrigger(KeyCode.D)); + } + }; @Override public void initGameMode() { @@ -50,59 +102,13 @@ private void initPlayer2() { @Override public void rebindInput(Input input) { - // TODO: Implementer les touches de jeu avec getInput. - // getInput().addAction(game_mode.getMoveLeft(), game_mode.getMoveLeftAction()); - // getInput().addAction(() -> playerComponent1.moveLeft(), KeyCode.LEFT); if (playerComponent1 == null || playerComponent2 == null) { System.out.println("No PlayerComponent"); return; } else { System.out.println("PlayerComponent OK"); } - UserAction player1_shoot = new UserAction("player1_shoot") { - @Override - protected void onAction() { - playerComponent1.shoot(); - } - }; - getInput().rebind(player1_shoot, KeyCode.ENTER); - UserAction player1_moveLeft = new UserAction("player1_moveLeft") { - @Override - protected void onAction() { - playerComponent1.moveLeft(); - } - }; - UserAction player1_moveRight = new UserAction("player1_moveRight") { - @Override - protected void onAction() { - playerComponent1.moveRight(); - } - }; - UserAction player2_shoot = new UserAction("player2_shoot") { - @Override - protected void onAction() { - playerComponent2.shoot(); - } - }; - UserAction player2_moveLeft = new UserAction("player2_moveLeft") { - @Override - protected void onAction() { - playerComponent2.moveLeft(); - } - }; - UserAction player2_moveRight = new UserAction("player2_moveRight") { - @Override - protected void onAction() { - playerComponent2.moveRight(); - } - }; - - input.addAction(player1_shoot, KeyCode.ENTER); - input.addAction(player1_moveLeft, KeyCode.LEFT); - input.addAction(player1_moveRight, KeyCode.RIGHT); - input.addAction(player2_shoot, KeyCode.SPACE); - input.addAction(player2_moveLeft, KeyCode.Q); - input.addAction(player2_moveRight, KeyCode.D); + input.getAllBindings().putAll(inputMap); } // Getters and Setters @@ -137,7 +143,12 @@ private void makeAlienLine(int line, Settings.Direction direction) { @Override public void initInput(Input input) { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'initInput'"); + if (playerComponent1 == null || playerComponent2 == null) { + System.out.println("No PlayerComponent"); + return; + } else { + System.out.println("PlayerComponent OK"); + } + input.getAllBindings().putAll(inputMap); } } From 5127261bcb2185f3383365fe108cd0d24dc25231 Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Mon, 27 Feb 2023 16:37:49 +0100 Subject: [PATCH 10/50] Added shot sharing and key remapping Server <-> Client (Player 1 or 2 shoot), in multi, you can only use your ship --- .../org/enstabretagne/Game/GameLauncher.java | 91 +++++++++++++++---- 1 file changed, 71 insertions(+), 20 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 4e96564..2ffdc3c 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -120,20 +120,52 @@ public FXGLMenu newMainMenu() { @Override protected void initInput() { onKey(KeyCode.ENTER, () -> { - playerComponent1.shoot(); + if (multiplayerGameInProgress){ + onShootBroadcastLogic(); + if(isServer){ + playerComponent1.shoot(); + }else { + playerComponent2.shoot(); + } + } else { + playerComponent1.shoot(); + } }); onKey(KeyCode.RIGHT, () -> { - playerComponent1.moveRight(); + if (multiplayerGameInProgress) { + if(isServer) { + playerComponent1.moveRight(); + } else { + playerComponent2.moveRight(); + } + }else { + playerComponent1.moveRight(); + } }); onKey(KeyCode.LEFT, () -> { - playerComponent1.moveLeft(); + if (multiplayerGameInProgress) { + if(isServer) { + playerComponent1.moveLeft(); + } else { + playerComponent2.moveLeft(); + } + }else { + playerComponent1.moveLeft(); + } }); onKey(KeyCode.SPACE, () -> { if (GameMode == SOLO) { playerComponent1.shoot(); + } else if (multiplayerGameInProgress){ + onShootBroadcastLogic(); + if(isServer){ + playerComponent1.shoot(); + }else { + playerComponent2.shoot(); + } } else { playerComponent2.shoot(); } @@ -142,7 +174,13 @@ protected void initInput() { onKey(KeyCode.D, () -> { if (GameMode == SOLO) { playerComponent1.moveRight(); - } else { + } else if (multiplayerGameInProgress) { + if(isServer) { + playerComponent1.moveRight(); + } else { + playerComponent2.moveRight(); + } + }else { playerComponent2.moveRight(); } }); @@ -150,6 +188,12 @@ protected void initInput() { onKey(KeyCode.Q, () -> { if (GameMode == SOLO) { playerComponent1.moveLeft(); + } else if (multiplayerGameInProgress) { + if(isServer) { + playerComponent1.moveLeft(); + } else { + playerComponent2.moveLeft(); + } } else { playerComponent2.moveLeft(); } @@ -233,8 +277,12 @@ private void isServer(){ server.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { System.out.println("message from client"); - player2.setX(message.get("x")); - player2.setY(message.get("y")); + if (message.getName().equals("Player2") ) { + player2.setX(message.get("x")); + player2.setY(message.get("y")); + }else if (message.getName().equals("Player2Shoot")) { + playerComponent2.shoot(); + } }); }); server.startAsync(); @@ -245,12 +293,14 @@ private void isServer(){ client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port client.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { - System.out.println("message from server"); - player1.setX(message.get("x")); - player1.setY(message.get("y")); + if(message.getName().equals("Player1")){ + player1.setX(message.get("x")); + player1.setY(message.get("y")); + } else if (message.getName().equals("Player1Shoot")) { + playerComponent1.shoot(); + } }); }); - // todo -> logique du client client.connectAsync(); multiplayerGameInProgress = true; } @@ -259,28 +309,29 @@ private void isServer(){ },Duration.seconds(0)); } - private void onUpdateServerLogic(){ //todo -> logique du serveur - //Broadcast player 1 - System.out.println("isServer : " + isServer); + private void onUpdateServerLogic(){ Bundle bundle = new Bundle("Player1"); bundle.put("type", "Player1"); bundle.put("x", player1.getX()); bundle.put("y", player1.getY()); - if (isServer) { - System.out.println("server broadcast"); - server.broadcast(bundle); - } + server.broadcast(bundle); } private void onUpdateClientLogic(){ - //Broadcast player 2 Bundle bundle = new Bundle("Player2"); bundle.put("type", "Player2"); bundle.put("x", player2.getX()); bundle.put("y", player2.getY()); - if (!isServer) { + client.broadcast(bundle); + } + + private void onShootBroadcastLogic(){ + if (isServer) { + System.out.println("server broadcast"); + server.broadcast(new Bundle("Player1Shoot")); + } else { System.out.println("client broadcast"); - client.broadcast(bundle); + client.broadcast(new Bundle("Player2Shoot")); } } From 68e60c4e1959675c9828bfba8f4f3d3a9824a7f5 Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Mon, 27 Feb 2023 16:42:54 +0100 Subject: [PATCH 11/50] Life and score broadcast --- .../main/java/org/enstabretagne/Game/GameLauncher.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 2ffdc3c..08e814e 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -280,6 +280,8 @@ private void isServer(){ if (message.getName().equals("Player2") ) { player2.setX(message.get("x")); player2.setY(message.get("y")); + playerComponent2.setScore(message.get("score")); + playerComponent2.setLife(message.get("life")); }else if (message.getName().equals("Player2Shoot")) { playerComponent2.shoot(); } @@ -296,6 +298,8 @@ private void isServer(){ if(message.getName().equals("Player1")){ player1.setX(message.get("x")); player1.setY(message.get("y")); + playerComponent1.setScore(message.get("score")); + playerComponent1.setLife(message.get("life")); } else if (message.getName().equals("Player1Shoot")) { playerComponent1.shoot(); } @@ -314,6 +318,8 @@ private void onUpdateServerLogic(){ bundle.put("type", "Player1"); bundle.put("x", player1.getX()); bundle.put("y", player1.getY()); + bundle.put("score", playerComponent1.getScore()); + bundle.put("life", playerComponent1.getLife()); server.broadcast(bundle); } @@ -322,6 +328,8 @@ private void onUpdateClientLogic(){ bundle.put("type", "Player2"); bundle.put("x", player2.getX()); bundle.put("y", player2.getY()); + bundle.put("score", playerComponent2.getScore()); + bundle.put("life", playerComponent2.getLife()); client.broadcast(bundle); } From 50cbc2188203d180e5760161b882ca510abf0e32 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 3 Mar 2023 11:13:54 +0100 Subject: [PATCH 12/50] fix(input): :bug: fix input bug in classic mode Made an `initInput` method for the GameMode class that will initialize the input for the game mode. This will be called in the `initGame` method of the GameLauncher class. This will fix the bug where the input was not being initialized in classic mode. --- .../org/enstabretagne/Game/GameLauncher.java | 3 +- .../Game/GameModes/ClassicGameMode.java | 72 ++----------------- .../Game/GameModes/GameMode.java | 1 - 3 files changed, 8 insertions(+), 68 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index c27e32e..6a47cf3 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -116,7 +116,6 @@ public FXGLMenu newMainMenu() { @Override protected void initInput() { super.initInput(); - game_mode.initInput(getGameScene().getInput()); } /** @@ -141,7 +140,7 @@ protected void initGame() { game_mode.initGameMode(); try { - game_mode.rebindInput(getGameScene().getInput()); + game_mode.initInput(getGameScene().getInput()); } catch (Exception exception) { System.out.println("Erreur lors de l'initialisation des inputs : " + exception.getMessage()); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java index 192b8a7..92e8b25 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java @@ -1,10 +1,7 @@ package org.enstabretagne.Game.GameModes; +import static com.almasb.fxgl.dsl.FXGL.onKey; import static com.almasb.fxgl.dsl.FXGL.spawn; -import static com.almasb.fxgl.dsl.FXGL.*; - -import java.util.HashMap; -import java.util.Map; import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.PlayerComponent; @@ -14,9 +11,6 @@ import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.input.Input; -import com.almasb.fxgl.input.KeyTrigger; -import com.almasb.fxgl.input.Trigger; -import com.almasb.fxgl.input.UserAction; import javafx.scene.input.KeyCode; @@ -26,52 +20,6 @@ public class ClassicGameMode implements GameMode { private Entity player1; private Entity player2; private GameModeTypes gameModeType = GameModeTypes.CLASSIQUE; - UserAction player1_shoot = new UserAction("player1_shoot") { - @Override - protected void onAction() { - playerComponent1.shoot(); - } - }; - UserAction player1_moveLeft = new UserAction("player1_moveLeft") { - @Override - protected void onAction() { - playerComponent1.moveLeft(); - } - }; - UserAction player1_moveRight = new UserAction("player1_moveRight") { - @Override - protected void onAction() { - playerComponent1.moveRight(); - } - }; - UserAction player2_shoot = new UserAction("player2_shoot") { - @Override - protected void onAction() { - playerComponent2.shoot(); - } - }; - UserAction player2_moveLeft = new UserAction("player2_moveLeft") { - @Override - protected void onAction() { - playerComponent2.moveLeft(); - } - }; - UserAction player2_moveRight = new UserAction("player2_moveRight") { - @Override - protected void onAction() { - playerComponent2.moveRight(); - } - }; - Map inputMap = new HashMap() { - { - put(player1_shoot, new KeyTrigger(KeyCode.ENTER)); - put(player1_moveLeft, new KeyTrigger(KeyCode.RIGHT)); - put(player1_moveRight, new KeyTrigger(KeyCode.LEFT)); - put(player2_shoot, new KeyTrigger(KeyCode.SPACE)); - put(player2_moveLeft, new KeyTrigger(KeyCode.Q)); - put(player2_moveRight, new KeyTrigger(KeyCode.D)); - } - }; @Override public void initGameMode() { @@ -100,17 +48,6 @@ private void initPlayer2() { playerComponent2.initializeLife(); } - @Override - public void rebindInput(Input input) { - if (playerComponent1 == null || playerComponent2 == null) { - System.out.println("No PlayerComponent"); - return; - } else { - System.out.println("PlayerComponent OK"); - } - input.getAllBindings().putAll(inputMap); - } - // Getters and Setters @Override public GameModeTypes getGameModeType() { @@ -149,6 +86,11 @@ public void initInput(Input input) { } else { System.out.println("PlayerComponent OK"); } - input.getAllBindings().putAll(inputMap); + onKey(KeyCode.ENTER, () -> playerComponent1.shoot()); + onKey(KeyCode.RIGHT, () -> playerComponent1.moveRight()); + onKey(KeyCode.LEFT, () -> playerComponent1.moveLeft()); + onKey(KeyCode.SPACE, () -> playerComponent2.shoot()); + onKey(KeyCode.D, () -> playerComponent2.moveRight()); + onKey(KeyCode.Q, () -> playerComponent2.moveLeft()); } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java index 756497c..a32e654 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java @@ -7,6 +7,5 @@ public interface GameMode { public void initGameMode(); public void initInput(Input input); - public void rebindInput(Input input); public GameModeTypes getGameModeType(); } \ No newline at end of file From ffd7927381bebe014d55b9d192516c920c6955f7 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 3 Mar 2023 11:47:12 +0100 Subject: [PATCH 13/50] refactor(ui): :recycle: players lives and scores refactoring UI for players lives and scores --- .../java/org/enstabretagne/Game/GameLauncher.java | 10 +++++++--- .../main/java/org/enstabretagne/UI/UI_Factory.java | 13 ++++++++----- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 6a47cf3..0d52b73 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -203,7 +203,8 @@ protected void initPhysics() { */ @Override protected void initUI() { - showPlayersLivesAndScores(playersUI); + playersUI = showPlayersLivesAndScores(getGameWorld()); + getGameScene().addChild(playersUI); } /** @@ -223,8 +224,11 @@ protected void onUpdate(double tpf) { last_ambient_sound = System.currentTimeMillis(); delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); } - if (getGameScene().getContentRoot().getChildren().contains(playersUI)) - showPlayersLivesAndScores(playersUI); + if (getGameScene().getContentRoot().getChildren().contains(playersUI)) { + getGameScene().removeChild(playersUI); + playersUI = showPlayersLivesAndScores(getGameWorld()); + getGameScene().addChild(playersUI); + } run(() -> { getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { if (FXGLMath.randomBoolean(0.01)) diff --git a/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java b/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java index 25d5e7a..c559576 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java +++ b/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java @@ -12,6 +12,7 @@ import org.enstabretagne.Utils.assetNames; import com.almasb.fxgl.core.math.FXGLMath; +import com.almasb.fxgl.entity.GameWorld; import javafx.geometry.Pos; import javafx.scene.layout.HBox; @@ -21,11 +22,12 @@ public class UI_Factory { - public static void showPlayersLivesAndScores(VBox playersUI) { - getGameScene().removeChild(playersUI); + public static VBox showPlayersLivesAndScores(GameWorld gameWorld) { + // getGameScene().removeChild(playersUI); + // System.out.println("Players Lives and Scores"); List playersViews = new ArrayList<>(); - List players = getGameWorld().getEntitiesByType(EntityType.PLAYER).stream() + List players = gameWorld.getEntitiesByType(EntityType.PLAYER).stream() .map(player -> player.getComponent(PlayerComponent.class)).collect(Collectors.toList()); for (PlayerComponent playerComponent : players) { HBox scoreUI = createScoreUI(playerComponent.getScore(), playerComponent.getId()); @@ -34,8 +36,9 @@ public static void showPlayersLivesAndScores(VBox playersUI) { var playerUI = new HBox(30, scoreUI, lifeUI); playersViews.add(playerUI); } - playersUI = new VBox(20, playersViews.toArray(new HBox[0])); - getGameScene().addChild(playersUI); + VBox players_ui = new VBox(20, playersViews.toArray(new HBox[0])); + return players_ui; + // getGameScene().addChild(players_ui); } public static HBox createScoreUI(int score, int player_id) { From 6e6e61e3f52c532c48b958a6551119d38ee9568f Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Sun, 5 Mar 2023 16:11:59 +0100 Subject: [PATCH 14/50] Added comment with LBF tag to facilitate merge --- .../org/enstabretagne/Game/GameLauncher.java | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 08e814e..9e43fa0 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -70,7 +70,8 @@ public static void setGameMode(GameMode gameMode) { private boolean isServer; private Server server; private Client client; - private boolean multiplayerGameInProgress = false; + private boolean multiplayerGameInProgress = false; // indique si la partie multijoueur est lancée ou non + // LBF : dans le mode multi ??? /** * Initialisation des paramètres du jeu @@ -218,13 +219,13 @@ protected void initGameVars(Map vars) { */ @Override protected void initGame() { - if(GameMode == MULTI) { + if(GameMode == MULTI) { // LBF : dans le mode multijoueur isServer(); } play(assetNames.sounds.START_CLAIRON); getGameWorld().addEntityFactory(new SpaceInvadersFactory()); - player1 = spawn(entityNames.PLAYER); + player1 = spawn(entityNames.PLAYER); // LBF : dans tous les modes de jeu player1.setX(Constant.GAME_WIDTH / 2); player1.setY(Constant.GAME_HEIGHT - player1.getHeight()); playerComponent1 = player1.getComponent(PlayerComponent.class); @@ -232,7 +233,7 @@ protected void initGame() { playerComponent1.initializeScore(); playerComponent1.initializeLife(); - if (GameMode != SOLO) { + if (GameMode != SOLO) { // LBF : dans tous les modes de jeu sauf solo player2 = spawn(entityNames.PLAYER); player2.setX(Constant.GAME_WIDTH / 2); player2.setY(0); @@ -242,8 +243,7 @@ protected void initGame() { playerComponent2.initializeLife(); } - if (GameMode == INFINITY_MODE) { - // spawn Aliens pour infinity mode + if (GameMode == INFINITY_MODE) { // LBF : dans le mode infinity Entity alien1 = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); alien1.getComponent(AlienComponent.class).initialize(Constant.Direction.UP); Entity alien2 = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); @@ -257,9 +257,9 @@ protected void initGame() { alien.getComponent(AlienComponent.class).initialize(Constant.Direction.DOWN); }, Duration.seconds(1.5)); - } else if (GameMode == CLASSIQUE) { + } else if (GameMode == CLASSIQUE) { // LBF : dans le mode classique makeAlienBlock(); - } else if (GameMode == SOLO) { + } else if (GameMode == SOLO) { // LBF : dans le mode solo makeAlienBlockSolo(); } @@ -267,7 +267,7 @@ protected void initGame() { loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); } - private void isServer(){ + private void isServer(){ // LBF : dans le mode multijoueur runOnce(() -> { getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { if (yes) { @@ -313,7 +313,10 @@ private void isServer(){ },Duration.seconds(0)); } - private void onUpdateServerLogic(){ + /** + * Envoie des données du joueur 1 par le serveur + */ + private void onUpdateServerLogic(){ // LBF : dans le mode multijoueur Bundle bundle = new Bundle("Player1"); bundle.put("type", "Player1"); bundle.put("x", player1.getX()); @@ -323,7 +326,10 @@ private void onUpdateServerLogic(){ server.broadcast(bundle); } - private void onUpdateClientLogic(){ + /** + * Envoie des données du joueur 2 par le client + */ + private void onUpdateClientLogic(){ // LBF : dans le mode multijoueur Bundle bundle = new Bundle("Player2"); bundle.put("type", "Player2"); bundle.put("x", player2.getX()); @@ -333,7 +339,7 @@ private void onUpdateClientLogic(){ client.broadcast(bundle); } - private void onShootBroadcastLogic(){ + private void onShootBroadcastLogic(){ // LBF : dans le mode multijoueur if (isServer) { System.out.println("server broadcast"); server.broadcast(new Bundle("Player1Shoot")); @@ -440,7 +446,7 @@ private HBox createLifeUI(int life) { */ @Override protected void onUpdate(double tpf) { - if (multiplayerGameInProgress) { + if (multiplayerGameInProgress) { // LBF : dans le mode multijoueur ou réecrire autrement?? if (isServer) { onUpdateServerLogic(); } else { From 09d548a8024c4f041d17fc1b762c3c39d4331dcd Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Sun, 5 Mar 2023 16:26:59 +0100 Subject: [PATCH 15/50] Refactoring of the TCP message reception logic In two new methods: onReceiveMessageClient onReceiveMessageServer --- .../org/enstabretagne/Game/GameLauncher.java | 70 +++++++++++-------- 1 file changed, 41 insertions(+), 29 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 9e43fa0..2eb09ce 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -274,37 +274,14 @@ private void isServer(){ // LBF : dans le mode multijoueur isServer = true; System.out.println("server"); server = getNetService().newTCPServer(55555); // todo -> selection du port - server.setOnConnected(connection -> { - connection.addMessageHandlerFX((conn, message) -> { - System.out.println("message from client"); - if (message.getName().equals("Player2") ) { - player2.setX(message.get("x")); - player2.setY(message.get("y")); - playerComponent2.setScore(message.get("score")); - playerComponent2.setLife(message.get("life")); - }else if (message.getName().equals("Player2Shoot")) { - playerComponent2.shoot(); - } - }); - }); + onReceiveMessageServer(); server.startAsync(); multiplayerGameInProgress = true; } else { isServer = false; System.out.println("client"); client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port - client.setOnConnected(connection -> { - connection.addMessageHandlerFX((conn, message) -> { - if(message.getName().equals("Player1")){ - player1.setX(message.get("x")); - player1.setY(message.get("y")); - playerComponent1.setScore(message.get("score")); - playerComponent1.setLife(message.get("life")); - } else if (message.getName().equals("Player1Shoot")) { - playerComponent1.shoot(); - } - }); - }); + onReceiveMessageClient(); client.connectAsync(); multiplayerGameInProgress = true; } @@ -314,7 +291,7 @@ private void isServer(){ // LBF : dans le mode multijoueur } /** - * Envoie des données du joueur 1 par le serveur + * Envoie des données du serveur vers le client */ private void onUpdateServerLogic(){ // LBF : dans le mode multijoueur Bundle bundle = new Bundle("Player1"); @@ -327,7 +304,25 @@ private void onUpdateServerLogic(){ // LBF : dans le mode multijoueur } /** - * Envoie des données du joueur 2 par le client + * Logique lors de la réception des données du client par le serveur + */ + private void onReceiveMessageServer(){ // LBF : dans le mode multijoueur + server.setOnConnected(connection -> { + connection.addMessageHandlerFX((conn, message) -> { + if (message.getName().equals("Player2")) { + player2.setX(message.get("x")); + player2.setY(message.get("y")); + playerComponent2.setScore(message.get("score")); + playerComponent2.setLife(message.get("life")); + }else if (message.getName().equals("Player2Shoot")) { + playerComponent2.shoot(); + } + }); + }); + } + + /** + * Envoie des données du client vers le serveur */ private void onUpdateClientLogic(){ // LBF : dans le mode multijoueur Bundle bundle = new Bundle("Player2"); @@ -339,12 +334,29 @@ private void onUpdateClientLogic(){ // LBF : dans le mode multijoueur client.broadcast(bundle); } + /** + * Logique lors de la réception des données du serveur par le client + */ + private void onReceiveMessageClient() { // LBF : dans le mode multijoueur + client.setOnConnected(connection -> { + connection.addMessageHandlerFX((conn, message) -> { + if (message.getName().equals("Player1")) { + player1.setX(message.get("x")); + player1.setY(message.get("y")); + playerComponent1.setScore(message.get("score")); + playerComponent1.setLife(message.get("life")); + } else if (message.getName().equals("Player1Shoot")) { + playerComponent1.shoot(); + } + }); + }); + } + + private void onShootBroadcastLogic(){ // LBF : dans le mode multijoueur if (isServer) { - System.out.println("server broadcast"); server.broadcast(new Bundle("Player1Shoot")); } else { - System.out.println("client broadcast"); client.broadcast(new Bundle("Player2Shoot")); } } From 78c386e952d6a6368e19d3a0499c54159e75ec3d Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sun, 5 Mar 2023 16:46:56 +0100 Subject: [PATCH 16/50] refactor(GameMode): :recycle: abstract game modes I tried to make abstract classes for one and two players game modes so that it is easier to create new game modes from them. WIP: it is not working yet, I need to fix the refactoring. :construction: --- .../org/enstabretagne/Game/GameLauncher.java | 11 --- .../Game/GameModes/AlienFactory.java | 43 +++++++++ .../Game/GameModes/ClassicGameMode.java | 89 +------------------ .../Game/GameModes/OnePlayerGameMode.java | 61 +++++++++++++ .../Game/GameModes/TwoPlayerGameMode.java | 40 +++++++++ .../enstabretagne/Utils/GameModeTypes.java | 2 +- 6 files changed, 148 insertions(+), 98 deletions(-) create mode 100644 duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java create mode 100644 duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java create mode 100644 duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 0d52b73..db8281c 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -41,7 +41,6 @@ import com.almasb.fxgl.app.scene.FXGLMenu; import com.almasb.fxgl.app.scene.SceneFactory; import com.almasb.fxgl.core.math.FXGLMath; -import com.almasb.fxgl.entity.Entity; import javafx.scene.layout.VBox; import javafx.util.Duration; @@ -175,16 +174,6 @@ protected void initGame() { loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); } - private void makeAlienBlockSolo() { - for (int line = 0; line < 4; line++) { - for (int k = 0; k < Settings.ALIENS_NUMBER; k++) { - Entity alien = spawn(entityNames.ALIEN, k * Settings.ALIEN_WIDTH, (line - 1) * Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); - alien.getComponent(AlienComponent.class).setAlienNumber(k); - } - } - } - /** * Initialisation des propriétés physiques du jeu liées aux collisions */ diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java new file mode 100644 index 0000000..d1047e3 --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java @@ -0,0 +1,43 @@ +package org.enstabretagne.Game.GameModes; + +import org.enstabretagne.Component.AlienComponent; +import org.enstabretagne.Utils.Settings; +import org.enstabretagne.Utils.entityNames; +import static com.almasb.fxgl.dsl.FXGL.*; + +import com.almasb.fxgl.entity.Entity; + +public class AlienFactory { + static protected void makeAlienBlock() { + for (int i = 0; i < 2; i++) { + makeAlienLine(i, Settings.Direction.DOWN); + makeAlienLine(i, Settings.Direction.UP); + } + } + + static protected void makeAlienLine(int line, Settings.Direction direction) { + for (int i = 0; i < Settings.ALIENS_NUMBER; i++) { + if (direction == Settings.Direction.DOWN) { + Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, + Settings.GAME_HEIGHT / 2 + (line - 1) * Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(direction); + alien.getComponent(AlienComponent.class).setAlienNumber(i); + } else { + Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, + Settings.GAME_HEIGHT / 2 + (line - 2) * Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(direction); + alien.getComponent(AlienComponent.class).setAlienNumber(i); + } + } + } + + static protected void makeAlienBlockSolo() { + for (int line = 0; line < 4; line++) { + for (int k = 0; k < Settings.ALIENS_NUMBER; k++) { + Entity alien = spawn(entityNames.ALIEN, k * Settings.ALIEN_WIDTH, (line - 1) * Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); + alien.getComponent(AlienComponent.class).setAlienNumber(k); + } + } + } +} diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java index 92e8b25..c9218f8 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java @@ -1,96 +1,13 @@ package org.enstabretagne.Game.GameModes; -import static com.almasb.fxgl.dsl.FXGL.onKey; -import static com.almasb.fxgl.dsl.FXGL.spawn; +import static org.enstabretagne.Game.GameModes.AlienFactory.*; -import org.enstabretagne.Component.AlienComponent; -import org.enstabretagne.Component.PlayerComponent; -import org.enstabretagne.Utils.GameModeTypes; -import org.enstabretagne.Utils.Settings; -import org.enstabretagne.Utils.entityNames; - -import com.almasb.fxgl.entity.Entity; -import com.almasb.fxgl.input.Input; - -import javafx.scene.input.KeyCode; - -public class ClassicGameMode implements GameMode { - private PlayerComponent playerComponent1; - private PlayerComponent playerComponent2; - private Entity player1; - private Entity player2; - private GameModeTypes gameModeType = GameModeTypes.CLASSIQUE; +public class ClassicGameMode extends TwoPlayerGameMode { @Override public void initGameMode() { - initPlayer1(); - initPlayer2(); + super.initGameMode(); makeAlienBlock(); } - private void initPlayer1() { - player1 = spawn(entityNames.PLAYER); - player1.setX(Settings.GAME_WIDTH / 2); - player1.setY(Settings.GAME_HEIGHT - player1.getHeight()); - playerComponent1 = player1.getComponent(PlayerComponent.class); - playerComponent1.setDirection(Settings.Direction.UP); - playerComponent1.initializeScore(); - playerComponent1.initializeLife(); - } - - private void initPlayer2() { - player2 = spawn(entityNames.PLAYER); - player2.setX(Settings.GAME_WIDTH / 2); - player2.setY(0); - playerComponent2 = player2.getComponent(PlayerComponent.class); - playerComponent2.setDirection(Settings.Direction.DOWN); - playerComponent2.initializeScore(); - playerComponent2.initializeLife(); - } - - // Getters and Setters - @Override - public GameModeTypes getGameModeType() { - return gameModeType; - } - - // Methods - private void makeAlienBlock() { - for (int i = 0; i < 2; i++) { - makeAlienLine(i, Settings.Direction.DOWN); - makeAlienLine(i, Settings.Direction.UP); - } - } - - private void makeAlienLine(int line, Settings.Direction direction) { - for (int i = 0; i < Settings.ALIENS_NUMBER; i++) { - if (direction == Settings.Direction.DOWN) { - Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, - Settings.GAME_HEIGHT / 2 + (line - 1) * Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(direction); - alien.getComponent(AlienComponent.class).setAlienNumber(i); - } else { - Entity alien = spawn(entityNames.ALIEN, i * Settings.ALIEN_WIDTH, - Settings.GAME_HEIGHT / 2 + (line - 2) * Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(direction); - alien.getComponent(AlienComponent.class).setAlienNumber(i); - } - } - } - - @Override - public void initInput(Input input) { - if (playerComponent1 == null || playerComponent2 == null) { - System.out.println("No PlayerComponent"); - return; - } else { - System.out.println("PlayerComponent OK"); - } - onKey(KeyCode.ENTER, () -> playerComponent1.shoot()); - onKey(KeyCode.RIGHT, () -> playerComponent1.moveRight()); - onKey(KeyCode.LEFT, () -> playerComponent1.moveLeft()); - onKey(KeyCode.SPACE, () -> playerComponent2.shoot()); - onKey(KeyCode.D, () -> playerComponent2.moveRight()); - onKey(KeyCode.Q, () -> playerComponent2.moveLeft()); - } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java new file mode 100644 index 0000000..66a60d1 --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -0,0 +1,61 @@ +package org.enstabretagne.Game.GameModes; + +import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.GameModeTypes; +import org.enstabretagne.Utils.Settings; +import org.enstabretagne.Utils.entityNames; +import org.enstabretagne.Utils.Settings.Direction; + +import static com.almasb.fxgl.dsl.FXGL.*; +import com.almasb.fxgl.entity.Entity; +import com.almasb.fxgl.input.Input; + +import javafx.scene.input.KeyCode; + +public abstract class OnePlayerGameMode implements GameMode { + protected Entity player1; + protected PlayerComponent playerComponent1; + + @Override + public GameModeTypes getGameModeType() { + return GameModeTypes.SOLO; + } + + @Override + public void initGameMode() { + player1 = initPlayer(player1, Settings.GAME_WIDTH / 2, Settings.GAME_HEIGHT - player1.getHeight()); + playerComponent1 = initPlayerComponent(player1, Direction.UP); + } + + protected Entity initPlayer(Entity player, double positionX, double positionY) { + player = spawn(entityNames.PLAYER); + player.setX(positionX); + player.setY(positionY); + return player; + } + + protected PlayerComponent initPlayerComponent(Entity player, Direction direction) { + PlayerComponent playerComponent = player.getComponent(PlayerComponent.class); + playerComponent.setDirection(direction); + playerComponent.initializeScore(); + playerComponent.initializeLife(); + return playerComponent; + } + + @Override + public void initInput(Input input) { + if (playerComponent1 == null) { + System.out.println("No PlayerComponent"); + return; + } else { + System.out.println("PlayerComponent OK"); + } + onKey(KeyCode.ENTER, () -> playerComponent1.shoot()); + onKey(KeyCode.RIGHT, () -> playerComponent1.moveRight()); + onKey(KeyCode.LEFT, () -> playerComponent1.moveLeft()); + onKey(KeyCode.SPACE, () -> playerComponent1.shoot()); + onKey(KeyCode.D, () -> playerComponent1.moveRight()); + onKey(KeyCode.Q, () -> playerComponent1.moveLeft()); + } + +} diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java new file mode 100644 index 0000000..f5b76d8 --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java @@ -0,0 +1,40 @@ +package org.enstabretagne.Game.GameModes; + +import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.GameModeTypes; +import org.enstabretagne.Utils.Settings; +import org.enstabretagne.Utils.Settings.Direction; + +import com.almasb.fxgl.entity.Entity; +import com.almasb.fxgl.input.Input; +import static com.almasb.fxgl.dsl.FXGL.*; + +import javafx.scene.input.KeyCode; + +public abstract class TwoPlayerGameMode extends OnePlayerGameMode { + protected Entity player2; + protected PlayerComponent playerComponent2; + + @Override + public GameModeTypes getGameModeType() { + return GameModeTypes.DUO; + } + + @Override + public void initGameMode() { + super.initGameMode(); + player2 = initPlayer(player2, Settings.GAME_WIDTH / 2, 0); + playerComponent2 = initPlayerComponent(player1, Direction.DOWN); + } + + @Override + public void initInput(Input input) { + onKey(KeyCode.ENTER, () -> playerComponent1.shoot()); + onKey(KeyCode.RIGHT, () -> playerComponent1.moveRight()); + onKey(KeyCode.LEFT, () -> playerComponent1.moveLeft()); + onKey(KeyCode.SPACE, () -> playerComponent2.shoot()); + onKey(KeyCode.D, () -> playerComponent2.moveRight()); + onKey(KeyCode.Q, () -> playerComponent2.moveLeft()); + } + +} diff --git a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java index 0ebecec..4f8cf65 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java @@ -7,5 +7,5 @@ * @since 0.2.0 */ public enum GameModeTypes { - CLASSIQUE, INFINITY_MODE, SOLO, MUSIC_DEMO, MULTI + CLASSIQUE, INFINITY_MODE, SOLO, DUO, MUSIC_DEMO, MULTI } From 1bb127c9eb6a56cff5fb9d90a3a733b0ab22a314 Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Sun, 5 Mar 2023 17:51:14 +0100 Subject: [PATCH 17/50] First version, alien spawn --- .../Component/AlienComponent.java | 1 + .../org/enstabretagne/Game/GameLauncher.java | 91 ++++++++++++++++--- 2 files changed, 79 insertions(+), 13 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java index 36e740c..d5d501e 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java @@ -24,6 +24,7 @@ public class AlienComponent extends Component { private Double last_shot = 0.0; private double limit_right = Constant.GAME_WIDTH; private double limit_left = 0.0; + public double alien_tag = -1; //sert à identifier l'alien en multi-joueur /** * Constructeur de la classe AlienComponent diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 2eb09ce..870fd91 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -12,6 +12,7 @@ import java.util.stream.Collectors; import com.almasb.fxgl.core.serialization.Bundle; +import com.almasb.fxgl.entity.component.Component; import com.almasb.fxgl.net.Client; import com.almasb.fxgl.net.Server; import org.enstabretagne.Component.AlienComponent; @@ -73,6 +74,7 @@ public static void setGameMode(GameMode gameMode) { private boolean multiplayerGameInProgress = false; // indique si la partie multijoueur est lancée ou non // LBF : dans le mode multi ??? + private double alienTag= 0; //permet de numéroter les aliens /** * Initialisation des paramètres du jeu * @@ -219,12 +221,14 @@ protected void initGameVars(Map vars) { */ @Override protected void initGame() { - if(GameMode == MULTI) { // LBF : dans le mode multijoueur - isServer(); - } play(assetNames.sounds.START_CLAIRON); getGameWorld().addEntityFactory(new SpaceInvadersFactory()); + if(GameMode == MULTI) { // LBF : dans le mode multijoueur + isServer(); + } + + player1 = spawn(entityNames.PLAYER); // LBF : dans tous les modes de jeu player1.setX(Constant.GAME_WIDTH / 2); player1.setY(Constant.GAME_HEIGHT - player1.getHeight()); @@ -277,6 +281,14 @@ private void isServer(){ // LBF : dans le mode multijoueur onReceiveMessageServer(); server.startAsync(); multiplayerGameInProgress = true; + if(isServer) { + run(() -> { + AlienSpawnAndBroadcast(Constant.Direction.UP); + }, Duration.seconds(1.4)); + run(() -> { + AlienSpawnAndBroadcast(Constant.Direction.DOWN); + }, Duration.seconds(1.5)); + } } else { isServer = false; System.out.println("client"); @@ -290,10 +302,19 @@ private void isServer(){ // LBF : dans le mode multijoueur },Duration.seconds(0)); } + + private void onUpdateLogic(){// LBF : dans le mode multijoueur + if (isServer) { + Player1Broadcast(); + } else { + Player2Broadcast(); + } + } + /** * Envoie des données du serveur vers le client */ - private void onUpdateServerLogic(){ // LBF : dans le mode multijoueur + private void Player1Broadcast(){ // LBF : dans le mode multijoueur Bundle bundle = new Bundle("Player1"); bundle.put("type", "Player1"); bundle.put("x", player1.getX()); @@ -303,10 +324,11 @@ private void onUpdateServerLogic(){ // LBF : dans le mode multijoueur server.broadcast(bundle); } + /** * Logique lors de la réception des données du client par le serveur */ - private void onReceiveMessageServer(){ // LBF : dans le mode multijoueur + private void onReceiveMessageServer() { // LBF : dans le mode multijoueur server.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { if (message.getName().equals("Player2")) { @@ -314,8 +336,11 @@ private void onReceiveMessageServer(){ // LBF : dans le mode multijoueur player2.setY(message.get("y")); playerComponent2.setScore(message.get("score")); playerComponent2.setLife(message.get("life")); - }else if (message.getName().equals("Player2Shoot")) { + } else if (message.getName().equals("Player2Shoot")) { playerComponent2.shoot(); + } else if (message.getName().equals("AlienClientShoot")){ + + } }); }); @@ -324,7 +349,7 @@ private void onReceiveMessageServer(){ // LBF : dans le mode multijoueur /** * Envoie des données du client vers le serveur */ - private void onUpdateClientLogic(){ // LBF : dans le mode multijoueur + private void Player2Broadcast(){ // LBF : dans le mode multijoueur Bundle bundle = new Bundle("Player2"); bundle.put("type", "Player2"); bundle.put("x", player2.getX()); @@ -347,11 +372,35 @@ private void onReceiveMessageClient() { // LBF : dans le mode multijoueur playerComponent1.setLife(message.get("life")); } else if (message.getName().equals("Player1Shoot")) { playerComponent1.shoot(); + } else if (message.getName().equals("AlienSpawn")) { + if (message.get("direction") == Constant.Direction.DOWN) { + Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Constant.Direction.DOWN); + alien.getComponent(AlienComponent.class).alien_tag = message.get("alien_tag"); + } else{ + Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Constant.Direction.UP); + alien.getComponent(AlienComponent.class).alien_tag = message.get("alien_tag"); + } } }); }); } + private void AlienShoot(Entity alien){ // LBF : dans le mode multijoueur + if (isServer) { + Bundle bundle = new Bundle("AlienServerShoot"); + bundle.put("x", alien.getX()); + bundle.put("y", alien.getY()); + server.broadcast(bundle); + } else { + Bundle bundle = new Bundle("AlienClientShoot"); + bundle.put("x", alien.getX()); + bundle.put("y", alien.getY()); + client.broadcast(bundle); + } + } + private void onShootBroadcastLogic(){ // LBF : dans le mode multijoueur if (isServer) { @@ -361,6 +410,25 @@ private void onShootBroadcastLogic(){ // LBF : dans le mode multijoueur } } + private void AlienSpawnAndBroadcast(Constant.Direction direction) { // LBF : dans le mode multijoueur + if (direction == Constant.Direction.DOWN) { + Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Constant.Direction.DOWN); + alien.getComponent(AlienComponent.class).alien_tag = alienTag; + alienTag++; + } else{ + Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Constant.Direction.UP); + alien.getComponent(AlienComponent.class).alien_tag = alienTag; + alienTag++; + } + Bundle bundle = new Bundle("AlienSpawn"); + bundle.put("direction", direction); + bundle.put("alien_tag", alienTag); + server.broadcast(bundle); + } + + private void makeAlienBlock() { for (int i = 0; i < 2; i++) { makeAlienLine(i, Constant.Direction.DOWN); @@ -459,11 +527,7 @@ private HBox createLifeUI(int life) { @Override protected void onUpdate(double tpf) { if (multiplayerGameInProgress) { // LBF : dans le mode multijoueur ou réecrire autrement?? - if (isServer) { - onUpdateServerLogic(); - } else { - onUpdateClientLogic(); - } + onUpdateLogic(); } if (getb(GameVariableNames.isGameOver)) gameOverScreen(); @@ -479,8 +543,9 @@ protected void onUpdate(double tpf) { showPlayersLivesAndScores(); run(() -> { getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { - if (FXGLMath.randomBoolean(0.01)) + if (FXGLMath.randomBoolean(0.0001)){ alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); + AlienShoot(alien);} }); }, Duration.seconds(Constant.random.nextDouble() * 10)); } From 34409bcdf21f8088e0891a41318c1e505d12c34c Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Sun, 5 Mar 2023 18:13:01 +0100 Subject: [PATCH 18/50] Added Alien Shots the alien only shoots at us --- .../Component/AlienComponent.java | 4 +++ .../org/enstabretagne/Game/GameLauncher.java | 30 ++++++------------- 2 files changed, 13 insertions(+), 21 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java index d5d501e..5c38dd8 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java @@ -78,6 +78,10 @@ public void onUpdate(double tpf) { this.move(dx); } + public Direction getDirection() { + return globalDirection; + } + /** * Déplacement de l'alien selon la direction et les limites du jeu. * L'alien se déplace de dx pixels. diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 870fd91..56fe1e6 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -338,9 +338,6 @@ private void onReceiveMessageServer() { // LBF : dans le mode multijoueur playerComponent2.setLife(message.get("life")); } else if (message.getName().equals("Player2Shoot")) { playerComponent2.shoot(); - } else if (message.getName().equals("AlienClientShoot")){ - - } }); }); @@ -387,21 +384,6 @@ private void onReceiveMessageClient() { // LBF : dans le mode multijoueur }); } - private void AlienShoot(Entity alien){ // LBF : dans le mode multijoueur - if (isServer) { - Bundle bundle = new Bundle("AlienServerShoot"); - bundle.put("x", alien.getX()); - bundle.put("y", alien.getY()); - server.broadcast(bundle); - } else { - Bundle bundle = new Bundle("AlienClientShoot"); - bundle.put("x", alien.getX()); - bundle.put("y", alien.getY()); - client.broadcast(bundle); - } - } - - private void onShootBroadcastLogic(){ // LBF : dans le mode multijoueur if (isServer) { server.broadcast(new Bundle("Player1Shoot")); @@ -541,13 +523,19 @@ protected void onUpdate(double tpf) { } if (getGameScene().getContentRoot().getChildren().contains(playersUI)) showPlayersLivesAndScores(); + run(() -> { getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { - if (FXGLMath.randomBoolean(0.0001)){ - alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); - AlienShoot(alien);} + if (FXGLMath.randomBoolean(0.005)){ + if(isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.DOWN) { + alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); + } else if (!isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.UP) { + alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); + } + } }); }, Duration.seconds(Constant.random.nextDouble() * 10)); + } /** From 48079ac0c1a185f3163a6392ff7199d933e9a24e Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Sun, 5 Mar 2023 18:33:53 +0100 Subject: [PATCH 19/50] Synchronization at startup --- .../org/enstabretagne/Game/GameLauncher.java | 80 ++++++++++++------- 1 file changed, 50 insertions(+), 30 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 56fe1e6..9f97543 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -71,8 +71,13 @@ public static void setGameMode(GameMode gameMode) { private boolean isServer; private Server server; private Client client; + + + // LBF : dans le mode multi ?? + //utile pour la synchro du lancement du multijoueur private boolean multiplayerGameInProgress = false; // indique si la partie multijoueur est lancée ou non - // LBF : dans le mode multi ??? + private boolean multiplayerGameWaiting = false; // indique si une partie multijoueur est en attente + private boolean alienSpawnStart = false; // indique si les aliens ont commencé à spawn private double alienTag= 0; //permet de numéroter les aliens /** @@ -280,26 +285,20 @@ private void isServer(){ // LBF : dans le mode multijoueur server = getNetService().newTCPServer(55555); // todo -> selection du port onReceiveMessageServer(); server.startAsync(); - multiplayerGameInProgress = true; - if(isServer) { - run(() -> { - AlienSpawnAndBroadcast(Constant.Direction.UP); - }, Duration.seconds(1.4)); - run(() -> { - AlienSpawnAndBroadcast(Constant.Direction.DOWN); - }, Duration.seconds(1.5)); - } + multiplayerGameWaiting = true; + } else { isServer = false; System.out.println("client"); client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port onReceiveMessageClient(); client.connectAsync(); - multiplayerGameInProgress = true; + multiplayerGameWaiting = true; } }); return null; },Duration.seconds(0)); + } @@ -338,6 +337,10 @@ private void onReceiveMessageServer() { // LBF : dans le mode multijoueur playerComponent2.setLife(message.get("life")); } else if (message.getName().equals("Player2Shoot")) { playerComponent2.shoot(); + } else if (message.getName().equals("Client Connected")) { + server.broadcast(new Bundle("Server Start")); + multiplayerGameInProgress = true; + } }); }); @@ -379,6 +382,8 @@ private void onReceiveMessageClient() { // LBF : dans le mode multijoueur alien.getComponent(AlienComponent.class).initialize(Constant.Direction.UP); alien.getComponent(AlienComponent.class).alien_tag = message.get("alien_tag"); } + } else if (message.getName().equals("Server Start")) { + multiplayerGameInProgress = true; } }); }); @@ -510,31 +515,46 @@ private HBox createLifeUI(int life) { protected void onUpdate(double tpf) { if (multiplayerGameInProgress) { // LBF : dans le mode multijoueur ou réecrire autrement?? onUpdateLogic(); - } - if (getb(GameVariableNames.isGameOver)) - gameOverScreen(); - if (getb(GameVariableNames.isGameWon)) - winScreen(); - - if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { - ambientSound(); - last_ambient_sound = System.currentTimeMillis(); - delay_ambient_sound = FXGLMath.random(Constant.AMBIENT_SOUND_DELAY_MIN, Constant.AMBIENT_SOUND_DELAY_MAX); - } - if (getGameScene().getContentRoot().getChildren().contains(playersUI)) - showPlayersLivesAndScores(); + if(!alienSpawnStart && isServer){ + run(() -> { + AlienSpawnAndBroadcast(Constant.Direction.UP); + }, Duration.seconds(1.4)); + run(() -> { + AlienSpawnAndBroadcast(Constant.Direction.DOWN); + }, Duration.seconds(1.5)); + alienSpawnStart = true; + } + } else if (multiplayerGameInProgress || GameMode !=MULTI) { + if (getb(GameVariableNames.isGameOver)) + gameOverScreen(); + if (getb(GameVariableNames.isGameWon)) + winScreen(); + + if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { + ambientSound(); + last_ambient_sound = System.currentTimeMillis(); + delay_ambient_sound = FXGLMath.random(Constant.AMBIENT_SOUND_DELAY_MIN, Constant.AMBIENT_SOUND_DELAY_MAX); + } + if (getGameScene().getContentRoot().getChildren().contains(playersUI)) + showPlayersLivesAndScores(); - run(() -> { - getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { - if (FXGLMath.randomBoolean(0.005)){ - if(isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.DOWN) { + run(() -> { + getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { + if (FXGLMath.randomBoolean(0.005)) { + if (isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.DOWN) { alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); } else if (!isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.UP) { alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); } } - }); - }, Duration.seconds(Constant.random.nextDouble() * 10)); + }); + }, Duration.seconds(Constant.random.nextDouble() * 10)); + } else { + //Synchronise le début de la partie entre les deux joueurs + if(!isServer && multiplayerGameWaiting){ + client.broadcast(new Bundle("Client Connected")); + } + } } From a1c86f719e5fee909c66764bfef552d19731d08b Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Sun, 5 Mar 2023 18:38:56 +0100 Subject: [PATCH 20/50] Prevents from moving before the game starts --- .../java/org/enstabretagne/Game/GameLauncher.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 9f97543..d1285c6 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -135,7 +135,7 @@ protected void initInput() { }else { playerComponent2.shoot(); } - } else { + } else if (!multiplayerGameWaiting){ playerComponent1.shoot(); } }); @@ -147,7 +147,7 @@ protected void initInput() { } else { playerComponent2.moveRight(); } - }else { + }else if (!multiplayerGameWaiting) { playerComponent1.moveRight(); } }); @@ -159,7 +159,7 @@ protected void initInput() { } else { playerComponent2.moveLeft(); } - }else { + }else if (!multiplayerGameWaiting) { playerComponent1.moveLeft(); } }); @@ -174,7 +174,7 @@ protected void initInput() { }else { playerComponent2.shoot(); } - } else { + } else if (!multiplayerGameWaiting) { playerComponent2.shoot(); } }); @@ -188,7 +188,7 @@ protected void initInput() { } else { playerComponent2.moveRight(); } - }else { + }else if (!multiplayerGameWaiting) { playerComponent2.moveRight(); } }); @@ -202,7 +202,7 @@ protected void initInput() { } else { playerComponent2.moveLeft(); } - } else { + } else if (!multiplayerGameWaiting) { playerComponent2.moveLeft(); } }); @@ -233,7 +233,6 @@ protected void initGame() { isServer(); } - player1 = spawn(entityNames.PLAYER); // LBF : dans tous les modes de jeu player1.setX(Constant.GAME_WIDTH / 2); player1.setY(Constant.GAME_HEIGHT - player1.getHeight()); From b11908998d8b5b53bee0b9b7dd1df2a602dcd3b6 Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Sun, 5 Mar 2023 18:42:34 +0100 Subject: [PATCH 21/50] Minor change --- .../src/main/java/org/enstabretagne/Game/GameLauncher.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index d1285c6..d3e2b3a 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -339,7 +339,6 @@ private void onReceiveMessageServer() { // LBF : dans le mode multijoueur } else if (message.getName().equals("Client Connected")) { server.broadcast(new Bundle("Server Start")); multiplayerGameInProgress = true; - } }); }); @@ -548,7 +547,7 @@ protected void onUpdate(double tpf) { } }); }, Duration.seconds(Constant.random.nextDouble() * 10)); - } else { + } else { // LBF : dans le mode multijoueur //Synchronise le début de la partie entre les deux joueurs if(!isServer && multiplayerGameWaiting){ client.broadcast(new Bundle("Client Connected")); From 8d3feeb27797209a135475199a039a6b5744badd Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Mon, 6 Mar 2023 18:14:34 +0100 Subject: [PATCH 22/50] Code cleaning --- .../org/enstabretagne/Game/GameLauncher.java | 189 ++++++++++-------- 1 file changed, 108 insertions(+), 81 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index d3e2b3a..ad89e18 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -12,7 +12,6 @@ import java.util.stream.Collectors; import com.almasb.fxgl.core.serialization.Bundle; -import com.almasb.fxgl.entity.component.Component; import com.almasb.fxgl.net.Client; import com.almasb.fxgl.net.Server; import org.enstabretagne.Component.AlienComponent; @@ -75,6 +74,7 @@ public static void setGameMode(GameMode gameMode) { // LBF : dans le mode multi ?? //utile pour la synchro du lancement du multijoueur + // todo : reinitialiser à false à chaque fin de partie ou lancement private boolean multiplayerGameInProgress = false; // indique si la partie multijoueur est lancée ou non private boolean multiplayerGameWaiting = false; // indique si une partie multijoueur est en attente private boolean alienSpawnStart = false; // indique si les aliens ont commencé à spawn @@ -275,42 +275,55 @@ protected void initGame() { loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); } + /** + * Input box pour le choix héberger/rejoindre une partie multijoueur + */ private void isServer(){ // LBF : dans le mode multijoueur runOnce(() -> { getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { - if (yes) { - isServer = true; - System.out.println("server"); - server = getNetService().newTCPServer(55555); // todo -> selection du port - onReceiveMessageServer(); - server.startAsync(); - multiplayerGameWaiting = true; - - } else { - isServer = false; - System.out.println("client"); - client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port - onReceiveMessageClient(); - client.connectAsync(); - multiplayerGameWaiting = true; - } + if (yes) { isServer_ServerInit(); } else { isServer_ClientInit(); } }); return null; },Duration.seconds(0)); + } + /** + * Initialisation du serveur + */ + private void isServer_ServerInit(){ + isServer = true; + System.out.println("server"); + server = getNetService().newTCPServer(55555); // todo -> selection du port + onReceiveMessageServer(); + server.startAsync(); + multiplayerGameWaiting = true; } + /** + * Initialisation du client + */ + private void isServer_ClientInit(){ + isServer = false; + System.out.println("client"); + client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port + onReceiveMessageClient(); + client.connectAsync(); + multiplayerGameWaiting = true; + } - private void onUpdateLogic(){// LBF : dans le mode multijoueur + /** + * Logique d'envoi des données à chaque frame + */ + private void onUpdateBroadcastLogic(){// LBF : dans le mode multijoueur if (isServer) { Player1Broadcast(); } else { Player2Broadcast(); - } + } //Ne sert à rien pour le moment mais utile si plus de choses à transférer à chaque frame } /** - * Envoie des données du serveur vers le client + * Envoie des données du joueur 1 du serveur vers le client */ private void Player1Broadcast(){ // LBF : dans le mode multijoueur Bundle bundle = new Bundle("Player1"); @@ -322,6 +335,18 @@ private void Player1Broadcast(){ // LBF : dans le mode multijoueur server.broadcast(bundle); } + /** + * Envoie des données du joueur 2 du client vers le serveur + */ + private void Player2Broadcast(){ // LBF : dans le mode multijoueur + Bundle bundle = new Bundle("Player2"); + bundle.put("type", "Player2"); + bundle.put("x", player2.getX()); + bundle.put("y", player2.getY()); + bundle.put("score", playerComponent2.getScore()); + bundle.put("life", playerComponent2.getLife()); + client.broadcast(bundle); + } /** * Logique lors de la réception des données du client par le serveur @@ -339,24 +364,13 @@ private void onReceiveMessageServer() { // LBF : dans le mode multijoueur } else if (message.getName().equals("Client Connected")) { server.broadcast(new Bundle("Server Start")); multiplayerGameInProgress = true; + } else{ + System.out.println("Message non reconnu"); } }); }); } - /** - * Envoie des données du client vers le serveur - */ - private void Player2Broadcast(){ // LBF : dans le mode multijoueur - Bundle bundle = new Bundle("Player2"); - bundle.put("type", "Player2"); - bundle.put("x", player2.getX()); - bundle.put("y", player2.getY()); - bundle.put("score", playerComponent2.getScore()); - bundle.put("life", playerComponent2.getLife()); - client.broadcast(bundle); - } - /** * Logique lors de la réception des données du serveur par le client */ @@ -382,11 +396,16 @@ private void onReceiveMessageClient() { // LBF : dans le mode multijoueur } } else if (message.getName().equals("Server Start")) { multiplayerGameInProgress = true; + } else{ + System.out.println("Message non reconnu"); } }); }); } + /** + * Logique d'envoi des données lors du tir d'un joueur + */ private void onShootBroadcastLogic(){ // LBF : dans le mode multijoueur if (isServer) { server.broadcast(new Bundle("Player1Shoot")); @@ -395,18 +414,15 @@ private void onShootBroadcastLogic(){ // LBF : dans le mode multijoueur } } + /** + * Logique d'envoi des données lors de l'apparition d'un alien + */ private void AlienSpawnAndBroadcast(Constant.Direction direction) { // LBF : dans le mode multijoueur - if (direction == Constant.Direction.DOWN) { - Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Constant.Direction.DOWN); - alien.getComponent(AlienComponent.class).alien_tag = alienTag; - alienTag++; - } else{ - Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Constant.Direction.UP); - alien.getComponent(AlienComponent.class).alien_tag = alienTag; - alienTag++; - } + Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(direction); + alien.getComponent(AlienComponent.class).alien_tag = alienTag; + alienTag++; + Bundle bundle = new Bundle("AlienSpawn"); bundle.put("direction", direction); bundle.put("alien_tag", alienTag); @@ -447,6 +463,16 @@ private void makeAlienBlockSolo() { } } + private void onStartAlienSpawnServer(){ + run(() -> { + AlienSpawnAndBroadcast(Constant.Direction.UP); + }, Duration.seconds(1.4)); + run(() -> { + AlienSpawnAndBroadcast(Constant.Direction.DOWN); + }, Duration.seconds(1.5)); + alienSpawnStart = true; + } + /** * Initialisation des propriétés physiques du jeu liées aux collisions */ @@ -511,50 +537,51 @@ private HBox createLifeUI(int life) { */ @Override protected void onUpdate(double tpf) { + if(GameMode == MULTI){ + onUpdateMultiplayer(tpf); + } else{ + onUpdateCommon(tpf); + } + } + private void onUpdateMultiplayer(double tpf){ // LBF : dans le mode multijoueur if (multiplayerGameInProgress) { // LBF : dans le mode multijoueur ou réecrire autrement?? - onUpdateLogic(); - if(!alienSpawnStart && isServer){ - run(() -> { - AlienSpawnAndBroadcast(Constant.Direction.UP); - }, Duration.seconds(1.4)); - run(() -> { - AlienSpawnAndBroadcast(Constant.Direction.DOWN); - }, Duration.seconds(1.5)); - alienSpawnStart = true; - } - } else if (multiplayerGameInProgress || GameMode !=MULTI) { - if (getb(GameVariableNames.isGameOver)) - gameOverScreen(); - if (getb(GameVariableNames.isGameWon)) - winScreen(); - - if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { - ambientSound(); - last_ambient_sound = System.currentTimeMillis(); - delay_ambient_sound = FXGLMath.random(Constant.AMBIENT_SOUND_DELAY_MIN, Constant.AMBIENT_SOUND_DELAY_MAX); - } - if (getGameScene().getContentRoot().getChildren().contains(playersUI)) - showPlayersLivesAndScores(); - - run(() -> { - getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { - if (FXGLMath.randomBoolean(0.005)) { - if (isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.DOWN) { - alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); - } else if (!isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.UP) { - alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); - } - } - }); - }, Duration.seconds(Constant.random.nextDouble() * 10)); - } else { // LBF : dans le mode multijoueur + onUpdateBroadcastLogic(); + onUpdateCommon(tpf); + if(!alienSpawnStart && isServer){onStartAlienSpawnServer();} + } else { //Synchronise le début de la partie entre les deux joueurs if(!isServer && multiplayerGameWaiting){ client.broadcast(new Bundle("Client Connected")); } } - } + private void onUpdateCommon(double tpf){ // LBF : dans tous les modes de jeu + if (getb(GameVariableNames.isGameOver)) + gameOverScreen(); + if (getb(GameVariableNames.isGameWon)) + winScreen(); + + if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { + ambientSound(); + last_ambient_sound = System.currentTimeMillis(); + delay_ambient_sound = FXGLMath.random(Constant.AMBIENT_SOUND_DELAY_MIN, Constant.AMBIENT_SOUND_DELAY_MAX); + } + if (getGameScene().getContentRoot().getChildren().contains(playersUI)) + showPlayersLivesAndScores(); + + run(() -> { + getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { + if (FXGLMath.randomBoolean(0.005)) { + if (isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.DOWN) { + alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); + } else if (!isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.UP) { + alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); + } + } + }); + }, Duration.seconds(Constant.random.nextDouble() * 10)); + } + /** * Affichage de l'écran de fin de partie From 230c842b450330eadb690a8c036b0cfd8d2003cb Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Mon, 6 Mar 2023 18:33:23 +0100 Subject: [PATCH 23/50] Alien Spawn in block in multiplayer --- .../org/enstabretagne/Game/GameLauncher.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index ad89e18..249f84f 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -311,6 +311,11 @@ private void isServer_ClientInit(){ multiplayerGameWaiting = true; } + private void startMultiGame(){ + long startGameTime = System.currentTimeMillis(); + System.out.println("startGameTime : " + startGameTime); + makeAlienBlock(); + } /** * Logique d'envoi des données à chaque frame */ @@ -362,8 +367,11 @@ private void onReceiveMessageServer() { // LBF : dans le mode multijoueur } else if (message.getName().equals("Player2Shoot")) { playerComponent2.shoot(); } else if (message.getName().equals("Client Connected")) { - server.broadcast(new Bundle("Server Start")); - multiplayerGameInProgress = true; + if(!multiplayerGameInProgress) { + server.broadcast(new Bundle("Server Start")); + multiplayerGameInProgress = true; + startMultiGame(); + } } else{ System.out.println("Message non reconnu"); } @@ -396,6 +404,7 @@ private void onReceiveMessageClient() { // LBF : dans le mode multijoueur } } else if (message.getName().equals("Server Start")) { multiplayerGameInProgress = true; + startMultiGame(); } else{ System.out.println("Message non reconnu"); } @@ -536,7 +545,7 @@ private HBox createLifeUI(int life) { * @param tpf */ @Override - protected void onUpdate(double tpf) { + protected void onUpdate(double tpf ) { if(GameMode == MULTI){ onUpdateMultiplayer(tpf); } else{ @@ -547,7 +556,7 @@ private void onUpdateMultiplayer(double tpf){ // LBF : dans le mode multijoueur if (multiplayerGameInProgress) { // LBF : dans le mode multijoueur ou réecrire autrement?? onUpdateBroadcastLogic(); onUpdateCommon(tpf); - if(!alienSpawnStart && isServer){onStartAlienSpawnServer();} +// if(!alienSpawnStart && isServer){onStartAlienSpawnServer();} } else { //Synchronise le début de la partie entre les deux joueurs if(!isServer && multiplayerGameWaiting){ From 2550a3993b72cf2a209cd4e2e585513f26dc8c9b Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Mon, 6 Mar 2023 18:48:26 +0100 Subject: [PATCH 24/50] Delete Alien_tag feature, refactoring of sync variables in GameVariableNames --- .../Component/AlienComponent.java | 1 - .../enstabretagne/Core/GameVariableNames.java | 6 +++ .../org/enstabretagne/Game/GameLauncher.java | 52 ++++++++----------- 3 files changed, 27 insertions(+), 32 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java index 5c38dd8..74c59b4 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java @@ -24,7 +24,6 @@ public class AlienComponent extends Component { private Double last_shot = 0.0; private double limit_right = Constant.GAME_WIDTH; private double limit_left = 0.0; - public double alien_tag = -1; //sert à identifier l'alien en multi-joueur /** * Constructeur de la classe AlienComponent diff --git a/duelinvaders/src/main/java/org/enstabretagne/Core/GameVariableNames.java b/duelinvaders/src/main/java/org/enstabretagne/Core/GameVariableNames.java index 6b48aac..df31363 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Core/GameVariableNames.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Core/GameVariableNames.java @@ -15,4 +15,10 @@ public class GameVariableNames { public static final String PLAYER2_LIFE = "Player2_lives"; public static final String isGameOver = "isGameOver"; public static final String isGameWon = "isGameWon"; + + + // LBF : dans le mode multi ?? + //utile pour la synchro du lancement du multijoueur + public static boolean multiplayerGameInProgress = false; + public static boolean multiplayerGameWaiting = false; } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 249f84f..25d062b 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -71,15 +71,8 @@ public static void setGameMode(GameMode gameMode) { private Server server; private Client client; - - // LBF : dans le mode multi ?? - //utile pour la synchro du lancement du multijoueur - // todo : reinitialiser à false à chaque fin de partie ou lancement - private boolean multiplayerGameInProgress = false; // indique si la partie multijoueur est lancée ou non - private boolean multiplayerGameWaiting = false; // indique si une partie multijoueur est en attente private boolean alienSpawnStart = false; // indique si les aliens ont commencé à spawn - private double alienTag= 0; //permet de numéroter les aliens /** * Initialisation des paramètres du jeu * @@ -128,38 +121,38 @@ public FXGLMenu newMainMenu() { @Override protected void initInput() { onKey(KeyCode.ENTER, () -> { - if (multiplayerGameInProgress){ + if (GameVariableNames.multiplayerGameInProgress){ onShootBroadcastLogic(); if(isServer){ playerComponent1.shoot(); }else { playerComponent2.shoot(); } - } else if (!multiplayerGameWaiting){ + } else if (!GameVariableNames.multiplayerGameWaiting){ playerComponent1.shoot(); } }); onKey(KeyCode.RIGHT, () -> { - if (multiplayerGameInProgress) { + if (GameVariableNames.multiplayerGameInProgress) { if(isServer) { playerComponent1.moveRight(); } else { playerComponent2.moveRight(); } - }else if (!multiplayerGameWaiting) { + }else if (!GameVariableNames.multiplayerGameWaiting) { playerComponent1.moveRight(); } }); onKey(KeyCode.LEFT, () -> { - if (multiplayerGameInProgress) { + if (GameVariableNames.multiplayerGameInProgress) { if(isServer) { playerComponent1.moveLeft(); } else { playerComponent2.moveLeft(); } - }else if (!multiplayerGameWaiting) { + }else if (!GameVariableNames.multiplayerGameWaiting) { playerComponent1.moveLeft(); } }); @@ -167,14 +160,14 @@ protected void initInput() { onKey(KeyCode.SPACE, () -> { if (GameMode == SOLO) { playerComponent1.shoot(); - } else if (multiplayerGameInProgress){ + } else if (GameVariableNames.multiplayerGameInProgress){ onShootBroadcastLogic(); if(isServer){ playerComponent1.shoot(); }else { playerComponent2.shoot(); } - } else if (!multiplayerGameWaiting) { + } else if (!GameVariableNames.multiplayerGameWaiting) { playerComponent2.shoot(); } }); @@ -182,13 +175,13 @@ protected void initInput() { onKey(KeyCode.D, () -> { if (GameMode == SOLO) { playerComponent1.moveRight(); - } else if (multiplayerGameInProgress) { + } else if (GameVariableNames.multiplayerGameInProgress) { if(isServer) { playerComponent1.moveRight(); } else { playerComponent2.moveRight(); } - }else if (!multiplayerGameWaiting) { + }else if (!GameVariableNames.multiplayerGameWaiting) { playerComponent2.moveRight(); } }); @@ -196,13 +189,13 @@ protected void initInput() { onKey(KeyCode.Q, () -> { if (GameMode == SOLO) { playerComponent1.moveLeft(); - } else if (multiplayerGameInProgress) { + } else if (GameVariableNames.multiplayerGameInProgress) { if(isServer) { playerComponent1.moveLeft(); } else { playerComponent2.moveLeft(); } - } else if (!multiplayerGameWaiting) { + } else if (!GameVariableNames.multiplayerGameWaiting) { playerComponent2.moveLeft(); } }); @@ -218,6 +211,8 @@ protected void initInput() { protected void initGameVars(Map vars) { vars.put(GameVariableNames.isGameOver, false); vars.put(GameVariableNames.isGameWon, false); + GameVariableNames.multiplayerGameInProgress= false; + GameVariableNames.multiplayerGameWaiting= false; } /** @@ -296,7 +291,7 @@ private void isServer_ServerInit(){ server = getNetService().newTCPServer(55555); // todo -> selection du port onReceiveMessageServer(); server.startAsync(); - multiplayerGameWaiting = true; + GameVariableNames.multiplayerGameWaiting = true; } /** @@ -308,7 +303,7 @@ private void isServer_ClientInit(){ client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port onReceiveMessageClient(); client.connectAsync(); - multiplayerGameWaiting = true; + GameVariableNames.multiplayerGameWaiting = true; } private void startMultiGame(){ @@ -367,9 +362,9 @@ private void onReceiveMessageServer() { // LBF : dans le mode multijoueur } else if (message.getName().equals("Player2Shoot")) { playerComponent2.shoot(); } else if (message.getName().equals("Client Connected")) { - if(!multiplayerGameInProgress) { + if(!GameVariableNames.multiplayerGameInProgress) { server.broadcast(new Bundle("Server Start")); - multiplayerGameInProgress = true; + GameVariableNames.multiplayerGameInProgress = true; startMultiGame(); } } else{ @@ -396,14 +391,12 @@ private void onReceiveMessageClient() { // LBF : dans le mode multijoueur if (message.get("direction") == Constant.Direction.DOWN) { Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); alien.getComponent(AlienComponent.class).initialize(Constant.Direction.DOWN); - alien.getComponent(AlienComponent.class).alien_tag = message.get("alien_tag"); } else{ Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); alien.getComponent(AlienComponent.class).initialize(Constant.Direction.UP); - alien.getComponent(AlienComponent.class).alien_tag = message.get("alien_tag"); } } else if (message.getName().equals("Server Start")) { - multiplayerGameInProgress = true; + GameVariableNames.multiplayerGameInProgress = true; startMultiGame(); } else{ System.out.println("Message non reconnu"); @@ -429,12 +422,9 @@ private void onShootBroadcastLogic(){ // LBF : dans le mode multijoueur private void AlienSpawnAndBroadcast(Constant.Direction direction) { // LBF : dans le mode multijoueur Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); alien.getComponent(AlienComponent.class).initialize(direction); - alien.getComponent(AlienComponent.class).alien_tag = alienTag; - alienTag++; Bundle bundle = new Bundle("AlienSpawn"); bundle.put("direction", direction); - bundle.put("alien_tag", alienTag); server.broadcast(bundle); } @@ -553,13 +543,13 @@ protected void onUpdate(double tpf ) { } } private void onUpdateMultiplayer(double tpf){ // LBF : dans le mode multijoueur - if (multiplayerGameInProgress) { // LBF : dans le mode multijoueur ou réecrire autrement?? + if (GameVariableNames.multiplayerGameInProgress) { // LBF : dans le mode multijoueur ou réecrire autrement?? onUpdateBroadcastLogic(); onUpdateCommon(tpf); // if(!alienSpawnStart && isServer){onStartAlienSpawnServer();} } else { //Synchronise le début de la partie entre les deux joueurs - if(!isServer && multiplayerGameWaiting){ + if(!isServer && GameVariableNames.multiplayerGameWaiting){ client.broadcast(new Bundle("Client Connected")); } } From 39bf13c89faa056d61879cb5a9c44e1629bb9c8d Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 10 Mar 2023 16:37:51 +0100 Subject: [PATCH 25/50] refactor(GameMode): :recycle: heavy refactor This commit fixes a lot of issues with the game mode system. I extracted all the game mode logic into abstract classes corresponding to the number of players for the game mode. Moreover, I fixed the GameLauncher for displaying the update on players' life and points. Removed some unused GameVariableNames. --- .../Collision/AlienBulletCollision.java | 6 +- .../Component/BulletComponent.java | 10 +-- .../Component/PlayerComponent.java | 85 ++++--------------- .../org/enstabretagne/Game/GameLauncher.java | 12 ++- .../Game/GameModes/ClassicGameMode.java | 16 +++- .../Game/GameModes/OnePlayerGameMode.java | 12 +-- .../Game/GameModes/TwoPlayerGameMode.java | 7 +- .../Utils/GameVariableNames.java | 4 - 8 files changed, 57 insertions(+), 95 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Collision/AlienBulletCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Collision/AlienBulletCollision.java index 2a03a03..b0b9ddb 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Collision/AlienBulletCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Collision/AlienBulletCollision.java @@ -44,10 +44,8 @@ public AlienBulletCollision() { protected void onCollisionBegin(Entity bullet, Entity alien) { bullet.removeFromWorld(); alien.removeFromWorld(); - int playerId = bullet.getComponent(BulletComponent.class).getPlayerId(); - Entity player = getGameWorld().getEntitiesByType(EntityType.PLAYER).stream() - .filter(p -> p.getComponent(PlayerComponent.class).getId() == playerId).findFirst().get(); - player.getComponent(PlayerComponent.class).incrementScore(); + PlayerComponent playerComponent = bullet.getComponent(BulletComponent.class).getPlayerComponent(); + playerComponent.incrementScore(); spawn(entityNames.EXPLOSION_ALIEN, alien.getPosition()); play(assetNames.sounds.EXPLOSION_ALIEN); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/BulletComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/BulletComponent.java index ef900ac..0b10b83 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/BulletComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/BulletComponent.java @@ -20,14 +20,14 @@ public class BulletComponent extends Component { private Double speed = Settings.SPEED_SHOOT; private Duration duration = Settings.BULLET_DURATION; private Point2D direction = new Point2D(0, -1); - private int playerId; + private PlayerComponent playerComponent; - public int getPlayerId() { - return playerId; + public PlayerComponent getPlayerComponent() { + return playerComponent; } - public void setPlayerId(int player_id) { - this.playerId = player_id; + public void setPlayer(PlayerComponent playerComponent) { + this.playerComponent = playerComponent; } public BulletComponent() { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java index eed370d..2809275 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java @@ -1,19 +1,16 @@ package org.enstabretagne.Component; import static com.almasb.fxgl.dsl.FXGL.getGameTimer; -import static com.almasb.fxgl.dsl.FXGL.geti; import static com.almasb.fxgl.dsl.FXGL.runOnce; -import static com.almasb.fxgl.dsl.FXGL.set; import static com.almasb.fxgl.dsl.FXGL.spawn; import static org.enstabretagne.Utils.Settings.DELAY_BETWEEN_SHOOT; import static org.enstabretagne.Utils.Settings.GAME_WIDTH; import static org.enstabretagne.Utils.Settings.PLAYER_HEIGHT; import static org.enstabretagne.Utils.Settings.SPEED_SPACESHIP; -import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; -import org.enstabretagne.Utils.entityNames; import org.enstabretagne.Utils.Settings.Direction; +import org.enstabretagne.Utils.entityNames; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.entity.component.Component; @@ -33,7 +30,9 @@ public class PlayerComponent extends Component { private Direction side_shoot = Direction.LEFT; private Settings.Direction direction = Settings.Direction.UP; private int id; - private static int counter; + private static int counter = 1; + private int score = 0; + private int life = 5; public int getId() { return id; @@ -131,7 +130,7 @@ private Point2D calculateShootPosition() { private void createBullet(Point2D position) { Entity bullet = spawn(entityNames.BULLET, position); bullet.getComponent(BulletComponent.class).initialize(this.direction); - bullet.getComponent(BulletComponent.class).setPlayerId(this.getId()); + bullet.getComponent(BulletComponent.class).setPlayer(this); last_shot = getGameTimer().getNow(); shootingRecoil(); } @@ -162,104 +161,54 @@ private void createSmoke(Point2D position) { * Incrémente le score du joueur */ public void incrementScore() { - if (isPlayer1()) - set(GameVariableNames.PLAYER1_SCORE, geti(GameVariableNames.PLAYER1_SCORE) + 1); - else - set(GameVariableNames.PLAYER2_SCORE, geti(GameVariableNames.PLAYER2_SCORE) + 1); - } - - /** - * @return boolean - */ - private boolean isPlayer1() { - return id % 2 == 1; - } - - /** - * Initialisation du score du joueur - */ - public void initializeScore() { - if (isPlayer1()) - set(GameVariableNames.PLAYER1_SCORE, 0); - else - set(GameVariableNames.PLAYER2_SCORE, 0); + setScore(getScore() + 1); + System.out.println("Score Player " + getId() + ": " + getScore()); } /** * @return int */ public int getScore() { - if (isPlayer1()) - return geti(GameVariableNames.PLAYER1_SCORE); - else - return geti(GameVariableNames.PLAYER2_SCORE); + return score; } /** * @param score */ - public void setScore(int score) { - if (isPlayer1()) - set(GameVariableNames.PLAYER1_SCORE, score); - else - set(GameVariableNames.PLAYER2_SCORE, score); + public void setScore(int newScore) { + score = Math.max(0, newScore); } public void decrementScore() { - if (isPlayer1()) - set(GameVariableNames.PLAYER1_SCORE, geti(GameVariableNames.PLAYER1_SCORE) - 1); - else - set(GameVariableNames.PLAYER2_SCORE, geti(GameVariableNames.PLAYER2_SCORE) - 1); + setScore(getScore() - 1); } /** * Incrémente le nombre de vie du joueur */ public void incrementLife() { - if (isPlayer1()) - set(GameVariableNames.PLAYER1_LIFE, geti(GameVariableNames.PLAYER1_LIFE) + 1); - else - set(GameVariableNames.PLAYER2_LIFE, geti(GameVariableNames.PLAYER2_LIFE) + 1); - } - - /** - * Initialise le nombre de vie du joueur - */ - public void initializeLife() { - int life = 5; - if (isPlayer1()) - set(GameVariableNames.PLAYER1_LIFE, life); - else - set(GameVariableNames.PLAYER2_LIFE, life); + setLife(getLife() + 1); } /** * @return int */ public int getLife() { - if (isPlayer1()) - return geti(GameVariableNames.PLAYER1_LIFE); - else - return geti(GameVariableNames.PLAYER2_LIFE); + return life; } /** * @param life */ - public void setLife(int life) { - if (isPlayer1()) - set(GameVariableNames.PLAYER1_LIFE, life); - else - set(GameVariableNames.PLAYER2_LIFE, life); + public void setLife(int newLife) { + life = Math.max(0, newLife); } /** * Décrémente le nombre de vie du joueur */ public void decrementLife() { - if (isPlayer1()) - set(GameVariableNames.PLAYER1_LIFE, geti(GameVariableNames.PLAYER1_LIFE) - 1); - else - set(GameVariableNames.PLAYER2_LIFE, geti(GameVariableNames.PLAYER2_LIFE) - 1); + setLife(getLife() - 1); + System.out.println("Player " + getId() + " lost a life" + " (" + getLife() + " left)"); } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index db8281c..f7de013 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -192,6 +192,8 @@ protected void initPhysics() { */ @Override protected void initUI() { + if (getGameScene().getContentRoot().getChildren().contains(playersUI)) + getGameScene().removeUINode(playersUI); playersUI = showPlayersLivesAndScores(getGameWorld()); getGameScene().addChild(playersUI); } @@ -203,10 +205,14 @@ protected void initUI() { */ @Override protected void onUpdate(double tpf) { - if (getb(GameVariableNames.isGameOver)) - gameOverScreen("to refactor", "to refactor"); // TODO : refactor - if (getb(GameVariableNames.isGameWon)) + if (getb(GameVariableNames.isGameOver)) { + getGameScene().removeChild(playersUI); + gameOverScreen("to refactor", "to refactor"); + } // TODO : refactor + if (getb(GameVariableNames.isGameWon)) { + getGameScene().removeChild(playersUI); winScreen("to refactor", "to refactor"); // TODO : refactor + } if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { ambientSound(); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java index c9218f8..f5bacff 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java @@ -1,13 +1,25 @@ package org.enstabretagne.Game.GameModes; -import static org.enstabretagne.Game.GameModes.AlienFactory.*; +import static org.enstabretagne.Game.GameModes.AlienFactory.makeAlienBlock; + +import org.enstabretagne.Utils.GameModeTypes; public class ClassicGameMode extends TwoPlayerGameMode { @Override public void initGameMode() { - super.initGameMode(); + System.out.println("Init Classic Game Mode"); + super.initTwoPlayerGameMode(); + System.out.println("Init Two Player Game Mode"); makeAlienBlock(); + System.out.println("Init Alien Block"); + System.out.println("Player1 initialized ? " + (player1 != null)); + System.out.println("Game infos : \nPlayer1 :" + playerComponent1.getId() + "\nPlayer2 :" + playerComponent2.getId()); + } + + @Override + public GameModeTypes getGameModeType() { + return GameModeTypes.CLASSIQUE; } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index 66a60d1..83e683c 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -21,9 +21,9 @@ public GameModeTypes getGameModeType() { return GameModeTypes.SOLO; } - @Override - public void initGameMode() { - player1 = initPlayer(player1, Settings.GAME_WIDTH / 2, Settings.GAME_HEIGHT - player1.getHeight()); + public void initOnePlayerGameMode() { + player1 = initPlayer(player1, Settings.GAME_WIDTH / 2); + player1.setY(Settings.GAME_HEIGHT - player1.getHeight()); playerComponent1 = initPlayerComponent(player1, Direction.UP); } @@ -34,11 +34,13 @@ protected Entity initPlayer(Entity player, double positionX, double positionY) { return player; } + protected Entity initPlayer(Entity player, double positionX) { + return initPlayer(player, positionX, 0); + } + protected PlayerComponent initPlayerComponent(Entity player, Direction direction) { PlayerComponent playerComponent = player.getComponent(PlayerComponent.class); playerComponent.setDirection(direction); - playerComponent.initializeScore(); - playerComponent.initializeLife(); return playerComponent; } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java index f5b76d8..9ed6c12 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java @@ -20,11 +20,10 @@ public GameModeTypes getGameModeType() { return GameModeTypes.DUO; } - @Override - public void initGameMode() { - super.initGameMode(); + public void initTwoPlayerGameMode() { + super.initOnePlayerGameMode(); player2 = initPlayer(player2, Settings.GAME_WIDTH / 2, 0); - playerComponent2 = initPlayerComponent(player1, Direction.DOWN); + playerComponent2 = initPlayerComponent(player2, Direction.DOWN); } @Override diff --git a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java index 7c9091f..de60b16 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java @@ -9,10 +9,6 @@ * @since 0.1.0 */ public class GameVariableNames { - public static final String PLAYER1_SCORE = "Player1_score"; - public static final String PLAYER2_SCORE = "Player2_score"; - public static final String PLAYER1_LIFE = "Player1_lives"; - public static final String PLAYER2_LIFE = "Player2_lives"; public static final String isGameOver = "isGameOver"; public static final String isGameWon = "isGameWon"; } From a1a27c13b8716812ded46ce7640750600e01f728 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 10 Mar 2023 16:56:08 +0100 Subject: [PATCH 26/50] feat(GameMode): :sparkles: create game modes Created the game modes that we already had in the GameLauncher. It is now in its own class for each game mode. And it is correctly working ! --- .../org/enstabretagne/Game/GameLauncher.java | 25 ----------- .../Game/GameModes/InfinityGameMode.java | 42 +++++++++++++++++++ .../Game/GameModes/MusicDemoGameMode.java | 10 +++++ .../Game/GameModes/SoloGameMode.java | 20 +++++++++ .../org/enstabretagne/Game/NewMainMenu.java | 9 ++-- 5 files changed, 78 insertions(+), 28 deletions(-) create mode 100644 duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java create mode 100644 duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MusicDemoGameMode.java create mode 100644 duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/SoloGameMode.java diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index f7de013..0840429 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -145,31 +145,6 @@ protected void initGame() { exception.getMessage()); } - // if (GameModeType == INFINITY_MODE) { - // // spawn Aliens pour infinity mode - // Entity alien1 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - - // Settings.ALIEN_HEIGHT); - // alien1.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); - // Entity alien2 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - - // Settings.ALIEN_HEIGHT); - // alien2.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); - // run(() -> { - // Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - - // Settings.ALIEN_HEIGHT); - // alien.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); - // }, Duration.seconds(1.4)); - // run(() -> { - // Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - - // Settings.ALIEN_HEIGHT); - // alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); - // }, Duration.seconds(1.5)); - - // } else if (GameModeType == CLASSIQUE) { - // makeAlienBlock(); - // } else if (GameModeType == SOLO) { - // makeAlienBlockSolo(); - // } - spawn(entityNames.BACKGROUND); loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java new file mode 100644 index 0000000..faef18d --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java @@ -0,0 +1,42 @@ +package org.enstabretagne.Game.GameModes; + +import org.enstabretagne.Component.AlienComponent; +import org.enstabretagne.Utils.GameModeTypes; +import org.enstabretagne.Utils.Settings; +import org.enstabretagne.Utils.entityNames; + +import com.almasb.fxgl.entity.Entity; +import static com.almasb.fxgl.dsl.FXGL.*; + +import javafx.util.Duration; + +public class InfinityGameMode extends TwoPlayerGameMode { + + @Override + public void initGameMode() { + super.initTwoPlayerGameMode(); + // spawn Aliens pour infinity mode + Entity alien1 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - + Settings.ALIEN_HEIGHT); + alien1.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); + Entity alien2 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - + Settings.ALIEN_HEIGHT); + alien2.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); + run(() -> { + Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - + Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); + }, Duration.seconds(1.4)); + run(() -> { + Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - + Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); + }, Duration.seconds(1.5)); + } + + @Override + public GameModeTypes getGameModeType() { + return GameModeTypes.INFINITY_MODE; + } + +} diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MusicDemoGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MusicDemoGameMode.java new file mode 100644 index 0000000..559c01b --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MusicDemoGameMode.java @@ -0,0 +1,10 @@ +package org.enstabretagne.Game.GameModes; + +public class MusicDemoGameMode extends TwoPlayerGameMode { + + @Override + public void initGameMode() { + super.initTwoPlayerGameMode(); + } + +} diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/SoloGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/SoloGameMode.java new file mode 100644 index 0000000..d6363db --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/SoloGameMode.java @@ -0,0 +1,20 @@ +package org.enstabretagne.Game.GameModes; + +import static org.enstabretagne.Game.GameModes.AlienFactory.makeAlienBlockSolo; + +import org.enstabretagne.Utils.GameModeTypes; + +public class SoloGameMode extends OnePlayerGameMode { + + @Override + public void initGameMode() { + super.initOnePlayerGameMode(); + makeAlienBlockSolo(); + } + + @Override + public GameModeTypes getGameModeType() { + return GameModeTypes.SOLO; + } + +} diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java index 86f0064..0966846 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java @@ -6,6 +6,9 @@ import static com.almasb.fxgl.dsl.FXGL.texture; import org.enstabretagne.Game.GameModes.ClassicGameMode; +import org.enstabretagne.Game.GameModes.InfinityGameMode; +import org.enstabretagne.Game.GameModes.MusicDemoGameMode; +import org.enstabretagne.Game.GameModes.SoloGameMode; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.assetNames; @@ -72,17 +75,17 @@ private VBox createMenu() { }); SpaceButton buttonInfinityMode = new SpaceButton("Play Infinity", () -> { - GameLauncher.setGameMode(new ClassicGameMode()); // TODO: change for infinity mode + GameLauncher.setGameMode(new InfinityGameMode()); fireNewGame(); }); SpaceButton buttonSoloMode = new SpaceButton("Play Solo", () -> { - GameLauncher.setGameMode(new ClassicGameMode()); // TODO: change for solo mode + GameLauncher.setGameMode(new SoloGameMode()); fireNewGame(); }); SpaceButton buttonMusicDemo = new SpaceButton("Play Music Demo", () -> { - GameLauncher.setGameMode(new ClassicGameMode()); // TODO: change for music demo mode + GameLauncher.setGameMode(new MusicDemoGameMode()); fireNewGame(); }); From 4fc8dbecc1b7106aa9579a72dd29187e320d4077 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 10 Mar 2023 17:00:04 +0100 Subject: [PATCH 27/50] refactor(GameMode): :recycle: game mode types moved file to game mode folder/package. cleaned game mode types. --- .../src/main/java/org/enstabretagne/Game/GameLauncher.java | 2 +- .../org/enstabretagne/Game/GameModes/ClassicGameMode.java | 4 +--- .../main/java/org/enstabretagne/Game/GameModes/GameMode.java | 2 -- .../{Utils => Game/GameModes}/GameModeTypes.java | 4 ++-- .../org/enstabretagne/Game/GameModes/InfinityGameMode.java | 3 +-- .../org/enstabretagne/Game/GameModes/OnePlayerGameMode.java | 1 - .../java/org/enstabretagne/Game/GameModes/SoloGameMode.java | 2 -- .../org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java | 1 - .../src/main/java/org/enstabretagne/Game/NewMainMenu.java | 2 +- 9 files changed, 6 insertions(+), 15 deletions(-) rename duelinvaders/src/main/java/org/enstabretagne/{Utils => Game/GameModes}/GameModeTypes.java (56%) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 0840429..1271845 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -27,8 +27,8 @@ import org.enstabretagne.Component.SpaceInvadersFactory; import org.enstabretagne.Game.GameModes.ClassicGameMode; import org.enstabretagne.Game.GameModes.GameMode; +import org.enstabretagne.Game.GameModes.GameModeTypes; import org.enstabretagne.Utils.EntityType; -import org.enstabretagne.Utils.GameModeTypes; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.assetNames; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java index f5bacff..8807c3b 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java @@ -2,8 +2,6 @@ import static org.enstabretagne.Game.GameModes.AlienFactory.makeAlienBlock; -import org.enstabretagne.Utils.GameModeTypes; - public class ClassicGameMode extends TwoPlayerGameMode { @Override @@ -19,7 +17,7 @@ public void initGameMode() { @Override public GameModeTypes getGameModeType() { - return GameModeTypes.CLASSIQUE; + return GameModeTypes.CLASSIC; } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java index a32e654..8a013fd 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java @@ -1,7 +1,5 @@ package org.enstabretagne.Game.GameModes; -import org.enstabretagne.Utils.GameModeTypes; - import com.almasb.fxgl.input.Input; public interface GameMode { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameModeTypes.java similarity index 56% rename from duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java rename to duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameModeTypes.java index 4f8cf65..82118db 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameModeTypes.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameModeTypes.java @@ -1,4 +1,4 @@ -package org.enstabretagne.Utils; +package org.enstabretagne.Game.GameModes; /** * Modes de jeu disponibles @@ -7,5 +7,5 @@ * @since 0.2.0 */ public enum GameModeTypes { - CLASSIQUE, INFINITY_MODE, SOLO, DUO, MUSIC_DEMO, MULTI + CLASSIC, INFINITY, SOLO, DUO, MUSIC_DEMO, MULTI } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java index faef18d..b4f9949 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java @@ -1,7 +1,6 @@ package org.enstabretagne.Game.GameModes; import org.enstabretagne.Component.AlienComponent; -import org.enstabretagne.Utils.GameModeTypes; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.entityNames; @@ -36,7 +35,7 @@ public void initGameMode() { @Override public GameModeTypes getGameModeType() { - return GameModeTypes.INFINITY_MODE; + return GameModeTypes.INFINITY; } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index 83e683c..2e6b96c 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -1,7 +1,6 @@ package org.enstabretagne.Game.GameModes; import org.enstabretagne.Component.PlayerComponent; -import org.enstabretagne.Utils.GameModeTypes; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.entityNames; import org.enstabretagne.Utils.Settings.Direction; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/SoloGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/SoloGameMode.java index d6363db..d42a2d2 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/SoloGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/SoloGameMode.java @@ -2,8 +2,6 @@ import static org.enstabretagne.Game.GameModes.AlienFactory.makeAlienBlockSolo; -import org.enstabretagne.Utils.GameModeTypes; - public class SoloGameMode extends OnePlayerGameMode { @Override diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java index 9ed6c12..52fb912 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java @@ -1,7 +1,6 @@ package org.enstabretagne.Game.GameModes; import org.enstabretagne.Component.PlayerComponent; -import org.enstabretagne.Utils.GameModeTypes; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.Settings.Direction; diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java index 0966846..bcfccd7 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java @@ -69,7 +69,7 @@ private VBox createMenu() { VBox options = createOptions(); FXGLTextFlow creditsText = createCredits(); - SpaceButton buttonClassicMode = new SpaceButton("Play Classique", () -> { + SpaceButton buttonClassicMode = new SpaceButton("Play Classic", () -> { GameLauncher.setGameMode(new ClassicGameMode()); fireNewGame(); }); From aecbd827bf7ab108839a6a767dc032ad82fc478f Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 10 Mar 2023 17:10:37 +0100 Subject: [PATCH 28/50] refactor(collision): :recycle: simplified code --- .../Collision/BulletPlayerCollision.java | 12 ++++++------ .../Collision/EnemyShootPlayerCollision.java | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Collision/BulletPlayerCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Collision/BulletPlayerCollision.java index 861f51d..78a1943 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Collision/BulletPlayerCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Collision/BulletPlayerCollision.java @@ -43,14 +43,14 @@ protected void onCollisionBegin(Entity bullet, Entity player) { if (bullet.hasComponent(PlayerComponent.class)) { bullet.getComponent(PlayerComponent.class).incrementScore(); } - if (playerComponent.getLife() == 0) { - spawn(entityNames.EXPLOSION_PLAYER_DEATH, player.getPosition()); - player.removeFromWorld(); - play(assetNames.sounds.EXPLOSION_PLAYER_DEATH); - runOnce(() -> set(GameVariableNames.isGameOver, true), Duration.seconds(2)); - } else { + if (playerComponent.getLife() != 0) { spawn(entityNames.EXPLOSION_PLAYER_BULLET, bullet.getPosition()); play(assetNames.sounds.EXPLOSION_PLAYER_LIFE); + return; } + spawn(entityNames.EXPLOSION_PLAYER_DEATH, player.getPosition()); + player.removeFromWorld(); + play(assetNames.sounds.EXPLOSION_PLAYER_DEATH); + runOnce(() -> set(GameVariableNames.isGameOver, true), Duration.seconds(2)); } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootPlayerCollision.java b/duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootPlayerCollision.java index 43dd1c6..ed95438 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootPlayerCollision.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Collision/EnemyShootPlayerCollision.java @@ -37,14 +37,14 @@ protected void onCollisionBegin(Entity enemy_shoot, Entity player) { enemy_shoot.removeFromWorld(); PlayerComponent playerComponent = player.getComponent(PlayerComponent.class); playerComponent.decrementLife(); - if (playerComponent.getLife() == 0) { - spawn(entityNames.EXPLOSION_PLAYER_DEATH, player.getPosition()); - play(assetNames.sounds.EXPLOSION_PLAYER_DEATH); - set(GameVariableNames.isGameOver, true); - player.removeFromWorld(); - } else { + if (playerComponent.getLife() != 0) { spawn(entityNames.EXPLOSION_PLAYER_BULLET, enemy_shoot.getPosition()); play(assetNames.sounds.EXPLOSION_PLAYER_LIFE); + return; } + spawn(entityNames.EXPLOSION_PLAYER_DEATH, player.getPosition()); + play(assetNames.sounds.EXPLOSION_PLAYER_DEATH); + set(GameVariableNames.isGameOver, true); + player.removeFromWorld(); } } From 9fb71d18677453b54ea2bb44ce2d02afc6f09abe Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Fri, 10 Mar 2023 17:25:40 +0100 Subject: [PATCH 29/50] Add Input box for IP and Port --- .../org/enstabretagne/Game/GameLauncher.java | 52 +++++++++++++++++-- 1 file changed, 47 insertions(+), 5 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 25d062b..6d72212 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -73,6 +73,9 @@ public static void setGameMode(GameMode gameMode) { private boolean alienSpawnStart = false; // indique si les aliens ont commencé à spawn + private int Port; + private String IP; + /** * Initialisation des paramètres du jeu * @@ -276,7 +279,13 @@ protected void initGame() { private void isServer(){ // LBF : dans le mode multijoueur runOnce(() -> { getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { - if (yes) { isServer_ServerInit(); } else { isServer_ClientInit(); } + if (yes) { + isServer = true; + PortSelection(); + } else { + isServer = false; + PortSelection(); + } }); return null; },Duration.seconds(0)); @@ -286,9 +295,8 @@ private void isServer(){ // LBF : dans le mode multijoueur * Initialisation du serveur */ private void isServer_ServerInit(){ - isServer = true; System.out.println("server"); - server = getNetService().newTCPServer(55555); // todo -> selection du port + server = getNetService().newTCPServer(Port); onReceiveMessageServer(); server.startAsync(); GameVariableNames.multiplayerGameWaiting = true; @@ -298,14 +306,48 @@ private void isServer_ServerInit(){ * Initialisation du client */ private void isServer_ClientInit(){ - isServer = false; System.out.println("client"); - client = getNetService().newTCPClient("localhost", 55555); // todo -> selection du port + client = getNetService().newTCPClient(IP, Port); onReceiveMessageClient(); client.connectAsync(); GameVariableNames.multiplayerGameWaiting = true; } + private void PortSelection(){ + runOnce(() -> { + getDialogService().showInputBox("Entrez le port (ex:55555)", port -> { + if (port != null) { + Port = Integer.parseInt(port); + } + else { + Port = 55555; + } + System.out.println("Port : " + Port); + if(!isServer){ + IPSelection(); + } + else{ + isServer_ServerInit(); + } + }); + return null; + },Duration.seconds(0)); + } + private void IPSelection() { + runOnce(() -> { + getDialogService().showInputBox("Entrez l'adresse IP du serveur (ex: localhost ou 111.222.333.444)", ip -> { + if (ip != null) { + IP = ip; + } else { + IP = "localhost"; + } + System.out.println("IP : " + IP); + isServer_ClientInit(); + }); + return null; + }, Duration.seconds(0)); + } + private void startMultiGame(){ long startGameTime = System.currentTimeMillis(); System.out.println("startGameTime : " + startGameTime); From 2815fe4f7cf51473fa1be3a92f21a4698896861f Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 10 Mar 2023 17:29:05 +0100 Subject: [PATCH 30/50] refactor(component): :fire: cleaned components removed unused LifeComponent. updated SpaceInvadersFactory --- .../Component/AlienComponent.java | 30 +- .../Component/LifeComponent.java | 31 -- .../Component/SpaceInvadersFactory.java | 447 +++++++++--------- 3 files changed, 231 insertions(+), 277 deletions(-) delete mode 100644 duelinvaders/src/main/java/org/enstabretagne/Component/LifeComponent.java diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java index 519aaa8..ddf1b31 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/AlienComponent.java @@ -98,14 +98,15 @@ else if (this.movementDirection == Direction.LEFT) public void moveRight(Double dx) { if (this.entity.getRightX() + dx <= limit_right) { this.entity.translateX(dx); - } else { - if (this.globalDirection == Settings.Direction.DOWN) { - this.entity.translateY(dy); - } else if (this.globalDirection == Settings.Direction.UP) { - this.entity.translateY(-dy); - } - this.movementDirection = Direction.LEFT; + return; + } + + if (this.globalDirection == Settings.Direction.DOWN) { + this.entity.translateY(dy); + } else if (this.globalDirection == Settings.Direction.UP) { + this.entity.translateY(-dy); } + this.movementDirection = Direction.LEFT; } /** @@ -116,14 +117,15 @@ public void moveRight(Double dx) { public void moveLeft(Double dx) { if (this.entity.getX() - dx >= limit_left) { this.entity.translateX(-dx); - } else { - if (this.globalDirection == Settings.Direction.DOWN) { - this.entity.translateY(dy); - } else if (this.globalDirection == Settings.Direction.UP) { - this.entity.translateY(-dy); - } - this.movementDirection = Direction.RIGHT; + return; + } + + if (this.globalDirection == Settings.Direction.DOWN) { + this.entity.translateY(dy); + } else if (this.globalDirection == Settings.Direction.UP) { + this.entity.translateY(-dy); } + this.movementDirection = Direction.RIGHT; } public void setAlienNumber(int AlienNumber) { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/LifeComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/LifeComponent.java deleted file mode 100644 index a599d1f..0000000 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/LifeComponent.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.enstabretagne.Component; - -import org.enstabretagne.Utils.Settings; - -import com.almasb.fxgl.entity.component.Component; - -/** - * Cette classe représente l'affichage du nombre de vies restantes. - * - * @author MathieuDFS, jufch - * @since 0.2.0 - * @deprecated since 0.3.0 - */ -public class LifeComponent extends Component { - /** - * Initialise le composant affichage de vie - */ - public void initialize(Settings.Direction direction) { - if (direction == Settings.Direction.UP) { - entity.setX(Settings.GAME_WIDTH - Settings.LIFE_DISPLAY_WIDTH); - entity.setY(0); - } else if (direction == Settings.Direction.DOWN) { - entity.setX(Settings.GAME_WIDTH - Settings.LIFE_DISPLAY_WIDTH); - entity.setY(Settings.GAME_HEIGHT - Settings.LIFE_DISPLAY_HEIGHT); - } - } - - public void updateLife(boolean isActive) { - entity.getViewComponent().setOpacity(isActive ? 1 : 0); - } -} diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/SpaceInvadersFactory.java b/duelinvaders/src/main/java/org/enstabretagne/Component/SpaceInvadersFactory.java index 7b00368..ac5d0ad 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/SpaceInvadersFactory.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/SpaceInvadersFactory.java @@ -30,254 +30,237 @@ * @since 0.1.0 */ public class SpaceInvadersFactory implements EntityFactory { - /** - * Définition de l'entité joueur, nommé player - * - * @param data - * @return Entity - */ - @Spawns(entityNames.PLAYER) - public Entity newPlayer(SpawnData data) { - Texture texture = texture(assetNames.textures.SPACESHIP, Settings.PLAYER_WIDTH, Settings.PLAYER_HEIGHT); - return entityBuilder() - .type(EntityType.PLAYER) - .at(data.getX(), data.getY()) - .viewWithBBox(texture) - .with(new PlayerComponent()) - .collidable() - .build(); - } + /** + * Définition de l'entité joueur, nommé player + * + * @param data + * @return Entity + */ + @Spawns(entityNames.PLAYER) + public Entity newPlayer(SpawnData data) { + Texture texture = texture(assetNames.textures.SPACESHIP, Settings.PLAYER_WIDTH, Settings.PLAYER_HEIGHT); - /** - * Définition de l'entité alien, nommé alien - * - * @param data - * @return Entity - */ - @Spawns(entityNames.ALIEN) - public Entity newAlien(SpawnData data) { - int randomIndex = Settings.random.nextInt(Settings.AlienColor.values().length); - Settings.AlienColor randomColor = Settings.AlienColor.values()[randomIndex]; - Color color = Color.valueOf(randomColor.name()); - - Texture texture = texture(assetNames.textures.ALIEN, Settings.ALIEN_WIDTH, Settings.ALIEN_HEIGHT) - .multiplyColor(color); - return entityBuilder() - .type(EntityType.ALIEN) - .at(data.getX(), data.getY()) - .viewWithBBox(texture) - .with(new AlienComponent()) - .collidable() - .build(); - } + return entityBuilder() + .type(EntityType.PLAYER) + .at(data.getX(), data.getY()) + .viewWithBBox(texture) + .with(new PlayerComponent()) + .collidable() + .build(); + } - /** - * Définition de l'entité tir du joueur, nommé bullet - * Elle est uniquement utilisée par le joueur - * - * @param data - * @return Entity - */ - @Spawns(entityNames.BULLET) - public Entity newBullet(SpawnData data) { - int bulletWidth = 20; - int bulletHeight = 20; - Texture texture = texture(assetNames.textures.ROCKET, bulletWidth, bulletHeight); - texture.setRotate(90); - play(assetNames.sounds.CANNON_SHOT); + /** + * Définition de l'entité alien, nommé alien + * + * @param data + * @return Entity + */ + @Spawns(entityNames.ALIEN) + public Entity newAlien(SpawnData data) { + int randomIndex = Settings.random.nextInt(Settings.AlienColor.values().length); + Settings.AlienColor randomColor = Settings.AlienColor.values()[randomIndex]; + Color color = Color.valueOf(randomColor.name()); - return entityBuilder() - .type(EntityType.BULLET) - .at(data.getX() - bulletWidth / 2, data.getY()) - .viewWithBBox(texture) - .with(new BulletComponent()) - .with(new OffscreenCleanComponent()) - .collidable() - .build(); - } + Texture texture = texture(assetNames.textures.ALIEN, Settings.ALIEN_WIDTH, Settings.ALIEN_HEIGHT) + .multiplyColor(color); + return entityBuilder() + .type(EntityType.ALIEN) + .at(data.getX(), data.getY()) + .viewWithBBox(texture) + .with(new AlienComponent()) + .collidable() + .build(); + } - /** - * Définition de l'entité tir de l'alien, nommé alienBullet - * Elle est uniquement utilisée par les aliens - * - * @param data - * @return Entity - */ - @Spawns(entityNames.BULLET_ALIEN) - public Entity newAlienBullet(SpawnData data) { - int laserWidth = 20; - int laserHeight = 20; - Texture texture = texture(assetNames.textures.LASER, laserWidth, laserHeight); - String randomLaserSound = assetNames.sounds.LASER_SOUNDS - .get(FXGLMath.random(0, Settings.NUMBER_OF_LASER_SOUNDS - 1)); - play(randomLaserSound); + /** + * Définition de l'entité tir du joueur, nommé bullet + * Elle est uniquement utilisée par le joueur + * + * @param data + * @return Entity + */ + @Spawns(entityNames.BULLET) + public Entity newBullet(SpawnData data) { + int bulletWidth = 20; + int bulletHeight = 20; + Texture texture = texture(assetNames.textures.ROCKET, bulletWidth, bulletHeight); + texture.setRotate(90); + play(assetNames.sounds.CANNON_SHOT); - return entityBuilder() - .type(EntityType.ENEMY_SHOOT) - .at(data.getX() - laserWidth / 2, data.getY()) - .viewWithBBox(texture) - .with(new BulletComponent()) - .collidable() - .build(); - } + return entityBuilder() + .type(EntityType.BULLET) + .at(data.getX() - bulletWidth / 2, data.getY()) + .viewWithBBox(texture) + .with(new BulletComponent()) + .with(new OffscreenCleanComponent()) + .collidable() + .build(); + } - /** - * Définition de l'entité eclat, nommé eclat - * Décoration pour agrémenter le jeu lors d'un tir alien - * - * @param data - * @return Entity - */ - @Spawns(entityNames.ECLAT) - public Entity newEclat(SpawnData data) { - int eclatWidth = 150; - int eclatHeight = 150; - Texture texture = texture(assetNames.textures.ECLAT2, eclatWidth, eclatHeight); - texture.setRotate(180); - return entityBuilder() - .at(data.getX() - eclatWidth / 2, data.getY() - eclatHeight / 2) - .viewWithBBox(texture) - .with(new ExpireCleanComponent(Duration.seconds(0.05))) - .build(); - } + /** + * Définition de l'entité tir de l'alien, nommé alienBullet + * Elle est uniquement utilisée par les aliens + * + * @param data + * @return Entity + */ + @Spawns(entityNames.BULLET_ALIEN) + public Entity newAlienBullet(SpawnData data) { + int laserWidth = 20; + int laserHeight = 20; + Texture texture = texture(assetNames.textures.LASER, laserWidth, laserHeight); + String randomLaserSound = assetNames.sounds.LASER_SOUNDS + .get(FXGLMath.random(0, Settings.NUMBER_OF_LASER_SOUNDS - 1)); + play(randomLaserSound); - /** - * Définition de l'entité pour l'arrière-plan, nommé background - * Elle est utilisée pour l'arrière-plan du jeu - * - * @param data - * @return Entity - */ - @Spawns(entityNames.BACKGROUND) - public Entity newBackground(SpawnData data) { - return entityBuilder() - .at(-10, -10) - .view(texture(assetNames.textures.GAME_BACKGROUND, Settings.GAME_WIDTH + 20, Settings.GAME_HEIGHT + 20)) - .zIndex(-500) - .build(); - } + return entityBuilder() + .type(EntityType.ENEMY_SHOOT) + .at(data.getX() - laserWidth / 2, data.getY()) + .viewWithBBox(texture) + .with(new BulletComponent()) + .collidable() + .build(); + } - /** - * Définition de l'entité pour le tir du joueur, nommé shooting_start - * A but décoratif pour agrémenter le jeu - * - * @param data - * @return Entity - */ - @Spawns(entityNames.SHOOTING_START) - public Entity shooting_start(SpawnData data) { - Texture texture = texture(assetNames.textures.FIRE, Settings.SHOOTING_START_WIDTH, - Settings.SHOOTING_START_HEIGHT); - texture.setRotate(180); + /** + * Définition de l'entité eclat, nommé eclat + * Décoration pour agrémenter le jeu lors d'un tir alien + * + * @param data + * @return Entity + */ + @Spawns(entityNames.ECLAT) + public Entity newEclat(SpawnData data) { + int eclatWidth = 150; + int eclatHeight = 150; + Texture texture = texture(assetNames.textures.ECLAT2, eclatWidth, eclatHeight); + texture.setRotate(180); + return entityBuilder() + .at(data.getX() - eclatWidth / 2, data.getY() - eclatHeight / 2) + .viewWithBBox(texture) + .with(new ExpireCleanComponent(Duration.seconds(0.05))) + .build(); + } - return entityBuilder() - .at(data.getX(), data.getY()) - .view(texture) - .with(new ShootingStartComponent()) - .build(); - } + /** + * Définition de l'entité pour l'arrière-plan, nommé background + * Elle est utilisée pour l'arrière-plan du jeu + * + * @param data + * @return Entity + */ + @Spawns(entityNames.BACKGROUND) + public Entity newBackground(SpawnData data) { + return entityBuilder() + .at(-10, -10) + .view(texture(assetNames.textures.GAME_BACKGROUND, Settings.GAME_WIDTH + 20, + Settings.GAME_HEIGHT + 20)) + .zIndex(-500) + .build(); + } - /** - * Définition de l'entité pour le tir du joueur, nommé shooting_smoke - * A but décoratif pour agrémenter le jeu - * - * @param data - * @return Entity - */ - @Spawns(entityNames.SHOOTING_SMOKE) - public Entity shooting_smoke(SpawnData data) { - Texture texture = texture(assetNames.textures.SMOKE, Settings.SHOOTING_SMOKE_WIDTH, - Settings.SHOOTING_SMOKE_HEIGHT); - return entityBuilder() - .at(data.getX(), data.getY()) - .view(texture) - .with(new ShootingSmokeComponent()) - .build(); - } + /** + * Définition de l'entité pour le tir du joueur, nommé shooting_start + * A but décoratif pour agrémenter le jeu + * + * @param data + * @return Entity + */ + @Spawns(entityNames.SHOOTING_START) + public Entity shooting_start(SpawnData data) { + Texture texture = texture(assetNames.textures.FIRE, Settings.SHOOTING_START_WIDTH, + Settings.SHOOTING_START_HEIGHT); + texture.setRotate(180); - /** - * Définition de l'entité pour l'explosion, nommé explosion_alien - * A but décoratif pour agrémenter le jeu - * - * @param data - * @return Entity - */ - @Spawns(entityNames.EXPLOSION_ALIEN) - public Entity explosion_alien(SpawnData data) { - int explosion_width = 60; - int explosion_height = 60; - String randomTexture = assetNames.textures.EXPLOSIONS - .get(FXGLMath.random(0, Settings.NUMBER_OF_EXPLOSIONS - 1)); - Texture texture = texture(randomTexture, explosion_width, explosion_height); - return entityBuilder() - .at(data.getX(), data.getY()) - .view(texture) - .with(new ExpireCleanComponent(Duration.seconds(0.3))) - .build(); - } + return entityBuilder() + .at(data.getX(), data.getY()) + .view(texture) + .with(new ShootingStartComponent()) + .build(); + } - /** - * Définition de l'entité pour l'explosion, nommé explosion_player_bullet - * A but décoratif pour agrémenter le jeu - * - * @param data - * @return Entity - */ - @Spawns(entityNames.EXPLOSION_PLAYER_BULLET) - public Entity explosion_player_bullet(SpawnData data) { - int explosion_width = 70; - int explosion_height = 60; - Texture texture = texture(assetNames.textures.EXPLOSION_PLAYER, explosion_width, explosion_height); - return entityBuilder() - .at(data.getX() - explosion_width / 2, data.getY() - explosion_height / 2) - .view(texture) - .with(new ExpireCleanComponent(Duration.seconds(0.3))) - .build(); - } + /** + * Définition de l'entité pour le tir du joueur, nommé shooting_smoke + * A but décoratif pour agrémenter le jeu + * + * @param data + * @return Entity + */ + @Spawns(entityNames.SHOOTING_SMOKE) + public Entity shooting_smoke(SpawnData data) { + Texture texture = texture(assetNames.textures.SMOKE, Settings.SHOOTING_SMOKE_WIDTH, + Settings.SHOOTING_SMOKE_HEIGHT); + return entityBuilder() + .at(data.getX(), data.getY()) + .view(texture) + .with(new ShootingSmokeComponent()) + .build(); + } - /** - * Définition de l'entité pour l'explosion, nommé explosion_player_death - * A but décoratif pour agrémenter le jeu - * - * @param data - * @return Entity - */ - @Spawns(entityNames.EXPLOSION_PLAYER_DEATH) - public Entity explosion_player_death(SpawnData data) { - int explosion_width = 200; - int explosion_height = 200; - Texture texture = texture(assetNames.textures.EXPLOSION_FINAL, explosion_width, explosion_height); + /** + * Définition de l'entité pour l'explosion, nommé explosion_alien + * A but décoratif pour agrémenter le jeu + * + * @param data + * @return Entity + */ + @Spawns(entityNames.EXPLOSION_ALIEN) + public Entity explosion_alien(SpawnData data) { + int explosion_width = 60; + int explosion_height = 60; + String randomTexture = assetNames.textures.EXPLOSIONS + .get(FXGLMath.random(0, Settings.NUMBER_OF_EXPLOSIONS - 1)); + Texture texture = texture(randomTexture, explosion_width, explosion_height); + return entityBuilder() + .at(data.getX(), data.getY()) + .view(texture) + .with(new ExpireCleanComponent(Duration.seconds(0.3))) + .build(); + } - for (int i = 0; i < 20; i++) { - double x = data.getX() + FXGLMath.random(-100, 100); - double y = data.getY() + FXGLMath.random(-100, 100); - spawn(entityNames.EXPLOSION_ALIEN, x, y); + /** + * Définition de l'entité pour l'explosion, nommé explosion_player_bullet + * A but décoratif pour agrémenter le jeu + * + * @param data + * @return Entity + */ + @Spawns(entityNames.EXPLOSION_PLAYER_BULLET) + public Entity explosion_player_bullet(SpawnData data) { + int explosion_width = 70; + int explosion_height = 60; + Texture texture = texture(assetNames.textures.EXPLOSION_PLAYER, explosion_width, explosion_height); + return entityBuilder() + .at(data.getX() - explosion_width / 2, data.getY() - explosion_height / 2) + .view(texture) + .with(new ExpireCleanComponent(Duration.seconds(0.3))) + .build(); } - return entityBuilder() - .at(data.getX(), data.getY()) - .view(texture) - .zIndex(-100) - .build(); - } + /** + * Définition de l'entité pour l'explosion, nommé explosion_player_death + * A but décoratif pour agrémenter le jeu + * + * @param data + * @return Entity + */ + @Spawns(entityNames.EXPLOSION_PLAYER_DEATH) + public Entity explosion_player_death(SpawnData data) { + int explosion_width = 200; + int explosion_height = 200; + Texture texture = texture(assetNames.textures.EXPLOSION_FINAL, explosion_width, explosion_height); + + for (int i = 0; i < 20; i++) { + double x = data.getX() + FXGLMath.random(-100, 100); + double y = data.getY() + FXGLMath.random(-100, 100); + spawn(entityNames.EXPLOSION_ALIEN, x, y); + } - /** - * Définition de l'entité affichage des vies restantes - * - * @param data - * @return Entity - * @deprecated - */ - @Spawns(entityNames.LIFE) - public Entity life(SpawnData data) { - int x = (int) data.getX(); - Texture texture = texture(assetNames.textures.LIFES.get(x - 1), Settings.LIFE_DISPLAY_WIDTH, - Settings.LIFE_DISPLAY_HEIGHT); - return entityBuilder() - .at(data.getX(), data.getY()) - .view(texture) - .with(new LifeComponent()) - .build(); - } + return entityBuilder() + .at(data.getX(), data.getY()) + .view(texture) + .zIndex(-100) + .build(); + } } From 65dfc0a9bcb008359b9219b811072113d36236e4 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 10 Mar 2023 17:47:55 +0100 Subject: [PATCH 31/50] refactor(GameMode): :fire: cleaned code --- .../Game/GameModes/AlienFactory.java | 21 ++++++++++++++- .../Game/GameModes/ClassicGameMode.java | 5 ---- .../Game/GameModes/GameMode.java | 5 ++++ .../Game/GameModes/InfinityGameMode.java | 27 ++----------------- .../Game/GameModes/OnePlayerGameMode.java | 6 ----- 5 files changed, 27 insertions(+), 37 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java index d1047e3..5fc189b 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java @@ -1,12 +1,17 @@ package org.enstabretagne.Game.GameModes; +import static com.almasb.fxgl.dsl.FXGL.run; +import static com.almasb.fxgl.dsl.FXGL.spawn; + import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.entityNames; -import static com.almasb.fxgl.dsl.FXGL.*; +import org.enstabretagne.Utils.Settings.Direction; import com.almasb.fxgl.entity.Entity; +import javafx.util.Duration; + public class AlienFactory { static protected void makeAlienBlock() { for (int i = 0; i < 2; i++) { @@ -40,4 +45,18 @@ static protected void makeAlienBlockSolo() { } } } + + static protected void makeAliensInfinitely() { + makeOneAlien(Direction.UP); + makeOneAlien(Direction.DOWN); + run(() -> { + makeOneAlien(Direction.UP); + makeOneAlien(Direction.DOWN); + }, Duration.seconds(1.5)); + } + + static protected void makeOneAlien(Direction direction) { + Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(direction); + } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java index 8807c3b..41af58a 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/ClassicGameMode.java @@ -6,13 +6,8 @@ public class ClassicGameMode extends TwoPlayerGameMode { @Override public void initGameMode() { - System.out.println("Init Classic Game Mode"); super.initTwoPlayerGameMode(); - System.out.println("Init Two Player Game Mode"); makeAlienBlock(); - System.out.println("Init Alien Block"); - System.out.println("Player1 initialized ? " + (player1 != null)); - System.out.println("Game infos : \nPlayer1 :" + playerComponent1.getId() + "\nPlayer2 :" + playerComponent2.getId()); } @Override diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java index 8a013fd..8713325 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java @@ -2,6 +2,11 @@ import com.almasb.fxgl.input.Input; +/** + * Defines the contract for a game mode. + * + * @author LBF38 + */ public interface GameMode { public void initGameMode(); public void initInput(Input input); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java index b4f9949..e1b2acd 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/InfinityGameMode.java @@ -1,36 +1,13 @@ package org.enstabretagne.Game.GameModes; -import org.enstabretagne.Component.AlienComponent; -import org.enstabretagne.Utils.Settings; -import org.enstabretagne.Utils.entityNames; - -import com.almasb.fxgl.entity.Entity; -import static com.almasb.fxgl.dsl.FXGL.*; - -import javafx.util.Duration; +import static org.enstabretagne.Game.GameModes.AlienFactory.makeAliensInfinitely; public class InfinityGameMode extends TwoPlayerGameMode { @Override public void initGameMode() { super.initTwoPlayerGameMode(); - // spawn Aliens pour infinity mode - Entity alien1 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - - Settings.ALIEN_HEIGHT); - alien1.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); - Entity alien2 = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - - Settings.ALIEN_HEIGHT); - alien2.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); - run(() -> { - Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - - Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); - }, Duration.seconds(1.4)); - run(() -> { - Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - - Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); - }, Duration.seconds(1.5)); + makeAliensInfinitely(); } @Override diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index 2e6b96c..39e79bb 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -45,12 +45,6 @@ protected PlayerComponent initPlayerComponent(Entity player, Direction direction @Override public void initInput(Input input) { - if (playerComponent1 == null) { - System.out.println("No PlayerComponent"); - return; - } else { - System.out.println("PlayerComponent OK"); - } onKey(KeyCode.ENTER, () -> playerComponent1.shoot()); onKey(KeyCode.RIGHT, () -> playerComponent1.moveRight()); onKey(KeyCode.LEFT, () -> playerComponent1.moveLeft()); From 90360828ce203e35b91491fe04efc9e29abfe781 Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Fri, 10 Mar 2023 18:32:53 +0100 Subject: [PATCH 32/50] Minor change Delet infini online mod --- .../org/enstabretagne/Game/GameLauncher.java | 26 ++----------------- 1 file changed, 2 insertions(+), 24 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 6d72212..76e2710 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -458,17 +458,6 @@ private void onShootBroadcastLogic(){ // LBF : dans le mode multijoueur } } - /** - * Logique d'envoi des données lors de l'apparition d'un alien - */ - private void AlienSpawnAndBroadcast(Constant.Direction direction) { // LBF : dans le mode multijoueur - Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(direction); - - Bundle bundle = new Bundle("AlienSpawn"); - bundle.put("direction", direction); - server.broadcast(bundle); - } private void makeAlienBlock() { @@ -504,16 +493,6 @@ private void makeAlienBlockSolo() { } } - private void onStartAlienSpawnServer(){ - run(() -> { - AlienSpawnAndBroadcast(Constant.Direction.UP); - }, Duration.seconds(1.4)); - run(() -> { - AlienSpawnAndBroadcast(Constant.Direction.DOWN); - }, Duration.seconds(1.5)); - alienSpawnStart = true; - } - /** * Initialisation des propriétés physiques du jeu liées aux collisions */ @@ -588,7 +567,6 @@ private void onUpdateMultiplayer(double tpf){ // LBF : dans le mode multijoueur if (GameVariableNames.multiplayerGameInProgress) { // LBF : dans le mode multijoueur ou réecrire autrement?? onUpdateBroadcastLogic(); onUpdateCommon(tpf); -// if(!alienSpawnStart && isServer){onStartAlienSpawnServer();} } else { //Synchronise le début de la partie entre les deux joueurs if(!isServer && GameVariableNames.multiplayerGameWaiting){ @@ -612,7 +590,7 @@ private void onUpdateCommon(double tpf){ // LBF : dans tous les modes de jeu run(() -> { getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { - if (FXGLMath.randomBoolean(0.005)) { + if (FXGLMath.randomBoolean(0.005)) { // LBF : dans le mode multijoeur (tir unidirectionnel) if (isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.DOWN) { alien.getComponent(AlienComponent.class).randomShoot(Constant.ALIEN_SHOOT_CHANCE); } else if (!isServer && alien.getComponent(AlienComponent.class).getDirection() == Constant.Direction.UP) { @@ -631,7 +609,7 @@ private void gameOverScreen() { play(assetNames.sounds.DEFEAT_CLAIRON); String message = "Game Over ! \n Scores are as follows : \n" + "Player 1 : " + playerComponent1.getScore() + "\n"; - if (playerComponent2 != null) { + if (playerComponent2 != null ) { String player2 = "Player 2 : " + playerComponent2.getScore(); message += player2; } From dd1a47f0f0a3b330653c5a3129528a668797280b Mon Sep 17 00:00:00 2001 From: Mathieu_D Date: Fri, 10 Mar 2023 18:45:59 +0100 Subject: [PATCH 33/50] Game over/win synchronisation --- .../org/enstabretagne/Game/GameLauncher.java | 38 ++++++++++++++++--- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 76e2710..4695b35 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -404,12 +404,19 @@ private void onReceiveMessageServer() { // LBF : dans le mode multijoueur } else if (message.getName().equals("Player2Shoot")) { playerComponent2.shoot(); } else if (message.getName().equals("Client Connected")) { - if(!GameVariableNames.multiplayerGameInProgress) { + if (!GameVariableNames.multiplayerGameInProgress) { server.broadcast(new Bundle("Server Start")); GameVariableNames.multiplayerGameInProgress = true; startMultiGame(); } - } else{ + } else if (message.getName().equals("Game End")) { + System.out.println("Game End Received"); + if(message.get("type").equals("Game Over")){ + gameOverScreen(); + } else if(message.get("type").equals("Game Win")){ + winScreen(); + } + }else{ System.out.println("Message non reconnu"); } }); @@ -440,6 +447,13 @@ private void onReceiveMessageClient() { // LBF : dans le mode multijoueur } else if (message.getName().equals("Server Start")) { GameVariableNames.multiplayerGameInProgress = true; startMultiGame(); + } else if (message.getName().equals("Game End")) { + System.out.println("Game End Received"); + if(message.get("type").equals("Game Over")){ + gameOverScreen(); + } else if(message.get("type").equals("Game Win")){ + winScreen(); + } } else{ System.out.println("Message non reconnu"); } @@ -574,12 +588,15 @@ private void onUpdateMultiplayer(double tpf){ // LBF : dans le mode multijoueur } } } - private void onUpdateCommon(double tpf){ // LBF : dans tous les modes de jeu - if (getb(GameVariableNames.isGameOver)) + private void onUpdateCommon(double tpf) { // LBF : dans tous les modes de jeu + if (getb(GameVariableNames.isGameOver)){ + GameEndBroadcastLogic("Game Over"); gameOverScreen(); - if (getb(GameVariableNames.isGameWon)) + } + if (getb(GameVariableNames.isGameWon)) { + GameEndBroadcastLogic("Game Win"); winScreen(); - + } if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { ambientSound(); last_ambient_sound = System.currentTimeMillis(); @@ -601,6 +618,15 @@ private void onUpdateCommon(double tpf){ // LBF : dans tous les modes de jeu }, Duration.seconds(Constant.random.nextDouble() * 10)); } + private void GameEndBroadcastLogic(String message){ + Bundle bundle = new Bundle("Game End"); + bundle.put("type", message); + if(isServer){ + server.broadcast(bundle); + } else { + client.broadcast(bundle); + } + } /** * Affichage de l'écran de fin de partie From d04d866a7c33d777349b3e5807509bd594cdaa9d Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 10 Mar 2023 21:12:36 +0100 Subject: [PATCH 34/50] refactor(ui): :recycle: end game screens refactored end game screens in game mode to display relevant players' scores. => winScreen and gameOverScreen are now in game mode. --- .../org/enstabretagne/Game/GameLauncher.java | 13 ++------ .../Game/GameModes/GameMode.java | 1 + .../Game/GameModes/OnePlayerGameMode.java | 13 ++++++++ .../Game/GameModes/TwoPlayerGameMode.java | 14 ++++++++- .../java/org/enstabretagne/UI/UI_Factory.java | 31 +++++++++++++++---- 5 files changed, 55 insertions(+), 17 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 1271845..227750e 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -9,9 +9,7 @@ import static com.almasb.fxgl.dsl.FXGL.run; import static com.almasb.fxgl.dsl.FXGL.spawn; import static org.enstabretagne.UI.UI_Factory.ambientSound; -import static org.enstabretagne.UI.UI_Factory.gameOverScreen; import static org.enstabretagne.UI.UI_Factory.showPlayersLivesAndScores; -import static org.enstabretagne.UI.UI_Factory.winScreen; import java.util.Arrays; import java.util.EnumSet; @@ -168,7 +166,7 @@ protected void initPhysics() { @Override protected void initUI() { if (getGameScene().getContentRoot().getChildren().contains(playersUI)) - getGameScene().removeUINode(playersUI); + getGameScene().removeChild(playersUI); playersUI = showPlayersLivesAndScores(getGameWorld()); getGameScene().addChild(playersUI); } @@ -180,15 +178,10 @@ protected void initUI() { */ @Override protected void onUpdate(double tpf) { - if (getb(GameVariableNames.isGameOver)) { - getGameScene().removeChild(playersUI); - gameOverScreen("to refactor", "to refactor"); - } // TODO : refactor - if (getb(GameVariableNames.isGameWon)) { + if (getb(GameVariableNames.isGameOver) || getb(GameVariableNames.isGameWon)) { getGameScene().removeChild(playersUI); - winScreen("to refactor", "to refactor"); // TODO : refactor + game_mode.gameFinished(); } - if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { ambientSound(); last_ambient_sound = System.currentTimeMillis(); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java index 8713325..724a7ed 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java @@ -11,4 +11,5 @@ public interface GameMode { public void initGameMode(); public void initInput(Input input); public GameModeTypes getGameModeType(); + public void gameFinished(); } \ No newline at end of file diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index 39e79bb..d31f47b 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -1,9 +1,11 @@ package org.enstabretagne.Game.GameModes; import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.entityNames; import org.enstabretagne.Utils.Settings.Direction; +import static org.enstabretagne.UI.UI_Factory.*; import static com.almasb.fxgl.dsl.FXGL.*; import com.almasb.fxgl.entity.Entity; @@ -53,4 +55,15 @@ public void initInput(Input input) { onKey(KeyCode.Q, () -> playerComponent1.moveLeft()); } + @Override + public void gameFinished() { + if (getb(GameVariableNames.isGameOver)) { + gameOverScreen(Integer.toString(playerComponent1.getScore())); + } + if (getb(GameVariableNames.isGameWon)) { + // getGameScene().removeChild(playersUI); + winScreen(Integer.toString(playerComponent1.getScore())); + } + } + } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java index 52fb912..2fcaaa8 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java @@ -1,9 +1,10 @@ package org.enstabretagne.Game.GameModes; import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.Settings.Direction; - +import static org.enstabretagne.UI.UI_Factory.*; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.input.Input; import static com.almasb.fxgl.dsl.FXGL.*; @@ -35,4 +36,15 @@ public void initInput(Input input) { onKey(KeyCode.Q, () -> playerComponent2.moveLeft()); } + @Override + public void gameFinished() { + if (getb(GameVariableNames.isGameOver)) { + // getGameScene().removeChild(playersUI); + gameOverScreen(playerComponent1.getScore(), playerComponent2.getScore()); + } + if (getb(GameVariableNames.isGameWon)) { + // getGameScene().removeChild(playersUI); + winScreen(playerComponent1.getScore(), playerComponent2.getScore()); + } + } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java b/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java index c559576..2ba9ee8 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java +++ b/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.function.Consumer; import java.util.stream.Collectors; import org.enstabretagne.Component.PlayerComponent; @@ -75,31 +76,49 @@ public static void playAgain(Boolean yes) { */ public static void winScreen(String score_player1, String score_player2) { play(assetNames.sounds.VICTORY_CLAIRON); - String message = "You won ! \n Scores are as follows : \n" + + String message = "You won ! \nScores are as follows : \n" + "Player 1 : " + score_player1 + "\n"; if (score_player2 != null) { String player2 = "Player 2 : " + score_player2; message += player2; } + askConfirmationToUser(message, (yes) -> playAgain(yes)); + } + + private static void askConfirmationToUser(String message, Consumer responseCallback) { getDialogService().showMessageBox(message, () -> { - getDialogService().showConfirmationBox("Do you want to play again?", (yes) -> playAgain(yes)); + getDialogService().showConfirmationBox("Do you want to play again?", responseCallback); }); } + public static void winScreen(String score_player1) { + winScreen(score_player1, null); + } + + public static void winScreen(int score_player1, int score_player2) { + winScreen(Integer.toString(score_player1), Integer.toString(score_player2)); + } + /** * Affichage de l'écran de fin de partie */ public static void gameOverScreen(String score_player1, String score_player2) { play(assetNames.sounds.DEFEAT_CLAIRON); - String message = "Game Over ! \n Scores are as follows : \n" + + String message = "Game Over ! \nScores are as follows : \n" + "Player 1 : " + score_player1 + "\n"; if (score_player2 != null) { String player2 = "Player 2 : " + score_player2; message += player2; } - getDialogService().showMessageBox(message, () -> { - getDialogService().showConfirmationBox("Do you want to play again?", (yes) -> playAgain(yes)); - }); + askConfirmationToUser(message, (yes) -> playAgain(yes)); + } + + public static void gameOverScreen(String score_player1) { + gameOverScreen(score_player1, null); + } + + public static void gameOverScreen(int score_player1, int score_player2) { + gameOverScreen(Integer.toString(score_player1), Integer.toString(score_player2)); } /** From a5d15e7fe5f601069370b863fc23e01c635f5c89 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 10 Mar 2023 21:35:18 +0100 Subject: [PATCH 35/50] refactor(ui): :recycle: show players infos refactored the UI to show the players infos (lives and scores). refactored aliens random shooting. cleaned some code too. --- .../org/enstabretagne/Game/GameLauncher.java | 30 +++++-------------- .../Game/GameModes/AlienFactory.java | 12 ++++++++ .../Game/GameModes/OnePlayerGameMode.java | 1 - .../Game/GameModes/TwoPlayerGameMode.java | 2 -- .../java/org/enstabretagne/UI/UI_Factory.java | 16 ++++++---- 5 files changed, 29 insertions(+), 32 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 227750e..817d292 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -6,7 +6,6 @@ import static com.almasb.fxgl.dsl.FXGL.getb; import static com.almasb.fxgl.dsl.FXGL.loopBGM; import static com.almasb.fxgl.dsl.FXGL.play; -import static com.almasb.fxgl.dsl.FXGL.run; import static com.almasb.fxgl.dsl.FXGL.spawn; import static org.enstabretagne.UI.UI_Factory.ambientSound; import static org.enstabretagne.UI.UI_Factory.showPlayersLivesAndScores; @@ -21,12 +20,11 @@ import org.enstabretagne.Collision.BulletPlayerCollision; import org.enstabretagne.Collision.EnemyShootBulletCollision; import org.enstabretagne.Collision.EnemyShootPlayerCollision; -import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.SpaceInvadersFactory; +import org.enstabretagne.Game.GameModes.AlienFactory; import org.enstabretagne.Game.GameModes.ClassicGameMode; import org.enstabretagne.Game.GameModes.GameMode; import org.enstabretagne.Game.GameModes.GameModeTypes; -import org.enstabretagne.Utils.EntityType; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.assetNames; @@ -40,9 +38,6 @@ import com.almasb.fxgl.app.scene.SceneFactory; import com.almasb.fxgl.core.math.FXGLMath; -import javafx.scene.layout.VBox; -import javafx.util.Duration; - /** * Classe principale du jeu * C'est la classe qui lance le jeu et gère les fonctions principales @@ -55,7 +50,6 @@ public class GameLauncher extends GameApplication { private long last_ambient_sound = System.currentTimeMillis(); private int delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); - VBox playersUI = new VBox(); public static void setGameMode(GameMode gameMode) { game_mode = gameMode; @@ -165,10 +159,7 @@ protected void initPhysics() { */ @Override protected void initUI() { - if (getGameScene().getContentRoot().getChildren().contains(playersUI)) - getGameScene().removeChild(playersUI); - playersUI = showPlayersLivesAndScores(getGameWorld()); - getGameScene().addChild(playersUI); + showPlayersLivesAndScores(getGameWorld(), getGameScene()); } /** @@ -179,25 +170,18 @@ protected void initUI() { @Override protected void onUpdate(double tpf) { if (getb(GameVariableNames.isGameOver) || getb(GameVariableNames.isGameWon)) { - getGameScene().removeChild(playersUI); game_mode.gameFinished(); } + if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { ambientSound(); last_ambient_sound = System.currentTimeMillis(); delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); } - if (getGameScene().getContentRoot().getChildren().contains(playersUI)) { - getGameScene().removeChild(playersUI); - playersUI = showPlayersLivesAndScores(getGameWorld()); - getGameScene().addChild(playersUI); - } - run(() -> { - getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { - if (FXGLMath.randomBoolean(0.01)) - alien.getComponent(AlienComponent.class).randomShoot(Settings.ALIEN_SHOOT_CHANCE); - }); - }, Duration.seconds(Settings.random.nextDouble() * 10)); + + showPlayersLivesAndScores(getGameWorld(), getGameScene()); + + AlienFactory.aliensRandomlyShoot(); } public static void main(String[] args) { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java index 5fc189b..9439a38 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java @@ -1,13 +1,16 @@ package org.enstabretagne.Game.GameModes; +import static com.almasb.fxgl.dsl.FXGL.getGameWorld; import static com.almasb.fxgl.dsl.FXGL.run; import static com.almasb.fxgl.dsl.FXGL.spawn; import org.enstabretagne.Component.AlienComponent; +import org.enstabretagne.Utils.EntityType; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.entityNames; import org.enstabretagne.Utils.Settings.Direction; +import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.entity.Entity; import javafx.util.Duration; @@ -59,4 +62,13 @@ static protected void makeOneAlien(Direction direction) { Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); alien.getComponent(AlienComponent.class).initialize(direction); } + + public static void aliensRandomlyShoot() { + run(() -> { + getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { + if (FXGLMath.randomBoolean(0.01)) + alien.getComponent(AlienComponent.class).randomShoot(Settings.ALIEN_SHOOT_CHANCE); + }); + }, Duration.seconds(Settings.random.nextDouble() * 10)); + } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index d31f47b..1874d74 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -61,7 +61,6 @@ public void gameFinished() { gameOverScreen(Integer.toString(playerComponent1.getScore())); } if (getb(GameVariableNames.isGameWon)) { - // getGameScene().removeChild(playersUI); winScreen(Integer.toString(playerComponent1.getScore())); } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java index 2fcaaa8..dbed192 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java @@ -39,11 +39,9 @@ public void initInput(Input input) { @Override public void gameFinished() { if (getb(GameVariableNames.isGameOver)) { - // getGameScene().removeChild(playersUI); gameOverScreen(playerComponent1.getScore(), playerComponent2.getScore()); } if (getb(GameVariableNames.isGameWon)) { - // getGameScene().removeChild(playersUI); winScreen(playerComponent1.getScore(), playerComponent2.getScore()); } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java b/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java index 2ba9ee8..16e4d00 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java +++ b/duelinvaders/src/main/java/org/enstabretagne/UI/UI_Factory.java @@ -12,6 +12,7 @@ import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.assetNames; +import com.almasb.fxgl.app.scene.GameScene; import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.entity.GameWorld; @@ -22,9 +23,11 @@ import javafx.scene.text.Text; public class UI_Factory { + private static VBox playersUI = new VBox(); - public static VBox showPlayersLivesAndScores(GameWorld gameWorld) { - // getGameScene().removeChild(playersUI); + public static VBox showPlayersLivesAndScores(GameWorld gameWorld,GameScene gameScene) { + if (getGameScene().getContentRoot().getChildren().contains(playersUI)) + getGameScene().removeChild(playersUI); // System.out.println("Players Lives and Scores"); List playersViews = new ArrayList<>(); @@ -37,14 +40,15 @@ public static VBox showPlayersLivesAndScores(GameWorld gameWorld) { var playerUI = new HBox(30, scoreUI, lifeUI); playersViews.add(playerUI); } - VBox players_ui = new VBox(20, playersViews.toArray(new HBox[0])); - return players_ui; - // getGameScene().addChild(players_ui); + playersUI = new VBox(20, playersViews.toArray(new HBox[0])); + + getGameScene().addChild(playersUI); + return playersUI; } public static HBox createScoreUI(int score, int player_id) { Text scoreText = getUIFactoryService().newText(Integer.toString(score), Color.WHITE, 24.0); - Text playerText = getUIFactoryService().newText("Player " + Integer.toString(player_id % 2 + 1), Color.WHITE, + Text playerText = getUIFactoryService().newText("Player " + Integer.toString(player_id), Color.WHITE, 24.0); var scoreView = new HBox(10, playerText, scoreText); scoreView.setAlignment(Pos.CENTER); From 46fe26cc8c09a65c1057b1f985263d8d2e2e4a5f Mon Sep 17 00:00:00 2001 From: LBF38 Date: Fri, 10 Mar 2023 23:09:51 +0100 Subject: [PATCH 36/50] refactor(input): :poop: error when rebinding inputs There is an error that I don't understand when rebinding inputs. Inputs correctly work when first mapped, but when rebinding, there is a NullPointerException in the InputManager. I don't understand why this happens, as I'm changing the playerComponents that are being used by the keybindings. --- .../Game/GameModes/OnePlayerGameMode.java | 21 +++++--- .../Game/GameModes/TwoPlayerGameMode.java | 50 ++++++++++++++++--- 2 files changed, 57 insertions(+), 14 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index 1874d74..1280ab8 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -7,6 +7,8 @@ import org.enstabretagne.Utils.Settings.Direction; import static org.enstabretagne.UI.UI_Factory.*; +import java.util.Map; + import static com.almasb.fxgl.dsl.FXGL.*; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.input.Input; @@ -16,6 +18,7 @@ public abstract class OnePlayerGameMode implements GameMode { protected Entity player1; protected PlayerComponent playerComponent1; + protected Map keyBindings; @Override public GameModeTypes getGameModeType() { @@ -47,12 +50,18 @@ protected PlayerComponent initPlayerComponent(Entity player, Direction direction @Override public void initInput(Input input) { - onKey(KeyCode.ENTER, () -> playerComponent1.shoot()); - onKey(KeyCode.RIGHT, () -> playerComponent1.moveRight()); - onKey(KeyCode.LEFT, () -> playerComponent1.moveLeft()); - onKey(KeyCode.SPACE, () -> playerComponent1.shoot()); - onKey(KeyCode.D, () -> playerComponent1.moveRight()); - onKey(KeyCode.Q, () -> playerComponent1.moveLeft()); + keyBindings = Map.of(KeyCode.ENTER, () -> playerComponent1.shoot(), KeyCode.RIGHT, + () -> playerComponent1.moveRight(), KeyCode.LEFT, () -> playerComponent1.moveLeft(), + KeyCode.SPACE, () -> playerComponent1.shoot(), KeyCode.D, () -> playerComponent1.moveRight(), + KeyCode.Q, () -> playerComponent1.moveLeft()); + + try { + input.clearAll(); + input.getAllBindings().clear(); + keyBindings.forEach((keycode, action) -> onKey(keycode, action)); + } catch (Exception e) { + System.out.println("Error while initializing input :" + e.getMessage()); + } } @Override diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java index dbed192..5f41948 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java @@ -1,13 +1,19 @@ package org.enstabretagne.Game.GameModes; +import static com.almasb.fxgl.dsl.FXGL.getb; +import static com.almasb.fxgl.dsl.FXGL.onKey; +import static org.enstabretagne.UI.UI_Factory.gameOverScreen; +import static org.enstabretagne.UI.UI_Factory.winScreen; + +import java.util.Map; + import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.Settings.Direction; -import static org.enstabretagne.UI.UI_Factory.*; + import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.input.Input; -import static com.almasb.fxgl.dsl.FXGL.*; import javafx.scene.input.KeyCode; @@ -28,12 +34,40 @@ public void initTwoPlayerGameMode() { @Override public void initInput(Input input) { - onKey(KeyCode.ENTER, () -> playerComponent1.shoot()); - onKey(KeyCode.RIGHT, () -> playerComponent1.moveRight()); - onKey(KeyCode.LEFT, () -> playerComponent1.moveLeft()); - onKey(KeyCode.SPACE, () -> playerComponent2.shoot()); - onKey(KeyCode.D, () -> playerComponent2.moveRight()); - onKey(KeyCode.Q, () -> playerComponent2.moveLeft()); + keyBindings = Map.of(KeyCode.ENTER, () -> playerComponent1.shoot(), KeyCode.RIGHT, + () -> playerComponent1.moveRight(), KeyCode.LEFT, () -> playerComponent1.moveLeft(), + KeyCode.SPACE, () -> playerComponent2.shoot(), KeyCode.D, () -> playerComponent2.moveRight(), + KeyCode.Q, () -> playerComponent2.moveLeft()); + + try { + input.clearAll(); + input.getAllBindings().clear(); + keyBindings.forEach((keycode, action) -> onKey(keycode, action)); + } catch (Exception e) { + System.out.println("Error while initializing input :" + e.getMessage()); + // keyBindings.forEach((keycode, action) ->{ + // if(input.getAllBindings().containsValue(new KeyTrigger(keycode))) { + // System.out.println("Key " + keycode + " is already binded"); + // input.getAllBindings().replace(null, null, null); + // } + // }); + input.getAllBindings().forEach((useraction, trigger) -> { + System.out.println("UserAction: " + useraction + " Trigger: " + trigger); + if (trigger.isKey()) { + if (keyBindings.containsKey(KeyCode.getKeyCode(trigger.getName()))) { + System.out.println("Key " + trigger.getName() + " is already binded"); + boolean isremoved = input.getAllBindings().remove(useraction, trigger); + System.out.println("UserAction: " + useraction + " Trigger: " + trigger + " removed : " + + isremoved); + onKey(KeyCode.getKeyCode(trigger.getName()), + keyBindings.get(KeyCode.getKeyCode(trigger.getName()))); + System.out.println("Input: " + trigger.getName() + " reinitialized"); + } + } + }); + keyBindings.forEach((keycode, action) -> onKey(keycode, action)); + System.out.println("Input reinitialized"); + } } @Override From 72657d53b7419978ae85774d3b47b37e4856a246 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sat, 11 Mar 2023 19:30:59 +0100 Subject: [PATCH 37/50] fix(input): :poop: trying to fix input issues Still have the issue when we change game modes. The inputs aren't rebinded. And it is hard to fix as it is in the game engine. Trying to find a workaround. --- .../Game/GameModes/OnePlayerGameMode.java | 58 +++++++++++----- .../Game/GameModes/TwoPlayerGameMode.java | 67 ++++++++++--------- 2 files changed, 79 insertions(+), 46 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index 1280ab8..24373ab 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -1,24 +1,54 @@ package org.enstabretagne.Game.GameModes; +import static com.almasb.fxgl.dsl.FXGL.getb; +import static com.almasb.fxgl.dsl.FXGL.spawn; +import static org.enstabretagne.UI.UI_Factory.gameOverScreen; +import static org.enstabretagne.UI.UI_Factory.winScreen; + +import java.util.HashMap; +import java.util.Map; + import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; -import org.enstabretagne.Utils.entityNames; import org.enstabretagne.Utils.Settings.Direction; -import static org.enstabretagne.UI.UI_Factory.*; - -import java.util.Map; +import org.enstabretagne.Utils.entityNames; -import static com.almasb.fxgl.dsl.FXGL.*; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.input.Input; +import com.almasb.fxgl.input.UserAction; import javafx.scene.input.KeyCode; public abstract class OnePlayerGameMode implements GameMode { protected Entity player1; protected PlayerComponent playerComponent1; - protected Map keyBindings; + protected UserAction player1_shoot = new UserAction("player1_shoot") { + @Override + protected void onAction() { + playerComponent1.shoot(); + } + }; + protected UserAction player1_moveLeft = new UserAction("player1_moveLeft") { + @Override + protected void onAction() { + playerComponent1.moveLeft(); + } + }; + protected UserAction player1_moveRight = new UserAction("player1_moveRight") { + @Override + protected void onAction() { + playerComponent1.moveRight(); + } + }; + + protected Map inputMap = new HashMap() { + { + put(player1_shoot, KeyCode.ENTER); + put(player1_moveLeft, KeyCode.LEFT); + put(player1_moveRight, KeyCode.RIGHT); + } + }; @Override public GameModeTypes getGameModeType() { @@ -50,17 +80,15 @@ protected PlayerComponent initPlayerComponent(Entity player, Direction direction @Override public void initInput(Input input) { - keyBindings = Map.of(KeyCode.ENTER, () -> playerComponent1.shoot(), KeyCode.RIGHT, - () -> playerComponent1.moveRight(), KeyCode.LEFT, () -> playerComponent1.moveLeft(), - KeyCode.SPACE, () -> playerComponent1.shoot(), KeyCode.D, () -> playerComponent1.moveRight(), - KeyCode.Q, () -> playerComponent1.moveLeft()); - try { - input.clearAll(); - input.getAllBindings().clear(); - keyBindings.forEach((keycode, action) -> onKey(keycode, action)); + inputMap.forEach((action, key) -> { + input.addAction(action, key); + }); } catch (Exception e) { - System.out.println("Error while initializing input :" + e.getMessage()); + System.out.println("Error while binding keys : " + e.getMessage()); + inputMap.forEach((action, key) -> { + input.rebind(action, key); + }); } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java index 5f41948..0833742 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java @@ -1,10 +1,10 @@ package org.enstabretagne.Game.GameModes; import static com.almasb.fxgl.dsl.FXGL.getb; -import static com.almasb.fxgl.dsl.FXGL.onKey; import static org.enstabretagne.UI.UI_Factory.gameOverScreen; import static org.enstabretagne.UI.UI_Factory.winScreen; +import java.util.HashMap; import java.util.Map; import org.enstabretagne.Component.PlayerComponent; @@ -14,12 +14,41 @@ import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.input.Input; +import com.almasb.fxgl.input.UserAction; import javafx.scene.input.KeyCode; public abstract class TwoPlayerGameMode extends OnePlayerGameMode { protected Entity player2; protected PlayerComponent playerComponent2; + protected UserAction player2_shoot = new UserAction("player2_shoot") { + @Override + protected void onAction() { + playerComponent2.shoot(); + } + }; + protected UserAction player2_moveLeft = new UserAction("player2_moveLeft") { + @Override + protected void onAction() { + playerComponent2.moveLeft(); + } + }; + protected UserAction player2_moveRight = new UserAction("player2_moveRight") { + @Override + protected void onAction() { + playerComponent2.moveRight(); + } + }; + protected Map inputMap = new HashMap() { + { + put(player1_shoot, KeyCode.ENTER); + put(player1_moveLeft, KeyCode.LEFT); + put(player1_moveRight, KeyCode.RIGHT); + put(player2_shoot, KeyCode.SPACE); + put(player2_moveLeft, KeyCode.Q); + put(player2_moveRight, KeyCode.D); + } + }; @Override public GameModeTypes getGameModeType() { @@ -34,39 +63,15 @@ public void initTwoPlayerGameMode() { @Override public void initInput(Input input) { - keyBindings = Map.of(KeyCode.ENTER, () -> playerComponent1.shoot(), KeyCode.RIGHT, - () -> playerComponent1.moveRight(), KeyCode.LEFT, () -> playerComponent1.moveLeft(), - KeyCode.SPACE, () -> playerComponent2.shoot(), KeyCode.D, () -> playerComponent2.moveRight(), - KeyCode.Q, () -> playerComponent2.moveLeft()); - try { - input.clearAll(); - input.getAllBindings().clear(); - keyBindings.forEach((keycode, action) -> onKey(keycode, action)); + inputMap.forEach((action, key) -> { + input.addAction(action, key); + }); } catch (Exception e) { - System.out.println("Error while initializing input :" + e.getMessage()); - // keyBindings.forEach((keycode, action) ->{ - // if(input.getAllBindings().containsValue(new KeyTrigger(keycode))) { - // System.out.println("Key " + keycode + " is already binded"); - // input.getAllBindings().replace(null, null, null); - // } - // }); - input.getAllBindings().forEach((useraction, trigger) -> { - System.out.println("UserAction: " + useraction + " Trigger: " + trigger); - if (trigger.isKey()) { - if (keyBindings.containsKey(KeyCode.getKeyCode(trigger.getName()))) { - System.out.println("Key " + trigger.getName() + " is already binded"); - boolean isremoved = input.getAllBindings().remove(useraction, trigger); - System.out.println("UserAction: " + useraction + " Trigger: " + trigger + " removed : " - + isremoved); - onKey(KeyCode.getKeyCode(trigger.getName()), - keyBindings.get(KeyCode.getKeyCode(trigger.getName()))); - System.out.println("Input: " + trigger.getName() + " reinitialized"); - } - } + System.out.println("Error while binding keys : " + e.getMessage()); + inputMap.forEach((action, key) -> { + input.rebind(action, key); }); - keyBindings.forEach((keycode, action) -> onKey(keycode, action)); - System.out.println("Input reinitialized"); } } From 93a676ed46d708ba73a426dc5e276f5c5955372f Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sat, 11 Mar 2023 20:26:32 +0100 Subject: [PATCH 38/50] fix(input): :ambulance: finally fixed all inputs ! :tada: I finally got the right perception to fix this bug !!! The solution is to put the inputs in the gameLauncher. The binding will ask the game mode the playerComponent that will be used for the active game. So, it is very simple as the One player or Two player game modes can return either the playerComponent1 or the playerComponent2. This is pure awesomeness ! :tada: --- .../org/enstabretagne/Game/GameLauncher.java | 28 ++++++--- .../Game/GameModes/GameMode.java | 9 ++- .../Game/GameModes/OnePlayerGameMode.java | 57 ++++--------------- .../Game/GameModes/TwoPlayerGameMode.java | 54 ++---------------- 4 files changed, 43 insertions(+), 105 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 817d292..2ea0aeb 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -5,6 +5,7 @@ import static com.almasb.fxgl.dsl.FXGL.getPhysicsWorld; import static com.almasb.fxgl.dsl.FXGL.getb; import static com.almasb.fxgl.dsl.FXGL.loopBGM; +import static com.almasb.fxgl.dsl.FXGL.onKey; import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.spawn; import static org.enstabretagne.UI.UI_Factory.ambientSound; @@ -38,6 +39,8 @@ import com.almasb.fxgl.app.scene.SceneFactory; import com.almasb.fxgl.core.math.FXGLMath; +import javafx.scene.input.KeyCode; + /** * Classe principale du jeu * C'est la classe qui lance le jeu et gère les fonctions principales @@ -106,7 +109,24 @@ public FXGLMenu newMainMenu() { */ @Override protected void initInput() { - super.initInput(); + onKey(KeyCode.Q, () -> { + game_mode.getPlayerComponent1().moveLeft(); + }); + onKey(KeyCode.D, () -> { + game_mode.getPlayerComponent1().moveRight(); + }); + onKey(KeyCode.SPACE, () -> { + game_mode.getPlayerComponent1().shoot(); + }); + onKey(KeyCode.ENTER, () -> { + game_mode.getPlayerComponent2().shoot(); + }); + onKey(KeyCode.LEFT, () -> { + game_mode.getPlayerComponent2().moveLeft(); + }); + onKey(KeyCode.RIGHT, () -> { + game_mode.getPlayerComponent2().moveRight(); + }); } /** @@ -130,12 +150,6 @@ protected void initGame() { getGameWorld().addEntityFactory(new SpaceInvadersFactory()); game_mode.initGameMode(); - try { - game_mode.initInput(getGameScene().getInput()); - } catch (Exception exception) { - System.out.println("Erreur lors de l'initialisation des inputs : " + - exception.getMessage()); - } spawn(entityNames.BACKGROUND); loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java index 724a7ed..eba1443 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java @@ -1,6 +1,6 @@ package org.enstabretagne.Game.GameModes; -import com.almasb.fxgl.input.Input; +import org.enstabretagne.Component.PlayerComponent; /** * Defines the contract for a game mode. @@ -8,8 +8,13 @@ * @author LBF38 */ public interface GameMode { + public PlayerComponent getPlayerComponent1(); + + public PlayerComponent getPlayerComponent2(); + public void initGameMode(); - public void initInput(Input input); + public GameModeTypes getGameModeType(); + public void gameFinished(); } \ No newline at end of file diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index 24373ab..60a4459 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -5,9 +5,6 @@ import static org.enstabretagne.UI.UI_Factory.gameOverScreen; import static org.enstabretagne.UI.UI_Factory.winScreen; -import java.util.HashMap; -import java.util.Map; - import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; @@ -15,40 +12,10 @@ import org.enstabretagne.Utils.entityNames; import com.almasb.fxgl.entity.Entity; -import com.almasb.fxgl.input.Input; -import com.almasb.fxgl.input.UserAction; - -import javafx.scene.input.KeyCode; public abstract class OnePlayerGameMode implements GameMode { protected Entity player1; protected PlayerComponent playerComponent1; - protected UserAction player1_shoot = new UserAction("player1_shoot") { - @Override - protected void onAction() { - playerComponent1.shoot(); - } - }; - protected UserAction player1_moveLeft = new UserAction("player1_moveLeft") { - @Override - protected void onAction() { - playerComponent1.moveLeft(); - } - }; - protected UserAction player1_moveRight = new UserAction("player1_moveRight") { - @Override - protected void onAction() { - playerComponent1.moveRight(); - } - }; - - protected Map inputMap = new HashMap() { - { - put(player1_shoot, KeyCode.ENTER); - put(player1_moveLeft, KeyCode.LEFT); - put(player1_moveRight, KeyCode.RIGHT); - } - }; @Override public GameModeTypes getGameModeType() { @@ -78,20 +45,6 @@ protected PlayerComponent initPlayerComponent(Entity player, Direction direction return playerComponent; } - @Override - public void initInput(Input input) { - try { - inputMap.forEach((action, key) -> { - input.addAction(action, key); - }); - } catch (Exception e) { - System.out.println("Error while binding keys : " + e.getMessage()); - inputMap.forEach((action, key) -> { - input.rebind(action, key); - }); - } - } - @Override public void gameFinished() { if (getb(GameVariableNames.isGameOver)) { @@ -102,4 +55,14 @@ public void gameFinished() { } } + @Override + public PlayerComponent getPlayerComponent1() { + return playerComponent1; + } + + @Override + public PlayerComponent getPlayerComponent2() { + return playerComponent1; + } + } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java index 0833742..821c1ee 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/TwoPlayerGameMode.java @@ -4,51 +4,16 @@ import static org.enstabretagne.UI.UI_Factory.gameOverScreen; import static org.enstabretagne.UI.UI_Factory.winScreen; -import java.util.HashMap; -import java.util.Map; - import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.Settings.Direction; import com.almasb.fxgl.entity.Entity; -import com.almasb.fxgl.input.Input; -import com.almasb.fxgl.input.UserAction; - -import javafx.scene.input.KeyCode; public abstract class TwoPlayerGameMode extends OnePlayerGameMode { protected Entity player2; protected PlayerComponent playerComponent2; - protected UserAction player2_shoot = new UserAction("player2_shoot") { - @Override - protected void onAction() { - playerComponent2.shoot(); - } - }; - protected UserAction player2_moveLeft = new UserAction("player2_moveLeft") { - @Override - protected void onAction() { - playerComponent2.moveLeft(); - } - }; - protected UserAction player2_moveRight = new UserAction("player2_moveRight") { - @Override - protected void onAction() { - playerComponent2.moveRight(); - } - }; - protected Map inputMap = new HashMap() { - { - put(player1_shoot, KeyCode.ENTER); - put(player1_moveLeft, KeyCode.LEFT); - put(player1_moveRight, KeyCode.RIGHT); - put(player2_shoot, KeyCode.SPACE); - put(player2_moveLeft, KeyCode.Q); - put(player2_moveRight, KeyCode.D); - } - }; @Override public GameModeTypes getGameModeType() { @@ -61,20 +26,6 @@ public void initTwoPlayerGameMode() { playerComponent2 = initPlayerComponent(player2, Direction.DOWN); } - @Override - public void initInput(Input input) { - try { - inputMap.forEach((action, key) -> { - input.addAction(action, key); - }); - } catch (Exception e) { - System.out.println("Error while binding keys : " + e.getMessage()); - inputMap.forEach((action, key) -> { - input.rebind(action, key); - }); - } - } - @Override public void gameFinished() { if (getb(GameVariableNames.isGameOver)) { @@ -84,4 +35,9 @@ public void gameFinished() { winScreen(playerComponent1.getScore(), playerComponent2.getScore()); } } + + @Override + public PlayerComponent getPlayerComponent2() { + return playerComponent2; + } } From 58da1d6f23c8f75876d003106730a72ba5268643 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sat, 11 Mar 2023 21:35:38 +0100 Subject: [PATCH 39/50] refactor(serverTCP): :recycle: Multiplayer class creating the Multiplayer game mode class. This commit is just a checkpoint for refactoring the methods from the previous merge commit. The code might not be working yet. :construction: WIP: refactoring the Multiplayer game mode :construction: --- .../org/enstabretagne/Game/GameLauncher.java | 222 +--------------- .../Game/GameModes/GameModeTypes.java | 2 +- .../Game/GameModes/MultiplayerGameMode.java | 239 ++++++++++++++++++ .../org/enstabretagne/Game/NewMainMenu.java | 9 +- 4 files changed, 247 insertions(+), 225 deletions(-) create mode 100644 duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index 0fa650a..a1150fd 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -1,15 +1,12 @@ package org.enstabretagne.Game; -import static com.almasb.fxgl.dsl.FXGL.getDialogService; import static com.almasb.fxgl.dsl.FXGL.getGameScene; import static com.almasb.fxgl.dsl.FXGL.getGameWorld; -import static com.almasb.fxgl.dsl.FXGL.getNetService; import static com.almasb.fxgl.dsl.FXGL.getPhysicsWorld; import static com.almasb.fxgl.dsl.FXGL.getb; import static com.almasb.fxgl.dsl.FXGL.loopBGM; import static com.almasb.fxgl.dsl.FXGL.onKey; import static com.almasb.fxgl.dsl.FXGL.play; -import static com.almasb.fxgl.dsl.FXGL.runOnce; import static com.almasb.fxgl.dsl.FXGL.spawn; import static org.enstabretagne.UI.UI_Factory.ambientSound; import static org.enstabretagne.UI.UI_Factory.showPlayersLivesAndScores; @@ -24,7 +21,6 @@ import org.enstabretagne.Collision.BulletPlayerCollision; import org.enstabretagne.Collision.EnemyShootBulletCollision; import org.enstabretagne.Collision.EnemyShootPlayerCollision; -import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.SpaceInvadersFactory; import org.enstabretagne.Game.GameModes.AlienFactory; import org.enstabretagne.Game.GameModes.ClassicGameMode; @@ -42,13 +38,8 @@ import com.almasb.fxgl.app.scene.FXGLMenu; import com.almasb.fxgl.app.scene.SceneFactory; import com.almasb.fxgl.core.math.FXGLMath; -import com.almasb.fxgl.core.serialization.Bundle; -import com.almasb.fxgl.entity.Entity; -import com.almasb.fxgl.net.Client; -import com.almasb.fxgl.net.Server; import javafx.scene.input.KeyCode; -import javafx.util.Duration; /** * Classe principale du jeu @@ -71,15 +62,6 @@ public static GameModeTypes getGameModeType() { return game_mode.getGameModeType(); } - private boolean isServer; - private Server server; - private Client client; - - private boolean alienSpawnStart = false; // indique si les aliens ont commencé à spawn - - private int Port; - private String IP; - /** * Initialisation des paramètres du jeu * @@ -156,8 +138,8 @@ protected void initInput() { protected void initGameVars(Map vars) { vars.put(GameVariableNames.isGameOver, false); vars.put(GameVariableNames.isGameWon, false); - GameVariableNames.multiplayerGameInProgress = false; - GameVariableNames.multiplayerGameWaiting = false; + GameVariableNames.multiplayerGameInProgress = false; // TODO: refactor + GameVariableNames.multiplayerGameWaiting = false; // TODO: refactor } /** @@ -175,206 +157,6 @@ protected void initGame() { loopBGM(assetNames.music.MUSIC_ACROSS_THE_UNIVERSE); } - /** - * Input box pour le choix héberger/rejoindre une partie multijoueur - */ - private void isServer() { - runOnce(() -> { - getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { - if (yes) { - isServer = true; - PortSelection(); - } else { - isServer = false; - PortSelection(); - } - }); - return; - }, Duration.seconds(0)); - } - - /** - * Initialisation du serveur - */ - private void isServer_ServerInit() { - System.out.println("server"); - server = getNetService().newTCPServer(Port); - onReceiveMessageServer(); - server.startAsync(); - GameVariableNames.multiplayerGameWaiting = true; - } - - /** - * Initialisation du client - */ - private void isServer_ClientInit() { - System.out.println("client"); - client = getNetService().newTCPClient(IP, Port); - onReceiveMessageClient(); - client.connectAsync(); - GameVariableNames.multiplayerGameWaiting = true; - } - - private void PortSelection() { - runOnce(() -> { - getDialogService().showInputBox("Entrez le port (ex:55555)", port -> { - if (port != null) { - Port = Integer.parseInt(port); - } else { - Port = 55555; - } - System.out.println("Port : " + Port); - if (!isServer) { - IPSelection(); - } else { - isServer_ServerInit(); - } - }); - return; - }, Duration.seconds(0)); - } - - private void IPSelection() { - runOnce(() -> { - getDialogService().showInputBox("Entrez l'adresse IP du serveur (ex: localhost ou 111.222.333.444)", ip -> { - if (ip != null) { - IP = ip; - } else { - IP = "localhost"; - } - System.out.println("IP : " + IP); - isServer_ClientInit(); - }); - return; - }, Duration.seconds(0)); - } - - private void startMultiGame() { - long startGameTime = System.currentTimeMillis(); - System.out.println("startGameTime : " + startGameTime); - AlienFactory.makeAlienBlock(); - } - - /** - * Logique d'envoi des données à chaque frame - */ - private void onUpdateBroadcastLogic() {// LBF : dans le mode multijoueur - if (isServer) { - Player1Broadcast(); - } else { - Player2Broadcast(); - } // Ne sert à rien pour le moment mais utile si plus de choses à transférer à - // chaque frame - } - - /** - * Envoie des données du joueur 1 du serveur vers le client - */ - private void Player1Broadcast() { // LBF : dans le mode multijoueur - Bundle bundle = new Bundle("Player1"); - bundle.put("type", "Player1"); - bundle.put("x", player1.getX()); - bundle.put("y", player1.getY()); - bundle.put("score", playerComponent1.getScore()); - bundle.put("life", playerComponent1.getLife()); - server.broadcast(bundle); - } - - /** - * Envoie des données du joueur 2 du client vers le serveur - */ - private void Player2Broadcast() { // LBF : dans le mode multijoueur - Bundle bundle = new Bundle("Player2"); - bundle.put("type", "Player2"); - bundle.put("x", player2.getX()); - bundle.put("y", player2.getY()); - bundle.put("score", playerComponent2.getScore()); - bundle.put("life", playerComponent2.getLife()); - client.broadcast(bundle); - } - - /** - * Logique lors de la réception des données du client par le serveur - */ - private void onReceiveMessageServer() { // LBF : dans le mode multijoueur - server.setOnConnected(connection -> { - connection.addMessageHandlerFX((conn, message) -> { - if (message.getName().equals("Player2")) { - player2.setX(message.get("x")); - player2.setY(message.get("y")); - playerComponent2.setScore(message.get("score")); - playerComponent2.setLife(message.get("life")); - } else if (message.getName().equals("Player2Shoot")) { - playerComponent2.shoot(); - } else if (message.getName().equals("Client Connected")) { - if (!GameVariableNames.multiplayerGameInProgress) { - server.broadcast(new Bundle("Server Start")); - GameVariableNames.multiplayerGameInProgress = true; - startMultiGame(); - } - } else if (message.getName().equals("Game End")) { - System.out.println("Game End Received"); - if (message.get("type").equals("Game Over")) { - gameOverScreen(); - } else if (message.get("type").equals("Game Win")) { - winScreen(); - } - } else { - System.out.println("Message non reconnu"); - } - }); - }); - } - - /** - * Logique lors de la réception des données du serveur par le client - */ - private void onReceiveMessageClient() { // LBF : dans le mode multijoueur - client.setOnConnected(connection -> { - connection.addMessageHandlerFX((conn, message) -> { - if (message.getName().equals("Player1")) { - player1.setX(message.get("x")); - player1.setY(message.get("y")); - playerComponent1.setScore(message.get("score")); - playerComponent1.setLife(message.get("life")); - } else if (message.getName().equals("Player1Shoot")) { - playerComponent1.shoot(); - } else if (message.getName().equals("AlienSpawn")) { - if (message.get("direction") == Constant.Direction.DOWN) { - Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Constant.Direction.DOWN); - } else { - Entity alien = spawn(entityNames.ALIEN, 0, Constant.GAME_HEIGHT / 2 - Constant.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Constant.Direction.UP); - } - } else if (message.getName().equals("Server Start")) { - GameVariableNames.multiplayerGameInProgress = true; - startMultiGame(); - } else if (message.getName().equals("Game End")) { - System.out.println("Game End Received"); - if (message.get("type").equals("Game Over")) { - gameOverScreen(); - } else if (message.get("type").equals("Game Win")) { - winScreen(); - } - } else { - System.out.println("Message non reconnu"); - } - }); - }); - } - - /** - * Logique d'envoi des données lors du tir d'un joueur - */ - private void onShootBroadcastLogic() { // LBF : dans le mode multijoueur - if (isServer) { - server.broadcast(new Bundle("Player1Shoot")); - } else { - client.broadcast(new Bundle("Player2Shoot")); - } - } - /** * Initialisation des propriétés physiques du jeu liées aux collisions */ diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameModeTypes.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameModeTypes.java index 82118db..160e5b7 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameModeTypes.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameModeTypes.java @@ -7,5 +7,5 @@ * @since 0.2.0 */ public enum GameModeTypes { - CLASSIC, INFINITY, SOLO, DUO, MUSIC_DEMO, MULTI + CLASSIC, INFINITY, SOLO, DUO, MUSIC_DEMO, MULTIPLAYER } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java new file mode 100644 index 0000000..f5d235c --- /dev/null +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java @@ -0,0 +1,239 @@ +package org.enstabretagne.Game.GameModes; + +import static com.almasb.fxgl.dsl.FXGL.getDialogService; +import static com.almasb.fxgl.dsl.FXGL.getNetService; +import static com.almasb.fxgl.dsl.FXGL.runOnce; +import static com.almasb.fxgl.dsl.FXGL.spawn; +import static org.enstabretagne.UI.UI_Factory.gameOverScreen; +import static org.enstabretagne.UI.UI_Factory.winScreen; + +import org.enstabretagne.Component.AlienComponent; +import org.enstabretagne.Utils.GameVariableNames; +import org.enstabretagne.Utils.Settings; +import org.enstabretagne.Utils.entityNames; + +import com.almasb.fxgl.core.serialization.Bundle; +import com.almasb.fxgl.entity.Entity; +import com.almasb.fxgl.net.Client; +import com.almasb.fxgl.net.Server; + +import javafx.util.Duration; + +public class MultiplayerGameMode extends TwoPlayerGameMode { + private boolean isServer; + private Server server; + private Client client; + + private boolean alienSpawnStart = false; // indique si les aliens ont commencé à spawn + + private int Port; + private String IP; + + @Override + public void initGameMode() { + super.initTwoPlayerGameMode(); + } + + @Override + public GameModeTypes getGameModeType() { + return GameModeTypes.MULTIPLAYER; + } + + /** + * Input box pour le choix héberger/rejoindre une partie multijoueur + */ + private void isServer() { + getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { + if (yes) { + isServer = true; + PortSelection(); + } else { + isServer = false; + PortSelection(); + } + }); + } + + /** + * Initialisation du serveur + */ + private void isServer_ServerInit() { + System.out.println("server"); + server = getNetService().newTCPServer(Port); + onReceiveMessageServer(); + server.startAsync(); + GameVariableNames.multiplayerGameWaiting = true; + } + + /** + * Initialisation du client + */ + private void isServer_ClientInit() { + System.out.println("client"); + client = getNetService().newTCPClient(IP, Port); + onReceiveMessageClient(); + client.connectAsync(); + GameVariableNames.multiplayerGameWaiting = true; + } + + private void PortSelection() { + runOnce(() -> { + getDialogService().showInputBox("Entrez le port (ex:55555)", port -> { + if (port != null) { + Port = Integer.parseInt(port); + } else { + Port = 55555; + } + System.out.println("Port : " + Port); + if (!isServer) { + IPSelection(); + } else { + isServer_ServerInit(); + } + }); + return; + }, Duration.seconds(0)); + } + + private void IPSelection() { + runOnce(() -> { + getDialogService().showInputBox("Entrez l'adresse IP du serveur (ex: localhost ou 111.222.333.444)", ip -> { + if (ip != null) { + IP = ip; + } else { + IP = "localhost"; + } + System.out.println("IP : " + IP); + isServer_ClientInit(); + }); + return; + }, Duration.seconds(0)); + } + + private void startMultiGame() { + long startGameTime = System.currentTimeMillis(); + System.out.println("startGameTime : " + startGameTime); + AlienFactory.makeAlienBlock(); + } + + /** + * Logique d'envoi des données à chaque frame + */ + private void onUpdateBroadcastLogic() {// LBF : dans le mode multijoueur + if (isServer) { + Player1Broadcast(); + } else { + Player2Broadcast(); + } // Ne sert à rien pour le moment mais utile si plus de choses à transférer à + // chaque frame + } + + /** + * Envoie des données du joueur 1 du serveur vers le client + */ + private void Player1Broadcast() { // LBF : dans le mode multijoueur + Bundle bundle = new Bundle("Player1"); + bundle.put("type", "Player1"); + bundle.put("x", player1.getX()); + bundle.put("y", player1.getY()); + bundle.put("score", playerComponent1.getScore()); + bundle.put("life", playerComponent1.getLife()); + server.broadcast(bundle); + } + + /** + * Envoie des données du joueur 2 du client vers le serveur + */ + private void Player2Broadcast() { // LBF : dans le mode multijoueur + Bundle bundle = new Bundle("Player2"); + bundle.put("type", "Player2"); + bundle.put("x", player2.getX()); + bundle.put("y", player2.getY()); + bundle.put("score", playerComponent2.getScore()); + bundle.put("life", playerComponent2.getLife()); + client.broadcast(bundle); + } + + /** + * Logique lors de la réception des données du client par le serveur + */ + private void onReceiveMessageServer() { // LBF : dans le mode multijoueur + server.setOnConnected(connection -> { + connection.addMessageHandlerFX((conn, message) -> { + if (message.getName().equals("Player2")) { + player2.setX(message.get("x")); + player2.setY(message.get("y")); + playerComponent2.setScore(message.get("score")); + playerComponent2.setLife(message.get("life")); + } else if (message.getName().equals("Player2Shoot")) { + playerComponent2.shoot(); + } else if (message.getName().equals("Client Connected")) { + if (!GameVariableNames.multiplayerGameInProgress) { + server.broadcast(new Bundle("Server Start")); + GameVariableNames.multiplayerGameInProgress = true; + startMultiGame(); + } + } else if (message.getName().equals("Game End")) { + System.out.println("Game End Received"); + if (message.get("type").equals("Game Over")) { + gameOverScreen(playerComponent1.getScore(), playerComponent2.getScore()); + } else if (message.get("type").equals("Game Win")) { + winScreen(playerComponent1.getScore(), playerComponent2.getScore()); + } + } else { + System.out.println("Message non reconnu"); + } + }); + }); + } + + /** + * Logique lors de la réception des données du serveur par le client + */ + private void onReceiveMessageClient() { // LBF : dans le mode multijoueur + client.setOnConnected(connection -> { + connection.addMessageHandlerFX((conn, message) -> { + if (message.getName().equals("Player1")) { + player1.setX(message.get("x")); + player1.setY(message.get("y")); + playerComponent1.setScore(message.get("score")); + playerComponent1.setLife(message.get("life")); + } else if (message.getName().equals("Player1Shoot")) { + playerComponent1.shoot(); + } else if (message.getName().equals("AlienSpawn")) { + if (message.get("direction") == Settings.Direction.DOWN) { + Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); + } else { + Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); + alien.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); + } + } else if (message.getName().equals("Server Start")) { + GameVariableNames.multiplayerGameInProgress = true; + startMultiGame(); + } else if (message.getName().equals("Game End")) { + System.out.println("Game End Received"); + if (message.get("type").equals("Game Over")) { + gameOverScreen(playerComponent1.getScore(), playerComponent2.getScore()); + } else if (message.get("type").equals("Game Win")) { + winScreen(playerComponent1.getScore(), playerComponent2.getScore()); + } + } else { + System.out.println("Message non reconnu"); + } + }); + }); + } + + /** + * Logique d'envoi des données lors du tir d'un joueur + */ + private void onShootBroadcastLogic() { // LBF : dans le mode multijoueur + if (isServer) { + server.broadcast(new Bundle("Player1Shoot")); + } else { + client.broadcast(new Bundle("Player2Shoot")); + } + } + +} diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java index 5871275..cd60422 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/NewMainMenu.java @@ -7,6 +7,7 @@ import org.enstabretagne.Game.GameModes.ClassicGameMode; import org.enstabretagne.Game.GameModes.InfinityGameMode; +import org.enstabretagne.Game.GameModes.MultiplayerGameMode; import org.enstabretagne.Game.GameModes.MusicDemoGameMode; import org.enstabretagne.Game.GameModes.SoloGameMode; import org.enstabretagne.Utils.Settings; @@ -84,8 +85,8 @@ private VBox createMenu() { fireNewGame(); }); - SpaceButton buttonMultiMode = new SpaceButton("Play multi", () -> { - GameLauncher.setGameMode(GameMode.MULTI); + SpaceButton buttonMultiMode = new SpaceButton("Play Multiplayer", () -> { + GameLauncher.setGameMode(new MultiplayerGameMode()); fireNewGame(); }); @@ -94,14 +95,14 @@ private VBox createMenu() { fireNewGame(); }); - SpaceButton buttonOption = new SpaceButton("Option", () -> { + SpaceButton buttonOption = new SpaceButton("Options", () -> { if (!getContentRoot().getChildren().contains(options)) { getWindowService().getCurrentScene().removeChild(creditsText); getContentRoot().getChildren().add(options); } }); - SpaceButton buttonCredit = new SpaceButton("Credit", () -> { + SpaceButton buttonCredit = new SpaceButton("Credits", () -> { if (!getContentRoot().getChildren().contains(creditsText)) { getWindowService().getCurrentScene().removeChild(options); getContentRoot().getChildren().add(creditsText); From a2062706b6c759d1bcdb13654cc5b1a91d6fa04e Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sat, 11 Mar 2023 22:54:22 +0100 Subject: [PATCH 40/50] refactor(serverTCP): :construction: multiplayer Continuing the refactor for multiplayer mode. --- .../org/enstabretagne/Game/GameLauncher.java | 2 +- .../Game/GameModes/MultiplayerGameMode.java | 158 +++++++++++------- 2 files changed, 97 insertions(+), 63 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index a1150fd..ec6aed4 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -95,7 +95,7 @@ protected void initSettings(GameSettings settings) { "Sounds effect from:", "https://universal-soundbank.com/")); settings.setEnabledMenuItems(EnumSet.of(MenuItem.EXTRA)); - settings.setApplicationMode(ApplicationMode.RELEASE); + settings.setApplicationMode(ApplicationMode.DEBUG); // TODO: change to RELEASE settings.setSceneFactory(new SceneFactory() { @Override public FXGLMenu newMainMenu() { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java index f5d235c..934f0a1 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java @@ -2,12 +2,14 @@ import static com.almasb.fxgl.dsl.FXGL.getDialogService; import static com.almasb.fxgl.dsl.FXGL.getNetService; -import static com.almasb.fxgl.dsl.FXGL.runOnce; import static com.almasb.fxgl.dsl.FXGL.spawn; import static org.enstabretagne.UI.UI_Factory.gameOverScreen; import static org.enstabretagne.UI.UI_Factory.winScreen; +import java.util.regex.Pattern; + import org.enstabretagne.Component.AlienComponent; +import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.entityNames; @@ -17,8 +19,6 @@ import com.almasb.fxgl.net.Client; import com.almasb.fxgl.net.Server; -import javafx.util.Duration; - public class MultiplayerGameMode extends TwoPlayerGameMode { private boolean isServer; private Server server; @@ -26,12 +26,20 @@ public class MultiplayerGameMode extends TwoPlayerGameMode { private boolean alienSpawnStart = false; // indique si les aliens ont commencé à spawn - private int Port; - private String IP; + private int serverPort = 55555; + private String serverIPaddress = "localhost"; @Override public void initGameMode() { super.initTwoPlayerGameMode(); + areYouTheServer(); + selectPort(); + if (isServer) { + initializeServer(); + } else { + selectIPaddress(); + initializeClient(); + } } @Override @@ -42,96 +50,104 @@ public GameModeTypes getGameModeType() { /** * Input box pour le choix héberger/rejoindre une partie multijoueur */ - private void isServer() { + private void areYouTheServer() { getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { if (yes) { isServer = true; - PortSelection(); } else { isServer = false; - PortSelection(); } }); } + /** + * Input box pour le choix du port + */ + private void selectPort() { + getDialogService().showInputBox("Entrez le port (ex:55555)", port -> { + try { + serverPort = Integer.parseInt(port); + } catch (Exception e) { + serverPort = 55555; + } + System.out.println("Port : " + serverPort); + + }); + } + /** * Initialisation du serveur */ - private void isServer_ServerInit() { + private void initializeServer() { System.out.println("server"); - server = getNetService().newTCPServer(Port); + getDialogService() + .showMessageBox("You are the server on the following address : " + serverIPaddress + + " on port : " + serverPort); + server = getNetService().newTCPServer(serverPort); onReceiveMessageServer(); server.startAsync(); GameVariableNames.multiplayerGameWaiting = true; } + /** + * Input box pour la sélection de l'adresse IP du serveur + */ + private void selectIPaddress() { + getDialogService().showInputBox("Entrez l'adresse IP du serveur (ex: localhost ou 111.222.333.444)", + IPaddress -> { + // Regex expression for validating IPv4 + String regex_ipv4 = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; + + // Regex expression for validating IPv6 + String regex_ipv6 = "((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"; + Pattern pattern_ipv4 = Pattern.compile(regex_ipv4); + Pattern pattern_ipv6 = Pattern.compile(regex_ipv6); + if (!pattern_ipv4.matcher(IPaddress).matches() && !pattern_ipv6.matcher(IPaddress).matches()) { + serverIPaddress = "localhost"; + return; + } + serverIPaddress = IPaddress; + System.out.println("IP : " + serverIPaddress); + }); + } + /** * Initialisation du client */ - private void isServer_ClientInit() { + private void initializeClient() { System.out.println("client"); - client = getNetService().newTCPClient(IP, Port); + getDialogService() + .showMessageBox("You are connecting to the server on the following address : " + serverIPaddress + + " on port : " + serverPort); + client = getNetService().newTCPClient(serverIPaddress, serverPort); onReceiveMessageClient(); client.connectAsync(); GameVariableNames.multiplayerGameWaiting = true; } - private void PortSelection() { - runOnce(() -> { - getDialogService().showInputBox("Entrez le port (ex:55555)", port -> { - if (port != null) { - Port = Integer.parseInt(port); - } else { - Port = 55555; - } - System.out.println("Port : " + Port); - if (!isServer) { - IPSelection(); - } else { - isServer_ServerInit(); - } - }); - return; - }, Duration.seconds(0)); - } - - private void IPSelection() { - runOnce(() -> { - getDialogService().showInputBox("Entrez l'adresse IP du serveur (ex: localhost ou 111.222.333.444)", ip -> { - if (ip != null) { - IP = ip; - } else { - IP = "localhost"; - } - System.out.println("IP : " + IP); - isServer_ClientInit(); - }); - return; - }, Duration.seconds(0)); - } - private void startMultiGame() { long startGameTime = System.currentTimeMillis(); System.out.println("startGameTime : " + startGameTime); AlienFactory.makeAlienBlock(); } - /** - * Logique d'envoi des données à chaque frame - */ - private void onUpdateBroadcastLogic() {// LBF : dans le mode multijoueur - if (isServer) { - Player1Broadcast(); - } else { - Player2Broadcast(); - } // Ne sert à rien pour le moment mais utile si plus de choses à transférer à - // chaque frame - } + // /** + // * Logique d'envoi des données à chaque frame + // */ + // private void onUpdateBroadcastLogic() { + // if (isServer) { + // Player1Broadcast(); + // } else { + // Player2Broadcast(); + // } // Ne sert à rien pour le moment mais utile si plus de choses à transférer + // à + // // chaque frame + // } /** * Envoie des données du joueur 1 du serveur vers le client */ - private void Player1Broadcast() { // LBF : dans le mode multijoueur + private void Player1Broadcast() { Bundle bundle = new Bundle("Player1"); bundle.put("type", "Player1"); bundle.put("x", player1.getX()); @@ -144,7 +160,7 @@ private void Player1Broadcast() { // LBF : dans le mode multijoueur /** * Envoie des données du joueur 2 du client vers le serveur */ - private void Player2Broadcast() { // LBF : dans le mode multijoueur + private void Player2Broadcast() { Bundle bundle = new Bundle("Player2"); bundle.put("type", "Player2"); bundle.put("x", player2.getX()); @@ -157,7 +173,7 @@ private void Player2Broadcast() { // LBF : dans le mode multijoueur /** * Logique lors de la réception des données du client par le serveur */ - private void onReceiveMessageServer() { // LBF : dans le mode multijoueur + private void onReceiveMessageServer() { server.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { if (message.getName().equals("Player2")) { @@ -190,7 +206,7 @@ private void onReceiveMessageServer() { // LBF : dans le mode multijoueur /** * Logique lors de la réception des données du serveur par le client */ - private void onReceiveMessageClient() { // LBF : dans le mode multijoueur + private void onReceiveMessageClient() { client.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { if (message.getName().equals("Player1")) { @@ -228,7 +244,7 @@ private void onReceiveMessageClient() { // LBF : dans le mode multijoueur /** * Logique d'envoi des données lors du tir d'un joueur */ - private void onShootBroadcastLogic() { // LBF : dans le mode multijoueur + private void onShootBroadcastLogic() { if (isServer) { server.broadcast(new Bundle("Player1Shoot")); } else { @@ -236,4 +252,22 @@ private void onShootBroadcastLogic() { // LBF : dans le mode multijoueur } } + @Override + public PlayerComponent getPlayerComponent2() { + if (isServer) { + return playerComponent1; + } else { + return playerComponent2; + } + } + + @Override + public PlayerComponent getPlayerComponent1() { + if (isServer) { + return playerComponent1; + } else { + return playerComponent2; + } + } + } From 6b681655af52bf507993f3b02930817a0cbd67a0 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sun, 12 Mar 2023 16:39:45 +0100 Subject: [PATCH 41/50] refactor(GameMode): :recycle: creating onUpdate This method in the GameMode contract, allows the game mode to define its own update logic. This is useful for game modes that need to update particular entities or perform specific actions. --- .../org/enstabretagne/Game/GameLauncher.java | 23 +------ .../Game/GameModes/GameMode.java | 2 + .../Game/GameModes/OnePlayerGameMode.java | 60 +++++++++++++------ 3 files changed, 45 insertions(+), 40 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index ec6aed4..b1984b4 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -3,12 +3,10 @@ import static com.almasb.fxgl.dsl.FXGL.getGameScene; import static com.almasb.fxgl.dsl.FXGL.getGameWorld; import static com.almasb.fxgl.dsl.FXGL.getPhysicsWorld; -import static com.almasb.fxgl.dsl.FXGL.getb; import static com.almasb.fxgl.dsl.FXGL.loopBGM; import static com.almasb.fxgl.dsl.FXGL.onKey; import static com.almasb.fxgl.dsl.FXGL.play; import static com.almasb.fxgl.dsl.FXGL.spawn; -import static org.enstabretagne.UI.UI_Factory.ambientSound; import static org.enstabretagne.UI.UI_Factory.showPlayersLivesAndScores; import java.util.Arrays; @@ -22,7 +20,6 @@ import org.enstabretagne.Collision.EnemyShootBulletCollision; import org.enstabretagne.Collision.EnemyShootPlayerCollision; import org.enstabretagne.Component.SpaceInvadersFactory; -import org.enstabretagne.Game.GameModes.AlienFactory; import org.enstabretagne.Game.GameModes.ClassicGameMode; import org.enstabretagne.Game.GameModes.GameMode; import org.enstabretagne.Game.GameModes.GameModeTypes; @@ -37,7 +34,6 @@ import com.almasb.fxgl.app.MenuItem; import com.almasb.fxgl.app.scene.FXGLMenu; import com.almasb.fxgl.app.scene.SceneFactory; -import com.almasb.fxgl.core.math.FXGLMath; import javafx.scene.input.KeyCode; @@ -50,9 +46,6 @@ */ public class GameLauncher extends GameApplication { private static GameMode game_mode = new ClassicGameMode(); - private long last_ambient_sound = System.currentTimeMillis(); - private int delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, - Settings.AMBIENT_SOUND_DELAY_MAX); public static void setGameMode(GameMode gameMode) { game_mode = gameMode; @@ -73,7 +66,7 @@ protected void initSettings(GameSettings settings) { settings.setHeight(Settings.GAME_HEIGHT.intValue()); settings.setTitle("Duel Invaders"); settings.setAppIcon(assetNames.textures.APP_ICON); - settings.setVersion("0.2.0"); + settings.setVersion("0.3.0"); settings.setMainMenuEnabled(true); settings.setGameMenuEnabled(true); settings.setFullScreenAllowed(true); @@ -185,19 +178,7 @@ protected void initUI() { */ @Override protected void onUpdate(double tpf) { - if (getb(GameVariableNames.isGameOver) || getb(GameVariableNames.isGameWon)) { - game_mode.gameFinished(); - } - - if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { - ambientSound(); - last_ambient_sound = System.currentTimeMillis(); - delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); - } - - showPlayersLivesAndScores(getGameWorld(), getGameScene()); - - AlienFactory.aliensRandomlyShoot(); + game_mode.onUpdate(tpf); } public static void main(String[] args) { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java index eba1443..99e61f1 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/GameMode.java @@ -16,5 +16,7 @@ public interface GameMode { public GameModeTypes getGameModeType(); + public void onUpdate(double tpf); + public void gameFinished(); } \ No newline at end of file diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index 60a4459..23124c5 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -1,9 +1,9 @@ package org.enstabretagne.Game.GameModes; import static com.almasb.fxgl.dsl.FXGL.getb; -import static com.almasb.fxgl.dsl.FXGL.spawn; +import static com.almasb.fxgl.dsl.FXGL.*; import static org.enstabretagne.UI.UI_Factory.gameOverScreen; -import static org.enstabretagne.UI.UI_Factory.winScreen; +import static org.enstabretagne.UI.UI_Factory.*; import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.GameVariableNames; @@ -11,11 +11,15 @@ import org.enstabretagne.Utils.Settings.Direction; import org.enstabretagne.Utils.entityNames; +import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.entity.Entity; public abstract class OnePlayerGameMode implements GameMode { protected Entity player1; protected PlayerComponent playerComponent1; + private long last_ambient_sound = System.currentTimeMillis(); + private int delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, + Settings.AMBIENT_SOUND_DELAY_MAX); @Override public GameModeTypes getGameModeType() { @@ -28,23 +32,6 @@ public void initOnePlayerGameMode() { playerComponent1 = initPlayerComponent(player1, Direction.UP); } - protected Entity initPlayer(Entity player, double positionX, double positionY) { - player = spawn(entityNames.PLAYER); - player.setX(positionX); - player.setY(positionY); - return player; - } - - protected Entity initPlayer(Entity player, double positionX) { - return initPlayer(player, positionX, 0); - } - - protected PlayerComponent initPlayerComponent(Entity player, Direction direction) { - PlayerComponent playerComponent = player.getComponent(PlayerComponent.class); - playerComponent.setDirection(direction); - return playerComponent; - } - @Override public void gameFinished() { if (getb(GameVariableNames.isGameOver)) { @@ -65,4 +52,39 @@ public PlayerComponent getPlayerComponent2() { return playerComponent1; } + @Override + public void onUpdate(double tpf) { + if (getb(GameVariableNames.isGameOver) || getb(GameVariableNames.isGameWon)) { + gameFinished(); + } + + if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { + ambientSound(); + last_ambient_sound = System.currentTimeMillis(); + delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); + } + + showPlayersLivesAndScores(getGameWorld(), getGameScene()); + + AlienFactory.aliensRandomlyShoot(); + + } + + protected Entity initPlayer(Entity player, double positionX, double positionY) { + player = spawn(entityNames.PLAYER); + player.setX(positionX); + player.setY(positionY); + return player; + } + + protected Entity initPlayer(Entity player, double positionX) { + return initPlayer(player, positionX, 0); + } + + protected PlayerComponent initPlayerComponent(Entity player, Direction direction) { + PlayerComponent playerComponent = player.getComponent(PlayerComponent.class); + playerComponent.setDirection(direction); + return playerComponent; + } + } From 9f620694e44f0a16819fa22002628dab68baa43c Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sun, 12 Mar 2023 20:30:41 +0100 Subject: [PATCH 42/50] refactor(serverTCP): :construction: dialog boxes Trying to make the dialog boxes pop up in order and according to user choices. Still a work in progress. --- .../Game/GameModes/MultiplayerGameMode.java | 264 ++++++++++++------ 1 file changed, 183 insertions(+), 81 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java index 934f0a1..95c0d36 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java @@ -1,13 +1,24 @@ package org.enstabretagne.Game.GameModes; import static com.almasb.fxgl.dsl.FXGL.getDialogService; +import static com.almasb.fxgl.dsl.FXGL.getGameController; import static com.almasb.fxgl.dsl.FXGL.getNetService; -import static com.almasb.fxgl.dsl.FXGL.spawn; +import static com.almasb.fxgl.dsl.FXGL.runOnce; +import static com.almasb.fxgl.dsl.FXGL.*; import static org.enstabretagne.UI.UI_Factory.gameOverScreen; import static org.enstabretagne.UI.UI_Factory.winScreen; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Function; import java.util.regex.Pattern; +import javax.naming.LimitExceededException; + import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.GameVariableNames; @@ -16,11 +27,17 @@ import com.almasb.fxgl.core.serialization.Bundle; import com.almasb.fxgl.entity.Entity; +import com.almasb.fxgl.logging.Logger; import com.almasb.fxgl.net.Client; import com.almasb.fxgl.net.Server; +import com.almasb.fxgl.time.TimerAction; + +import javafx.animation.PauseTransition; +import javafx.util.Duration; public class MultiplayerGameMode extends TwoPlayerGameMode { - private boolean isServer; + private boolean isServer = false; + private boolean hasChosen = false; private Server server; private Client client; @@ -32,14 +49,67 @@ public class MultiplayerGameMode extends TwoPlayerGameMode { @Override public void initGameMode() { super.initTwoPlayerGameMode(); - areYouTheServer(); - selectPort(); - if (isServer) { - initializeServer(); - } else { - selectIPaddress(); - initializeClient(); + + List dialogQueue = dialogQueue(); + PauseTransition dialogPauseTransition = new PauseTransition(Duration.seconds(1)); + dialogPauseTransition.setOnFinished(event -> { + if (dialogQueue.size() > 0) { + dialogQueue.get(0).play(); + dialogQueue.remove(0); + dialogPauseTransition.playFromStart(); + } + }); + dialogPauseTransition.play(); + } + + private enum DialogType { + SERVER_CHOICE, PORT_CHOICE, IP_CHOICE + } + + private List dialogQueue() { + Map dialogQueueMessages = new HashMap<>(); + dialogQueueMessages.put(DialogType.SERVER_CHOICE, "Voulez-vous être le serveur ?"); + dialogQueueMessages.put(DialogType.PORT_CHOICE, "Entrez le port (ex:55555)"); + dialogQueueMessages.put(DialogType.IP_CHOICE, "Entrez l'adresse IP du serveur (format:255.255.255.255)"); + Map> dialogQueueStringActions = new HashMap<>(); + Map> dialogQueueBooleanActions = new HashMap<>(); + dialogQueueStringActions.put(DialogType.PORT_CHOICE, port -> { + try { + serverPort = Integer.parseInt(port); + } catch (Exception e) { + serverPort = 55555; + } + Logger.get(getClass()).info("Port : " + serverPort); + }); + dialogQueueStringActions.put(DialogType.IP_CHOICE, ip -> { + serverIPaddress = ip; + Logger.get(getClass()).info("IP address : " + serverIPaddress); + }); + dialogQueueBooleanActions.put(DialogType.SERVER_CHOICE, yes -> { + isServer = yes; + Logger.get(getClass()).info("Are you the server ? : " + isServer); + }); + return pauseDialogQueue(dialogQueueMessages, dialogQueueStringActions, dialogQueueBooleanActions); + } + + private List pauseDialogQueue(Map dialogQueueMessages, + Map> dialogQueueStringActions, + Map> dialogQueueBooleanActions) { + List pauses = new ArrayList<>(); + for (DialogType dialogType : dialogQueueMessages.keySet()) { + PauseTransition pause = new PauseTransition(Duration.seconds(1)); + pause.setOnFinished(event -> { + if (dialogQueueBooleanActions.containsKey(dialogType)) { + getDialogService().showConfirmationBox(dialogQueueMessages.get(dialogType), + dialogQueueBooleanActions.get(dialogType)); + } else if (dialogQueueStringActions.containsKey(dialogType)) { + getDialogService().showInputBox(dialogQueueMessages.get(dialogType), + dialogQueueStringActions.get(dialogType)); + } + }); + pauses.add(pause); } + return pauses; } @Override @@ -47,68 +117,129 @@ public GameModeTypes getGameModeType() { return GameModeTypes.MULTIPLAYER; } + @Override + public PlayerComponent getPlayerComponent2() { + if (isServer) { + return playerComponent1; + } else { + return playerComponent2; + } + } + + @Override + public PlayerComponent getPlayerComponent1() { + if (isServer) { + return playerComponent1; + } else { + return playerComponent2; + } + } + + @Override + public void onUpdate(double tpf) { + // TODO: make the game logic too. + } + + @Override + public void gameFinished() { + // TODO: clean server/client connection. + super.gameFinished(); + } + + private void initializePlayers() { + if (isServer) { + initializeServer(); + return; + } + selectIPaddress(); + initializeClient(); + } + /** * Input box pour le choix héberger/rejoindre une partie multijoueur */ - private void areYouTheServer() { - getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { - if (yes) { - isServer = true; - } else { - isServer = false; - } - }); + private TimerAction areYouTheServer() { + // On attend 1 seconde pour que le joueur puisse choisir si il est le serveur ou + // le client + // Cela permet au jeu de s'initialiser avant de demander à l'utilisateur + return runOnce(() -> { + getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { + isServer = yes; + Logger.get(getClass()).info("Are you the server ? : " + isServer); + }); + }, Duration.seconds(1)); } /** * Input box pour le choix du port */ - private void selectPort() { - getDialogService().showInputBox("Entrez le port (ex:55555)", port -> { - try { - serverPort = Integer.parseInt(port); - } catch (Exception e) { - serverPort = 55555; - } - System.out.println("Port : " + serverPort); - - }); + private TimerAction selectPort() { + return runOnce(() -> { + getDialogService().showInputBox("Entrez le port (ex:55555)", port -> { + try { + serverPort = Integer.parseInt(port); + } catch (Exception e) { + serverPort = 55555; + } + Logger.get(getClass()).info("Port : " + serverPort); + }); + hasChosen = true; + }, Duration.seconds(2)); } + // /** + // * Logique d'envoi des données à chaque frame + // */ + // private void onUpdateBroadcastLogic() { + // if (isServer) { + // Player1Broadcast(); + // } else { + // Player2Broadcast(); + // } // Ne sert à rien pour le moment mais utile si plus de choses à transférer + // à + // // chaque frame + // } + /** * Initialisation du serveur */ private void initializeServer() { - System.out.println("server"); - getDialogService() - .showMessageBox("You are the server on the following address : " + serverIPaddress - + " on port : " + serverPort); + Logger.get(getClass()).info("Server starting..."); + runOnce(() -> { + getDialogService() + .showMessageBox("You are the server on the following address : " + serverIPaddress + + " on port : " + serverPort); + }, Duration.seconds(1)); server = getNetService().newTCPServer(serverPort); onReceiveMessageServer(); server.startAsync(); GameVariableNames.multiplayerGameWaiting = true; + Logger.get(getClass()).info("Server started on port : " + serverPort); } /** * Input box pour la sélection de l'adresse IP du serveur */ private void selectIPaddress() { - getDialogService().showInputBox("Entrez l'adresse IP du serveur (ex: localhost ou 111.222.333.444)", - IPaddress -> { - // Regex expression for validating IPv4 - String regex_ipv4 = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; - - // Regex expression for validating IPv6 - String regex_ipv6 = "((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"; - Pattern pattern_ipv4 = Pattern.compile(regex_ipv4); - Pattern pattern_ipv6 = Pattern.compile(regex_ipv6); - if (!pattern_ipv4.matcher(IPaddress).matches() && !pattern_ipv6.matcher(IPaddress).matches()) { - serverIPaddress = "localhost"; - return; - } - serverIPaddress = IPaddress; - System.out.println("IP : " + serverIPaddress); - }); + runOnce(() -> { + getDialogService().showInputBox("Entrez l'adresse IP du serveur (ex: localhost ou 111.222.333.444)", + IPaddress -> { + // Regex expression for validating IPv4 + String regex_ipv4 = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; + + // Regex expression for validating IPv6 + String regex_ipv6 = "((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"; + Pattern pattern_ipv4 = Pattern.compile(regex_ipv4); + Pattern pattern_ipv6 = Pattern.compile(regex_ipv6); + if (!pattern_ipv4.matcher(IPaddress).matches() && !pattern_ipv6.matcher(IPaddress).matches()) { + serverIPaddress = "localhost"; + return; + } + serverIPaddress = IPaddress; + Logger.get(getClass()).info("IP : " + serverIPaddress); + }); + + }, Duration.seconds(3)); } /** @@ -116,9 +247,11 @@ private void selectIPaddress() { */ private void initializeClient() { System.out.println("client"); - getDialogService() - .showMessageBox("You are connecting to the server on the following address : " + serverIPaddress - + " on port : " + serverPort); + runOnce(() -> { + getDialogService() + .showMessageBox("You are connecting to the server on the following address : " + serverIPaddress + + " on port : " + serverPort); + }, Duration.seconds(3)); client = getNetService().newTCPClient(serverIPaddress, serverPort); onReceiveMessageClient(); client.connectAsync(); @@ -131,19 +264,6 @@ private void startMultiGame() { AlienFactory.makeAlienBlock(); } - // /** - // * Logique d'envoi des données à chaque frame - // */ - // private void onUpdateBroadcastLogic() { - // if (isServer) { - // Player1Broadcast(); - // } else { - // Player2Broadcast(); - // } // Ne sert à rien pour le moment mais utile si plus de choses à transférer - // à - // // chaque frame - // } - /** * Envoie des données du joueur 1 du serveur vers le client */ @@ -252,22 +372,4 @@ private void onShootBroadcastLogic() { } } - @Override - public PlayerComponent getPlayerComponent2() { - if (isServer) { - return playerComponent1; - } else { - return playerComponent2; - } - } - - @Override - public PlayerComponent getPlayerComponent1() { - if (isServer) { - return playerComponent1; - } else { - return playerComponent2; - } - } - } From 77a4b04b1dc890ae81fa7d6134b80ea43c248aa0 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sun, 12 Mar 2023 21:00:09 +0100 Subject: [PATCH 43/50] fix(serverTCP): :recycle: showing dialog boxes The popups are now correctly shown in the right order too. --- .../Game/GameModes/MultiplayerGameMode.java | 207 +++++++----------- 1 file changed, 76 insertions(+), 131 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java index 95c0d36..dbe39d1 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java @@ -1,24 +1,17 @@ package org.enstabretagne.Game.GameModes; import static com.almasb.fxgl.dsl.FXGL.getDialogService; -import static com.almasb.fxgl.dsl.FXGL.getGameController; import static com.almasb.fxgl.dsl.FXGL.getNetService; -import static com.almasb.fxgl.dsl.FXGL.runOnce; +import static com.almasb.fxgl.dsl.FXGL.getNotificationService; +import static com.almasb.fxgl.dsl.FXGL.showConfirm; import static com.almasb.fxgl.dsl.FXGL.*; import static org.enstabretagne.UI.UI_Factory.gameOverScreen; import static org.enstabretagne.UI.UI_Factory.winScreen; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Function; import java.util.regex.Pattern; -import javax.naming.LimitExceededException; - import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.PlayerComponent; import org.enstabretagne.Utils.GameVariableNames; @@ -30,86 +23,27 @@ import com.almasb.fxgl.logging.Logger; import com.almasb.fxgl.net.Client; import com.almasb.fxgl.net.Server; -import com.almasb.fxgl.time.TimerAction; import javafx.animation.PauseTransition; import javafx.util.Duration; public class MultiplayerGameMode extends TwoPlayerGameMode { + private enum DialogType { + SERVER_CHOICE, PORT_CHOICE, IP_CHOICE + } + private boolean isServer = false; - private boolean hasChosen = false; private Server server; - private Client client; - - private boolean alienSpawnStart = false; // indique si les aliens ont commencé à spawn + private Client client; private int serverPort = 55555; + private String serverIPaddress = "localhost"; @Override public void initGameMode() { super.initTwoPlayerGameMode(); - - List dialogQueue = dialogQueue(); - PauseTransition dialogPauseTransition = new PauseTransition(Duration.seconds(1)); - dialogPauseTransition.setOnFinished(event -> { - if (dialogQueue.size() > 0) { - dialogQueue.get(0).play(); - dialogQueue.remove(0); - dialogPauseTransition.playFromStart(); - } - }); - dialogPauseTransition.play(); - } - - private enum DialogType { - SERVER_CHOICE, PORT_CHOICE, IP_CHOICE - } - - private List dialogQueue() { - Map dialogQueueMessages = new HashMap<>(); - dialogQueueMessages.put(DialogType.SERVER_CHOICE, "Voulez-vous être le serveur ?"); - dialogQueueMessages.put(DialogType.PORT_CHOICE, "Entrez le port (ex:55555)"); - dialogQueueMessages.put(DialogType.IP_CHOICE, "Entrez l'adresse IP du serveur (format:255.255.255.255)"); - Map> dialogQueueStringActions = new HashMap<>(); - Map> dialogQueueBooleanActions = new HashMap<>(); - dialogQueueStringActions.put(DialogType.PORT_CHOICE, port -> { - try { - serverPort = Integer.parseInt(port); - } catch (Exception e) { - serverPort = 55555; - } - Logger.get(getClass()).info("Port : " + serverPort); - }); - dialogQueueStringActions.put(DialogType.IP_CHOICE, ip -> { - serverIPaddress = ip; - Logger.get(getClass()).info("IP address : " + serverIPaddress); - }); - dialogQueueBooleanActions.put(DialogType.SERVER_CHOICE, yes -> { - isServer = yes; - Logger.get(getClass()).info("Are you the server ? : " + isServer); - }); - return pauseDialogQueue(dialogQueueMessages, dialogQueueStringActions, dialogQueueBooleanActions); - } - - private List pauseDialogQueue(Map dialogQueueMessages, - Map> dialogQueueStringActions, - Map> dialogQueueBooleanActions) { - List pauses = new ArrayList<>(); - for (DialogType dialogType : dialogQueueMessages.keySet()) { - PauseTransition pause = new PauseTransition(Duration.seconds(1)); - pause.setOnFinished(event -> { - if (dialogQueueBooleanActions.containsKey(dialogType)) { - getDialogService().showConfirmationBox(dialogQueueMessages.get(dialogType), - dialogQueueBooleanActions.get(dialogType)); - } else if (dialogQueueStringActions.containsKey(dialogType)) { - getDialogService().showInputBox(dialogQueueMessages.get(dialogType), - dialogQueueStringActions.get(dialogType)); - } - }); - pauses.add(pause); - } - return pauses; + dialogQueue().play(); } @Override @@ -146,45 +80,65 @@ public void gameFinished() { super.gameFinished(); } + private PauseTransition dialogQueue() { + Map dialogQueueMessages = new HashMap<>(); + dialogQueueMessages.put(DialogType.SERVER_CHOICE, "Voulez-vous être le serveur ?"); + dialogQueueMessages.put(DialogType.PORT_CHOICE, "Entrez le port (ex:55555)"); + dialogQueueMessages.put(DialogType.IP_CHOICE, "Entrez l'adresse IP du serveur (format:255.255.255.255)"); + PauseTransition pause = new PauseTransition(Duration.seconds(2)); + pause.setOnFinished(event -> { + showConfirm(dialogQueueMessages.get(DialogType.SERVER_CHOICE), + (yes) -> { + areYouTheServer(yes); + showPortInput(dialogQueueMessages); + }); + }); + return pause; + } + + private void showPortInput(Map dialogQueueMessages) { + getDialogService().showInputBox(dialogQueueMessages.get(DialogType.PORT_CHOICE), (port) -> { + selectPort(port); + if (!isServer) { + getDialogService().showInputBox(dialogQueueMessages.get(DialogType.IP_CHOICE), + (IPaddress) -> { + selectIPaddress(IPaddress); + initializePlayers(); + }); + } else { + initializePlayers(); + } + }); + } + private void initializePlayers() { if (isServer) { initializeServer(); return; } - selectIPaddress(); + // selectIPaddress(); initializeClient(); } /** - * Input box pour le choix héberger/rejoindre une partie multijoueur + * Choix utilisateur pour héberger/rejoindre une partie multijoueur */ - private TimerAction areYouTheServer() { - // On attend 1 seconde pour que le joueur puisse choisir si il est le serveur ou - // le client - // Cela permet au jeu de s'initialiser avant de demander à l'utilisateur - return runOnce(() -> { - getDialogService().showConfirmationBox("Voulez-vous être le serveur ?", yes -> { - isServer = yes; - Logger.get(getClass()).info("Are you the server ? : " + isServer); - }); - }, Duration.seconds(1)); + private Boolean areYouTheServer(Boolean yes) { + isServer = yes; + Logger.get(getClass()).info("Are you the server ? : " + isServer); + return isServer; } /** - * Input box pour le choix du port + * Choix du port du serveur */ - private TimerAction selectPort() { - return runOnce(() -> { - getDialogService().showInputBox("Entrez le port (ex:55555)", port -> { - try { - serverPort = Integer.parseInt(port); - } catch (Exception e) { - serverPort = 55555; - } - Logger.get(getClass()).info("Port : " + serverPort); - }); - hasChosen = true; - }, Duration.seconds(2)); + private void selectPort(String port) { + try { + serverPort = Integer.parseInt(port); + } catch (Exception e) { + serverPort = 55555; + } + Logger.get(getClass()).info("Port : " + serverPort); } // /** @@ -205,11 +159,8 @@ private TimerAction selectPort() { */ private void initializeServer() { Logger.get(getClass()).info("Server starting..."); - runOnce(() -> { - getDialogService() - .showMessageBox("You are the server on the following address : " + serverIPaddress - + " on port : " + serverPort); - }, Duration.seconds(1)); + getNotificationService().pushNotification("You are the server on the following address : " + serverIPaddress + + " on port : " + serverPort); server = getNetService().newTCPServer(serverPort); onReceiveMessageServer(); server.startAsync(); @@ -220,42 +171,36 @@ private void initializeServer() { /** * Input box pour la sélection de l'adresse IP du serveur */ - private void selectIPaddress() { - runOnce(() -> { - getDialogService().showInputBox("Entrez l'adresse IP du serveur (ex: localhost ou 111.222.333.444)", - IPaddress -> { - // Regex expression for validating IPv4 - String regex_ipv4 = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; - - // Regex expression for validating IPv6 - String regex_ipv6 = "((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"; - Pattern pattern_ipv4 = Pattern.compile(regex_ipv4); - Pattern pattern_ipv6 = Pattern.compile(regex_ipv6); - if (!pattern_ipv4.matcher(IPaddress).matches() && !pattern_ipv6.matcher(IPaddress).matches()) { - serverIPaddress = "localhost"; - return; - } - serverIPaddress = IPaddress; - Logger.get(getClass()).info("IP : " + serverIPaddress); - }); - - }, Duration.seconds(3)); + private void selectIPaddress(String IPaddress) { + // TODO: improve IP address validation + // Regex expression for validating IPv4 + String regex_ipv4 = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; + + // Regex expression for validating IPv6 + String regex_ipv6 = "((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"; + Pattern pattern_ipv4 = Pattern.compile(regex_ipv4); + Pattern pattern_ipv6 = Pattern.compile(regex_ipv6); + if (!pattern_ipv4.matcher(IPaddress).matches() && !pattern_ipv6.matcher(IPaddress).matches()) { + serverIPaddress = "localhost"; + return; + } + serverIPaddress = IPaddress; + Logger.get(getClass()).info("IP : " + serverIPaddress); } /** * Initialisation du client */ private void initializeClient() { - System.out.println("client"); - runOnce(() -> { - getDialogService() - .showMessageBox("You are connecting to the server on the following address : " + serverIPaddress - + " on port : " + serverPort); - }, Duration.seconds(3)); + Logger.get(getClass()).info("Client starting..."); + getNotificationService() + .pushNotification("You are connecting to the server on the following address : " + serverIPaddress + + " on port : " + serverPort); client = getNetService().newTCPClient(serverIPaddress, serverPort); onReceiveMessageClient(); client.connectAsync(); GameVariableNames.multiplayerGameWaiting = true; + Logger.get(getClass()).info("Client connected to server !"); } private void startMultiGame() { From df90378a1439214cf40de76bc9e961377c4f1ee4 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sun, 12 Mar 2023 21:21:48 +0100 Subject: [PATCH 44/50] refactor(serverTCP): :recycle: firstly working ! Finally got the multiplayer mode working on two instances ! Not everything is working yet, but it's a good start ! Still need to sync the shooting logic and handle errors when no server connection or other types of errors. --- .../Game/GameModes/MultiplayerGameMode.java | 88 ++++++++++++++----- .../Game/GameModes/OnePlayerGameMode.java | 4 +- 2 files changed, 70 insertions(+), 22 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java index dbe39d1..128584b 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java @@ -1,11 +1,7 @@ package org.enstabretagne.Game.GameModes; -import static com.almasb.fxgl.dsl.FXGL.getDialogService; -import static com.almasb.fxgl.dsl.FXGL.getNetService; -import static com.almasb.fxgl.dsl.FXGL.getNotificationService; -import static com.almasb.fxgl.dsl.FXGL.showConfirm; import static com.almasb.fxgl.dsl.FXGL.*; -import static org.enstabretagne.UI.UI_Factory.gameOverScreen; +import static org.enstabretagne.UI.UI_Factory.*; import static org.enstabretagne.UI.UI_Factory.winScreen; import java.util.HashMap; @@ -14,10 +10,12 @@ import org.enstabretagne.Component.AlienComponent; import org.enstabretagne.Component.PlayerComponent; +import org.enstabretagne.Utils.EntityType; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; import org.enstabretagne.Utils.entityNames; +import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.core.serialization.Bundle; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.logging.Logger; @@ -71,13 +69,64 @@ public PlayerComponent getPlayerComponent1() { @Override public void onUpdate(double tpf) { - // TODO: make the game logic too. + if (GameVariableNames.multiplayerGameInProgress) { + onUpdateBroadcastLogic(); + onUpdateCommon(tpf); + } else { + // Synchronise le début de la partie entre les deux joueurs + if (!isServer && GameVariableNames.multiplayerGameWaiting) { + client.broadcast(new Bundle("Client Connected")); + } + } + } + + private void onUpdateCommon(double tpf) { + if (getb(GameVariableNames.isGameOver) || getb(GameVariableNames.isGameWon)) { + gameFinished(); + } + + if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { + ambientSound(); + last_ambient_sound = System.currentTimeMillis(); + delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); + } + showPlayersLivesAndScores(getGameWorld(), getGameScene()); + + run(() -> { + getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { + if (FXGLMath.randomBoolean(0.005)) { + if (isServer + && alien.getComponent(AlienComponent.class).getDirection() == Settings.Direction.DOWN) { + alien.getComponent(AlienComponent.class).randomShoot(Settings.ALIEN_SHOOT_CHANCE); + } else if (!isServer + && alien.getComponent(AlienComponent.class).getDirection() == Settings.Direction.UP) { + alien.getComponent(AlienComponent.class).randomShoot(Settings.ALIEN_SHOOT_CHANCE); + } + } + }); + }, Duration.seconds(Settings.random.nextDouble() * 10)); + } + + private void GameEndBroadcastLogic(String message) { + Bundle bundle = new Bundle("Game End"); + bundle.put("type", message); + if (isServer) { + server.broadcast(bundle); + } else { + client.broadcast(bundle); + } } @Override public void gameFinished() { - // TODO: clean server/client connection. - super.gameFinished(); + if (getb(GameVariableNames.isGameOver)) { + GameEndBroadcastLogic("Game Over"); + gameOverScreen(""); + } + if (getb(GameVariableNames.isGameWon)) { + GameEndBroadcastLogic("Game Win"); + winScreen(""); + } } private PauseTransition dialogQueue() { @@ -141,18 +190,17 @@ private void selectPort(String port) { Logger.get(getClass()).info("Port : " + serverPort); } - // /** - // * Logique d'envoi des données à chaque frame - // */ - // private void onUpdateBroadcastLogic() { - // if (isServer) { - // Player1Broadcast(); - // } else { - // Player2Broadcast(); - // } // Ne sert à rien pour le moment mais utile si plus de choses à transférer - // à - // // chaque frame - // } + /** + * Logique d'envoi des données à chaque frame + */ + private void onUpdateBroadcastLogic() { + if (isServer) { + Player1Broadcast(); + } else { + Player2Broadcast(); + } // Ne sert à rien pour le moment mais utile si plus de choses à transférer + // chaque frame + } /** * Initialisation du serveur diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index 23124c5..f8a917d 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -17,8 +17,8 @@ public abstract class OnePlayerGameMode implements GameMode { protected Entity player1; protected PlayerComponent playerComponent1; - private long last_ambient_sound = System.currentTimeMillis(); - private int delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, + protected long last_ambient_sound = System.currentTimeMillis(); + protected int delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); @Override From 8eff90ca678fa424fcfc65074e30f17d4393c829 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sun, 12 Mar 2023 21:49:36 +0100 Subject: [PATCH 45/50] fix(serverTCP): :bug: sync players shooting Can now play and the shoots are synced between players --- .../org/enstabretagne/Game/GameLauncher.java | 6 ++++++ .../Game/GameModes/MultiplayerGameMode.java | 16 ++++++++++------ .../enstabretagne/Utils/GameVariableNames.java | 4 ++-- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index b1984b4..e6b2058 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -109,9 +109,15 @@ protected void initInput() { game_mode.getPlayerComponent1().moveRight(); }); onKey(KeyCode.SPACE, () -> { + if (game_mode.getGameModeType().equals(GameModeTypes.MULTIPLAYER)) { + GameVariableNames.isShooting = true; + } game_mode.getPlayerComponent1().shoot(); }); onKey(KeyCode.ENTER, () -> { + if (game_mode.getGameModeType().equals(GameModeTypes.MULTIPLAYER)) { + GameVariableNames.isShooting = true; + } game_mode.getPlayerComponent2().shoot(); }); onKey(KeyCode.LEFT, () -> { diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java index 128584b..d91dc23 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java @@ -51,15 +51,19 @@ public GameModeTypes getGameModeType() { @Override public PlayerComponent getPlayerComponent2() { - if (isServer) { - return playerComponent1; - } else { - return playerComponent2; - } + // Même logique car mode multijoueur + return getPlayerComponent1(); } @Override public PlayerComponent getPlayerComponent1() { + if (!GameVariableNames.multiplayerGameInProgress) { + // Pour éviter d'autoriser le joueur 2 à jouer avant le début de la partie + return new PlayerComponent(); + } + if (GameVariableNames.isShooting) { + onShootBroadcastLogic(); + } if (isServer) { return playerComponent1; } else { @@ -84,7 +88,7 @@ private void onUpdateCommon(double tpf) { if (getb(GameVariableNames.isGameOver) || getb(GameVariableNames.isGameWon)) { gameFinished(); } - + if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { ambientSound(); last_ambient_sound = System.currentTimeMillis(); diff --git a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java index cd1d2b6..9e5aef8 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Utils/GameVariableNames.java @@ -12,9 +12,9 @@ public class GameVariableNames { public static final String isGameOver = "isGameOver"; public static final String isGameWon = "isGameWon"; - // LBF : dans le mode multi ?? - //utile pour la synchro du lancement du multijoueur + // utile pour la synchro du lancement du multijoueur public static boolean multiplayerGameInProgress = false; public static boolean multiplayerGameWaiting = false; + public static boolean isShooting = false; } From fd14e0f1565335124c9509723eb177a0920527cc Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sun, 12 Mar 2023 22:24:09 +0100 Subject: [PATCH 46/50] refactor(serverTCP): :art: made code simpler rearranged all the methods in Multiplayer Game Mode for easier reading. simplified the code for creating bundles and sending them. --- .../Game/GameModes/MultiplayerGameMode.java | 223 +++++++++--------- 1 file changed, 114 insertions(+), 109 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java index d91dc23..ecbda7a 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java @@ -32,10 +32,9 @@ private enum DialogType { private boolean isServer = false; private Server server; - private Client client; - private int serverPort = 55555; + private int serverPort = 55555; private String serverIPaddress = "localhost"; @Override @@ -59,7 +58,7 @@ public PlayerComponent getPlayerComponent2() { public PlayerComponent getPlayerComponent1() { if (!GameVariableNames.multiplayerGameInProgress) { // Pour éviter d'autoriser le joueur 2 à jouer avant le début de la partie - return new PlayerComponent(); + // TODO: à revoir } if (GameVariableNames.isShooting) { onShootBroadcastLogic(); @@ -84,6 +83,18 @@ public void onUpdate(double tpf) { } } + @Override + public void gameFinished() { + if (getb(GameVariableNames.isGameOver)) { + GameEndBroadcastLogic("Game Over"); + gameOverScreen(""); + } + if (getb(GameVariableNames.isGameWon)) { + GameEndBroadcastLogic("Game Win"); + winScreen(""); + } + } + private void onUpdateCommon(double tpf) { if (getb(GameVariableNames.isGameOver) || getb(GameVariableNames.isGameWon)) { gameFinished(); @@ -121,23 +132,12 @@ private void GameEndBroadcastLogic(String message) { } } - @Override - public void gameFinished() { - if (getb(GameVariableNames.isGameOver)) { - GameEndBroadcastLogic("Game Over"); - gameOverScreen(""); - } - if (getb(GameVariableNames.isGameWon)) { - GameEndBroadcastLogic("Game Win"); - winScreen(""); - } - } - private PauseTransition dialogQueue() { Map dialogQueueMessages = new HashMap<>(); dialogQueueMessages.put(DialogType.SERVER_CHOICE, "Voulez-vous être le serveur ?"); dialogQueueMessages.put(DialogType.PORT_CHOICE, "Entrez le port (ex:55555)"); - dialogQueueMessages.put(DialogType.IP_CHOICE, "Entrez l'adresse IP du serveur (format:255.255.255.255)"); + dialogQueueMessages.put(DialogType.IP_CHOICE, + "Entrez l'adresse IP du serveur (format:255.255.255.255 ou localhost)"); PauseTransition pause = new PauseTransition(Duration.seconds(2)); pause.setOnFinished(event -> { showConfirm(dialogQueueMessages.get(DialogType.SERVER_CHOICE), @@ -149,30 +149,6 @@ private PauseTransition dialogQueue() { return pause; } - private void showPortInput(Map dialogQueueMessages) { - getDialogService().showInputBox(dialogQueueMessages.get(DialogType.PORT_CHOICE), (port) -> { - selectPort(port); - if (!isServer) { - getDialogService().showInputBox(dialogQueueMessages.get(DialogType.IP_CHOICE), - (IPaddress) -> { - selectIPaddress(IPaddress); - initializePlayers(); - }); - } else { - initializePlayers(); - } - }); - } - - private void initializePlayers() { - if (isServer) { - initializeServer(); - return; - } - // selectIPaddress(); - initializeClient(); - } - /** * Choix utilisateur pour héberger/rejoindre une partie multijoueur */ @@ -182,6 +158,21 @@ private Boolean areYouTheServer(Boolean yes) { return isServer; } + private void showPortInput(Map dialogQueueMessages) { + getDialogService().showInputBox(dialogQueueMessages.get(DialogType.PORT_CHOICE), (port) -> { + selectPort(port); + if (isServer) { + initializePlayers(); + return; + } + getDialogService().showInputBox(dialogQueueMessages.get(DialogType.IP_CHOICE), + (IPaddress) -> { + selectIPaddress(IPaddress); + initializePlayers(); + }); + }); + } + /** * Choix du port du serveur */ @@ -194,32 +185,6 @@ private void selectPort(String port) { Logger.get(getClass()).info("Port : " + serverPort); } - /** - * Logique d'envoi des données à chaque frame - */ - private void onUpdateBroadcastLogic() { - if (isServer) { - Player1Broadcast(); - } else { - Player2Broadcast(); - } // Ne sert à rien pour le moment mais utile si plus de choses à transférer - // chaque frame - } - - /** - * Initialisation du serveur - */ - private void initializeServer() { - Logger.get(getClass()).info("Server starting..."); - getNotificationService().pushNotification("You are the server on the following address : " + serverIPaddress - + " on port : " + serverPort); - server = getNetService().newTCPServer(serverPort); - onReceiveMessageServer(); - server.startAsync(); - GameVariableNames.multiplayerGameWaiting = true; - Logger.get(getClass()).info("Server started on port : " + serverPort); - } - /** * Input box pour la sélection de l'adresse IP du serveur */ @@ -240,57 +205,32 @@ private void selectIPaddress(String IPaddress) { Logger.get(getClass()).info("IP : " + serverIPaddress); } - /** - * Initialisation du client - */ - private void initializeClient() { - Logger.get(getClass()).info("Client starting..."); - getNotificationService() - .pushNotification("You are connecting to the server on the following address : " + serverIPaddress - + " on port : " + serverPort); - client = getNetService().newTCPClient(serverIPaddress, serverPort); - onReceiveMessageClient(); - client.connectAsync(); - GameVariableNames.multiplayerGameWaiting = true; - Logger.get(getClass()).info("Client connected to server !"); - } - - private void startMultiGame() { - long startGameTime = System.currentTimeMillis(); - System.out.println("startGameTime : " + startGameTime); - AlienFactory.makeAlienBlock(); - } - - /** - * Envoie des données du joueur 1 du serveur vers le client - */ - private void Player1Broadcast() { - Bundle bundle = new Bundle("Player1"); - bundle.put("type", "Player1"); - bundle.put("x", player1.getX()); - bundle.put("y", player1.getY()); - bundle.put("score", playerComponent1.getScore()); - bundle.put("life", playerComponent1.getLife()); - server.broadcast(bundle); + private void initializePlayers() { + if (isServer) { + initializeServer(); + return; + } + initializeClient(); } /** - * Envoie des données du joueur 2 du client vers le serveur + * Initialisation du serveur */ - private void Player2Broadcast() { - Bundle bundle = new Bundle("Player2"); - bundle.put("type", "Player2"); - bundle.put("x", player2.getX()); - bundle.put("y", player2.getY()); - bundle.put("score", playerComponent2.getScore()); - bundle.put("life", playerComponent2.getLife()); - client.broadcast(bundle); + private void initializeServer() { + Logger.get(getClass()).info("Server starting..."); + getNotificationService().pushNotification("You are the server on the following address : " + serverIPaddress + + " on port : " + serverPort); + server = getNetService().newTCPServer(serverPort); + onReceiveMessageServer(); + server.startAsync(); + GameVariableNames.multiplayerGameWaiting = true; + Logger.get(getClass()).info("Server started on port : " + serverPort); } /** * Logique lors de la réception des données du client par le serveur */ - private void onReceiveMessageServer() { + private void onReceiveMessageServer() { // TODO: refactor this server.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { if (message.getName().equals("Player2")) { @@ -320,10 +260,25 @@ private void onReceiveMessageServer() { }); } + /** + * Initialisation du client + */ + private void initializeClient() { + Logger.get(getClass()).info("Client starting..."); + getNotificationService() + .pushNotification("You are connecting to the server on the following address : " + serverIPaddress + + " on port : " + serverPort); + client = getNetService().newTCPClient(serverIPaddress, serverPort); + onReceiveMessageClient(); + client.connectAsync(); + GameVariableNames.multiplayerGameWaiting = true; + Logger.get(getClass()).info("Client connected to server !"); + } + /** * Logique lors de la réception des données du serveur par le client */ - private void onReceiveMessageClient() { + private void onReceiveMessageClient() {// TODO: refactor this client.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { if (message.getName().equals("Player1")) { @@ -358,6 +313,56 @@ private void onReceiveMessageClient() { }); } + /** + * Logique d'envoi des données à chaque frame + */ + private void onUpdateBroadcastLogic() { + if (isServer) { + Bundle bundle = createPlayerInfosBundle(player1, playerComponent1, "Player1", "Player1"); + server.broadcast(bundle); + } else { + Bundle bundle = createPlayerInfosBundle(player2, playerComponent2, "Player2", "Player2"); + client.broadcast(bundle); + } + } + + /** + * Création d'un bundle contenant les données du joueur + * + * Informations transmises : + *
    + *
  • type : type de joueur
  • + *
  • x : position x du joueur
  • + *
  • y : position y du joueur
  • + *
  • score : score du joueur
  • + *
  • life : vie du joueur
  • + *
+ * + * @param player + * @param playerComponent + * @param bundleName + * @param bundleType + * @return bundle contenant les données du joueur + * + * @author LBF38 + */ + private Bundle createPlayerInfosBundle(Entity player, PlayerComponent playerComponent, String bundleName, + String bundleType) { + Bundle bundle = new Bundle(bundleName); + bundle.put("type", bundleType); + bundle.put("x", player.getX()); + bundle.put("y", player.getY()); + bundle.put("score", playerComponent.getScore()); + bundle.put("life", playerComponent.getLife()); + return bundle; + } + + private void startMultiGame() { + long startGameTime = System.currentTimeMillis(); + System.out.println("startGameTime : " + startGameTime); + AlienFactory.makeAlienBlock(); + } + /** * Logique d'envoi des données lors du tir d'un joueur */ From 8683a522708a02d9e6d1b185cdd12e6bab3d521a Mon Sep 17 00:00:00 2001 From: LBF38 Date: Sun, 12 Mar 2023 23:02:30 +0100 Subject: [PATCH 47/50] refactor(serverTCP): :recycle: onUpdate and bundle onUpdate: reused the super implementation to factorise code. bundle: created a BundleKey class for defining the keys of the bundle. This is for improving the reliability of the code when transmitting data. --- .../Game/GameModes/AlienFactory.java | 8 ++- .../Game/GameModes/MultiplayerGameMode.java | 53 +++++++++---------- .../Game/GameModes/OnePlayerGameMode.java | 3 +- 3 files changed, 33 insertions(+), 31 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java index 9439a38..7fc92a5 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/AlienFactory.java @@ -63,12 +63,16 @@ static protected void makeOneAlien(Direction direction) { alien.getComponent(AlienComponent.class).initialize(direction); } - public static void aliensRandomlyShoot() { + public static void aliensRandomlyShoot(double shootingChance) { run(() -> { getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { - if (FXGLMath.randomBoolean(0.01)) + if (FXGLMath.randomBoolean(shootingChance)) alien.getComponent(AlienComponent.class).randomShoot(Settings.ALIEN_SHOOT_CHANCE); }); }, Duration.seconds(Settings.random.nextDouble() * 10)); } + + public static void aliensRandomlyShoot() { + aliensRandomlyShoot(0.005); + } } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java index ecbda7a..e8e82b2 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java @@ -30,6 +30,14 @@ private enum DialogType { SERVER_CHOICE, PORT_CHOICE, IP_CHOICE } + private class BundleKey { + public static final String TYPE = "type"; + public static final String X = "x"; + public static final String Y = "y"; + public static final String SCORE = "score"; + public static final String LIFE = "life"; + } + private boolean isServer = false; private Server server; private Client client; @@ -74,7 +82,8 @@ public PlayerComponent getPlayerComponent1() { public void onUpdate(double tpf) { if (GameVariableNames.multiplayerGameInProgress) { onUpdateBroadcastLogic(); - onUpdateCommon(tpf); + super.onUpdate(tpf); + aliensShootInPlayersDirection(); } else { // Synchronise le début de la partie entre les deux joueurs if (!isServer && GameVariableNames.multiplayerGameWaiting) { @@ -95,27 +104,17 @@ public void gameFinished() { } } - private void onUpdateCommon(double tpf) { - if (getb(GameVariableNames.isGameOver) || getb(GameVariableNames.isGameWon)) { - gameFinished(); - } - - if ((System.currentTimeMillis() - last_ambient_sound) > delay_ambient_sound) { - ambientSound(); - last_ambient_sound = System.currentTimeMillis(); - delay_ambient_sound = FXGLMath.random(Settings.AMBIENT_SOUND_DELAY_MIN, Settings.AMBIENT_SOUND_DELAY_MAX); - } - showPlayersLivesAndScores(getGameWorld(), getGameScene()); - + private void aliensShootInPlayersDirection() { run(() -> { getGameWorld().getEntitiesByType(EntityType.ALIEN).forEach((alien) -> { if (FXGLMath.randomBoolean(0.005)) { + AlienComponent alienComponent = alien.getComponent(AlienComponent.class); if (isServer - && alien.getComponent(AlienComponent.class).getDirection() == Settings.Direction.DOWN) { - alien.getComponent(AlienComponent.class).randomShoot(Settings.ALIEN_SHOOT_CHANCE); + && alienComponent.getDirection() == Settings.Direction.DOWN) { + alienComponent.randomShoot(Settings.ALIEN_SHOOT_CHANCE); } else if (!isServer - && alien.getComponent(AlienComponent.class).getDirection() == Settings.Direction.UP) { - alien.getComponent(AlienComponent.class).randomShoot(Settings.ALIEN_SHOOT_CHANCE); + && alienComponent.getDirection() == Settings.Direction.UP) { + alienComponent.randomShoot(Settings.ALIEN_SHOOT_CHANCE); } } }); @@ -168,6 +167,7 @@ private void showPortInput(Map dialogQueueMessages) { getDialogService().showInputBox(dialogQueueMessages.get(DialogType.IP_CHOICE), (IPaddress) -> { selectIPaddress(IPaddress); + Logger.get(getClass()).info("IP : " + serverIPaddress); initializePlayers(); }); }); @@ -189,12 +189,10 @@ private void selectPort(String port) { * Input box pour la sélection de l'adresse IP du serveur */ private void selectIPaddress(String IPaddress) { - // TODO: improve IP address validation // Regex expression for validating IPv4 - String regex_ipv4 = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; - + final String regex_ipv4 = "^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$"; // Regex expression for validating IPv6 - String regex_ipv6 = "((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"; + final String regex_ipv6 = "^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"; Pattern pattern_ipv4 = Pattern.compile(regex_ipv4); Pattern pattern_ipv6 = Pattern.compile(regex_ipv6); if (!pattern_ipv4.matcher(IPaddress).matches() && !pattern_ipv6.matcher(IPaddress).matches()) { @@ -202,7 +200,6 @@ private void selectIPaddress(String IPaddress) { return; } serverIPaddress = IPaddress; - Logger.get(getClass()).info("IP : " + serverIPaddress); } private void initializePlayers() { @@ -349,17 +346,17 @@ private void onUpdateBroadcastLogic() { private Bundle createPlayerInfosBundle(Entity player, PlayerComponent playerComponent, String bundleName, String bundleType) { Bundle bundle = new Bundle(bundleName); - bundle.put("type", bundleType); - bundle.put("x", player.getX()); - bundle.put("y", player.getY()); - bundle.put("score", playerComponent.getScore()); - bundle.put("life", playerComponent.getLife()); + bundle.put(BundleKey.TYPE, bundleType); + bundle.put(BundleKey.X, player.getX()); + bundle.put(BundleKey.Y, player.getY()); + bundle.put(BundleKey.SCORE, playerComponent.getScore()); + bundle.put(BundleKey.LIFE, playerComponent.getLife()); return bundle; } private void startMultiGame() { long startGameTime = System.currentTimeMillis(); - System.out.println("startGameTime : " + startGameTime); + Logger.get(getClass()).info("startGameTime : " + startGameTime); AlienFactory.makeAlienBlock(); } diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java index f8a917d..5dfeab9 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/OnePlayerGameMode.java @@ -66,7 +66,8 @@ public void onUpdate(double tpf) { showPlayersLivesAndScores(getGameWorld(), getGameScene()); - AlienFactory.aliensRandomlyShoot(); + if (getGameModeType() != GameModeTypes.MULTIPLAYER) + AlienFactory.aliensRandomlyShoot(); } From aba9c9534103ba500e398756553cdceb7be946d5 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Mon, 13 Mar 2023 00:09:49 +0100 Subject: [PATCH 48/50] refactor(serverTCP): :recycle: final touches - created BundleType for better reliability when transmitting bundles. - created waitingForConnection() method to wait for a connection to be established. It shows a dialog box while waiting. Provides the possibility to go back to the main menu. - refactored onReceive...() method to use BundleType for server and client. Also simplified the logic by using a switch statement. More readable. - refactored code for creating a bundle to send player's infos. Cleaned and rearranged code for better readability. --- .../Game/GameModes/MultiplayerGameMode.java | 220 +++++++++++------- 1 file changed, 138 insertions(+), 82 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java index e8e82b2..44551bc 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameModes/MultiplayerGameMode.java @@ -1,7 +1,15 @@ package org.enstabretagne.Game.GameModes; -import static com.almasb.fxgl.dsl.FXGL.*; -import static org.enstabretagne.UI.UI_Factory.*; +import static com.almasb.fxgl.dsl.FXGL.getDialogService; +import static com.almasb.fxgl.dsl.FXGL.getGameController; +import static com.almasb.fxgl.dsl.FXGL.getGameWorld; +import static com.almasb.fxgl.dsl.FXGL.getNetService; +import static com.almasb.fxgl.dsl.FXGL.getNotificationService; +import static com.almasb.fxgl.dsl.FXGL.getb; +import static com.almasb.fxgl.dsl.FXGL.run; +import static com.almasb.fxgl.dsl.FXGL.runOnce; +import static com.almasb.fxgl.dsl.FXGL.showConfirm; +import static org.enstabretagne.UI.UI_Factory.gameOverScreen; import static org.enstabretagne.UI.UI_Factory.winScreen; import java.util.HashMap; @@ -13,7 +21,6 @@ import org.enstabretagne.Utils.EntityType; import org.enstabretagne.Utils.GameVariableNames; import org.enstabretagne.Utils.Settings; -import org.enstabretagne.Utils.entityNames; import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.core.serialization.Bundle; @@ -38,10 +45,20 @@ private class BundleKey { public static final String LIFE = "life"; } + private class BundleType { + public static final String PLAYER1 = "Player1"; + public static final String PLAYER2 = "Player2"; + public static final String PLAYER1_SHOOT = "Player1Shoot"; + public static final String PLAYER2_SHOOT = "Player2Shoot"; + public static final String CLIENT_CONNECTED = "Client Connected"; + public static final String SERVER_START = "Server Start"; + public static final String GAME_OVER = "Game Over"; + public static final String GAME_WIN = "Game Win"; + } + private boolean isServer = false; private Server server; private Client client; - private int serverPort = 55555; private String serverIPaddress = "localhost"; @@ -64,10 +81,6 @@ public PlayerComponent getPlayerComponent2() { @Override public PlayerComponent getPlayerComponent1() { - if (!GameVariableNames.multiplayerGameInProgress) { - // Pour éviter d'autoriser le joueur 2 à jouer avant le début de la partie - // TODO: à revoir - } if (GameVariableNames.isShooting) { onShootBroadcastLogic(); } @@ -87,20 +100,62 @@ public void onUpdate(double tpf) { } else { // Synchronise le début de la partie entre les deux joueurs if (!isServer && GameVariableNames.multiplayerGameWaiting) { - client.broadcast(new Bundle("Client Connected")); + client.broadcast(new Bundle(BundleType.CLIENT_CONNECTED)); } + runOnce(() -> waitingForConnection(), Duration.seconds(3)); } } @Override public void gameFinished() { if (getb(GameVariableNames.isGameOver)) { - GameEndBroadcastLogic("Game Over"); - gameOverScreen(""); + GameEndBroadcastLogic(BundleType.GAME_OVER); + gameOverScreen(playerComponent1.getScore(), playerComponent2.getScore()); } if (getb(GameVariableNames.isGameWon)) { - GameEndBroadcastLogic("Game Win"); - winScreen(""); + GameEndBroadcastLogic(BundleType.GAME_WIN); + winScreen(playerComponent1.getScore(), playerComponent2.getScore()); + } + } + + /** + * Logique d'envoi des données à chaque frame + */ + private void onUpdateBroadcastLogic() { + if (isServer) { + Bundle bundle = createPlayerInfosBundle(player1, playerComponent1, BundleType.PLAYER1, BundleType.PLAYER1); + server.broadcast(bundle); + } else { + Bundle bundle = createPlayerInfosBundle(player2, playerComponent2, BundleType.PLAYER2, BundleType.PLAYER2); + client.broadcast(bundle); + } + } + + /** + * Wait for a connexion to be established + */ + private void waitingForConnection() { + if (isServer) { + if (server.getConnections().size() == 0) { + getDialogService().showConfirmationBox("En attente d'un joueur...\n" + + "Voulez-vous quitter la partie ?", (yes) -> { + if (yes) { + server.stop(); + getGameController().gotoMainMenu(); + } + }); + } + } + if (client == null) + return; + if (client.getConnections().size() == 0) { + getDialogService().showConfirmationBox( + "En attente de la connexion...\n" + "Voulez-vous quitter la partie ?", (yes) -> { + if (yes) { + client.disconnect(); + getGameController().gotoMainMenu(); + } + }); } } @@ -121,13 +176,14 @@ private void aliensShootInPlayersDirection() { }, Duration.seconds(Settings.random.nextDouble() * 10)); } - private void GameEndBroadcastLogic(String message) { - Bundle bundle = new Bundle("Game End"); - bundle.put("type", message); + private void GameEndBroadcastLogic(String bundleType) { + Bundle bundle = new Bundle(bundleType); if (isServer) { server.broadcast(bundle); + server.stop(); } else { client.broadcast(bundle); + client.disconnect(); } } @@ -215,8 +271,8 @@ private void initializePlayers() { */ private void initializeServer() { Logger.get(getClass()).info("Server starting..."); - getNotificationService().pushNotification("You are the server on the following address : " + serverIPaddress - + " on port : " + serverPort); + getNotificationService().pushNotification("Server started at " + serverIPaddress + + ":" + serverPort); server = getNetService().newTCPServer(serverPort); onReceiveMessageServer(); server.startAsync(); @@ -227,102 +283,102 @@ private void initializeServer() { /** * Logique lors de la réception des données du client par le serveur */ - private void onReceiveMessageServer() { // TODO: refactor this + private void onReceiveMessageServer() { server.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { - if (message.getName().equals("Player2")) { - player2.setX(message.get("x")); - player2.setY(message.get("y")); - playerComponent2.setScore(message.get("score")); - playerComponent2.setLife(message.get("life")); - } else if (message.getName().equals("Player2Shoot")) { - playerComponent2.shoot(); - } else if (message.getName().equals("Client Connected")) { - if (!GameVariableNames.multiplayerGameInProgress) { - server.broadcast(new Bundle("Server Start")); - GameVariableNames.multiplayerGameInProgress = true; - startMultiGame(); - } - } else if (message.getName().equals("Game End")) { - System.out.println("Game End Received"); - if (message.get("type").equals("Game Over")) { + switch (message.getName()) { + case BundleType.PLAYER2: + updatePlayersInfos(player2, playerComponent2, message); + break; + case BundleType.PLAYER2_SHOOT: + playerComponent2.shoot(); + break; + case BundleType.CLIENT_CONNECTED: + if (!GameVariableNames.multiplayerGameInProgress) { + server.broadcast(new Bundle(BundleType.SERVER_START)); + GameVariableNames.multiplayerGameInProgress = true; + startMultiGame(); + } + break; + case BundleType.GAME_OVER: gameOverScreen(playerComponent1.getScore(), playerComponent2.getScore()); - } else if (message.get("type").equals("Game Win")) { + server.stop(); + break; + case BundleType.GAME_WIN: winScreen(playerComponent1.getScore(), playerComponent2.getScore()); - } - } else { - System.out.println("Message non reconnu"); + server.stop(); + break; + default: + Logger.get(getClass()).info("Server received unknown message: " + message); + break; } }); }); } + /** + * Update the players infos from the bundle received (client or server) + * + * @param player + * @param playerComponent + * @param bundle + */ + private void updatePlayersInfos(Entity player, PlayerComponent playerComponent, Bundle bundle) { + player.setX(bundle.get(BundleKey.X)); + player.setY(bundle.get(BundleKey.Y)); + playerComponent.setScore(bundle.get(BundleKey.SCORE)); + playerComponent.setLife(bundle.get(BundleKey.LIFE)); + } + /** * Initialisation du client */ private void initializeClient() { Logger.get(getClass()).info("Client starting..."); getNotificationService() - .pushNotification("You are connecting to the server on the following address : " + serverIPaddress - + " on port : " + serverPort); + .pushNotification("Connecting to the following server : " + serverIPaddress + + ":" + serverPort); client = getNetService().newTCPClient(serverIPaddress, serverPort); onReceiveMessageClient(); client.connectAsync(); GameVariableNames.multiplayerGameWaiting = true; Logger.get(getClass()).info("Client connected to server !"); + getNotificationService().pushNotification("Connected to the server !"); } /** * Logique lors de la réception des données du serveur par le client */ - private void onReceiveMessageClient() {// TODO: refactor this + private void onReceiveMessageClient() { client.setOnConnected(connection -> { connection.addMessageHandlerFX((conn, message) -> { - if (message.getName().equals("Player1")) { - player1.setX(message.get("x")); - player1.setY(message.get("y")); - playerComponent1.setScore(message.get("score")); - playerComponent1.setLife(message.get("life")); - } else if (message.getName().equals("Player1Shoot")) { - playerComponent1.shoot(); - } else if (message.getName().equals("AlienSpawn")) { - if (message.get("direction") == Settings.Direction.DOWN) { - Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Settings.Direction.DOWN); - } else { - Entity alien = spawn(entityNames.ALIEN, 0, Settings.GAME_HEIGHT / 2 - Settings.ALIEN_HEIGHT); - alien.getComponent(AlienComponent.class).initialize(Settings.Direction.UP); - } - } else if (message.getName().equals("Server Start")) { - GameVariableNames.multiplayerGameInProgress = true; - startMultiGame(); - } else if (message.getName().equals("Game End")) { - System.out.println("Game End Received"); - if (message.get("type").equals("Game Over")) { + switch (message.getName()) { + case BundleType.PLAYER1: + updatePlayersInfos(player1, playerComponent1, message); + break; + case BundleType.PLAYER1_SHOOT: + playerComponent1.shoot(); + break; + case BundleType.SERVER_START: + GameVariableNames.multiplayerGameInProgress = true; + startMultiGame(); + break; + case BundleType.GAME_OVER: gameOverScreen(playerComponent1.getScore(), playerComponent2.getScore()); - } else if (message.get("type").equals("Game Win")) { + client.disconnect(); + break; + case BundleType.GAME_WIN: winScreen(playerComponent1.getScore(), playerComponent2.getScore()); - } - } else { - System.out.println("Message non reconnu"); + client.disconnect(); + break; + default: + Logger.get(getClass()).info("Client received unknown message: " + message); + break; } }); }); } - /** - * Logique d'envoi des données à chaque frame - */ - private void onUpdateBroadcastLogic() { - if (isServer) { - Bundle bundle = createPlayerInfosBundle(player1, playerComponent1, "Player1", "Player1"); - server.broadcast(bundle); - } else { - Bundle bundle = createPlayerInfosBundle(player2, playerComponent2, "Player2", "Player2"); - client.broadcast(bundle); - } - } - /** * Création d'un bundle contenant les données du joueur * @@ -365,9 +421,9 @@ private void startMultiGame() { */ private void onShootBroadcastLogic() { if (isServer) { - server.broadcast(new Bundle("Player1Shoot")); + server.broadcast(new Bundle(BundleType.PLAYER1_SHOOT)); } else { - client.broadcast(new Bundle("Player2Shoot")); + client.broadcast(new Bundle(BundleType.PLAYER2_SHOOT)); } } From a4f60d92ec5a7bbd0927bac12e1ab60aa8a6ea8b Mon Sep 17 00:00:00 2001 From: LBF38 Date: Mon, 13 Mar 2023 00:29:36 +0100 Subject: [PATCH 49/50] chore(release): :bookmark: bump version to v1.0.0 :rocket: making the next big release of the project ! :rocket: --- duelinvaders/pom.xml | 2 +- .../src/main/java/org/enstabretagne/Game/GameLauncher.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/duelinvaders/pom.xml b/duelinvaders/pom.xml index ed04f7e..7ce5968 100644 --- a/duelinvaders/pom.xml +++ b/duelinvaders/pom.xml @@ -5,7 +5,7 @@ org.enstabretagne duelinvaders - 0.3.1 + 1.0.0 UTF-8 diff --git a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java index aab4fca..2684245 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Game/GameLauncher.java @@ -66,7 +66,7 @@ protected void initSettings(GameSettings settings) { settings.setHeight(Settings.GAME_HEIGHT.intValue()); settings.setTitle("Duel Invaders"); settings.setAppIcon(assetNames.textures.APP_ICON); - settings.setVersion("0.3.1"); + settings.setVersion("1.0.0"); settings.setMainMenuEnabled(true); settings.setGameMenuEnabled(true); settings.setFullScreenAllowed(true); From 2e5f4491bc2a3dfe4a4fed91f5d8fdf0dd7e5db6 Mon Sep 17 00:00:00 2001 From: LBF38 Date: Mon, 13 Mar 2023 00:42:05 +0100 Subject: [PATCH 50/50] fix(javadoc): :green_heart: PlayerComponent javadoc --- .../java/org/enstabretagne/Component/PlayerComponent.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java b/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java index 2809275..88c7bfb 100644 --- a/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java +++ b/duelinvaders/src/main/java/org/enstabretagne/Component/PlayerComponent.java @@ -173,7 +173,8 @@ public int getScore() { } /** - * @param score + * + * @param newScore */ public void setScore(int newScore) { score = Math.max(0, newScore); @@ -198,7 +199,8 @@ public int getLife() { } /** - * @param life + * + * @param newLife */ public void setLife(int newLife) { life = Math.max(0, newLife);