Multi Scene in back end

- Change maps url to get maps
 - Change GameScene to create scene with file since back end
 - Change LoginScene to upload scene and start game
This commit is contained in:
gparant 2020-05-09 19:41:21 +02:00
parent 7f989cfd23
commit fb8d9bf9a8
8 changed files with 101 additions and 53 deletions

View File

@ -13,7 +13,7 @@ class App {
public server: http.Server; public server: http.Server;
public ioSocketController: IoSocketController; public ioSocketController: IoSocketController;
public authenticateController: AuthenticateController; public authenticateController: AuthenticateController;
public AuthenticateMiddleware: AuthenticateMiddleware; //public AuthenticateMiddleware: AuthenticateMiddleware;
public mapController: MapController; public mapController: MapController;
constructor() { constructor() {
@ -26,7 +26,7 @@ class App {
//create socket controllers //create socket controllers
this.ioSocketController = new IoSocketController(this.server); this.ioSocketController = new IoSocketController(this.server);
this.authenticateController = new AuthenticateController(this.app); this.authenticateController = new AuthenticateController(this.app);
this.AuthenticateMiddleware = new AuthenticateMiddleware(this.app); //this.AuthenticateMiddleware = new AuthenticateMiddleware(this.app);
this.mapController = new MapController(this.app); this.mapController = new MapController(this.app);
} }

View File

@ -27,7 +27,11 @@ export class AuthenticateController{
return res.status(OK).send({ return res.status(OK).send({
token: token, token: token,
roomId: ROOM, roomId: ROOM,
userId: userId userId: userId,
maps: [
"floor0",
"floor1"
]
}); });
}); });
} }

View File

@ -3,33 +3,29 @@ import path from "path";
import {Application, Request, Response} from "express"; import {Application, Request, Response} from "express";
import {OK} from "http-status-codes"; import {OK} from "http-status-codes";
const MapFloor0 = require('../Assets/Maps/Floor0/floor0.json'); export class MapController {
const MapFloor1 = require('../Assets/Maps/Floor1/floor1.json'); App: Application;
export class MapController{ constructor(App: Application) {
App : Application;
constructor(App : Application) {
this.App = App; this.App = App;
this.getFloor0(); this.getMpas();
this.getFloor1();
this.assetMaps(); this.assetMaps();
} }
assetMaps(){ assetMaps() {
this.App.use('/maps', express.static('src/Assets/Maps')); this.App.use('/map/files', express.static('src/Assets/Maps'));
} }
//permit to login on application. Return token to connect on Websocket IO. //permit to login on application. Return token to connect on Websocket IO.
getFloor0(){ getMpas() {
this.App.get("/floor0", (req: Request, res: Response) => { this.App.get("/maps", (req: Request, res: Response) => {
return res.status(OK).send(MapFloor0); return res.status(OK).send({
}); startMapKey: "floor0",
} maps: [
{mapKey: "floor0", mapUrl: "/map/files/Floor0"},
getFloor1(){ {mapKey: "floor1", mapUrl: "/map/files/Floor1"},
this.App.get("/floor1", (req: Request, res: Response) => { ]
return res.status(OK).send(MapFloor1); });
}); });
} }
} }

View File

