Commit 76f7a8ac authored by Pablo R. Mier's avatar Pablo R. Mier

Probability of change checked in a timer

parent 3900f33e
......@@ -31,11 +31,11 @@ function bound_value(v, min_v, max_v) {
invadersApp.Invader = function (ctx, genes, x, y) {
var game = ctx.game;
x = x || game.world.randomX;
y = y || game.world.randomY % (game.world.height - WALL_MARGIN * 1.5);
Phaser.Sprite.call(this, game, x, y, 'invader');
game.physics.enable(this, Phaser.Physics.ARCADE);
this.game = ctx.game;
x = x || this.game.world.randomX;
y = y || this.game.world.randomY % (this.game.world.height - WALL_MARGIN * 1.5);
Phaser.Sprite.call(this, this.game, x, y, 'invader');
this.game.physics.enable(this, Phaser.Physics.ARCADE);
// Initialize genes by getting the default values from settings.json
this.genes = genes || function () {
......@@ -71,7 +71,20 @@ invadersApp.Invader = function (ctx, genes, x, y) {
this.body.bounce.set(1);
// Used to control the probability of x-y change in direction
this.lastTimeChanged = 0;
// this.lastTimeChanged = 0;
// Event loop to check the probability of changing directions (each 10ms)
// TODO: Move this timer to Game.js?
this.changeTimer = this.game.time.events.loop(10, function () {
if (this.alive && this.game != null) {
if (this.game.rnd.frac() < this.genes['x_prob_change_dir']) {
this.body.velocity.x = -this.body.velocity.x;
}
if (this.game.rnd.frac() < this.genes['y_prob_change_dir']) {
this.body.velocity.y = -this.body.velocity.y;
}
}
}, this);
this.fitness = 0;
......@@ -79,23 +92,11 @@ invadersApp.Invader = function (ctx, genes, x, y) {
this.shieldGraphics = this.game.make.graphics(0, 0);
// Add the invader to the game (move this outside this class?)
game.add.existing(this);
this.game.add.existing(this);
};
invadersApp.Invader.prototype = Object.create(Phaser.Sprite.prototype);
invadersApp.Invader.prototype.constructor = invadersApp.Invader;
invadersApp.Invader.prototype.update = function () {
// Decide if it is time to change direction.
if (this.game.time.now > this.lastTimeChanged + DIR_CHANGE_MIN_TIME) {
this.lastTimeChanged = this.game.time.now;
if (this.game.rnd.frac() < this.genes['x_prob_change_dir']) {
this.body.velocity.x = -this.body.velocity.x;
}
if (this.game.rnd.frac() < this.genes['y_prob_change_dir']) {
this.body.velocity.y = -this.body.velocity.y;
}
}
};
invadersApp.Invader.prototype.drawShield = function (color) {
this.shieldGraphics.clear();
this.shieldGraphics.lineStyle(1, color, 1);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment