Merge pull request #34 from thecodingmachine/Refactoring-Phaser-Class

Refactoring Phaser Game
This commit is contained in:
David Négrier 2020-04-08 18:38:28 +02:00 committed by GitHub
commit 6bec8b3703
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 427 additions and 206 deletions

View File

@ -103,7 +103,8 @@ export class IoSocketController{
roomId: <string>,
position: {
x : <number>,
y : <number>
y : <number>,
direction: <string>
}
},
...

View File

@ -4,19 +4,22 @@ import {PointInterface} from "./PointInterface";
export class Point implements PointInterface{
x: number;
y: number;
direction: string;
constructor(x : number, y : number) {
constructor(x : number, y : number, direction : string = "none") {
if(x === null || y === null){
throw Error("position x and y cannot be null");
}
this.x = x;
this.y = y;
this.direction = direction;
}
toJson(){
return {
x : this.x,
y: this.y
y: this.y,
direction: this.direction
}
}
}
@ -27,7 +30,7 @@ export class MessageUserPosition extends Message{
constructor(message: string) {
super(message);
let data = JSON.parse(message);
this.position = new Point(data.position.x, data.position.y);
this.position = new Point(data.position.x, data.position.y, data.position.direction);
}
toString() {

View File

@ -1,5 +1,6 @@
export interface PointInterface {
x: number;
y: number;
direction: string;
toJson() : object;
}

View File

@ -1,3 +1,5 @@
import {GameManagerInterface} from "./Phaser/Game/GameManager";
const SocketIo = require('socket.io-client');
import Axios from "axios";
import {API_URL} from "./Enum/EnvironmentVariable";
@ -28,19 +30,22 @@ export class Message {
export class Point implements PointInterface{
x: number;
y: number;
direction : string;
constructor(x : number, y : number) {
constructor(x : number, y : number, direction : string = "none") {
if(x === null || y === null){
throw Error("position x and y cannot be null");
}
this.x = x;
this.y = y;
this.direction = direction;
}
toJson(){
return {
x : this.x,
y: this.y
y: this.y,
direction: this.direction
}
}
}
@ -70,8 +75,11 @@ export class Connexion {
email : string;
startedRoom : string;
constructor(email : string) {
GameManager: GameManagerInterface;
constructor(email : string, GameManager: GameManagerInterface) {
this.email = email;
this.GameManager = GameManager;
Axios.post(`${API_URL}/login`, {email: email})
.then((res) => {
this.token = res.data.token;
@ -87,9 +95,8 @@ export class Connexion {
this.joinARoom(this.startedRoom);
//share your first position
this.sharePosition(0, 0);
this.sharePosition(this.startedRoom, 0, 0);
//create listen event to get all data user shared by the back
this.positionOfAllUser();
this.errorMessage();
@ -110,12 +117,17 @@ export class Connexion {
}
/**
* Permit to share your position in map
*
* @param roomId
* @param x
* @param y
* @param direction
*/
sharePosition(x : number, y : number){
let messageUserPosition = new MessageUserPosition(this.email, this.startedRoom, new Point(x, y));
sharePosition(roomId : string, x : number, y : number, direction : string = "none"){
if(!this.socket){
return;
}
let messageUserPosition = new MessageUserPosition(this.email, roomId, new Point(x, y, direction));
this.socket.emit('user-position', messageUserPosition.toString());
}
@ -127,7 +139,8 @@ export class Connexion {
* roomId: <string>,
* position: {
* x : <number>,
* y : <number>
* y : <number>,
* direction: <string>
* }
* },
* ...
@ -135,8 +148,10 @@ export class Connexion {
**/
positionOfAllUser(){
this.socket.on("user-position", (message : string) => {
//TODO show all user in map
console.info("user-position", message);
let data = JSON.parse(message);
data.forEach((UserPositions : any) => {
this.GameManager.sharedUserPosition(UserPositions);
});
});
}

View File

@ -1,7 +1,9 @@
const API_URL = process.env.API_URL || "http://api.workadventure.localhost";
const ROOM = [process.env.ROOM || "THECODINGMACHINE"];
const RESOLUTION = 2;
export {
API_URL,
RESOLUTION
RESOLUTION,
ROOM
}

View File

@ -1,185 +0,0 @@
import {RESOLUTION} from "./Enum/EnvironmentVariable";
export class GameScene extends Phaser.Scene {
private player: Phaser.GameObjects.Sprite;
private keyZ: Phaser.Input.Keyboard.Key;
private keyQ: Phaser.Input.Keyboard.Key;
private keyS: Phaser.Input.Keyboard.Key;
private keyD: Phaser.Input.Keyboard.Key;
private keyRight: Phaser.Input.Keyboard.Key;
private keyLeft: Phaser.Input.Keyboard.Key;
private keyUp: Phaser.Input.Keyboard.Key;
private keyDown: Phaser.Input.Keyboard.Key;
private keyShift: Phaser.Input.Keyboard.Key;
private Mappy : Phaser.Tilemaps.Tilemap;
private startX = ((window.innerWidth / 2) / RESOLUTION);
private startY = ((window.innerHeight / 2) / RESOLUTION);
constructor() {
super({
key: "GameScene"
});
}
preload(): void {
this.load.image('tiles', 'maps/tiles.png');
this.load.tilemapTiledJSON('map', 'maps/map2.json');
this.load.spritesheet('player',
'resources/characters/pipoya/Male 01-1.png',
{ frameWidth: 32, frameHeight: 32 }
);
}
init(): void {
this.keyShift = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SHIFT);
this.keyZ = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Z);
this.keyQ = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Q);
this.keyS = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.S);
this.keyD = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D);
this.keyUp = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.UP);
this.keyLeft = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.LEFT);
this.keyDown = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.DOWN);
this.keyRight = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.RIGHT);
}
private moveCamera(x:number, y:number, speedMultiplier: number): void {
this.cameras.main.scrollX += speedMultiplier * 2 * x;
this.cameras.main.scrollY += speedMultiplier * 2 * y;
}
create(): void {
this.Mappy = this.add.tilemap("map");
let terrain = this.Mappy.addTilesetImage("tiles", "tiles");
let bottomLayer = this.Mappy.createStaticLayer("Calque 1", [terrain], 0, 0);
let topLayer = this.Mappy.createStaticLayer("Calque 2", [terrain], 0, 0);
// Let's manage animations of the player
this.anims.create({
key: 'down',
frames: this.anims.generateFrameNumbers('player', { start: 0, end: 2 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('player', { start: 3, end: 5 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('player', { start: 6, end: 8 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'up',
frames: this.anims.generateFrameNumbers('player', { start: 9, end: 11 }),
frameRate: 10,
repeat: -1
});
//let player = this.add.sprite(450, 450, 'player');
//player.anims.play('down');
//player.setBounce(0.2);
//player.setCollideWorldBounds(true);
this.player = this.add.sprite(this.startX, this.startY, 'player');
}
private angle: number = 0;
update(dt: number): void {
let xCameraPosition = this.cameras.main.scrollX;
let yCameraPosition = this.cameras.main.scrollY;
let speedMultiplier = this.keyShift.isDown ? 5 : 1;
if (this.keyZ.isDown || this.keyUp.isDown) {
this.managePlayerAnimation('up');
if (this.player.y > 0) {
this.player.setY(this.player.y - 2);
} else {
this.player.setY(0);
}
if (yCameraPosition > 0) {
if (this.player.y < (this.Mappy.widthInPixels - this.startY)) {
this.moveCamera(0, -1, speedMultiplier);
}
} else {
this.cameras.main.scrollY = 0;
}
} else if (this.keyQ.isDown || this.keyLeft.isDown) {
this.managePlayerAnimation('left');
if (this.player.x > 0) {
this.player.setX(this.player.x - 2);
} else {
this.player.setX(0);
}
if (xCameraPosition > 0) {
if (this.player.x < (this.Mappy.heightInPixels - this.startX)) {
this.moveCamera(-1, 0, speedMultiplier);
}
} else {
this.cameras.main.scrollX = 0;
}
} else if (this.keyS.isDown || this.keyDown.isDown) {
this.managePlayerAnimation('down');
if (this.Mappy.heightInPixels > this.player.y) {
this.player.setY(this.player.y + 2);
} else {
this.player.setY(this.Mappy.heightInPixels);
}
if (this.Mappy.heightInPixels > (yCameraPosition + (window.innerHeight / RESOLUTION))) {
if (this.player.y > this.startY) {
this.moveCamera(0, 1, speedMultiplier);
}
} else {
this.cameras.main.scrollY = (this.Mappy.heightInPixels - (window.innerHeight / RESOLUTION));
}
} else if (this.keyD.isDown || this.keyRight.isDown) {
this.managePlayerAnimation('right');
if (this.Mappy.widthInPixels > this.player.x) {
this.player.setX(this.player.x + 2)
} else {
this.player.setX(this.Mappy.widthInPixels)
}
if (this.Mappy.widthInPixels > (xCameraPosition + (window.innerWidth / RESOLUTION))) {
if (this.player.x > this.startX) {
this.moveCamera(1, 0, speedMultiplier);
}
} else {
this.cameras.main.scrollX = (this.Mappy.widthInPixels - (window.innerWidth / RESOLUTION));
}
} else {
this.managePlayerAnimation('none');
}
/*this.cameras.main.scrollX = Math.floor(300 + 300 * Math.cos(this.angle));
this.cameras.main.scrollY = Math.floor(300 + 300 * Math.sin(this.angle));
this.angle = dt * 0.0001;*/
}
managePlayerAnimation(direction: string) {
if (!this.player.anims.currentAnim || this.player.anims.currentAnim.key !== direction) {
this.player.anims.play(direction);
} else if (direction === 'none' && this.player.anims.currentAnim) {
this.player.anims.currentAnim.destroy();
}
}
}

View File

@ -0,0 +1,54 @@
import {RESOLUTION} from "../../Enum/EnvironmentVariable";
import {Player} from "../Player/Player";
import {MapManagerInterface} from "./MapManager";
import {PlayerAnimationNames} from "../Player/Animation";
export interface CameraManagerInterface {
MapManager : MapManagerInterface;
moveCamera(CurrentPlayer : Player) : void;
}
export class CameraManager implements CameraManagerInterface{
Scene : Phaser.Scene;
Camera : Phaser.Cameras.Scene2D.Camera;
MapManager : MapManagerInterface;
constructor(
Scene: Phaser.Scene,
Camera : Phaser.Cameras.Scene2D.Camera,
MapManager: MapManagerInterface,
) {
this.Scene = Scene;
this.MapManager = MapManager;
this.Camera = Camera;
}
moveCamera(CurrentPlayer : Player): void {
//center of camera
let startX = ((window.innerWidth / 2) / RESOLUTION);
let startY = ((window.innerHeight / 2) / RESOLUTION);
let limit = {
top: startY,
left: startX,
bottom : this.MapManager.Map.heightInPixels - startY,
right: this.MapManager.Map.widthInPixels - startX,
};
if(CurrentPlayer.x < limit.left){
this.Camera.scrollX = 0;
}else if(CurrentPlayer.x > limit.right){
this.Camera.scrollX = (limit.right - startX);
}else {
this.Camera.scrollX = (CurrentPlayer.x - startX);
}
if(CurrentPlayer.y < limit.top){
this.Camera.scrollY = 0;
}else if(CurrentPlayer.y > limit.bottom){
this.Camera.scrollY = (limit.bottom - startY);
}else {
this.Camera.scrollY = (CurrentPlayer.y - startY);
}
}
}

View File

@ -0,0 +1,31 @@
import {GameSceneInterface, GameScene} from "./GameScene";
import {ROOM} from "../../Enum/EnvironmentVariable"
import {Connexion} from "../../Connexion";
export let ConnexionInstance : Connexion;
export interface GameManagerInterface {
GameScenes: Array<GameSceneInterface>;
sharedUserPosition(UserPositions: any): void;
}
export class GameManager implements GameManagerInterface {
GameScenes: Array<GameSceneInterface> = [];
constructor() {
this.configureGame();
ConnexionInstance = new Connexion("test@gmail.com", this);
}
configureGame() {
ROOM.forEach((roomId) => {
let newGame = new GameScene(roomId, this);
this.GameScenes.push(newGame);
});
}
sharedUserPosition(UserPositions: any) {
let Game: GameSceneInterface = this.GameScenes.find((Game: GameSceneInterface) => Game.RoomId === UserPositions.roomId);
Game.sharedUserPosition(UserPositions)
}
}

View File

@ -0,0 +1,47 @@
import {MapManagerInterface, MapManager} from "./MapManager";
import {GameManagerInterface} from "./GameManager";
export interface GameSceneInterface extends Phaser.Scene {
RoomId : string;
sharedUserPosition(data : []): void;
}
export class GameScene extends Phaser.Scene implements GameSceneInterface{
private MapManager : MapManagerInterface;
RoomId : string;
constructor(RoomId : string, GameManager : GameManagerInterface) {
super({
key: "GameScene"
});
this.RoomId = RoomId;
}
//hook preload scene
preload(): void {
this.load.image('tiles', 'maps/tiles.png');
this.load.tilemapTiledJSON('map', 'maps/map2.json');
this.load.spritesheet('player',
'resources/characters/pipoya/Male 01-1.png',
{ frameWidth: 32, frameHeight: 32 }
);
}
//hook initialisation
init(){}
//hook create scene
create(): void {
//create map manager
this.MapManager = new MapManager(this);
}
//hook update
update(dt: number): void {
this.MapManager.update();
}
sharedUserPosition(data: []): void {
//TODO share position of all user
//console.log("sharedUserPosition", data);
}
}

View File

@ -0,0 +1,86 @@
import {CameraManager, CameraManagerInterface} from "./CameraManager";
import {RESOLUTION} from "../../Enum/EnvironmentVariable";
import {Player} from "../Player/Player";
import {GameScene, GameSceneInterface} from "./GameScene";
export interface MapManagerInterface {
keyZ: Phaser.Input.Keyboard.Key;
keyQ: Phaser.Input.Keyboard.Key;
keyS: Phaser.Input.Keyboard.Key;
keyD: Phaser.Input.Keyboard.Key;
keyRight: Phaser.Input.Keyboard.Key;
keyLeft: Phaser.Input.Keyboard.Key;
keyUp: Phaser.Input.Keyboard.Key;
keyDown: Phaser.Input.Keyboard.Key;
keyShift: Phaser.Input.Keyboard.Key;
Map: Phaser.Tilemaps.Tilemap;
Terrain: Phaser.Tilemaps.Tileset;
Camera: CameraManagerInterface;
Scene: GameSceneInterface;
update(): void;
}
export class MapManager implements MapManagerInterface{
keyZ: Phaser.Input.Keyboard.Key;
keyQ: Phaser.Input.Keyboard.Key;
keyS: Phaser.Input.Keyboard.Key;
keyD: Phaser.Input.Keyboard.Key;
keyRight: Phaser.Input.Keyboard.Key;
keyLeft: Phaser.Input.Keyboard.Key;
keyUp: Phaser.Input.Keyboard.Key;
keyDown: Phaser.Input.Keyboard.Key;
keyShift: Phaser.Input.Keyboard.Key;
Terrain : Phaser.Tilemaps.Tileset;
Camera: CameraManagerInterface;
CurrentPlayer: Player;
Scene: GameSceneInterface;
Map: Phaser.Tilemaps.Tilemap;
startX = (window.innerWidth / 2) / RESOLUTION;
startY = (window.innerHeight / 2) / RESOLUTION;
constructor(scene: GameSceneInterface){
this.Scene = scene;
//initalise map
this.Map = this.Scene.add.tilemap("map");
this.Terrain = this.Map.addTilesetImage("tiles", "tiles");
this.Map.createStaticLayer("tiles", "tiles");
this.Map.createStaticLayer("Calque 1", [this.Terrain], 0, 0);
this.Map.createStaticLayer("Calque 2", [this.Terrain], 0, 0);
//initialise keyboard
this.initKeyBoard();
//initialise camera
this.Camera = new CameraManager(this.Scene, this.Scene.cameras.main, this);
//initialise player
this.CurrentPlayer = new Player(
this.Scene,
this.startX,
this.startY,
this.Camera,
this
);
this.CurrentPlayer.initAnimation();
}
initKeyBoard() {
this.keyShift = this.Scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SHIFT);
this.keyZ = this.Scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Z);
this.keyQ = this.Scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Q);
this.keyS = this.Scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.S);
this.keyD = this.Scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D);
this.keyUp = this.Scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.UP);
this.keyLeft = this.Scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.LEFT);
this.keyDown = this.Scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.DOWN);
this.keyRight = this.Scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.RIGHT);
}
update() : void {
this.CurrentPlayer.move();
}
}

View File

@ -0,0 +1,56 @@
interface AnimationData {
key: string;
frameRate: number;
repeat: number;
frameModel: string; //todo use an enum
frameStart: number;
frameEnd: number;
}
export enum PlayerAnimationNames {
WalkDown = 'down',
WalkLeft = 'left',
WalkUp = 'up',
WalkRight = 'right',
None = 'none',
}
export const getPlayerAnimations = (PlayerValue : string): AnimationData[] => {
return [{
key: PlayerAnimationNames.WalkDown,
frameModel: PlayerValue,
frameStart: 0,
frameEnd: 2,
frameRate: 10,
repeat: -1
}, {
key: PlayerAnimationNames.WalkLeft,
frameModel: PlayerValue,
frameStart: 3,
frameEnd: 5,
frameRate: 10,
repeat: -1
}, {
key: PlayerAnimationNames.WalkRight,
frameModel: PlayerValue,
frameStart: 6,
frameEnd: 8,
frameRate: 10,
repeat: -1
}, {
key: PlayerAnimationNames.WalkUp,
frameModel: PlayerValue,
frameStart: 9,
frameEnd: 11,
frameRate: 10,
repeat: -1
}];
};
export const playAnimation = (Player : Phaser.GameObjects.Sprite, direction : string) => {
if (!Player.anims.currentAnim || Player.anims.currentAnim.key !== direction) {
Player.anims.play(direction);
} else if (direction === PlayerAnimationNames.None && Player.anims.currentAnim) {
Player.anims.currentAnim.destroy();
}
};

View File

@ -0,0 +1,111 @@
import {MapManagerInterface} from "../Game/MapManager";
import {getPlayerAnimations, playAnimation, PlayerAnimationNames} from "./Animation";
import {GameSceneInterface} from "../Game/GameScene";
import {ConnexionInstance} from "../Game/GameManager";
import {CameraManagerInterface} from "../Game/CameraManager";
export class Player extends Phaser.GameObjects.Sprite{
MapManager : MapManagerInterface;
PlayerValue : string;
CameraManager: CameraManagerInterface;
constructor(
Scene : GameSceneInterface,
x : number,
y : number,
CameraManager: CameraManagerInterface,
MapManager: MapManagerInterface,
PlayerValue : string = "player"
) {
super(Scene, x, y, PlayerValue);
this.PlayerValue = PlayerValue;
Scene.add.existing(this);
this.MapManager = MapManager;
this.CameraManager = CameraManager;
}
initAnimation(){
getPlayerAnimations(this.PlayerValue).forEach(d => {
this.scene.anims.create({
key: d.key,
frames: this.scene.anims.generateFrameNumbers(d.frameModel, { start: d.frameStart, end: d.frameEnd }),
frameRate: d.frameRate,
repeat: d.repeat
});
})
}
move(){
//if user client on shift, camera and player speed
let speedMultiplier = this.MapManager.keyShift.isDown ? 5 : 1;
let haveMove = false;
let direction = null;
if((this.MapManager.keyZ.isDown || this.MapManager.keyUp.isDown)){
if(!this.CanMoveUp()){
return;
}
playAnimation(this, PlayerAnimationNames.WalkUp);
this.setY(this.y - (2 * speedMultiplier));
haveMove = true;
direction = PlayerAnimationNames.WalkUp;
}
if((this.MapManager.keyQ.isDown || this.MapManager.keyLeft.isDown)){
if(!this.CanMoveLeft()){
return;
}
playAnimation(this, PlayerAnimationNames.WalkLeft);
this.setX(this.x - (2 * speedMultiplier));
haveMove = true;
direction = PlayerAnimationNames.WalkLeft;
}
if((this.MapManager.keyS.isDown || this.MapManager.keyDown.isDown)){
if(!this.CanMoveDown()){
return;
}
playAnimation(this, PlayerAnimationNames.WalkDown);
this.setY(this.y + (2 * speedMultiplier));
haveMove = true;
direction = PlayerAnimationNames.WalkDown;
}
if((this.MapManager.keyD.isDown || this.MapManager.keyRight.isDown)){
if(!this.CanMoveRight()){
return;
}
playAnimation(this, PlayerAnimationNames.WalkRight);
this.setX(this.x + (2 * speedMultiplier));
haveMove = true;
direction = PlayerAnimationNames.WalkRight;
}
if(!haveMove){
playAnimation(this, PlayerAnimationNames.None);
}else{
this.sharePosition(direction);
}
this.CameraManager.moveCamera(this);
}
private sharePosition(direction : string){
if(ConnexionInstance) {
ConnexionInstance.sharePosition((this.scene as GameSceneInterface).RoomId, this.x, this.y, direction);
}
}
private CanMoveUp(){
return this.y > 0;
}
private CanMoveLeft(){
return this.x > 0;
}
private CanMoveDown(){
return this.MapManager.Map.heightInPixels > this.y;
}
private CanMoveRight(){
return this.MapManager.Map.widthInPixels > this.x;
}
}

View File

@ -1,15 +1,16 @@
import 'phaser';
import GameConfig = Phaser.Types.Core.GameConfig;
import {GameScene} from "./GameScene";
import {Connexion} from "./Connexion";
import {GameManager} from "./Phaser/Game/GameManager";
import {RESOLUTION} from "./Enum/EnvironmentVariable";
let gameManager = new GameManager();
const config: GameConfig = {
title: "Office game",
width: window.innerWidth / RESOLUTION,
height: window.innerHeight / RESOLUTION,
parent: "game",
scene: [GameScene],
scene: gameManager.GameScenes,
zoom: RESOLUTION,
};
@ -18,5 +19,3 @@ let game = new Phaser.Game(config);
window.addEventListener('resize', function (event) {
game.scale.resize(window.innerWidth / RESOLUTION, window.innerHeight / RESOLUTION);
});
const connexion = new Connexion("test@gmail.com");