Fixing use const instead of let

This commit is contained in:
David Négrier 2020-06-09 23:13:26 +02:00
parent 54f2518b5e
commit 8348d13bfe
17 changed files with 116 additions and 116 deletions

View file

@ -248,7 +248,7 @@ export class Connection implements ConnectionInterface {
if(!this.socket){ if(!this.socket){
return; return;
} }
let point = new Point(x, y, direction, moving); const point = new Point(x, y, direction, moving);
this.lastPositionShared = point; this.lastPositionShared = point;
this.getSocket().emit(EventMessage.USER_POSITION, point); this.getSocket().emit(EventMessage.USER_POSITION, point);
} }

View file

@ -2,7 +2,7 @@ export class MessageUI {
static warningMessage(text: string){ static warningMessage(text: string){
this.removeMessage(); this.removeMessage();
let body = document.getElementById("body"); const body = document.getElementById("body");
body?.insertAdjacentHTML('afterbegin', ` body?.insertAdjacentHTML('afterbegin', `
<div id="message-reconnect" class="message-info warning"> <div id="message-reconnect" class="message-info warning">
${text} ${text}
@ -12,13 +12,13 @@ export class MessageUI {
static removeMessage(id : string|null = null) { static removeMessage(id : string|null = null) {
if(!id){ if(!id){
let messages = document.getElementsByClassName("message-info"); const messages = document.getElementsByClassName("message-info");
for (let i = 0; i < messages.length; i++){ for (let i = 0; i < messages.length; i++){
messages.item(i)?.remove(); messages.item(i)?.remove();
} }
return; return;
} }
let previousElement = document.getElementById(id); const previousElement = document.getElementById(id);
if (!previousElement) { if (!previousElement) {
return; return;
} }

View file

@ -10,8 +10,8 @@ export class TextInput extends Phaser.GameObjects.BitmapText {
this.underLine = this.scene.add.text(x, y+1, '_______', { fontFamily: 'Arial', fontSize: "32px", color: '#ffffff'}) this.underLine = this.scene.add.text(x, y+1, '_______', { fontFamily: 'Arial', fontSize: "32px", color: '#ffffff'})
let keySpace = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); const keySpace = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
let keyBackspace = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.BACKSPACE); const keyBackspace = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.BACKSPACE);
this.scene.input.keyboard.on('keydown', (event: any) => { this.scene.input.keyboard.on('keydown', (event: any) => {
if (event.keyCode === 8 && this.text.length > 0) { if (event.keyCode === 8 && this.text.length > 0) {
this.deleteLetter(); this.deleteLetter();

View file

@ -13,10 +13,10 @@ export class SpeechBubble {
*/ */
constructor(scene: Scene, player: Character, text: string = "") { constructor(scene: Scene, player: Character, text: string = "") {
let bubbleHeight = 50; const bubbleHeight = 50;
let bubblePadding = 10; const bubblePadding = 10;
let bubbleWidth = bubblePadding * 2 + text.length * 10; const bubbleWidth = bubblePadding * 2 + text.length * 10;
let arrowHeight = bubbleHeight / 4; const arrowHeight = bubbleHeight / 4;
this.bubble = scene.add.graphics({ x: player.x + 16, y: player.y - 80 }); this.bubble = scene.add.graphics({ x: player.x + 16, y: player.y - 80 });
@ -35,12 +35,12 @@ export class SpeechBubble {
this.bubble.fillRoundedRect(0, 0, bubbleWidth, bubbleHeight, 16); this.bubble.fillRoundedRect(0, 0, bubbleWidth, bubbleHeight, 16);
// Calculate arrow coordinates // Calculate arrow coordinates
let point1X = Math.floor(bubbleWidth / 7); const point1X = Math.floor(bubbleWidth / 7);
let point1Y = bubbleHeight; const point1Y = bubbleHeight;
let point2X = Math.floor((bubbleWidth / 7) * 2); const point2X = Math.floor((bubbleWidth / 7) * 2);
let point2Y = bubbleHeight; const point2Y = bubbleHeight;
let point3X = Math.floor(bubbleWidth / 7); const point3X = Math.floor(bubbleWidth / 7);
let point3Y = Math.floor(bubbleHeight + arrowHeight); const point3Y = Math.floor(bubbleHeight + arrowHeight);
// bubble arrow shadow // bubble arrow shadow
this.bubble.lineStyle(4, 0x222222, 0.5); this.bubble.lineStyle(4, 0x222222, 0.5);
@ -54,7 +54,7 @@ export class SpeechBubble {
this.content = scene.add.text(0, 0, text, { fontFamily: 'Arial', fontSize: 20, color: '#000000', align: 'center', wordWrap: { width: bubbleWidth - (bubblePadding * 2) } }); this.content = scene.add.text(0, 0, text, { fontFamily: 'Arial', fontSize: 20, color: '#000000', align: 'center', wordWrap: { width: bubbleWidth - (bubblePadding * 2) } });
let bounds = this.content.getBounds(); const bounds = this.content.getBounds();
this.content.setPosition(this.bubble.x + (bubbleWidth / 2) - (bounds.width / 2), this.bubble.y + (bubbleHeight / 2) - (bounds.height / 2)); this.content.setPosition(this.bubble.x + (bubbleWidth / 2) - (bounds.width / 2), this.bubble.y + (bubbleHeight / 2) - (bounds.height / 2));
} }
@ -68,10 +68,10 @@ export class SpeechBubble {
this.bubble.setPosition((x + 16), (y - 80)); this.bubble.setPosition((x + 16), (y - 80));
} }
if (this.content) { if (this.content) {
let bubbleHeight = 50; const bubbleHeight = 50;
let bubblePadding = 10; const bubblePadding = 10;
let bubbleWidth = bubblePadding * 2 + this.content.text.length * 10; const bubbleWidth = bubblePadding * 2 + this.content.text.length * 10;
let bounds = this.content.getBounds(); const bounds = this.content.getBounds();
//this.content.setPosition(x, y); //this.content.setPosition(x, y);
this.content.setPosition(this.bubble.x + (bubbleWidth / 2) - (bounds.width / 2), this.bubble.y + (bubbleHeight / 2) - (bounds.height / 2)); this.content.setPosition(this.bubble.x + (bubbleWidth / 2) - (bounds.width / 2), this.bubble.y + (bubbleHeight / 2) - (bounds.height / 2));
} }

View file

@ -83,7 +83,7 @@ export class GameManager {
} }
onUserJoins(message: MessageUserJoined): void { onUserJoins(message: MessageUserJoined): void {
let userMessage: AddPlayerInterface = { const userMessage: AddPlayerInterface = {
userId: message.userId, userId: message.userId,
character: message.character, character: message.character,
name: message.name, name: message.name,
@ -154,11 +154,11 @@ export class GameManager {
} }
loadMap(mapUrl: string, scene: Phaser.Scenes.ScenePlugin, instance: string): string { loadMap(mapUrl: string, scene: Phaser.Scenes.ScenePlugin, instance: string): string {
let sceneKey = GameScene.getMapKeyByUrl(mapUrl); const sceneKey = GameScene.getMapKeyByUrl(mapUrl);
let gameIndex = scene.getIndex(sceneKey); const gameIndex = scene.getIndex(sceneKey);
if(gameIndex === -1){ if(gameIndex === -1){
let game : Phaser.Scene = GameScene.createFromUrl(mapUrl, instance); const game : Phaser.Scene = GameScene.createFromUrl(mapUrl, instance);
scene.add(sceneKey, game, false); scene.add(sceneKey, game, false);
} }
return sceneKey; return sceneKey;

View file

@ -62,7 +62,7 @@ export class GameScene extends Phaser.Scene {
private startLayerName: string|undefined; private startLayerName: string|undefined;
static createFromUrl(mapUrlFile: string, instance: string): GameScene { static createFromUrl(mapUrlFile: string, instance: string): GameScene {
let key = GameScene.getMapKeyByUrl(mapUrlFile); const key = GameScene.getMapKeyByUrl(mapUrlFile);
return new GameScene(key, mapUrlFile, instance); return new GameScene(key, mapUrlFile, instance);
} }
@ -92,7 +92,7 @@ export class GameScene extends Phaser.Scene {
// If the map has already been loaded as part of another GameScene, the "on load" event will not be triggered. // If the map has already been loaded as part of another GameScene, the "on load" event will not be triggered.
// In this case, we check in the cache to see if the map is here and trigger the event manually. // In this case, we check in the cache to see if the map is here and trigger the event manually.
if (this.cache.tilemap.exists(this.MapKey)) { if (this.cache.tilemap.exists(this.MapKey)) {
let data = this.cache.tilemap.get(this.MapKey); const data = this.cache.tilemap.get(this.MapKey);
this.onMapLoad(data); this.onMapLoad(data);
} }
@ -112,7 +112,7 @@ export class GameScene extends Phaser.Scene {
// 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.mapFile = data.data; this.mapFile = data.data;
let url = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/')); const url = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/'));
this.mapFile.tilesets.forEach((tileset) => { this.mapFile.tilesets.forEach((tileset) => {
if (typeof tileset.name === 'undefined' || typeof tileset.image === 'undefined') { if (typeof tileset.name === 'undefined' || typeof tileset.image === 'undefined') {
console.warn("Don't know how to handle tileset ", tileset) console.warn("Don't know how to handle tileset ", tileset)
@ -146,7 +146,7 @@ export class GameScene extends Phaser.Scene {
//add layer on map //add layer on map
this.Layers = new Array<Phaser.Tilemaps.StaticTilemapLayer>(); this.Layers = new Array<Phaser.Tilemaps.StaticTilemapLayer>();
let depth = -2; let depth = -2;
for (let layer of this.mapFile.layers) { for (const layer of this.mapFile.layers) {
if (layer.type === 'tilelayer') { if (layer.type === 'tilelayer') {
this.addLayer(this.Map.createStaticLayer(layer.name, this.Terrains, 0, 0).setDepth(depth)); this.addLayer(this.Map.createStaticLayer(layer.name, this.Terrains, 0, 0).setDepth(depth));
} }
@ -168,9 +168,9 @@ export class GameScene extends Phaser.Scene {
} else { } else {
// Now, let's find the start layer // Now, let's find the start layer
if (this.startLayerName) { if (this.startLayerName) {
for (let layer of this.mapFile.layers) { for (const layer of this.mapFile.layers) {
if (this.startLayerName === layer.name && layer.type === 'tilelayer' && this.isStartLayer(layer)) { if (this.startLayerName === layer.name && layer.type === 'tilelayer' && this.isStartLayer(layer)) {
let startPosition = this.startUser(layer); const startPosition = this.startUser(layer);
this.startX = startPosition.x; this.startX = startPosition.x;
this.startY = startPosition.y; this.startY = startPosition.y;
} }
@ -178,9 +178,9 @@ export class GameScene extends Phaser.Scene {
} }
if (this.startX === undefined) { if (this.startX === undefined) {
// If we have no start layer specified or if the hash passed does not exist, let's go with the default start position. // If we have no start layer specified or if the hash passed does not exist, let's go with the default start position.
for (let layer of this.mapFile.layers) { for (const layer of this.mapFile.layers) {
if (layer.type === 'tilelayer' && layer.name === "start") { if (layer.type === 'tilelayer' && layer.name === "start") {
let startPosition = this.startUser(layer); const startPosition = this.startUser(layer);
this.startX = startPosition.x; this.startX = startPosition.x;
this.startY = startPosition.y; this.startY = startPosition.y;
} }
@ -212,12 +212,12 @@ export class GameScene extends Phaser.Scene {
// Let's generate the circle for the group delimiter // Let's generate the circle for the group delimiter
let circleElement = Object.values(this.textures.list).find((object: Texture) => object.key === 'circleSprite'); const circleElement = Object.values(this.textures.list).find((object: Texture) => object.key === 'circleSprite');
if(circleElement) { if(circleElement) {
this.textures.remove('circleSprite'); this.textures.remove('circleSprite');
} }
this.circleTexture = this.textures.createCanvas('circleSprite', 96, 96); this.circleTexture = this.textures.createCanvas('circleSprite', 96, 96);
let context = this.circleTexture.context; const 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);
// context.lineWidth = 5; // context.lineWidth = 5;
@ -226,7 +226,7 @@ export class GameScene extends Phaser.Scene {
this.circleTexture.refresh(); this.circleTexture.refresh();
// Let's alter browser history // Let's alter browser history
let url = new URL(this.MapUrlFile); const url = new URL(this.MapUrlFile);
let path = '/_/'+this.instance+'/'+url.host+url.pathname; let path = '/_/'+this.instance+'/'+url.host+url.pathname;
if (this.startLayerName) { if (this.startLayerName) {
path += '#'+this.startLayerName; path += '#'+this.startLayerName;
@ -247,11 +247,11 @@ export class GameScene extends Phaser.Scene {
} }
private getProperty(layer: ITiledMapLayer, name: string): string|boolean|number|undefined { private getProperty(layer: ITiledMapLayer, name: string): string|boolean|number|undefined {
let properties : any = layer.properties; const properties : any = layer.properties;
if (!properties) { if (!properties) {
return undefined; return undefined;
} }
let obj = properties.find((property:any) => property.name === name); const obj = properties.find((property:any) => property.name === name);
if (obj === undefined) { if (obj === undefined) {
return undefined; return undefined;
} }
@ -266,7 +266,7 @@ export class GameScene extends Phaser.Scene {
* @param tileHeight * @param tileHeight
*/ */
private loadNextGame(layer: ITiledMapLayer, mapWidth: number, tileWidth: number, tileHeight: number){ private loadNextGame(layer: ITiledMapLayer, mapWidth: number, tileWidth: number, tileHeight: number){
let exitSceneUrl = this.getExitSceneUrl(layer); const exitSceneUrl = this.getExitSceneUrl(layer);
if (exitSceneUrl === undefined) { if (exitSceneUrl === undefined) {
throw new Error('Layer is not an exit scene layer.'); throw new Error('Layer is not an exit scene layer.');
} }
@ -276,18 +276,18 @@ export class GameScene extends Phaser.Scene {
} }
// TODO: eventually compute a relative URL // TODO: eventually compute a relative URL
let absoluteExitSceneUrl = new URL(exitSceneUrl, this.MapUrlFile).href; const absoluteExitSceneUrl = new URL(exitSceneUrl, this.MapUrlFile).href;
let exitSceneKey = gameManager.loadMap(absoluteExitSceneUrl, this.scene, instance); const exitSceneKey = gameManager.loadMap(absoluteExitSceneUrl, this.scene, instance);
let tiles : number[] = layer.data as number[]; const tiles : number[] = layer.data as number[];
for (let key=0; key < tiles.length; key++) { for (let key=0; key < tiles.length; key++) {
let objectKey = tiles[key]; const objectKey = tiles[key];
if(objectKey === 0){ if(objectKey === 0){
continue; continue;
} }
//key + 1 because the start x = 0; //key + 1 because the start x = 0;
let y : number = parseInt(((key + 1) / mapWidth).toString()); const y : number = parseInt(((key + 1) / mapWidth).toString());
let x : number = key - (y * mapWidth); const x : number = key - (y * mapWidth);
let hash = new URL(exitSceneUrl, this.MapUrlFile).hash; let hash = new URL(exitSceneUrl, this.MapUrlFile).hash;
if (hash) { if (hash) {
@ -317,8 +317,8 @@ export class GameScene extends Phaser.Scene {
if(objectKey === 0){ if(objectKey === 0){
return; return;
} }
let y = Math.floor(key / layer.width); const y = Math.floor(key / layer.width);
let x = key % layer.width; const x = key % layer.width;
possibleStartPositions.push({x: x*32, y: y*32}); possibleStartPositions.push({x: x*32, y: y*32});
}); });
@ -431,7 +431,7 @@ export class GameScene extends Phaser.Scene {
// debug code to get a tile properties by clicking on it // debug code to get a tile properties by clicking on it
this.input.on("pointerdown", (pointer: Phaser.Input.Pointer)=>{ this.input.on("pointerdown", (pointer: Phaser.Input.Pointer)=>{
//pixel position toz tile position //pixel position toz tile position
let tile = this.Map.getTileAt(this.Map.worldToTileX(pointer.worldX), this.Map.worldToTileY(pointer.worldY)); const tile = this.Map.getTileAt(this.Map.worldToTileX(pointer.worldX), this.Map.worldToTileY(pointer.worldY));
if(tile){ if(tile){
this.CurrentPlayer.say("Your touch " + tile.layer.name); this.CurrentPlayer.say("Your touch " + tile.layer.name);
} }
@ -447,16 +447,16 @@ export class GameScene extends Phaser.Scene {
this.CurrentPlayer.moveUser(delta); this.CurrentPlayer.moveUser(delta);
// Let's move all users // Let's move all users
let updatedPlayersPositions = this.playersPositionInterpolator.getUpdatedPositions(time); const updatedPlayersPositions = this.playersPositionInterpolator.getUpdatedPositions(time);
updatedPlayersPositions.forEach((moveEvent: HasMovedEvent, userId: string) => { updatedPlayersPositions.forEach((moveEvent: HasMovedEvent, userId: string) => {
let player : RemotePlayer | undefined = this.MapPlayersByKey.get(userId); const player : RemotePlayer | undefined = this.MapPlayersByKey.get(userId);
if (player === undefined) { if (player === undefined) {
throw new Error('Cannot find player with ID "' + userId +'"'); throw new Error('Cannot find player with ID "' + userId +'"');
} }
player.updatePosition(moveEvent); player.updatePosition(moveEvent);
}); });
let nextSceneKey = this.checkToExit(); const nextSceneKey = this.checkToExit();
if(nextSceneKey){ if(nextSceneKey){
// We are completely destroying the current scene to avoid using a half-backed instance when coming back to the same map. // We are completely destroying the current scene to avoid using a half-backed instance when coming back to the same map.
this.scene.remove(this.scene.key); this.scene.remove(this.scene.key);
@ -485,7 +485,7 @@ export class GameScene extends Phaser.Scene {
return; return;
} }
let currentPlayerId = this.GameManager.getPlayerId(); const currentPlayerId = this.GameManager.getPlayerId();
// clean map // clean map
this.MapPlayersByKey.forEach((player: RemotePlayer) => { this.MapPlayersByKey.forEach((player: RemotePlayer) => {
@ -516,7 +516,7 @@ export class GameScene extends Phaser.Scene {
return; return;
} }
//initialise player //initialise player
let player = new RemotePlayer( const player = new RemotePlayer(
addPlayerData.userId, addPlayerData.userId,
this, this,
addPlayerData.position.x, addPlayerData.position.x,
@ -538,7 +538,7 @@ export class GameScene extends Phaser.Scene {
public removePlayer(userId: string) { public removePlayer(userId: string) {
console.log('Removing player ', userId) console.log('Removing player ', userId)
let player = this.MapPlayersByKey.get(userId); const player = this.MapPlayersByKey.get(userId);
if (player === undefined) { if (player === undefined) {
console.error('Cannot find user with id ', userId); console.error('Cannot find user with id ', userId);
} else { } else {
@ -550,26 +550,26 @@ export class GameScene extends Phaser.Scene {
} }
updatePlayerPosition(message: MessageUserMovedInterface): void { updatePlayerPosition(message: MessageUserMovedInterface): void {
let player : RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId); const player : RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId);
if (player === undefined) { if (player === undefined) {
throw new Error('Cannot find player with ID "' + message.userId +'"'); throw new Error('Cannot find player with ID "' + message.userId +'"');
} }
// We do not update the player position directly (because it is sent only every 200ms). // We do not update the player position directly (because it is sent only every 200ms).
// Instead we use the PlayersPositionInterpolator that will do a smooth animation over the next 200ms. // Instead we use the PlayersPositionInterpolator that will do a smooth animation over the next 200ms.
let playerMovement = new PlayerMovement({ x: player.x, y: player.y }, this.currentTick, message.position, this.currentTick + POSITION_DELAY); const playerMovement = new PlayerMovement({ x: player.x, y: player.y }, this.currentTick, message.position, this.currentTick + POSITION_DELAY);
this.playersPositionInterpolator.updatePlayerPosition(player.userId, playerMovement); this.playersPositionInterpolator.updatePlayerPosition(player.userId, playerMovement);
} }
shareGroupPosition(groupPositionMessage: GroupCreatedUpdatedMessageInterface) { shareGroupPosition(groupPositionMessage: GroupCreatedUpdatedMessageInterface) {
let groupId = groupPositionMessage.groupId; const groupId = groupPositionMessage.groupId;
let group = this.groups.get(groupId); const group = this.groups.get(groupId);
if (group !== undefined) { if (group !== undefined) {
group.setPosition(Math.round(groupPositionMessage.position.x), Math.round(groupPositionMessage.position.y)); group.setPosition(Math.round(groupPositionMessage.position.x), Math.round(groupPositionMessage.position.y));
} else { } else {
// TODO: circle radius should not be hard stored // TODO: circle radius should not be hard stored
let sprite = new Sprite( const sprite = new Sprite(
this, this,
Math.round(groupPositionMessage.position.x), Math.round(groupPositionMessage.position.x),
Math.round(groupPositionMessage.position.y), Math.round(groupPositionMessage.position.y),
@ -581,7 +581,7 @@ export class GameScene extends Phaser.Scene {
} }
deleteGroup(groupId: string): void { deleteGroup(groupId: string): void {
let group = this.groups.get(groupId); const group = this.groups.get(groupId);
if(!group){ if(!group){
return; return;
} }
@ -591,8 +591,8 @@ export class GameScene extends Phaser.Scene {
public static getMapKeyByUrl(mapUrlStart: string) : string { public static getMapKeyByUrl(mapUrlStart: string) : string {
// FIXME: the key should be computed from the full URL of the map. // FIXME: the key should be computed from the full URL of the map.
let startPos = mapUrlStart.indexOf('://')+3; const startPos = mapUrlStart.indexOf('://')+3;
let endPos = mapUrlStart.indexOf(".json"); const endPos = mapUrlStart.indexOf(".json");
return mapUrlStart.substring(startPos, endPos); return mapUrlStart.substring(startPos, endPos);
} }
} }

View file

@ -23,8 +23,8 @@ export class PlayerMovement {
return this.endPosition; return this.endPosition;
} }
let x = (this.endPosition.x - this.startPosition.x) * ((tick - this.startTick) / (this.endTick - this.startTick)) + this.startPosition.x; const x = (this.endPosition.x - this.startPosition.x) * ((tick - this.startTick) / (this.endTick - this.startTick)) + this.startPosition.x;
let y = (this.endPosition.y - this.startPosition.y) * ((tick - this.startTick) / (this.endTick - this.startTick)) + this.startPosition.y; const y = (this.endPosition.y - this.startPosition.y) * ((tick - this.startTick) / (this.endTick - this.startTick)) + this.startPosition.y;
return { return {
x, x,

View file

@ -17,7 +17,7 @@ export class PlayersPositionInterpolator {
} }
getUpdatedPositions(tick: number) : Map<string, HasMovedEvent> { getUpdatedPositions(tick: number) : Map<string, HasMovedEvent> {
let positions = new Map<string, HasMovedEvent>(); const positions = new Map<string, HasMovedEvent>();
this.playerMovements.forEach((playerMovement: PlayerMovement, userId: string) => { this.playerMovements.forEach((playerMovement: PlayerMovement, userId: string) => {
if (playerMovement.isOutdated(tick)) { if (playerMovement.isOutdated(tick)) {
//console.log("outdated") //console.log("outdated")

View file

@ -67,7 +67,7 @@ export class LoginScene extends Phaser.Scene {
this.logo = new Image(this, this.game.renderer.width - 30, this.game.renderer.height - 20, LoginTextures.icon); this.logo = new Image(this, this.game.renderer.width - 30, this.game.renderer.height - 20, LoginTextures.icon);
this.add.existing(this.logo); this.add.existing(this.logo);
let infoText = "Commands: \n - Arrows or Z,Q,S,D to move\n - SHIFT to run"; const infoText = "Commands: \n - Arrows or Z,Q,S,D to move\n - SHIFT to run";
this.infoTextField = new TextField(this, 10, this.game.renderer.height - 35, infoText); this.infoTextField = new TextField(this, 10, this.game.renderer.height - 35, infoText);
this.input.keyboard.on('keyup-ENTER', () => { this.input.keyboard.on('keyup-ENTER', () => {

View file

@ -63,7 +63,7 @@ export class SelectCharacterScene extends Phaser.Scene {
this.pressReturnField = new TextField(this, this.game.renderer.width / 2, 230, 'Press enter to start'); this.pressReturnField = new TextField(this, this.game.renderer.width / 2, 230, 'Press enter to start');
this.pressReturnField.setOrigin(0.5).setCenterAlign() this.pressReturnField.setOrigin(0.5).setCenterAlign()
let rectangleXStart = this.game.renderer.width / 2 - (this.nbCharactersPerRow / 2) * 32 + 16; const rectangleXStart = this.game.renderer.width / 2 - (this.nbCharactersPerRow / 2) * 32 + 16;
this.selectedRectangle = this.add.rectangle(rectangleXStart, 90, 32, 32).setStrokeStyle(2, 0xFFFFFF); this.selectedRectangle = this.add.rectangle(rectangleXStart, 90, 32, 32).setStrokeStyle(2, 0xFFFFFF);
@ -103,8 +103,8 @@ export class SelectCharacterScene extends Phaser.Scene {
this.createCurrentPlayer(); this.createCurrentPlayer();
if (window.localStorage) { if (window.localStorage) {
let playerNumberStr: string = window.localStorage.getItem('selectedPlayer') ?? '0'; const playerNumberStr: string = window.localStorage.getItem('selectedPlayer') ?? '0';
let playerNumber: number = Number(playerNumberStr); const playerNumber: number = Number(playerNumberStr);
this.selectedRectangleXPos = playerNumber % this.nbCharactersPerRow; this.selectedRectangleXPos = playerNumber % this.nbCharactersPerRow;
this.selectedRectangleYPos = Math.floor(playerNumber / this.nbCharactersPerRow); this.selectedRectangleYPos = Math.floor(playerNumber / this.nbCharactersPerRow);
this.updateSelectedPlayer(); this.updateSelectedPlayer();
@ -118,10 +118,10 @@ export class SelectCharacterScene extends Phaser.Scene {
private async login(name: string) { private async login(name: string) {
return gameManager.connect(name, this.selectedPlayer.texture.key).then(() => { return gameManager.connect(name, this.selectedPlayer.texture.key).then(() => {
// Do we have a start URL in the address bar? If so, let's redirect to this address // Do we have a start URL in the address bar? If so, let's redirect to this address
let instanceAndMapUrl = this.findMapUrl(); const instanceAndMapUrl = this.findMapUrl();
if (instanceAndMapUrl !== null) { if (instanceAndMapUrl !== null) {
let [mapUrl, instance] = instanceAndMapUrl; const [mapUrl, instance] = instanceAndMapUrl;
let key = gameManager.loadMap(mapUrl, this.scene, instance); const key = gameManager.loadMap(mapUrl, this.scene, instance);
this.scene.start(key, { this.scene.start(key, {
startLayerName: window.location.hash ? window.location.hash.substr(1) : undefined startLayerName: window.location.hash ? window.location.hash.substr(1) : undefined
} as GameSceneInitInterface); } as GameSceneInitInterface);
@ -132,7 +132,7 @@ export class SelectCharacterScene extends Phaser.Scene {
if (!scene) { if (!scene) {
return; return;
} }
let key = gameManager.loadMap(window.location.protocol + "//" + scene.mapUrlStart, this.scene, scene.startInstance); const key = gameManager.loadMap(window.location.protocol + "//" + scene.mapUrlStart, this.scene, scene.startInstance);
this.scene.start(key); this.scene.start(key);
return scene; return scene;
}).catch((err) => { }).catch((err) => {
@ -150,28 +150,28 @@ export class SelectCharacterScene extends Phaser.Scene {
* Returns the map URL and the instance from the current URL * Returns the map URL and the instance from the current URL
*/ */
private findMapUrl(): [string, string]|null { private findMapUrl(): [string, string]|null {
let path = window.location.pathname; const path = window.location.pathname;
if (!path.startsWith('/_/')) { if (!path.startsWith('/_/')) {
return null; return null;
} }
let instanceAndMap = path.substr(3); const instanceAndMap = path.substr(3);
let firstSlash = instanceAndMap.indexOf('/'); const firstSlash = instanceAndMap.indexOf('/');
if (firstSlash === -1) { if (firstSlash === -1) {
return null; return null;
} }
let instance = instanceAndMap.substr(0, firstSlash); const instance = instanceAndMap.substr(0, firstSlash);
return [window.location.protocol+'//'+instanceAndMap.substr(firstSlash+1), instance]; return [window.location.protocol+'//'+instanceAndMap.substr(firstSlash+1), instance];
} }
createCurrentPlayer(): void { createCurrentPlayer(): void {
for (let i = 0; i <PLAYER_RESOURCES.length; i++) { for (let i = 0; i <PLAYER_RESOURCES.length; i++) {
let playerResource = PLAYER_RESOURCES[i]; const playerResource = PLAYER_RESOURCES[i];
let col = i % this.nbCharactersPerRow; const col = i % this.nbCharactersPerRow;
let row = Math.floor(i / this.nbCharactersPerRow); const row = Math.floor(i / this.nbCharactersPerRow);
let [x, y] = this.getCharacterPosition(col, row); const [x, y] = this.getCharacterPosition(col, row);
let player = this.physics.add.sprite(x, y, playerResource.name, 0); const player = this.physics.add.sprite(x, y, playerResource.name, 0);
player.setBounce(0.2); player.setBounce(0.2);
player.setCollideWorldBounds(true); player.setCollideWorldBounds(true);
this.anims.create({ this.anims.create({
@ -203,11 +203,11 @@ export class SelectCharacterScene extends Phaser.Scene {
private updateSelectedPlayer(): void { private updateSelectedPlayer(): void {
this.selectedPlayer.anims.pause(); this.selectedPlayer.anims.pause();
let [x, y] = this.getCharacterPosition(this.selectedRectangleXPos, this.selectedRectangleYPos); const [x, y] = this.getCharacterPosition(this.selectedRectangleXPos, this.selectedRectangleYPos);
this.selectedRectangle.setX(x); this.selectedRectangle.setX(x);
this.selectedRectangle.setY(y); this.selectedRectangle.setY(y);
let playerNumber = this.selectedRectangleXPos + this.selectedRectangleYPos * this.nbCharactersPerRow; const playerNumber = this.selectedRectangleXPos + this.selectedRectangleYPos * this.nbCharactersPerRow;
let player = this.players[playerNumber]; const player = this.players[playerNumber];
player.play(PLAYER_RESOURCES[playerNumber].name); player.play(PLAYER_RESOURCES[playerNumber].name);
this.selectedPlayer = player; this.selectedPlayer = player;
if (window.localStorage) { if (window.localStorage) {

View file

@ -39,9 +39,9 @@ export class Player extends Character implements CurrentGamerInterface {
let direction = null; let direction = null;
let moving = false; let moving = false;
let activeEvents = this.userInputManager.getEventListForGameTick(); const activeEvents = this.userInputManager.getEventListForGameTick();
let speedMultiplier = activeEvents.get(UserInputEvent.SpeedUp) ? 25 : 9; const speedMultiplier = activeEvents.get(UserInputEvent.SpeedUp) ? 25 : 9;
let moveAmount = speedMultiplier * 20; const moveAmount = speedMultiplier * 20;
let x = 0; let x = 0;
let y = 0; let y = 0;

View file

@ -43,7 +43,7 @@ export class ReconnectingScene extends Phaser.Scene {
this.reconnectingField = new TextField(this, this.game.renderer.width / 2, this.game.renderer.height / 2, "Connection lost. Reconnecting..."); this.reconnectingField = new TextField(this, this.game.renderer.width / 2, this.game.renderer.height / 2, "Connection lost. Reconnecting...");
this.reconnectingField.setOrigin(0.5, 0.5).setCenterAlign(); this.reconnectingField.setOrigin(0.5, 0.5).setCenterAlign();
let cat = this.physics.add.sprite(this.game.renderer.width / 2, this.game.renderer.height / 2 - 32, 'cat'); const cat = this.physics.add.sprite(this.game.renderer.width / 2, this.game.renderer.height / 2 - 32, 'cat');
this.anims.create({ this.anims.create({
key: 'right', key: 'right',
frames: this.anims.generateFrameNumbers('cat', { start: 6, end: 8 }), frames: this.anims.generateFrameNumbers('cat', { start: 6, end: 8 }),

View file

@ -55,7 +55,7 @@ export class UserInputManager {
} }
getEventListForGameTick(): ActiveEventList { getEventListForGameTick(): ActiveEventList {
let eventsMap = new ActiveEventList(); const eventsMap = new ActiveEventList();
this.KeysCode.forEach(d => { this.KeysCode.forEach(d => {
if (d. keyInstance.isDown) { if (d. keyInstance.isDown) {
eventsMap.set(d.event, true); eventsMap.set(d.event, true);

View file

@ -55,7 +55,7 @@ export class MediaManager {
} }
activeVisio(){ activeVisio(){
let webRtc = this.getElementByIdOrFail('webRtc'); const webRtc = this.getElementByIdOrFail('webRtc');
webRtc.classList.add('active'); webRtc.classList.add('active');
} }
@ -138,9 +138,9 @@ export class MediaManager {
*/ */
addActiveVideo(userId : string, userName: string = ""){ addActiveVideo(userId : string, userName: string = ""){
this.webrtcInAudio.play(); this.webrtcInAudio.play();
let elementRemoteVideo = this.getElementByIdOrFail("activeCam"); const elementRemoteVideo = this.getElementByIdOrFail("activeCam");
userName = userName.toUpperCase(); userName = userName.toUpperCase();
let color = this.getColorByString(userName); const color = this.getColorByString(userName);
elementRemoteVideo.insertAdjacentHTML('beforeend', ` elementRemoteVideo.insertAdjacentHTML('beforeend', `
<div id="div-${userId}" class="video-container" style="border-color: ${color};"> <div id="div-${userId}" class="video-container" style="border-color: ${color};">
<div class="connecting-spinner"></div> <div class="connecting-spinner"></div>
@ -158,7 +158,7 @@ export class MediaManager {
* @param userId * @param userId
*/ */
disabledMicrophoneByUserId(userId: string){ disabledMicrophoneByUserId(userId: string){
let element = document.getElementById(`microphone-${userId}`); const element = document.getElementById(`microphone-${userId}`);
if(!element){ if(!element){
return; return;
} }
@ -170,7 +170,7 @@ export class MediaManager {
* @param userId * @param userId
*/ */
enabledMicrophoneByUserId(userId: string){ enabledMicrophoneByUserId(userId: string){
let element = document.getElementById(`microphone-${userId}`); const element = document.getElementById(`microphone-${userId}`);
if(!element){ if(!element){
return; return;
} }
@ -223,7 +223,7 @@ export class MediaManager {
* @param userId * @param userId
*/ */
removeActiveVideo(userId : string){ removeActiveVideo(userId : string){
let element = document.getElementById(`div-${userId}`); const element = document.getElementById(`div-${userId}`);
if(!element){ if(!element){
return; return;
} }
@ -231,7 +231,7 @@ export class MediaManager {
} }
isConnecting(userId : string): void { isConnecting(userId : string): void {
let connectingSpinnerDiv = this.getSpinner(userId); const connectingSpinnerDiv = this.getSpinner(userId);
if (connectingSpinnerDiv === null) { if (connectingSpinnerDiv === null) {
return; return;
} }
@ -239,7 +239,7 @@ export class MediaManager {
} }
isConnected(userId : string): void { isConnected(userId : string): void {
let connectingSpinnerDiv = this.getSpinner(userId); const connectingSpinnerDiv = this.getSpinner(userId);
if (connectingSpinnerDiv === null) { if (connectingSpinnerDiv === null) {
return; return;
} }
@ -247,11 +247,11 @@ export class MediaManager {
} }
isError(userId : string): void { isError(userId : string): void {
let element = document.getElementById(`div-${userId}`); const element = document.getElementById(`div-${userId}`);
if(!element){ if(!element){
return; return;
} }
let errorDiv = element.getElementsByClassName('rtc-error').item(0) as HTMLDivElement|null; const errorDiv = element.getElementsByClassName('rtc-error').item(0) as HTMLDivElement|null;
if (errorDiv === null) { if (errorDiv === null) {
return; return;
} }
@ -259,11 +259,11 @@ export class MediaManager {
} }
private getSpinner(userId : string): HTMLDivElement|null { private getSpinner(userId : string): HTMLDivElement|null {
let element = document.getElementById(`div-${userId}`); const element = document.getElementById(`div-${userId}`);
if(!element){ if(!element){
return null; return null;
} }
let connnectingSpinnerDiv = element.getElementsByClassName('connecting-spinner').item(0) as HTMLDivElement|null; const connnectingSpinnerDiv = element.getElementsByClassName('connecting-spinner').item(0) as HTMLDivElement|null;
return connnectingSpinnerDiv; return connnectingSpinnerDiv;
} }
@ -280,14 +280,14 @@ export class MediaManager {
} }
let color = '#'; let color = '#';
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
let value = (hash >> (i * 8)) & 255; const value = (hash >> (i * 8)) & 255;
color += ('00' + value.toString(16)).substr(-2); color += ('00' + value.toString(16)).substr(-2);
} }
return color; return color;
} }
private getElementByIdOrFail<T extends HTMLElement>(id: string): T { private getElementByIdOrFail<T extends HTMLElement>(id: string): T {
let elem = document.getElementById(id); const elem = document.getElementById(id);
if (elem === null) { if (elem === null) {
throw new Error("Cannot find HTML element with id '"+id+"'"); throw new Error("Cannot find HTML element with id '"+id+"'");
} }

View file

@ -1,7 +1,7 @@
import {ConnectionInterface, WebRtcDisconnectMessageInterface, WebRtcStartMessageInterface} from "../Connection"; import {ConnectionInterface, WebRtcDisconnectMessageInterface, WebRtcStartMessageInterface} from "../Connection";
import {MediaManager} from "./MediaManager"; import {MediaManager} from "./MediaManager";
import * as SimplePeerNamespace from "simple-peer"; import * as SimplePeerNamespace from "simple-peer";
let Peer: SimplePeerNamespace.SimplePeer = require('simple-peer'); const Peer: SimplePeerNamespace.SimplePeer = require('simple-peer');
export interface UserSimplePeer{ export interface UserSimplePeer{
userId: string; userId: string;
@ -95,7 +95,7 @@ export class SimplePeer {
let name = user.name; let name = user.name;
if(!name){ if(!name){
let userSearch = this.Users.find((userSearch: UserSimplePeer) => userSearch.userId === user.userId); const userSearch = this.Users.find((userSearch: UserSimplePeer) => userSearch.userId === user.userId);
if(userSearch) { if(userSearch) {
name = userSearch.name; name = userSearch.name;
} }
@ -103,7 +103,7 @@ export class SimplePeer {
this.MediaManager.removeActiveVideo(user.userId); this.MediaManager.removeActiveVideo(user.userId);
this.MediaManager.addActiveVideo(user.userId, name); this.MediaManager.addActiveVideo(user.userId, name);
let peer : SimplePeerNamespace.Instance = new Peer({ const peer : SimplePeerNamespace.Instance = new Peer({
initiator: user.initiator ? user.initiator : false, initiator: user.initiator ? user.initiator : false,
reconnectTimer: 10000, reconnectTimer: 10000,
config: { config: {
@ -170,7 +170,7 @@ export class SimplePeer {
}); });
peer.on('data', (chunk: Buffer) => { peer.on('data', (chunk: Buffer) => {
let data = JSON.parse(chunk.toString('utf8')); const data = JSON.parse(chunk.toString('utf8'));
if(data.type === "stream"){ if(data.type === "stream"){
this.stream(user.userId, data.stream); this.stream(user.userId, data.stream);
} }
@ -187,7 +187,7 @@ export class SimplePeer {
private closeConnection(userId : string) { private closeConnection(userId : string) {
try { try {
this.MediaManager.removeActiveVideo(userId); this.MediaManager.removeActiveVideo(userId);
let peer = this.PeerConnectionArray.get(userId); const peer = this.PeerConnectionArray.get(userId);
if (peer === undefined) { if (peer === undefined) {
console.warn("Tried to close connection for user "+userId+" but could not find user") console.warn("Tried to close connection for user "+userId+" but could not find user")
return; return;
@ -222,7 +222,7 @@ export class SimplePeer {
if(data.signal.type === "offer"){ if(data.signal.type === "offer"){
this.createPeerConnection(data); this.createPeerConnection(data);
} }
let peer = this.PeerConnectionArray.get(data.userId); const peer = this.PeerConnectionArray.get(data.userId);
if (peer !== undefined) { if (peer !== undefined) {
peer.signal(data.signal); peer.signal(data.signal);
} else { } else {
@ -253,8 +253,8 @@ export class SimplePeer {
*/ */
private addMedia (userId : any = null) { private addMedia (userId : any = null) {
try { try {
let localStream: MediaStream|null = this.MediaManager.localStream; const localStream: MediaStream|null = this.MediaManager.localStream;
let peer = this.PeerConnectionArray.get(userId); const peer = this.PeerConnectionArray.get(userId);
if(localStream === null) { if(localStream === null) {
//send fake signal //send fake signal
if(peer === undefined){ if(peer === undefined){

View file

@ -24,7 +24,7 @@ const config: GameConfig = {
cypressAsserter.gameStarted(); cypressAsserter.gameStarted();
let game = new Phaser.Game(config); const game = new Phaser.Game(config);
window.addEventListener('resize', function (event) { window.addEventListener('resize', function (event) {
game.scale.resize(window.innerWidth / RESOLUTION, window.innerHeight / RESOLUTION); game.scale.resize(window.innerWidth / RESOLUTION, window.innerHeight / RESOLUTION);

View file

@ -3,7 +3,7 @@ import {PlayerMovement} from "../../../src/Phaser/Game/PlayerMovement";
describe("Interpolation / Extrapolation", () => { describe("Interpolation / Extrapolation", () => {
it("should interpolate", () => { it("should interpolate", () => {
let playerMovement = new PlayerMovement({ const playerMovement = new PlayerMovement({
x: 100, y: 200 x: 100, y: 200
}, 42000, }, 42000,
{ {
@ -39,7 +39,7 @@ describe("Interpolation / Extrapolation", () => {
}); });
it("should not extrapolate if we stop", () => { it("should not extrapolate if we stop", () => {
let playerMovement = new PlayerMovement({ const playerMovement = new PlayerMovement({
x: 100, y: 200 x: 100, y: 200
}, 42000, }, 42000,
{ {
@ -57,7 +57,7 @@ describe("Interpolation / Extrapolation", () => {
}); });
it("should should keep moving until it stops", () => { it("should should keep moving until it stops", () => {
let playerMovement = new PlayerMovement({ const playerMovement = new PlayerMovement({
x: 100, y: 200 x: 100, y: 200
}, 42000, }, 42000,
{ {