Files
tankz/src/client/haxe/ru/m/tankz/control/HumanControl.hx
2019-10-07 17:29:20 +03:00

119 lines
3.4 KiB
Haxe

package ru.m.tankz.control;
import flash.events.FocusEvent;
import haxe.Timer;
import ru.m.control.DeviceAction;
import ru.m.control.DeviceType;
import ru.m.control.IControlBus;
import ru.m.geom.Direction;
import ru.m.tankz.control.Control;
import ru.m.tankz.storage.SettingsStorage;
import ru.m.tankz.Type;
using haxe.EnumTools.EnumValueTools;
class HumanControl extends Control {
@:provide static var storage:SettingsStorage;
@:provide static var bus:IControlBus;
private var binding:Map<DeviceType, Map<DeviceAction, TankAction>>;
private var moveQueue:Array<Direction>;
private var shotTimers:Map<Int, Timer>;
public function new(playerId:PlayerId, controlIndex:Int) {
super(playerId);
var config = storage.getBinding(controlIndex);
binding = new Map();
for (action in config.keys()) {
var bind = config.get(action);
if (!binding.exists(bind.device)) {
binding.set(bind.device, new Map());
}
binding.get(bind.device).set(bind.action, action);
}
moveQueue = [];
shotTimers = new Map();
}
public function hasDevice(device:DeviceType):Bool {
for (d in binding.keys()) {
if (d.equals(device)) {
return true;
}
}
return false;
}
private function onDeviceAction(device:DeviceType, action:DeviceAction, on:Bool):Void {
if (binding.exists(device) && binding[device].exists(action)) {
toggleAction(binding[device][action], on);
}
}
override public function start():Void {
super.start();
bus.signal.connect(onDeviceAction);
}
override public function stop():Void {
super.stop();
bus.signal.disconnect(onDeviceAction);
moveQueue = [];
for (timer in shotTimers) {
timer.stop();
}
shotTimers = new Map();
}
public function toggleAction(action:TankAction, on:Bool):Void {
switch action {
case TankAction.MOVE(direction):
if (on) {
if (moveQueue.indexOf(direction) == -1) {
moveQueue.unshift(direction);
}
} else {
moveQueue.remove(direction);
}
updateMove();
case TankAction.SHOT(weapon):
if (on) {
if (!shotTimers.exists(weapon)) {
// ToDo: weapon.config.delay
var timer = new Timer(350);
timer.run = shooter(weapon);
timer.run();
shotTimers.set(weapon, timer);
}
} else {
if (shotTimers.exists(weapon)) {
shotTimers.get(weapon).stop();
shotTimers.remove(weapon);
}
}
case TankAction.STOP:
}
}
private function onFocusOut(event:FocusEvent):Void {
moveQueue = [];
updateMove();
}
private function updateMove():Void {
if (moveQueue.length == 0) {
action(STOP);
} else {
action(MOVE(moveQueue[0]));
}
}
private function shooter(weapon:Int):Void -> Void {
return function():Void {
action(SHOT(weapon));
}
}
}