Multi Scene in back end
authorgparant <g.parant@thecodingmachine.com>
Sat, 9 May 2020 17:41:21 +0000 (19:41 +0200)
committergparant <g.parant@thecodingmachine.com>
Sat, 9 May 2020 17:41:21 +0000 (19:41 +0200)
 - Change maps url to get maps
 - Change GameScene to create scene with file since back end
 - Change LoginScene to upload scene and start game

back/src/App.ts
back/src/Controller/AuthenticateController.ts
back/src/Controller/MapController.ts
front/src/Connexion.ts
front/src/Phaser/Game/GameManager.ts
front/src/Phaser/Game/GameScene.ts
front/src/Phaser/Login/LogincScene.ts
front/src/index.ts

index 9af57ac386ddd798155889f0f5745766b4e843e1..27006d8c3950d8d967fb1d352b9faf102684b74d 100644 (file)
@@ -13,7 +13,7 @@ class App {
     public server: http.Server;
     public ioSocketController: IoSocketController;
     public authenticateController: AuthenticateController;
-    public AuthenticateMiddleware: AuthenticateMiddleware;
+    //public AuthenticateMiddleware: AuthenticateMiddleware;
     public mapController: MapController;
 
     constructor() {
@@ -26,7 +26,7 @@ class App {
         //create socket controllers
         this.ioSocketController = new IoSocketController(this.server);
         this.authenticateController = new AuthenticateController(this.app);
-        this.AuthenticateMiddleware = new AuthenticateMiddleware(this.app);
+        //this.AuthenticateMiddleware = new AuthenticateMiddleware(this.app);
         this.mapController = new MapController(this.app);
     }
 
index f9eed470391dd87b2732baf0f5ccdab17920d5c9..0b27290b34bf09abdac9272024aed6a0ceea3f19 100644 (file)
@@ -27,7 +27,11 @@ export class AuthenticateController{
             return res.status(OK).send({
                 token: token,
                 roomId: ROOM,
-                userId: userId
+                userId: userId,
+                maps: [
+                    "floor0",
+                    "floor1"
+                ]
             });
         });
     }
index b51c36b3ca7ee23a8f49f15aaa49bf3fd8c41657..b9d30c61a354e3dffa922af5d87a9477c4fc642b 100644 (file)
@@ -3,33 +3,29 @@ import path from "path";
 import {Application, Request, Response} from "express";
 import {OK} from "http-status-codes";
 
-const MapFloor0 = require('../Assets/Maps/Floor0/floor0.json');
-const MapFloor1 = require('../Assets/Maps/Floor1/floor1.json');
+export class MapController {
+    App: Application;
 
-export class MapController{
-    App : Application;
-
-    constructor(App : Application) {
+    constructor(App: Application) {
         this.App = App;
-        this.getFloor0();
-        this.getFloor1();
+        this.getMpas();
         this.assetMaps();
     }
 
-    assetMaps(){
-        this.App.use('/maps', express.static('src/Assets/Maps'));
+    assetMaps() {
+        this.App.use('/map/files', express.static('src/Assets/Maps'));
     }
 
     //permit to login on application. Return token to connect on Websocket IO.
-    getFloor0(){
-        this.App.get("/floor0", (req: Request, res: Response) => {
-            return res.status(OK).send(MapFloor0);
-        });
-    }
-
-    getFloor1(){
-        this.App.get("/floor1", (req: Request, res: Response) => {
-            return res.status(OK).send(MapFloor1);
+    getMpas() {
+        this.App.get("/maps", (req: Request, res: Response) => {
+            return res.status(OK).send({
+                startMapKey: "floor0",
+                maps: [
+                    {mapKey: "floor0", mapUrl: "/map/files/Floor0"},
+                    {mapKey: "floor1", mapUrl: "/map/files/Floor1"},
+                ]
+            });
         });
     }
 }
\ No newline at end of file
index 0d0f13e4ec20d58e979f4eb0cd47df1b657e3635..2c695bd702327f95b1f5f769b762789dce344007 100644 (file)
@@ -143,6 +143,8 @@ export interface ConnexionInterface {
 
     createConnexion(characterSelected: string): Promise<any>;
 
+    loadMaps(): Promise<any>;
+
     joinARoom(roomId: string, character: string): void;
 
     sharePosition(x: number, y: number, direction: string, character: string): void;
@@ -173,6 +175,9 @@ export class Connexion implements ConnexionInterface {
         this.GameManager = GameManager;
     }
 
+    /**
+     * @param characterSelected
+     */
     createConnexion(characterSelected: string): Promise<ConnexionInterface> {
         return Axios.post(`${API_URL}/login`, {email: this.email})
             .then((res) => {
@@ -199,13 +204,22 @@ export class Connexion implements ConnexionInterface {
                 this.groupUpdatedOrCreated();
                 this.groupDeleted();
 
-                return this;
+                return res.data;
             })
             .catch((err) => {
                 console.error(err);
                 throw err;
             });
     }
+    
+    loadMaps() : Promise<any>{
+        return Axios.get(`${API_URL}/maps`).then((res) => {
+            return res.data;
+        }).catch((err) => {
+            console.error(err);
+            throw err;
+        });
+    }
 
     /**
      *
index 39afa8b7e24f61e6086b4e056c79aab1454e7a12..c590c2c8934ec7f41c02c4c918a55f9c205c916e 100644 (file)
@@ -1,13 +1,10 @@
-import {GameScene} from "./GameScene";
-import {ROOM} from "../../Enum/EnvironmentVariable"
+import {GameScene, GameSceneInterface} from "./GameScene";
 import {
     Connexion,
-    ConnexionInterface,
     GroupCreatedUpdatedMessageInterface,
     ListMessageUserPositionInterface
 } from "../../Connexion";
 import {SimplePeerInterface, SimplePeer} from "../../WebRtc/SimplePeer";
-import {LogincScene} from "../Login/LogincScene";
 
 export enum StatusGameManagerEnum {
     IN_PROGRESS = 1,
@@ -24,7 +21,7 @@ export interface HasMovedEvent {
 export class GameManager {
     status: number;
     private ConnexionInstance: Connexion;
-    private currentGameScene: GameScene;
+    private currentGameScene: GameSceneInterface;
     private playerName: string;
     SimplePeer : SimplePeerInterface;
     private characterUserSelected: string;
@@ -37,12 +34,23 @@ export class GameManager {
         this.playerName = name;
         this.characterUserSelected = characterUserSelected;
         this.ConnexionInstance = new Connexion(name, this);
-        return this.ConnexionInstance.createConnexion(characterUserSelected).then(() => {
+        return this.ConnexionInstance.createConnexion(characterUserSelected).then((data : any) => {
             this.SimplePeer = new SimplePeer(this.ConnexionInstance);
+            return data;
+        }).catch((err) => {
+          throw err;
         });
     }
 
-    setCurrentGameScene(gameScene: GameScene) {
+    loadMaps(){
+        return this.ConnexionInstance.loadMaps().then((maps) => {
+            return maps;
+        }).catch((err) => {
+            throw err;
+        });
+    }
+
+    setCurrentGameScene(gameScene: GameSceneInterface) {
         this.currentGameScene = gameScene;
     }
 
index 26ce32c2965902e0b2d1ce95d5cc09a15303a727..68ef1f32f361e080605bce71ba6d0e11f9fe7c45 100644 (file)
@@ -11,16 +11,12 @@ import Graphics = Phaser.GameObjects.Graphics;
 import Texture = Phaser.Textures.Texture;
 import Sprite = Phaser.GameObjects.Sprite;
 import CanvasTexture = Phaser.Textures.CanvasTexture;
-import {Floor1Name} from "./GameSceneFloor1";
+import CreateSceneFromObjectConfig = Phaser.Types.Scenes.CreateSceneFromObjectConfig;
 
 export enum Textures {
-    Player = "male1",
-    Map = 'floor0',
-    MapUrl = 'maps/floor0.json'
+    Player = "male1"
 }
 
-export const Floor0Name = "Floor0";
-
 export interface GameSceneInterface extends Phaser.Scene {
     Map: Phaser.Tilemaps.Tilemap;
     createCurrentPlayer(UserId : string) : void;
@@ -29,7 +25,7 @@ export interface GameSceneInterface extends Phaser.Scene {
     updateOrCreateMapPlayer(UsersPosition : Array<MessageUserPositionInterface>): void;
     deleteGroup(groupId: string): void;
 }
-export class GameScene extends Phaser.Scene implements GameSceneInterface{
+export class GameScene extends Phaser.Scene implements GameSceneInterface, CreateSceneFromObjectConfig{
     GameManager : GameManager;
     Terrains : Array<Phaser.Tilemaps.Tileset>;
     CurrentPlayer: CurrentGamerInterface;
@@ -38,24 +34,31 @@ export class GameScene extends Phaser.Scene implements GameSceneInterface{
     Layers : Array<Phaser.Tilemaps.StaticTilemapLayer>;
     Objects : Array<Phaser.Physics.Arcade.Sprite>;
     map: ITiledMap;
-    groups: Map<string, Sprite>
+    groups: Map<string, Sprite>;
     startX = 704;// 22 case
     startY = 32; // 1 case
     circleTexture: CanvasTexture;
 
-    constructor() {
+    MapKey: string;
+    MapUrlFile: string;
+
+    constructor(MapKey : string = "", MapUrlFile: string = "") {
         super({
-            key: Floor0Name
+            key: MapKey
         });
+
         this.GameManager = gameManager;
         this.Terrains = [];
         this.groups = new Map<string, Sprite>();
+
+        this.MapKey =  MapKey;
+        this.MapUrlFile = MapUrlFile;
     }
 
     //hook preload scene
     preload(): void {
         this.GameManager.setCurrentGameScene(this);
-        this.load.on('filecomplete-tilemapJSON-'+Textures.Map, (key: string, type: string, data: any) => {
+        this.load.on('filecomplete-tilemapJSON-'+this.MapKey, (key: string, type: string, data: any) => {
             // Triggered when the map is loaded
             // Load tiles attached to the map recursively
             this.map = data.data;
@@ -64,11 +67,13 @@ export class GameScene extends Phaser.Scene implements GameSceneInterface{
                     console.warn("Don't know how to handle tileset ", tileset)
                     return;
                 }
-                let path = Textures.MapUrl.substr(0, Textures.MapUrl.lastIndexOf('/'));
-                this.load.image(tileset.name, path + '/' + tileset.image);
+                console.log(tileset);
+                console.log(tileset.name, `${this.MapUrlFile}/${tileset.image}`);
+                this.load.image(tileset.name, `${this.MapUrlFile}/${tileset.image}`);
             })
         });
-        this.load.tilemapTiledJSON(Textures.Map, Textures.MapUrl);
+        console.log(this.MapKey, `${this.MapUrlFile}/${this.MapKey}.json`);
+        this.load.tilemapTiledJSON(this.MapKey, `${this.MapUrlFile}/${this.MapKey}.json`);
 
         //add player png
         PLAYER_RESOURCES.forEach((playerResource: any) => {
@@ -88,7 +93,7 @@ export class GameScene extends Phaser.Scene implements GameSceneInterface{
     //hook create scene
     create(): void {
         //initalise map
-        this.Map = this.add.tilemap(Textures.Map);
+        this.Map = this.add.tilemap(this.MapKey);
         this.map.tilesets.forEach((tileset: ITiledTileSet) => {
             this.Terrains.push(this.Map.addTilesetImage(tileset.name, tileset.name));
         });
@@ -132,6 +137,9 @@ export class GameScene extends Phaser.Scene implements GameSceneInterface{
         // Let's generate the circle for the group delimiter
 
         this.circleTexture = this.textures.createCanvas('circleSprite', 96, 96);
+        if(!this.circleTexture || this.circleTexture.context){
+            return;
+        }
         let context = this.circleTexture.context;
         context.beginPath();
         context.arc(48, 48, 48, 0, 2 * Math.PI, false);
@@ -224,6 +232,12 @@ export class GameScene extends Phaser.Scene implements GameSceneInterface{
      */
     update(time: number, delta: number) : void {
         this.CurrentPlayer.moveUser(delta);
+        if(
+           832 <= this.CurrentPlayer.x && this.CurrentPlayer.x <= 864
+            && 0 <= this.CurrentPlayer.y && this.CurrentPlayer.y <= 64
+        ){
+            //this.scene.start(Floor1Name);
+        }
     }
 
     /**
index c3aaa056ca4b386821c25e8c62f365c943031b75..f35ffc23fbbf2cc6ab8387371bdeb6e55db11857 100644 (file)
@@ -2,14 +2,13 @@ import {gameManager} from "../Game/GameManager";
 import {TextField} from "../Components/TextField";
 import {TextInput} from "../Components/TextInput";
 import {ClickButton} from "../Components/ClickButton";
-import {GameSceneInterface, Floor0Name, Textures} from "../Game/GameScene";
+import {GameScene, GameSceneInterface} from "../Game/GameScene";
 import Image = Phaser.GameObjects.Image;
-import {Player} from "../Player/Player";
-import {getPlayerAnimations, PlayerAnimationNames} from "../Player/Animation";
 import Rectangle = Phaser.GameObjects.Rectangle;
 import {PLAYER_RESOURCES} from "../Entity/PlayableCaracter";
 import {cypressAsserter} from "../../Cypress/CypressAsserter";
 import {GroupCreatedUpdatedMessageInterface, MessageUserPositionInterface} from "../../Connexion";
+import {API_URL} from "../../Enum/EnvironmentVariable";
 
 //todo: put this constants in a dedicated file
 export const LoginSceneName = "LoginScene";
@@ -94,15 +93,29 @@ export class LogincScene extends Phaser.Scene implements GameSceneInterface {
     }
 
     private async login(name: string) {
-        gameManager.connect(name, this.selectedPlayer.texture.key).then(() => {
-            this.scene.start(Floor0Name);
+        Promise.all([
+            gameManager.connect(name, this.selectedPlayer.texture.key),
+            gameManager.loadMaps()
+        ]).then((data) => {
+            if (!data) {
+                return;
+            }
+            let scene: any = data[1];
+            scene.maps.forEach((map : any) => {
+                let game = new GameScene(map.mapKey, `${API_URL}${map.mapUrl}`);
+                this.scene.add(map.mapKey, game, false);
+            });
+            this.scene.start(scene.startMapKey);
+        }).catch((err) => {
+            console.error(err);
+            throw err;
         });
     }
 
     Map: Phaser.Tilemaps.Tilemap;
 
     initAnimation(): void {
-
+        throw new Error("Method not implemented.");
     }
 
     createCurrentPlayer(UserId: string): void {
index d4f048c6baf56c1cb91031a6e32f6144e031f1b4..2116568188913200bf54e334f474a352cef481d3 100644 (file)
@@ -3,14 +3,13 @@ import GameConfig = Phaser.Types.Core.GameConfig;
 import {DEBUG_MODE, RESOLUTION} from "./Enum/EnvironmentVariable";
 import {cypressAsserter} from "./Cypress/CypressAsserter";
 import {LogincScene} from "./Phaser/Login/LogincScene";
-import {GameScene} from "./Phaser/Game/GameScene";
 
 const config: GameConfig = {
     title: "Office game",
     width: window.innerWidth / RESOLUTION,
     height: window.innerHeight / RESOLUTION,
     parent: "game",
-    scene: [LogincScene, GameScene],
+    scene: [LogincScene],
     zoom: RESOLUTION,
     physics: {
         default: "arcade",