Files
tankz/src/client/haxe/ru/m/tankz/control/HumanControl.hx

91 lines
2.7 KiB
Haxe

package ru.m.tankz.control;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.Lib;
import haxe.Timer;
import ru.m.tankz.control.ActionConfig;
import ru.m.tankz.control.Control;
import ru.m.tankz.storage.SettingsStorage;
import ru.m.tankz.Type;
class HumanControl extends Control {
@:provide var storage:SettingsStorage;
private var keyBinding:KeyBinding;
private var moveQueue:Array<Int>;
private var shotTimer:Timer;
public function new(playerId:PlayerId, controlIndex:Int) {
super(playerId);
this.keyBinding = storage.getActionConfig(controlIndex).asKeyBinding();
moveQueue = [];
}
override public function start():Void {
super.start();
Lib.current.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
Lib.current.stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
override public function stop():Void {
super.stop();
Lib.current.stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
Lib.current.stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp);
moveQueue = [];
}
private function onKeyDown(event:KeyboardEvent):Void {
if (keyBinding.exists(event.keyCode)) switch (keyBinding.get(event.keyCode)) {
case TankAction.MOVE(direction):
if (moveQueue.indexOf(event.keyCode) == -1) {
moveQueue.unshift(event.keyCode);
updateMove();
}
case TankAction.SHOT:
if (shotTimer == null) {
shotTimer = new Timer(300);
shotTimer.run = shot;
shot();
}
case _:
}
}
private function onKeyUp(event:KeyboardEvent):Void {
if (keyBinding.exists(event.keyCode)) switch (keyBinding.get(event.keyCode)) {
case TankAction.MOVE(direction):
moveQueue.remove(event.keyCode);
updateMove();
case TankAction.SHOT:
if (shotTimer != null) {
shotTimer.stop();
shotTimer = null;
}
case _:
}
}
private function onFocusOut(event:FocusEvent):Void {
moveQueue = [];
updateMove();
}
private function updateMove():Void {
if (moveQueue.length == 0) {
action(TankAction.STOP);
} else {
switch (keyBinding.get(moveQueue[0])) {
case TankAction.MOVE(direction):
action(TankAction.MOVE(direction));
case _:
}
}
}
private function shot():Void {
action(TankAction.SHOT);
}
}