Last active
April 30, 2024 10:32
-
-
Save michaelavila/6046184 to your computer and use it in GitHub Desktop.
Fight Code Game robot barebones statemachine bots
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Store all of the robots and their states so | |
// that they can be referenced throughout the robots | |
var ROBOT_STATES = {} | |
// states | |
// find and attack enemy with reckless abandon | |
var SEEK = { | |
onIdle: function(ev) { | |
ev.robot.turn(360); | |
}, | |
onScannedRobot: function(ev) { | |
changeState(ev.robot, DESTROY); | |
} | |
} | |
var DESTROY = { | |
onIdle: function(ev) { | |
changeState(ev.robot, SEEK); | |
}, | |
onScannedRobot: function(ev) { | |
if (friends(ev.robot, ev.scannedRobot)) { | |
return; | |
} | |
ev.robot.move(); | |
ev.robot.fire(); | |
} | |
} | |
// common state behavior | |
function friends(robot1, robot2) { | |
return robot1.parentId == robot2.id || robot1.id == robot2.parentId; | |
} | |
// wiring robots to states | |
var Robot = function(robot) { robot.clone(); } | |
Robot.prototype.onIdle = function(ev) { | |
state(ev.robot).onIdle(ev); | |
}; | |
Robot.prototype.onScannedRobot = function(ev) { | |
state(ev.robot).onScannedRobot(ev); | |
}; | |
Robot.prototype.onHitByBullet = function(ev) { | |
state(ev.robot).onHitByBullet(ev); | |
}; | |
Robot.prototype.onWallCollision = function(ev) { | |
state(ev.robot).onWallCollision(ev); | |
}; | |
Robot.prototype.onRobotCollision = function(ev) { | |
state(ev.robot).onRobotCollision(ev); | |
}; | |
// state machine | |
function changeState(robot, state) { | |
ROBOT_STATES[robot] = state; | |
bindEvents(robot, state); | |
} | |
function bindEvents(robot, state) { | |
var all_events = [ | |
'onIdle', | |
'onScannedRobot', | |
'onRobotCollision', | |
'onWallCollision', | |
'onHitByBullet' | |
]; | |
for (var event in all_events) { | |
if (event in state) { | |
robot.listen(event); | |
} else { | |
robot.ignore(event); | |
} | |
} | |
} | |
function determineFirstState(robot) { | |
return SEEK; | |
} | |
function state(robot) { | |
if (!(robot in ROBOT_STATES)) { | |
// set up initial state | |
ROBOT_STATES[robot] = determineFirstState(robot); | |
} | |
return ROBOT_STATES[robot]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment