This commit is contained in:
schmelczerandras 2020-11-04 16:01:17 +01:00
parent 1ce961d6c2
commit 99cdb62928
76 changed files with 340 additions and 433 deletions

View file

@ -1,6 +1,6 @@
import { Command, CommandReceiver, serialize, TransportEvents } from 'shared';
export class CommandReceiverSocket extends CommandReceiver {
export class CommandSocket extends CommandReceiver {
constructor(private readonly socket: SocketIOClient.Socket) {
super();
}

View file

@ -1,29 +0,0 @@
import { vec2 } from 'gl-matrix';
import { CommandGenerator, SecondaryActionCommand, TernaryActionCommand } from 'shared';
import { Game } from '../../game';
export class MouseListener extends CommandGenerator {
constructor(target: HTMLElement, private readonly game: Game) {
super();
target.addEventListener('mousedown', (event: MouseEvent) => {
const position = this.positionFromEvent(event);
if (event.button == 0) {
this.sendCommandToSubscribers(new SecondaryActionCommand(position));
}
});
target.addEventListener('contextmenu', (event: MouseEvent) => {
event.preventDefault();
const position = this.positionFromEvent(event);
this.sendCommandToSubscribers(new TernaryActionCommand(position));
});
}
private positionFromEvent(event: MouseEvent): vec2 {
return this.game.displayToWorldCoordinates(
vec2.fromValues(event.clientX, event.clientY),
);
}
}

View file

@ -1,101 +0,0 @@
import { vec2 } from 'gl-matrix';
import {
CommandGenerator,
SecondaryActionCommand,
MoveActionCommand,
last,
} from 'shared';
import { Game } from '../../game';
export class TouchJoystickListener extends CommandGenerator {
private readonly deadZone = 8;
private readonly deltaScaling = 0.4;
private joystick: HTMLElement;
private joystickButton: HTMLElement;
private isJoystickActive = false;
private touchStartPosition!: vec2;
constructor(
target: HTMLElement,
private overlay: HTMLElement,
private readonly game: Game,
) {
super();
this.joystick = document.createElement('div');
this.joystick.className = 'joystick';
this.joystickButton = document.createElement('div');
this.joystick.appendChild(this.joystickButton);
target.addEventListener('touchstart', (event: TouchEvent) => {
event.preventDefault();
if (this.isJoystickActive) {
const center = vec2.fromValues(
last(event.touches)!.clientX,
last(event.touches)!.clientY,
);
this.sendCommandToSubscribers(
new SecondaryActionCommand(this.game.displayToWorldCoordinates(center)),
);
} else {
this.touchStartPosition = vec2.fromValues(
event.touches[0].clientX,
event.touches[0].clientY,
);
}
});
target.addEventListener('touchmove', (event: TouchEvent) => {
event.preventDefault();
const touchPosition = vec2.fromValues(
event.touches[0].clientX,
event.touches[0].clientY,
);
const delta = vec2.subtract(vec2.create(), touchPosition, this.touchStartPosition);
vec2.scale(delta, delta, this.deltaScaling);
const deltaLength = vec2.length(delta);
if (!this.isJoystickActive && deltaLength > this.deadZone) {
this.isJoystickActive = true;
this.overlay.appendChild(this.joystick);
this.joystickButton.style.transform = `translateX(-50%) translateY(-50%)`;
this.joystick.style.transform = `translateX(${this.touchStartPosition.x}px) translateY(${this.touchStartPosition.y}px) translateX(-50%) translateY(-50%)`;
}
const maxLength = 20;
vec2.scale(delta, delta, Math.min(1, maxLength / deltaLength));
this.joystickButton.style.transform = `translateX(${delta.x}px) translateY(${delta.y}px) translateX(-50%) translateY(-50%)`;
vec2.set(delta, delta.x, -delta.y);
if (deltaLength > this.deadZone) {
this.sendCommandToSubscribers(
new MoveActionCommand(vec2.normalize(delta, delta)),
);
} else {
this.sendCommandToSubscribers(new MoveActionCommand(vec2.create()));
}
});
target.addEventListener('touchend', (event: TouchEvent) => {
event.preventDefault();
if (!this.isJoystickActive) {
const center = vec2.fromValues(
event.changedTouches[0].clientX,
event.changedTouches[0].clientY,
);
this.sendCommandToSubscribers(
new SecondaryActionCommand(this.game.displayToWorldCoordinates(center)),
);
} else if (event.touches.length === 0) {
this.isJoystickActive = false;
this.joystick.parentElement?.removeChild(this.joystick);
this.sendCommandToSubscribers(new MoveActionCommand(vec2.create()));
}
});
}
}

View file

@ -4,22 +4,29 @@ import { CommandGenerator, MoveActionCommand } from 'shared';
export class KeyboardListener extends CommandGenerator {
private keysDown: Set<string> = new Set();
constructor(target: HTMLElement) {
constructor() {
super();
target.addEventListener('keydown', (event: KeyboardEvent) => {
const key = this.normalize(event.key);
this.keysDown.add(key);
this.generateCommands();
});
target.addEventListener('keyup', (event: KeyboardEvent) => {
const key = this.normalize(event.key);
this.keysDown.delete(key);
this.generateCommands();
});
addEventListener('keydown', this.keyDownListener);
addEventListener('keyup', this.keyUpListener);
addEventListener('blur', this.blurListener);
}
private keyDownListener = (event: KeyboardEvent) => {
this.keysDown.add(event.key.toLowerCase());
this.generateCommands();
};
private keyUpListener = (event: KeyboardEvent) => {
this.keysDown.delete(event.key.toLowerCase());
this.generateCommands();
};
private blurListener = () => {
this.keysDown.clear();
this.generateCommands();
};
private generateCommands() {
const up = ~~(
this.keysDown.has('w') ||
@ -34,10 +41,13 @@ export class KeyboardListener extends CommandGenerator {
if (vec2.squaredLength(movement) > 0) {
vec2.normalize(movement, movement);
}
this.sendCommandToSubscribers(new MoveActionCommand(movement));
}
private normalize(key: string): string {
return key.toLowerCase();
public destroy() {
removeEventListener('keydown', this.keyDownListener);
removeEventListener('keyup', this.keyUpListener);
removeEventListener('blur', this.blurListener);
}
}

View file

@ -0,0 +1,38 @@
import { vec2 } from 'gl-matrix';
import { CommandGenerator, PrimaryActionCommand, SecondaryActionCommand } from 'shared';
import { Game } from '../game';
export class MouseListener extends CommandGenerator {
constructor(private readonly game: Game) {
super();
addEventListener('mousedown', this.mouseDownListener);
addEventListener('contextmenu', this.contextMenuListener);
}
private mouseDownListener = (event: MouseEvent) => {
const position = this.positionFromEvent(event);
if (event.button === 0) {
this.sendCommandToSubscribers(new PrimaryActionCommand(position));
}
};
private contextMenuListener = (event: MouseEvent) => {
event.preventDefault();
const position = this.positionFromEvent(event);
this.sendCommandToSubscribers(new SecondaryActionCommand(position));
};
private positionFromEvent(event: MouseEvent): vec2 {
return this.game.displayToWorldCoordinates(
vec2.fromValues(event.clientX, event.clientY),
);
}
public destroy() {
removeEventListener('mousedown', this.mouseDownListener);
removeEventListener('contextmenu', this.contextMenuListener);
}
}

View file

@ -0,0 +1,104 @@
import { vec2 } from 'gl-matrix';
import {
CommandGenerator,
SecondaryActionCommand,
MoveActionCommand,
last,
} from 'shared';
import { Game } from '../game';
export class TouchListener extends CommandGenerator {
private static readonly deadZone = 8;
private static readonly deltaScaling = 0.4;
private joystick: HTMLElement;
private joystickButton: HTMLElement;
private isJoystickActive = false;
private touchStartPosition!: vec2;
constructor(private overlay: HTMLElement, private readonly game: Game) {
super();
this.joystick = document.createElement('div');
this.joystick.className = 'joystick';
this.joystickButton = document.createElement('div');
this.joystick.appendChild(this.joystickButton);
addEventListener('touchstart', this.touchStartListener);
addEventListener('touchmove', this.touchMoveListener);
addEventListener('touchend', this.touchEndListener);
}
private touchStartListener = (event: TouchEvent) => {
event.preventDefault();
if (this.isJoystickActive) {
const center = vec2.fromValues(
last(event.touches)!.clientX,
last(event.touches)!.clientY,
);
this.sendCommandToSubscribers(
new SecondaryActionCommand(this.game.displayToWorldCoordinates(center)),
);
} else {
this.touchStartPosition = vec2.fromValues(
event.touches[0].clientX,
event.touches[0].clientY,
);
}
};
private touchMoveListener = (event: TouchEvent) => {
event.preventDefault();
const touchPosition = vec2.fromValues(
event.touches[0].clientX,
event.touches[0].clientY,
);
const delta = vec2.subtract(vec2.create(), touchPosition, this.touchStartPosition);
vec2.scale(delta, delta, TouchListener.deltaScaling);
const deltaLength = vec2.length(delta);
if (!this.isJoystickActive && deltaLength > TouchListener.deadZone) {
this.isJoystickActive = true;
this.overlay.appendChild(this.joystick);
this.joystickButton.style.transform = `translateX(-50%) translateY(-50%)`;
this.joystick.style.transform = `translateX(${this.touchStartPosition.x}px) translateY(${this.touchStartPosition.y}px) translateX(-50%) translateY(-50%)`;
}
const maxLength = 20;
vec2.scale(delta, delta, Math.min(1, maxLength / deltaLength));
this.joystickButton.style.transform = `translateX(${delta.x}px) translateY(${delta.y}px) translateX(-50%) translateY(-50%)`;
vec2.set(delta, delta.x, -delta.y);
if (deltaLength > TouchListener.deadZone) {
this.sendCommandToSubscribers(new MoveActionCommand(vec2.normalize(delta, delta)));
} else {
this.sendCommandToSubscribers(new MoveActionCommand(vec2.create()));
}
};
private touchEndListener = (event: TouchEvent) => {
event.preventDefault();
if (!this.isJoystickActive) {
const center = vec2.fromValues(
event.changedTouches[0].clientX,
event.changedTouches[0].clientY,
);
this.sendCommandToSubscribers(
new SecondaryActionCommand(this.game.displayToWorldCoordinates(center)),
);
} else if (event.touches.length === 0) {
this.isJoystickActive = false;
this.joystick.parentElement?.removeChild(this.joystick);
this.sendCommandToSubscribers(new MoveActionCommand(vec2.create()));
}
};
public destroy() {
removeEventListener('touchstart', this.touchStartListener);
removeEventListener('touchmove', this.touchMoveListener);
removeEventListener('touchend', this.touchEndListener);
}
}

View file

@ -1,8 +0,0 @@
import { vec2 } from 'gl-matrix';
import { Command } from 'shared';
export class MoveToCommand extends Command {
public constructor(public readonly position: vec2) {
super();
}
}

View file

@ -1,8 +0,0 @@
import { Renderer } from 'sdf-2d';
import { Command } from 'shared';
export class RenderCommand extends Command {
public constructor(public readonly renderer: Renderer) {
super();
}
}

View file

@ -1,28 +1,26 @@
import { vec2 } from 'gl-matrix';
import { Renderer, renderNoise } from 'sdf-2d';
import {
broadcastCommands,
deserialize,
TransportEvents,
SetAspectRatioActionCommand,
PlayerInformation,
PlayerDiedCommand,
UpdateOtherPlayerDirections,
clamp,
UpdateGameState,
GameEnd,
GameEndCommand,
CharacterTeam,
ServerAnnouncement,
GameStart,
GameStartCommand,
CommandReceiver,
CommandExecutors,
Command,
} from 'shared';
import io from 'socket.io-client';
import { KeyboardListener } from './commands/generators/keyboard-listener';
import { MouseListener } from './commands/generators/mouse-listener';
import { TouchJoystickListener } from './commands/generators/touch-joystick-listener';
import { CommandReceiverSocket } from './commands/receivers/command-receiver-socket';
import { KeyboardListener } from './commands/keyboard-listener';
import { MouseListener } from './commands/mouse-listener';
import { TouchListener } from './commands/touch-listener';
import { CommandSocket } from './commands/command-socket';
import { startAnimation } from './start-animation';
import { PlayerDecision } from './join-form-handler';
import { GameObjectContainer } from './objects/game-object-container';
@ -38,12 +36,16 @@ export class Game extends CommandReceiver {
public started: Promise<void>;
private resolveStarted!: () => unknown;
private keyboardListener: KeyboardListener;
private mouseListener: MouseListener;
private touchListener: TouchListener;
private declaPlanetCountElement = document.createElement('div');
private redPlanetCountElement = document.createElement('div');
private announcementText = document.createElement('h2');
private progressBar = document.createElement('div');
private arrows: { [id: number]: HTMLElement } = {};
private socketReceiver!: CommandReceiverSocket;
private socketReceiver!: CommandSocket;
constructor(
private readonly playerDecision: PlayerDecision,
@ -56,6 +58,10 @@ export class Game extends CommandReceiver {
this.progressBar.className = 'planet-progress';
this.progressBar.appendChild(this.declaPlanetCountElement);
this.progressBar.appendChild(this.redPlanetCountElement);
this.keyboardListener = new KeyboardListener();
this.mouseListener = new MouseListener(this);
this.touchListener = new TouchListener(this.overlay, this);
}
private initialize() {
@ -96,15 +102,13 @@ export class Game extends CommandReceiver {
commands.forEach((c) => this.sendCommand(c));
});
this.socketReceiver = new CommandReceiverSocket(this.socket);
broadcastCommands(
[
new KeyboardListener(document.body),
new MouseListener(this.canvas, this),
new TouchJoystickListener(this.canvas, this.overlay, this),
],
[this.socketReceiver],
);
this.socketReceiver = new CommandSocket(this.socket);
this.keyboardListener.clearSubscribers();
this.keyboardListener.subscribe(this.socketReceiver);
this.mouseListener.clearSubscribers();
this.mouseListener.subscribe(this.socketReceiver);
this.touchListener.clearSubscribers();
this.touchListener.subscribe(this.socketReceiver);
this.isBetweenGames = false;
@ -123,16 +127,15 @@ export class Game extends CommandReceiver {
protected commandExecutors: CommandExecutors = {
[ServerAnnouncement.type]: (c: ServerAnnouncement) =>
(this.lastAnnouncementText = c.text),
[PlayerDiedCommand.type]: (c: PlayerDiedCommand) => VibrationHandler.vibrate(150),
[UpdateGameState.type]: (c: UpdateGameState) => (this.lastGameState = c),
[GameEnd.type]: (c: GameEnd) => {
[GameEndCommand.type]: (c: GameEndCommand) => {
const team = `<span class="${c.winningTeam}">${c.winningTeam}</span>`;
this.lastAnnouncementText = `Team ${team} won 🎉`;
this.isEnding = true;
},
[UpdateOtherPlayerDirections.type]: (c: UpdateOtherPlayerDirections) =>
(this.lastOtherPlayerDirections = c),
[GameStart.type]: this.initialize.bind(this),
[GameStartCommand.type]: this.initialize.bind(this),
};
private lastOtherPlayerDirections?: UpdateOtherPlayerDirections;
@ -195,18 +198,19 @@ export class Game extends CommandReceiver {
public async start(): Promise<void> {
const noiseTexture = await renderNoise([256, 256], 2, 1);
this.initialize();
await startAnimation(this.canvas, this.gameLoop.bind(this), noiseTexture);
this.socket.close();
this.overlay.innerHTML = '';
this.keyboardListener.destroy();
this.mouseListener.destroy();
this.touchListener.destroy();
}
public displayToWorldCoordinates(p: vec2): vec2 {
const result = this.renderer?.displayToWorldCoordinates(p);
if (!result) {
return vec2.create();
}
return result;
return this.renderer?.displayToWorldCoordinates(p) ?? vec2.create();
}
public aspectRatioChanged(aspectRatio: number) {

View file

@ -1,6 +1,6 @@
import { ServerInformation, serverInformationEndpoint, TransportEvents } from 'shared';
import io from 'socket.io-client';
import { Configuration } from './config/configuration';
import { Configuration } from './configuration';
import parser from 'socket.io-msgpack-parser';
import { SoundHandler, Sounds } from './sound-handler';

View file

@ -1,16 +1,11 @@
import { vec2, vec3 } from 'gl-matrix';
import { CircleLight, Renderer } from 'sdf-2d';
import { CommandExecutors, Id, LampBase, UpdateProperty } from 'shared';
import { RenderCommand } from '../commands/types/render';
import { ViewObject } from './view-object';
export class LampView extends LampBase implements ViewObject {
private light: CircleLight;
protected commandExecutors: CommandExecutors = {
[RenderCommand.type]: (c: RenderCommand) => c.renderer.addDrawable(this.light),
};
constructor(id: Id, center: vec2, color: vec3, lightness: number) {
super(id, center, color, lightness);
this.light = new CircleLight(center, color, lightness);

View file

@ -1,7 +1,6 @@
import { vec2 } from 'gl-matrix';
import { Renderer } from 'sdf-2d';
import { CommandExecutors, Id, Random, PlanetBase, UpdateProperty } from 'shared';
import { RenderCommand } from '../commands/types/render';
import { Id, Random, PlanetBase, UpdateProperty } from 'shared';
import { PlanetShape } from '../shapes/planet-shape';
import { ViewObject } from './view-object';
@ -17,10 +16,6 @@ export class PlanetView extends PlanetBase implements ViewObject {
private shape: PlanetShape;
private ownershipProgess: HTMLElement;
protected commandExecutors: CommandExecutors = {
[RenderCommand.type]: (c: RenderCommand) => c.renderer.addDrawable(this.shape),
};
constructor(id: Id, vertices: Array<vec2>, ownership: number) {
super(id, vertices);
this.shape = new PlanetShape(vertices, ownership);

View file

@ -19,7 +19,6 @@ export class PlayerCharacterView extends PlayerCharacterBase implements ViewObje
private nameElement: HTMLElement = document.createElement('div');
private statsElement: HTMLElement = document.createElement('div');
private healthElement: HTMLElement = document.createElement('div');
private previousHealth;
public isMainCharacter = false;
@ -45,7 +44,6 @@ export class PlayerCharacterView extends PlayerCharacterBase implements ViewObje
this.rightFootExtrapolator = new CircleExtrapolator(this.rightFoot!);
this.headExtrapolator = new CircleExtrapolator(this.head!);
this.previousHealth = this.health;
this.nameElement.className = 'player-tag ' + this.team;
this.nameElement.innerText = this.name;
this.nameElement.appendChild(this.healthElement);
@ -77,17 +75,19 @@ export class PlayerCharacterView extends PlayerCharacterBase implements ViewObje
Sounds.hit,
(0.4 * 2 * (previousHealth - health)) / settings.playerMaxStrength,
);
if (this.isMainCharacter) {
VibrationHandler.vibrate(Math.min(200, (previousHealth - this.health) * 4));
}
}
public kill() {
if (this.isMainCharacter) {
VibrationHandler.vibrate(150);
}
}
public step(deltaTimeInSeconds: number): void {
if (this.previousHealth > this.health) {
if (this.isMainCharacter) {
VibrationHandler.vibrate(Math.min(200, (this.previousHealth - this.health) * 4));
}
this.previousHealth = this.health;
}
this.head! = this.headExtrapolator.getValue(deltaTimeInSeconds);
this.leftFoot! = this.leftFootExtrapolator.getValue(deltaTimeInSeconds);
this.rightFoot! = this.rightFootExtrapolator.getValue(deltaTimeInSeconds);