Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge branch 'experiments/fsm'
  • Loading branch information
gonzalodelgado committed Jun 4, 2020
2 parents 7d0b4fb + 11938be commit 14262f4
Show file tree
Hide file tree
Showing 5 changed files with 365 additions and 258 deletions.
1 change: 1 addition & 0 deletions index.html
Expand Up @@ -33,6 +33,7 @@
<script src="js/BikerEnemy.js"></script>
<script src="js/EnemyAlienGuard.js"></script>
<script src="js/PlayerColliderManager.js"></script>
<script src="js/FSM.js"></script>
<script src="js/Player.js"></script>
<script src="js/EnemyMech.js"></script>
<script src="js/Camera.js"></script>
Expand Down
43 changes: 43 additions & 0 deletions js/FSM.js
@@ -0,0 +1,43 @@
function FSM(initial) {
const NOSTATE = 'none';
let currentState = NOSTATE;
const states = {};
const transitions = [];

this.addState = function(name, enterFunc, updateFunc, exitFunc) {
states[name] = {
enter: enterFunc,
update: updateFunc,
exit: exitFunc,
};
};

this.addTransition = function(statesFrom, stateTo, conditionFunc) {
transitions.push({
from: statesFrom,
to: stateTo,
cond: conditionFunc,
});
};

this.update = function(deltaTime) {
if (currentState == NOSTATE) {
currentState = initial;
states[currentState].enter(deltaTime);
}
states[currentState].update(deltaTime);
for (let transition of transitions) {
for (let fromState of transition.from) {
if (fromState == currentState && transition.cond()) {
if (DEBUG) {
console.log('FSM: switch from', fromState, 'to', transition.to);
}
states[currentState].exit(deltaTime);
currentState = transition.to;
states[currentState].enter(deltaTime);
return;
}
}
}
};
}
38 changes: 37 additions & 1 deletion js/Input.js
Expand Up @@ -207,4 +207,40 @@ function mouseInside(x, y, width, height) {

function pointInside(pointX, pointY, x, y, width, height) {
return pointX > x && pointX < x + width && pointY > y && pointY < y + height;
}
}

function getKeyChecker(keys) {
const keyChecker = function() {
for (let i=0; i<heldButtons.length; i++) {
for (let j=0; j<keys.length; j++) {
if (heldButtons[i] == keys[j]) {
return true;
}
}
}
return false;
};
return keyChecker;
}

function getExclusiveKeyChecker(keys) {
const keysSet = new Set(keys)
const exclusiveKeyChecker = function() {
if (heldButtons.length != 1) {
return false;
}
const heldSet = new Set(heldButtons);
for (let key of keysSet) {
heldSet.delete(key);
if (heldSet.size == 0) {
break;
}
}
return heldSet.size == 0;
};
return exclusiveKeyChecker;
}

function checkForPressedKeys(keys) {
return getKeyChecker(keys)();
}

0 comments on commit 14262f4

Please sign in to comment.