cylon/examples/conway_sphero/fluent-conway_sphero.js

95 lines
1.7 KiB
JavaScript
Raw Normal View History

2014-12-14 08:19:25 +08:00
"use strict";
var Cylon = require("../..");
var Green = 0x0000FF,
Red = 0xFF0000;
var bots = {
2014-12-14 08:19:25 +08:00
"Thelma": "/dev/rfcomm0",
"Louise": "/dev/rfcomm1",
"Grace": "/dev/rfcomm2",
"Ada": "/dev/rfcomm3"
};
Object.keys(bots).forEach(function(name) {
var port = bots[name];
2014-12-14 08:19:25 +08:00
var robot = Cylon.robot({ name: name });
2014-11-26 01:45:20 +08:00
2014-12-14 08:19:25 +08:00
robot.connection("sphero", { adaptor: "sphero", port: port });
robot.device("sphero", { driver: "sphero" });
robot.move = function() {
2014-09-30 03:15:24 +08:00
robot.sphero.roll(60, Math.floor(Math.random() * 360));
};
robot.born = function() {
2014-09-30 03:15:24 +08:00
robot.contacts = 0;
robot.age = 0;
robot.life();
robot.move();
};
robot.life = function() {
2014-09-30 03:15:24 +08:00
robot.alive = true;
robot.sphero.setRGB(Green);
};
robot.death = function() {
2014-09-30 03:15:24 +08:00
robot.alive = false;
robot.sphero.setRGB(Red);
robot.sphero.stop();
};
robot.enoughContacts = function() {
2014-09-30 03:15:24 +08:00
return robot.contacts >= 2 && robot.contacts < 7;
};
robot.birthday = function() {
2014-09-30 03:15:24 +08:00
robot.age += 1;
2014-09-30 03:15:24 +08:00
if (robot.alive) {
2014-12-14 08:19:25 +08:00
var str = "Happy birthday, ";
str += robot.name;
str += ". You are ";
str += robot.age;
str += " and had ";
str += robot.contacts;
str += " contacts.";
console.log(str);
}
2014-09-30 03:15:24 +08:00
if (robot.enoughContacts()) {
if (!robot.alive) {
robot.born();
}
} else {
2014-09-30 03:15:24 +08:00
robot.death();
}
2014-09-30 03:15:24 +08:00
robot.contacts = 0;
};
2014-12-14 08:19:25 +08:00
robot.on("ready", function() {
2014-09-30 03:15:24 +08:00
robot.born();
2014-12-14 08:19:25 +08:00
robot.sphero.on("collision", function() {
2014-09-30 03:15:24 +08:00
robot.contacts += 1;
});
every((3).seconds(), function() {
2014-09-30 03:15:24 +08:00
if (robot.alive) {
robot.move();
}
});
every((10).seconds(), function() {
2014-09-30 03:15:24 +08:00
robot.birthday();
});
});
});
Cylon.start();