@ -143,6 +143,8 @@ export interface ConnexionInterface {
createConnexion(characterSelected: string): Promise<any>; createConnexion(characterSelected: string): Promise<any>;
loadMaps(): Promise<any>;
joinARoom(roomId: string, character: string): void; joinARoom(roomId: string, character: string): void;
sharePosition(x: number, y: number, direction: 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; this.GameManager = GameManager;
} }
/**
* @param characterSelected
*/
createConnexion(characterSelected: string): Promise<ConnexionInterface> { createConnexion(characterSelected: string): Promise<ConnexionInterface> {
return Axios.post(`${API_URL}/login`, {email: this.email}) return Axios.post(`${API_URL}/login`, {email: this.email})
.then((res) => { .then((res) => {
@ -199,13 +204,22 @@ export class Connexion implements ConnexionInterface {
this.groupUpdatedOrCreated(); this.groupUpdatedOrCreated();
this.groupDeleted(); this.groupDeleted();
return this; return res.data;
}) })
.catch((err) => { .catch((err) => {
console.error(err); console.error(err);
throw err; throw err;
}); });
} }
loadMaps() : Promise<any>{
return Axios.get(`${API_URL}/maps`).then((res) => {
return res.data;
}).catch((err) => {
console.error(err);
throw err;
});
}
/** /**
* *

View File

@ -1,13 +1,10 @@
import {GameScene} from "./GameScene"; import {GameScene, GameSceneInterface} from "./GameScene";
import {ROOM} from "../../Enum/EnvironmentVariable"
import { import {
Connexion, Connexion,
ConnexionInterface,
GroupCreatedUpdatedMessageInterface, GroupCreatedUpdatedMessageInterface,
ListMessageUserPositionInterface ListMessageUserPositionInterface
} from "../../Connexion"; } from "../../Connexion";
import {SimplePeerInterface, SimplePeer} from "../../WebRtc/SimplePeer"; import {SimplePeerInterface, SimplePeer} from "../../WebRtc/SimplePeer";
import {LogincScene} from "../Login/LogincScene";
export enum StatusGameManagerEnum { export enum StatusGameManagerEnum {
IN_PROGRESS = 1, IN_PROGRESS = 1,
@ -24,7 +21,7 @@ export interface HasMovedEvent {
export class GameManager { export class GameManager {
status: number; status: number;
private ConnexionInstance: Connexion; private ConnexionInstance: Connexion;
private currentGameScene: GameScene; private currentGameScene: GameSceneInterface;
private playerName: string; private playerName: string;
SimplePeer : SimplePeerInterface; SimplePeer : SimplePeerInterface;
private characterUserSelected: string; private characterUserSelected: string;
@ -37,12 +34,23 @@ export class GameManager {
this.playerName = name; this.playerName = name;
this.characterUserSelected = characterUserSelected; this.characterUserSelected = characterUserSelected;
this.ConnexionInstance = new Connexion(name, this); 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); 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; this.currentGameScene = gameScene;
} }

View File

@ -11,16 +11,12 @@ import Graphics = Phaser.GameObjects.Graphics;
import Texture = Phaser.Textures.Texture; import Texture = Phaser.Textures.Texture;
import Sprite = Phaser.GameObjects.Sprite; import Sprite = Phaser.GameObjects.Sprite;
import CanvasTexture = Phaser.Textures.CanvasTexture; import CanvasTexture = Phaser.Textures.CanvasTexture;
import {Floor1Name} from "./GameSceneFloor1"; import CreateSceneFromObjectConfig = Phaser.Types.Scenes.CreateSceneFromObjectConfig;
export enum Textures { export enum Textures {
Player = "male1", Player = "male1"
Map = 'floor0',
MapUrl = 'maps/floor0.json'
} }
export const Floor0Name = "Floor0";
export interface GameSceneInterface extends Phaser.Scene { export interface GameSceneInterface extends Phaser.Scene {
Map: Phaser.Tilemaps.Tilemap; Map: Phaser.Tilemaps.Tilemap;
createCurrentPlayer(UserId : string) : void; createCurrentPlayer(UserId : string) : void;
@ -29,7 +25,7 @@ export interface GameSceneInterface extends Phaser.Scene {
updateOrCreateMapPlayer(UsersPosition : Array<MessageUserPositionInterface>): void; updateOrCreateMapPlayer(UsersPosition : Array<MessageUserPositionInterface>): void;
deleteGroup(groupId: string): void; deleteGroup(groupId: string): void;
} }
export class GameScene extends Phaser.Scene implements GameSceneInterface{ export class GameScene extends Phaser.Scene implements GameSceneInterface, CreateSceneFromObjectConfig{
GameManager : GameManager; GameManager : GameManager;
Terrains : Array<Phaser.Tilemaps.Tileset>; Terrains : Array<Phaser.Tilemaps.Tileset>;
CurrentPlayer: CurrentGamerInterface; CurrentPlayer: CurrentGamerInterface;
@ -38,24 +34,31 @@ export class GameScene extends Phaser.Scene implements GameSceneInterface{
Layers : Array<Phaser.Tilemaps.StaticTilemapLayer>; Layers : Array<Phaser.Tilemaps.StaticTilemapLayer>;
Objects : Array<Phaser.Physics.Arcade.Sprite>; Objects : Array<Phaser.Physics.Arcade.Sprite>;
map: ITiledMap; map: ITiledMap;
groups: Map<string, Sprite> groups: Map<string, Sprite>;
startX = 704;// 22 case startX = 704;// 22 case
startY = 32; // 1 case startY = 32; // 1 case
circleTexture: CanvasTexture; circleTexture: CanvasTexture;
constructor() { MapKey: string;
MapUrlFile: string;
constructor(MapKey : string = "", MapUrlFile: string = "") {
super({ super({
key: Floor0Name key: MapKey
}); });
this.GameManager = gameManager; this.GameManager = gameManager;
this.Terrains = []; this.Terrains = [];
this.groups = new Map<string, Sprite>(); this.groups = new Map<string, Sprite>();
this.MapKey = MapKey;
this.MapUrlFile = MapUrlFile;
} }
//hook preload scene //hook preload scene
preload(): void { preload(): void {
this.GameManager.setCurrentGameScene(this); 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 // Triggered when the map is loaded
// Load tiles attached to the map recursively // Load tiles attached to the map recursively
this.map = data.data; 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) console.warn("Don't know how to handle tileset ", tileset)
return; return;
} }
let path = Textures.MapUrl.substr(0, Textures.MapUrl.lastIndexOf('/')); console.log(tileset);
this.load.image(tileset.name, path + '/' + tileset.image); 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 //add player png
PLAYER_RESOURCES.forEach((playerResource: any) => { PLAYER_RESOURCES.forEach((playerResource: any) => {
@ -88,7 +93,7 @@ export class GameScene extends Phaser.Scene implements GameSceneInterface{
//hook create scene //hook create scene
create(): void { create(): void {
//initalise map //initalise map
this.Map = this.add.tilemap(Textures.Map); this.Map = this.add.tilemap(this.MapKey);
this.map.tilesets.forEach((tileset: ITiledTileSet) => { this.map.tilesets.forEach((tileset: ITiledTileSet) => {
this.Terrains.push(this.Map.addTilesetImage(tileset.name, tileset.name)); 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 // Let's generate the circle for the group delimiter
this.circleTexture = this.textures.createCanvas('circleSprite', 96, 96); this.circleTexture = this.textures.createCanvas('circleSprite', 96, 96);
if(!this.circleTexture || this.circleTexture.context){
return;
}
let context = this.circleTexture.context; let context = this.circleTexture.context;
context.beginPath(); context.beginPath();
context.arc(48, 48, 48, 0, 2 * Math.PI, false); 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 { update(time: number, delta: number) : void {
this.CurrentPlayer.moveUser(delta); 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);
}
} }
/** /**

View File

@ -2,14 +2,13 @@ import {gameManager} from "../Game/GameManager";
import {TextField} from "../Components/TextField"; import {TextField} from "../Components/TextField";
import {TextInput} from "../Components/TextInput"; import {TextInput} from "../Components/TextInput";
import {ClickButton} from "../Components/ClickButton"; import {ClickButton} from "../Components/ClickButton";
import {GameSceneInterface, Floor0Name, Textures} from "../Game/GameScene"; import {GameScene, GameSceneInterface} from "../Game/GameScene";
import Image = Phaser.GameObjects.Image; import Image = Phaser.GameObjects.Image;
import {Player} from "../Player/Player";
import {getPlayerAnimations, PlayerAnimationNames} from "../Player/Animation";
import Rectangle = Phaser.GameObjects.Rectangle; import Rectangle = Phaser.GameObjects.Rectangle;
import {PLAYER_RESOURCES} from "../Entity/PlayableCaracter"; import {PLAYER_RESOURCES} from "../Entity/PlayableCaracter";
import {cypressAsserter} from "../../Cypress/CypressAsserter"; import {cypressAsserter} from "../../Cypress/CypressAsserter";
import {GroupCreatedUpdatedMessageInterface, MessageUserPositionInterface} from "../../Connexion"; import {GroupCreatedUpdatedMessageInterface, MessageUserPositionInterface} from "../../Connexion";
import {API_URL} from "../../Enum/EnvironmentVariable";
//todo: put this constants in a dedicated file //todo: put this constants in a dedicated file
export const LoginSceneName = "LoginScene"; export const LoginSceneName = "LoginScene";
@ -94,15 +93,29 @@ export class LogincScene extends Phaser.Scene implements GameSceneInterface {
} }
private async login(name: string) { private async login(name: string) {
gameManager.connect(name, this.selectedPlayer.texture.key).then(() => { Promise.all([
this.scene.start(Floor0Name); 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; Map: Phaser.Tilemaps.Tilemap;
initAnimation(): void { initAnimation(): void {
throw new Error("Method not implemented.");
} }
createCurrentPlayer(UserId: string): void { createCurrentPlayer(UserId: string): void {

View File

@ -3,14 +3,13 @@ import GameConfig = Phaser.Types.Core.GameConfig;
import {DEBUG_MODE, RESOLUTION} from "./Enum/EnvironmentVariable"; import {DEBUG_MODE, RESOLUTION} from "./Enum/EnvironmentVariable";
import {cypressAsserter} from "./Cypress/CypressAsserter"; import {cypressAsserter} from "./Cypress/CypressAsserter";
import {LogincScene} from "./Phaser/Login/LogincScene"; import {LogincScene} from "./Phaser/Login/LogincScene";
import {GameScene} from "./Phaser/Game/GameScene";
const config: GameConfig = { const config: GameConfig = {
title: "Office game", title: "Office game",
width: window.innerWidth / RESOLUTION, width: window.innerWidth / RESOLUTION,
height: window.innerHeight / RESOLUTION, height: window.innerHeight / RESOLUTION,
parent: "game", parent: "game",
scene: [LogincScene, GameScene], scene: [LogincScene],
zoom: RESOLUTION, zoom: RESOLUTION,
physics: { physics: {
default: "arcade", default: "arcade",