<commit_before>/**
Author: Alex Ball
screeps-scripts

scripts for the JavaScript-based MMO Screeps.
*/

const towerFunctions = require('tower');

const spawnFunctions = require('spawn');
const roomFunctions = require('room');
const roomConstruction = require('roomConstruction');
const creepBody = require('creepBody');

const roleDefender = require("role.defender");
const roleHarvester = require('role.harvester');
const roleUpgrader = require('role.upgrader');
const roleBuilder = require('role.builder');
const roleMiner = require('role.miner');
const roleCourier = require('role.courier');
const roleClaimer = require('role.claimer');
const roleColonist = require('role.colonist');

const roles = {
  defender: roleDefender,
  harvester: roleHarvester,
  upgrader: roleUpgrader,
  builder: roleBuilder,
  miner: roleMiner,
  courier: roleCourier,
  claimer: roleClaimer,
  colonist: roleColonist,
};

/**Diagnostic and utility functions*/
const utilityFunctions = require('functions');

//Begin main loop.
module.exports.loop = function() {
  utilityFunctions.respawn();
  utilityFunctions.clearDeadCreepMemory();
  utilityFunctions.clearMissingFlagMemory();

  // cleanup dead claimer
  if (Memory.claimerName && !Game.creeps[Memory.claimerName]) {
    Memory.claimerName = undefined;
  }

  // cleanup dead colonists
  for (let name in Memory.colonistNames) {
    if (!Game.creeps[name]) {
      delete Memory.colonistNames[name];
    }
  }

  towerFunctions.runTowerLogic();

  for (let roomName in Game.rooms) {
    let room = Game.rooms[roomName];

    roomFunctions.checkForSources(room);

    // if there is a newClaim in one of my rooms, delete it and replace
    // it with a newColony if there is not already a newColony.
    let claimFlag = Game.flags['newClaim'];
    if (claimFlag &&
      !Game.flags['newColony'] &&
      Game.rooms[claimFlag.pos.roomName] &&
      Game.rooms[claimFlag.pos.roomName].controller &&
      Game.rooms[claimFlag.pos.roomName].controller.my) {
      // replace newClaim with newColony in the same position
      claimFlag.pos.createFlag('newColony', COLOR_PURPLE);
      claimFlag.remove();
    }

    // if there is a newColony in one of my rooms, check if
    // there is a spawn in it. if so, then delete the newColony flag.
    // If not, check if there is a
    // constructionSite for a spawn in it. if not, place a constructionSite
    // on the position of the newColony flag.
    let colonyFlag = Game.flags['newColony'];
    if (colonyFlag) {
      if (!colonyFlag.room.controller.my) {
        // If the colony is in a room that is not mine, abandon it.
        console.log('Colony room not owned by me. Abandoning colony: ' + colonyFlag.room.name);
        Memory.colonySpawnSiteID = undefined;
        colonyFlag.remove();
      } else if (!Memory.colonySpawnSiteID) {
        // If the spawn constructionSite is not in memory, get it.
        colonyFlag.pos.createConstructionSite(STRUCTURE_SPAWN);
        let colonySpawnSites = colonyFlag.room.find(FIND_MY_CONSTRUCTION_SITES, {
          filter: {
            structureType: STRUCTURE_SPAWN
          }
        });
        if (colonySpawnSites.length && colonySpawnSites[0].id) {
          Memory.colonySpawnSiteID = colonySpawnSites[0].id;
        }
      } else if (!Game.getObjectById(Memory.colonySpawnSiteID)) {
        // If we can't find the spawn constructionSite, it either finished
        // or was destroyed. Either way, delete the colony flag.
        console.log('Colony spawn finished/destroyed. removing colony flag in: ' + colonyFlag.room.name);
        Memory.colonySpawnSiteID = undefined;
        colonyFlag.remove();
      }
    }

    let creepsOfRole = {};

    for (let roleName in roles) {
      creepsOfRole[roleName] = {};
    }

    let roomCreeps = room.find(FIND_MY_CREEPS);

    for (let creepIndex in roomCreeps) {
      let creep = roomCreeps[creepIndex];
      if (roles[creep.memory.role]) {
        creepsOfRole[creep.memory.role][creep.name] = creep.id;
        roles[creep.memory.role].run(creep);
      }
    }

    if (room.controller && room.controller.my) {
      utilityFunctions.checkForLevelUp(room);

      roomFunctions.createTowerAssignments(room);

      let spawns = room.find(FIND_MY_STRUCTURES, {
        filter: {
          structureType: STRUCTURE_SPAWN
        }
      });

      for (let spawnIndex in spawns) {
        let spawn = spawns[spawnIndex];
        let sourceIdMissingMiner = roomFunctions.findSourceIdMissingMiner(room);

        if (_.size(room.find(FIND_HOSTILE_CREEPS)) > 0 && _.size(creepsOfRole.defender) < 2) {
          spawnFunctions.createCreepWithRole(spawn, "defender", creepBody.defender);
        } else if (_.size(Game.creeps) < 2) {
          spawnFunctions.createCreepWithRole(spawn, "harvester", creepBody.harvester);
        } else if (_.size(creepsOfRole.courier) < 1) {
          spawnFunctions.createCreepWithRole(spawn, "courier", creepBody.courier);
        } else if (sourceIdMissingMiner) {
          let minerName = roomFunctions.buildMiner(room, sourceIdMissingMiner, spawn, creepBody.miner);
          if (minerName == ERR_NOT_ENOUGH_ENERGY && _.size(creepsOfRole.miner) < 1 && _.size(creepsOfRole.harvester) < 2) {
            spawnFunctions.createCreepWithRole(spawn, "harvester", creepBody.harvester);
          }
        } else if (_.size(creepsOfRole.courier) < 3) {
          spawnFunctions.createCreepWithRole(spawn, "courier", creepBody.courier);
        } else if (_.size(room.find(FIND_MY_CONSTRUCTION_SITES)) > 0 && _.size(creepsOfRole.builder) < 2) {
          spawnFunctions.createCreepWithRole(spawn, "builder", creepBody.builder);
        } else if (_.size(creepsOfRole.upgrader) < 2) {
          spawnFunctions.createCreepWithRole(spawn, "upgrader", creepBody.upgrader);
        } else if (Game.flags['newClaim'] && !Memory.claimerName) {
          let claimerName = spawnFunctions.createCreepWithRole(spawn, 'claimer', creepBody.claimer);
          if (typeof claimerName == 'string') {
            Memory.claimerName = claimerName;
          }
        } else if (Game.flags['newColony'] && _.size(Memory.colonistNames) < 3) {
          let colonistName = spawnFunctions.createCreepWithRole(spawn, 'colonist', creepBody.colonist);
          if (typeof colonistName == 'string') {
            Memory.colonistNames[colonistName] = colonistName;
          }
        }

        spawnFunctions.displayCreateCreepVisual(spawn);

        roomConstruction.placeUpgraderContainer(room, spawn.pos);

        roomConstruction.addExtensionsToRoom(room, spawn.pos);

        roomConstruction.placeTowers(room, spawn.pos);
      }
    }
  }
};
<commit_msg>Added myroomcount by counting owned rooms. This is used to check if we have enough GCL to claim a room (do not build claimers if we cannot claim).<commit_after>/**
Author: Alex Ball
screeps-scripts

scripts for the JavaScript-based MMO Screeps.
*/

const towerFunctions = require('tower');

const spawnFunctions = require('spawn');
const roomFunctions = require('room');
const roomConstruction = require('roomConstruction');
const creepBody = require('creepBody');

const roleDefender = require("role.defender");
const roleHarvester = require('role.harvester');
const roleUpgrader = require('role.upgrader');
const roleBuilder = require('role.builder');
const roleMiner = require('role.miner');
const roleCourier = require('role.courier');
const roleClaimer = require('role.claimer');
const roleColonist = require('role.colonist');

const roles = {
  defender: roleDefender,
  harvester: roleHarvester,
  upgrader: roleUpgrader,
  builder: roleBuilder,
  miner: roleMiner,
  courier: roleCourier,
  claimer: roleClaimer,
  colonist: roleColonist,
};

/**Diagnostic and utility functions*/
const utilityFunctions = require('functions');

//Begin main loop.
module.exports.loop = function() {
  utilityFunctions.respawn();
  utilityFunctions.clearDeadCreepMemory();
  utilityFunctions.clearMissingFlagMemory();

  // cleanup dead claimer
  if (Memory.claimerName && !Game.creeps[Memory.claimerName]) {
    Memory.claimerName = undefined;
  }

  // cleanup dead colonists
  for (let name in Memory.colonistNames) {
    if (!Game.creeps[name]) {
      delete Memory.colonistNames[name];
    }
  }

  // count my rooms (used for determining if I can expand)
  let myRooms = _.filter(Game.rooms, (room) => {
    return room.controller && room.controller.my;
  });
  let myRoomCount = _.size(myRooms);

  towerFunctions.runTowerLogic();

  for (let roomName in Game.rooms) {
    let room = Game.rooms[roomName];

    roomFunctions.checkForSources(room);

    // if there is a newClaim in one of my rooms, delete it and replace
    // it with a newColony if there is not already a newColony.
    let claimFlag = Game.flags['newClaim'];
    if (claimFlag &&
      !Game.flags['newColony'] &&
      Game.rooms[claimFlag.pos.roomName] &&
      Game.rooms[claimFlag.pos.roomName].controller &&
      Game.rooms[claimFlag.pos.roomName].controller.my) {
      // replace newClaim with newColony in the same position
      claimFlag.pos.createFlag('newColony', COLOR_PURPLE);
      claimFlag.remove();
    }

    // if there is a newColony in one of my rooms, check if
    // there is a spawn in it. if so, then delete the newColony flag.
    // If not, check if there is a
    // constructionSite for a spawn in it. if not, place a constructionSite
    // on the position of the newColony flag.
    let colonyFlag = Game.flags['newColony'];
    if (colonyFlag) {
      if (!colonyFlag.room.controller.my) {
        // If the colony is in a room that is not mine, abandon it.
        console.log('Colony room not owned by me. Abandoning colony: ' + colonyFlag.room.name);
        Memory.colonySpawnSiteID = undefined;
        colonyFlag.remove();
      } else if (!Memory.colonySpawnSiteID) {
        // If the spawn constructionSite is not in memory, get it.
        colonyFlag.pos.createConstructionSite(STRUCTURE_SPAWN);
        let colonySpawnSites = colonyFlag.room.find(FIND_MY_CONSTRUCTION_SITES, {
          filter: {
            structureType: STRUCTURE_SPAWN
          }
        });
        if (colonySpawnSites.length && colonySpawnSites[0].id) {
          Memory.colonySpawnSiteID = colonySpawnSites[0].id;
        }
      } else if (!Game.getObjectById(Memory.colonySpawnSiteID)) {
        // If we can't find the spawn constructionSite, it either finished
        // or was destroyed. Either way, delete the colony flag.
        console.log('Colony spawn finished/destroyed. removing colony flag in: ' + colonyFlag.room.name);
        Memory.colonySpawnSiteID = undefined;
        colonyFlag.remove();
      }
    }

    let creepsOfRole = {};

    for (let roleName in roles) {
      creepsOfRole[roleName] = {};
    }

    let roomCreeps = room.find(FIND_MY_CREEPS);

    for (let creepIndex in roomCreeps) {
      let creep = roomCreeps[creepIndex];
      if (roles[creep.memory.role]) {
        creepsOfRole[creep.memory.role][creep.name] = creep.id;
        roles[creep.memory.role].run(creep);
      }
    }

    if (room.controller && room.controller.my) {
      utilityFunctions.checkForLevelUp(room);

      roomFunctions.createTowerAssignments(room);

      let spawns = room.find(FIND_MY_STRUCTURES, {
        filter: {
          structureType: STRUCTURE_SPAWN
        }
      });

      for (let spawnIndex in spawns) {
        let spawn = spawns[spawnIndex];
        let sourceIdMissingMiner = roomFunctions.findSourceIdMissingMiner(room);

        if (_.size(room.find(FIND_HOSTILE_CREEPS)) > 0 && _.size(creepsOfRole.defender) < 2) {
          spawnFunctions.createCreepWithRole(spawn, "defender", creepBody.defender);
        } else if (_.size(Game.creeps) < 2) {
          spawnFunctions.createCreepWithRole(spawn, "harvester", creepBody.harvester);
        } else if (_.size(creepsOfRole.courier) < 1) {
          spawnFunctions.createCreepWithRole(spawn, "courier", creepBody.courier);
        } else if (sourceIdMissingMiner) {
          let minerName = roomFunctions.buildMiner(room, sourceIdMissingMiner, spawn, creepBody.miner);
          if (minerName == ERR_NOT_ENOUGH_ENERGY && _.size(creepsOfRole.miner) < 1 && _.size(creepsOfRole.harvester) < 2) {
            spawnFunctions.createCreepWithRole(spawn, "harvester", creepBody.harvester);
          }
        } else if (_.size(creepsOfRole.courier) < 3) {
          spawnFunctions.createCreepWithRole(spawn, "courier", creepBody.courier);
        } else if (_.size(room.find(FIND_MY_CONSTRUCTION_SITES)) > 0 && _.size(creepsOfRole.builder) < 2) {
          spawnFunctions.createCreepWithRole(spawn, "builder", creepBody.builder);
        } else if (_.size(creepsOfRole.upgrader) < 2) {
          spawnFunctions.createCreepWithRole(spawn, "upgrader", creepBody.upgrader);
        } else if (myRoomCount < Game.gcl.level && Game.flags['newClaim'] && !Memory.claimerName) {
          let claimerName = spawnFunctions.createCreepWithRole(spawn, 'claimer', creepBody.claimer);
          if (typeof claimerName == 'string') {
            Memory.claimerName = claimerName;
          }
        } else if (Game.flags['newColony'] && _.size(Memory.colonistNames) < 3) {
          let colonistName = spawnFunctions.createCreepWithRole(spawn, 'colonist', creepBody.colonist);
          if (typeof colonistName == 'string') {
            Memory.colonistNames[colonistName] = colonistName;
          }
        }

        spawnFunctions.displayCreateCreepVisual(spawn);

        roomConstruction.placeUpgraderContainer(room, spawn.pos);

        roomConstruction.addExtensionsToRoom(room, spawn.pos);

        roomConstruction.placeTowers(room, spawn.pos);
      }
    }
  }
};
<|endoftext|>


<commit_before>var api = require('./lib/api');
var sub = api.get_redis_client();
var redis = api.get_redis_client();

api.register_commands('semantics.js', []);

sub.subscribe('in');
sub.on('message', function(channel, message) {
    var msg = JSON.parse(message);
    if (msg.version == 1 && msg.type == 'privmsg') {
        redis.get('zenircbot:nick', function(err, nick) {
            if (msg.data.message.indexOf(nick + ': ') == 0) {
                directed_message(msg.data.message,
                                 msg.data.message.substr(nick.length+2),
                                 msg.data.sender,
                                 msg.data.channel);
            } else if (msg.data.message.indexOf('!') == 0) {
                directed_message(msg.data.message,
                                 msg.data.message.substr(1),
                                 msg.data.sender,
                                 msg.data.channel);
            } else if (msg.data.channel == msg.data.sender) {
                directed_message(msg.data.message,
                                 msg.data.message,
                                 msg.data.sender,
                                 msg.data.channel);

            }
        });
    }
});

function directed_message(raw_message, message, sender, channel) {
    redis.publish('in', JSON.stringify({
        version: 1,
        type: 'directed_privmsg',
        data: {
            channel: channel,
            raw_message: raw_message,
            message: message,
            sender: sender
        }
    }));
}
<commit_msg>semantics.js converted to use new libraries<commit_after>var api = require('zenircbot-api');
var bot_config = api.load_config('../bot.json');
var zen = new api.ZenIRCBot(bot_config.redis.host,
                            bot_config.redis.port,
                            bot_config.redis.db);
var sub = zen.get_redis_client();

zen.register_commands('semantics.js', []);

sub.subscribe('in');
sub.on('message', function(channel, message) {
    var msg = JSON.parse(message);
    if (msg.version == 1 && msg.type == 'privmsg') {
        zen.redis.get('zenircbot:nick', function(err, nick) {
            if (msg.data.message.indexOf(nick + ': ') == 0) {
                directed_message(msg.data.message,
                                 msg.data.message.substr(nick.length+2),
                                 msg.data.sender,
                                 msg.data.channel);
            } else if (msg.data.message.indexOf('!') == 0) {
                directed_message(msg.data.message,
                                 msg.data.message.substr(1),
                                 msg.data.sender,
                                 msg.data.channel);
            } else if (msg.data.channel == msg.data.sender) {
                directed_message(msg.data.message,
                                 msg.data.message,
                                 msg.data.sender,
                                 msg.data.channel);

            }
        });
    }
});

function directed_message(raw_message, message, sender, channel) {
    zen.redis.publish('in', JSON.stringify({
        version: 1,
        type: 'directed_privmsg',
        data: {
            channel: channel,
            raw_message: raw_message,
            message: message,
            sender: sender
        }
    }));
}
<|endoftext|>


<commit_before>
include('helma/functional');
require('core/string');

export('Storable', 'setStore');

importPackage(org.mozilla.javascript);

var typeRegistry = {};
var __shared__ = true;

// must be set to a store implementation using Storable.setStoreImplementation()
var store;

// TODO make store a Storable argument instead of a module variable
function Storable(type, arg) {

    if (!store) {
        throw new Error("Store implementation not set. Use one of the helma/storage/* submodules!");
    }

    // if called with one argument, return a constructor for a concrete type.
    if (arguments.length == 1) {
        if (type in typeRegistry) {
            return typeRegistry[type];
        }
        var ctor = bindArguments(Storable, type);
        ctor.all = bindArguments(store.all, type);
        ctor.get = bindArguments(store.get, type);
        ctor.query = bindArguments(store.query, type);
        ctor.prototype = Object.create(Storable.prototype);
        typeRegistry[type] = ctor;
        return ctor;
    }

    // if a constructor is registered make sure we use it to get the
    // right prototype chain on the instance object
    if (type in typeRegistry && !(this instanceof typeRegistry[type])) {
        return new typeRegistry[type](arg);
    }

    // arg must be one of these, and we have methods to convert from one to the other:
    var key, entity, props;

    function ensureEntity() {
        if (!entity) {
            entity = store.getEntity(type, arg);
        }
        return entity;
    }

    function ensureKey() {
        if (!key) {
            key = store.getKey(type, arg) || store.getKey(type, ensureEntity());
        }
        return key;
    }

    function ensureProps() {
        if (!props) {
            props = store.getProps(type, arg) || store.getProps(type, ensureEntity());
        }
        return props;
    }

    var storable = new JavaAdapter(NativeObject, {
        get: function(id, start) {
            if (this.super$get(id, start) != Scriptable.NOT_FOUND) {
                return this.super$get(id, start);
            } else if (ensureProps()) {
                return props[id];
            }
            return Scriptable.NOT_FOUND;
        },

        put: function(id, start, value) {
            if (typeof value == "function") {
                return this.super$put(id, start, value);
            } else if (ensureProps()) {
                props[id] = value;
            }
        },

        has: function(id, start) {
            return this.super$has(id, start) ||
                   (ensureProps() && id in props);
        },

        "delete": function(id) {
            if (ensureProps() && id in props) {
                delete(props[id]);
            } else {
                this.super$delete(id);
            }
        },

        getIds: function() {
            var ids = this.super$getIds().concat();
            if (ensureProps()) {
                for (var id in props) {
                    ids.push(id);
                }
            }
            return ids;
        },

        equivalentValues: function(other) {
            if (other == this) {
                return true;
            }
            if (other instanceof Storable && ensureKey() && store.equalKeys(key, other._key)) {
                return true;
            }
            return Scriptable.NOT_FOUND;
        },

        getPrototype: function() {
            return typeRegistry[type].prototype;
        }
    });

    Object.defineProperty(storable, "save", {
        value: function(transaction) {
            if (ensureProps() && ensureEntity()) {
                store.save(props, entity, transaction);
            } else {
                throw Error("Error creating properties or entity " + props + " // " + entity);
            }
        }
    });

    Object.defineProperty(storable, "remove", {
        value: function(transaction) {
            if (ensureKey()) {
                store.remove(key, transaction);
            }
        }
    });

    Object.defineProperty(storable, "_key", {
        get: function() {
            if (ensureKey()) {
                return key;
            }
            throw Error("Can't get key from " + arg);
        }
    });

    Object.defineProperty(storable, "_id", {
        get: function() {
            if (ensureKey()) {
                return store.getId(key);
            }
            throw Error("Can't get id from " + arg);
        }
    });

    return storable;
}

Storable.setStoreImplementation = function(storeImpl) {
    store = storeImpl;
}<commit_msg>Undo previous change to return Scriptable.NOT_FOUND on undefined properties<commit_after>
include('helma/functional');
require('core/string');

export('Storable', 'setStore');

importPackage(org.mozilla.javascript);

var typeRegistry = {};
var __shared__ = true;

// must be set to a store implementation using Storable.setStoreImplementation()
var store;

// TODO make store a Storable argument instead of a module variable
function Storable(type, arg) {

    if (!store) {
        throw new Error("Store implementation not set. Use one of the helma/storage/* submodules!");
    }

    // if called with one argument, return a constructor for a concrete type.
    if (arguments.length == 1) {
        if (type in typeRegistry) {
            return typeRegistry[type];
        }
        var ctor = bindArguments(Storable, type);
        ctor.all = bindArguments(store.all, type);
        ctor.get = bindArguments(store.get, type);
        ctor.query = bindArguments(store.query, type);
        ctor.prototype = Object.create(Storable.prototype);
        typeRegistry[type] = ctor;
        return ctor;
    }

    // if a constructor is registered make sure we use it to get the
    // right prototype chain on the instance object
    if (type in typeRegistry && !(this instanceof typeRegistry[type])) {
        return new typeRegistry[type](arg);
    }

    // arg must be one of these, and we have methods to convert from one to the other:
    var key, entity, props;

    function ensureEntity() {
        if (!entity) {
            entity = store.getEntity(type, arg);
        }
        return entity;
    }

    function ensureKey() {
        if (!key) {
            key = store.getKey(type, arg) || store.getKey(type, ensureEntity());
        }
        return key;
    }

    function ensureProps() {
        if (!props) {
            props = store.getProps(type, arg) || store.getProps(type, ensureEntity());
        }
        return props;
    }

    var storable = new JavaAdapter(NativeObject, {
        get: function(id, start) {
            if (this.super$get(id, start) != Scriptable.NOT_FOUND) {
                return this.super$get(id, start);
            } else if (ensureProps()) {
                var value = props[id];
                return (value === undefined) ? Scriptable.NOT_FOUND : value;
            }
            return Scriptable.NOT_FOUND;
        },

        put: function(id, start, value) {
            if (typeof value == "function") {
                return this.super$put(id, start, value);
            } else if (ensureProps()) {
                props[id] = value;
            }
        },

        has: function(id, start) {
            return this.super$has(id, start) ||
                   (ensureProps() && id in props);
        },

        "delete": function(id) {
            if (ensureProps() && id in props) {
                delete(props[id]);
            } else {
                this.super$delete(id);
            }
        },

        getIds: function() {
            var ids = this.super$getIds().concat();
            if (ensureProps()) {
                for (var id in props) {
                    ids.push(id);
                }
            }
            return ids;
        },

        equivalentValues: function(other) {
            if (other == this) {
                return true;
            }
            if (other instanceof Storable && ensureKey() && store.equalKeys(key, other._key)) {
                return true;
            }
            return Scriptable.NOT_FOUND;
        },

        getPrototype: function() {
            return typeRegistry[type].prototype;
        }
    });

    Object.defineProperty(storable, "save", {
        value: function(transaction) {
            if (ensureProps() && ensureEntity()) {
                store.save(props, entity, transaction);
            } else {
                throw Error("Error creating properties or entity " + props + " // " + entity);
            }
        }
    });

    Object.defineProperty(storable, "remove", {
        value: function(transaction) {
            if (ensureKey()) {
                store.remove(key, transaction);
            }
        }
    });

    Object.defineProperty(storable, "_key", {
        get: function() {
            if (ensureKey()) {
                return key;
            }
            throw Error("Can't get key from " + arg);
        }
    });

    Object.defineProperty(storable, "_id", {
        get: function() {
            if (ensureKey()) {
                return store.getId(key);
            }
            throw Error("Can't get id from " + arg);
        }
    });

    return storable;
}

Storable.setStoreImplementation = function(storeImpl) {
    store = storeImpl;
}<|endoftext|>


<commit_before>function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    // Draw drops.
    buffer.fillStyle = '#aaf';
    for(var drop in drops){
        buffer.fillRect(
          drops[drop]['x'],
          drops[drop]['y'],
          2,
          7
        );
    }

    // Draw object.
    buffer.fillStyle = '#777';
    buffer.fillRect(
      object['x'],
      object['y'],
      200,
      40
    );

    // Setup text display.
    buffer.fillStyle = '#fff';
    buffer.font = '23pt sans-serif';

    // Draw number of particles.
    buffer.fillText(
      drops.length,
      5,
      25
    );

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    window.requestAnimationFrame(draw);
}

function logic(){
    // Add some randomly placed drops.
    var loop_counter = drop_counter;
    do{
        drops.push({
          'x': Math.floor(Math.random() * width),
          'y': -99,
        });
    }while(loop_counter--);

    // Update drop positions.
    for(var drop in drops){
        drops[drop]['y'] += Math.random() * 9 + 9;

        // Delete drops below bottom of screen
        //   or that collided with the object.
        if(drops[drop]['y'] > height
          || !(
            drops[drop]['x'] <= object['x']
            || drops[drop]['y'] <= object['y']
            || drops[drop]['x'] - 200 >= object['x']
            || drops[drop]['y'] - 40 >= object['y']
          )){
            drops.splice(
              drop,
              1
            );
        }
    }
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
}

var buffer = document.getElementById('buffer').getContext('2d');
var canvas = document.getElementById('canvas').getContext('2d');
var drag = false;
var drop_counter = 1;
var drops = [];
var height = 0;
var object = {
  'x': 0,
  'y': 0,
};
var width = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // +: drop_counter++;
    if(key == 187){
        drop_counter++;

    // -: drop_counter--;
    }else if(key == 189){
        drop_counter = drop_counter > 0
          ? drop_counter - 1
          : 0;
    }
    console.log(drop_counter);
};

window.onload = function(e){
    resize();

    object['x'] = width / 2 - 100;
    object['y'] = height / 2 - 20;

    window.requestAnimationFrame(draw);
    window.setInterval(
      'logic()',
      30
    );
};

window.onmousedown =
  window.ontouchstart = function(e){
    drag = true;
    object['x'] = e.pageX - 100;
    object['y'] = e.pageY - 20;
};

window.onmousemove =
  window.ontouchmove = function(e){
    if(!drag){
        return;
    }

    object['x'] = e.pageX - 100;
    object['y'] = e.pageY - 20;
};

window.onmouseup =
  window.ontouchend = function(e){
    drag = false;
};

window.onresize = resize;
<commit_msg>removed unnecessary code<commit_after>function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    // Draw drops.
    buffer.fillStyle = '#aaf';
    for(var drop in drops){
        buffer.fillRect(
          drops[drop]['x'],
          drops[drop]['y'],
          2,
          7
        );
    }

    // Draw object.
    buffer.fillStyle = '#777';
    buffer.fillRect(
      object['x'],
      object['y'],
      200,
      40
    );

    // Setup text display.
    buffer.fillStyle = '#fff';
    buffer.font = '23pt sans-serif';

    // Draw number of particles.
    buffer.fillText(
      drops.length,
      5,
      25
    );

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    window.requestAnimationFrame(draw);
}

function logic(){
    // Add some randomly placed drops.
    var loop_counter = drop_counter;
    do{
        drops.push({
          'x': Math.floor(Math.random() * width),
          'y': -99,
        });
    }while(loop_counter--);

    // Update drop positions.
    for(var drop in drops){
        drops[drop]['y'] += Math.random() * 9 + 9;

        // Delete drops below bottom of screen
        //   or that collided with the object.
        if(drops[drop]['y'] > height
          || !(
            drops[drop]['x'] <= object['x']
            || drops[drop]['y'] <= object['y']
            || drops[drop]['x'] - 200 >= object['x']
            || drops[drop]['y'] - 40 >= object['y']
          )){
            drops.splice(
              drop,
              1
            );
        }
    }
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
}

var buffer = document.getElementById('buffer').getContext('2d');
var canvas = document.getElementById('canvas').getContext('2d');
var drag = false;
var drop_counter = 1;
var drops = [];
var height = 0;
var object = {
  'x': 0,
  'y': 0,
};
var width = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // +: drop_counter++;
    if(key == 187){
        drop_counter++;

    // -: drop_counter--;
    }else if(key == 189){
        drop_counter = drop_counter > 0
          ? drop_counter - 1
          : 0;
    }
};

window.onload = function(e){
    resize();

    object['x'] = width / 2 - 100;
    object['y'] = height / 2 - 20;

    window.requestAnimationFrame(draw);
    window.setInterval(
      'logic()',
      30
    );
};

window.onmousedown =
  window.ontouchstart = function(e){
    drag = true;
    object['x'] = e.pageX - 100;
    object['y'] = e.pageY - 20;
};

window.onmousemove =
  window.ontouchmove = function(e){
    if(!drag){
        return;
    }

    object['x'] = e.pageX - 100;
    object['y'] = e.pageY - 20;
};

window.onmouseup =
  window.ontouchend = function(e){
    drag = false;
};

window.onresize = resize;
<|endoftext|>


<commit_before>
var meses={
    'Enero':0,'Febrero':1,'Marzo':2,'Abril':3,'Mayo':4,'Junio':5,'Julio':6,'Agosto':7,'Septiembre':8,'Octubre':9,'Noviembre':10,'Diciembre':11
}
var mesesNuevos={
    "01-Ene-2015":0,"01-Feb-2015":1,"01-Mar-2015":2,"01-Abr-2015":3,"01-May-2015":4,"01-Jun-2015":5,"01-Jul-2015":6,'01-Ago-2015':7,'01-Sep-2015':8,'01-Oct-2015':9,'01-Nov-2015':10,'01-Dic-2015':11
}

function graficaImportExport(container,path){
      var svg = d3.select(container),
        margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        //var parseTime = d3.timeParse("%b");

    var parseRow=function(d) {
          d.Mes = mesesNuevos[d.Mes]
          d.Importado = d.Importado
          d.Exportado = d.Exportado;
          return d;
    }

    var xx = d3.scaleLinear().range([10, width]);
    var yy = d3.scaleLinear().range([ height,0]);

    var xaxis=  d3.axisBottom(xx).ticks(12).tickFormat(function(d){
        return Object.keys(meses)[d]
    })
    //.ticks(d3.timeMonths).tickSize(16, 0)
    //.tickFormat(d3.timeFormat("%B"));
//    xaxis.tickValues(Object.keys(meses));//.tickFormat(d3.timeFormat("%m"));
    var lineImport = d3.line()
      .x(function(d) {  return xx(d.Mes); })
      .y(function(d) { return yy(d.Importado); });

      var lineExport = d3.line()
        .x(function(d) { return xx(d.Mes); })
        .y(function(d) {  return yy(d.Exportado); });

    d3.csv(path, parseRow,function(error, data) {
            mdata=data
            console.log(data)
          if (error) throw error;
          maxImport=d3.max(data,function(d){return parseInt(d.Importado)})
          maxExport=d3.max(data,function(d){return parseInt(d.Exportado)})
          xx.domain([0,11]);
          yy.domain([0,1.1*d3.max([maxImport, maxExport])]);

          // .tickFormat(d3.time.format("%B"))
          g.append("g")
              .attr("transform", "translate(0," + height + ")")
              .call(xaxis )
            .select(".domain")
              .remove();

          g.append("g")
             .call(d3.axisLeft(yy))
            .append("text") //texto
              .attr("fill", "#000")
              .attr("transform", "rotate(-90)")
              .attr("y", 6)
              .attr("dy", "0.71em")
              .attr("text-anchor", "end")
              .text("Toneladas");

          g.append("path")
              .data([data])
              .classed("line import",true).transition()
              .attr("d", lineImport);

          g.append("path")
              .data([data])
              .classed("line export",true).transition()
              .attr("d", lineExport);

              /*d3.selectAll("body").append("div")
              .classed('d3-tooltip',true);*/
/*** import label **/
        g.append("text").text("Importación").attr("transform", function(){
            return "translate(" + xx(data[1].Mes) + "," + (yy(data[11].Importado) -20) + ")";
        })

        var g1 = g.selectAll("g.dotImport") //g1 is the update section
              .data(data)

        var element = g1.enter().append("g").attr("transform", function(d) {
            return "translate(" + xx(d.Mes) + "," + yy(d.Importado) + ")";
        })
        element.classed("dotImport ", true);
        element.append("svg:circle")
        .attr('r',0)
        .transition(300).delay(500)
        .attr('r',5)

/*** export label **/
        g.append("text").text("Exportación").attr("transform", function(){
            return "translate(" + xx(data[1].Mes) + "," + (yy(data[11].Exportado) -20) + ")";
        })
        var g1 = g.selectAll("g.dotExport") //g1 is the update section
              .data(data)

        var element = g1.enter().append("g").attr("transform", function(d) {
            return "translate(" + xx(d.Mes) + "," + yy(d.Exportado) + ")";
        })
        element.classed("dotExport", true);
        element.append("svg:circle")
        .attr('r',0)
        .transition(300).delay(500)
        .attr('r',5)

        element.on("mouseover", function(d,i) {/*
            $(".d3-tooltip").css('top',d3.mouse(svg)[1]+"px")
            $(".d3-tooltip").css('left',d3.mouse(svg)[0]+"px")
            $(".d3-tooltip").show();
            $(".d3-tooltip").html(d.Exportado);*/
        })

        element.on("mouseout", function(d,i) {
            $(".d3-tooltip").hide();
        //    d3.select(this).select("circle")
        })

    });
}

function dibujaGrafico(container, ficheroDeDatos) {
  var colorTexto = "#333";
  var largoGrafico = $(container).width();
  if (ficheroDeDatos === undefined) ficheroDeDatos = "data/grafico.csv";

  d3.csv(ficheroDeDatos, function(error, data) {
    var mdata = data;
    var numbers = [];
    mdata.forEach(function(el) {
      numbers.push(+el.Percent);
    });

    data = data.slice(0, 3);

    var x = d3
      .scaleLinear()
      .domain([0, d3.max(numbers)])
      .range([0, largoGrafico]);

    var enterSel = d3
      .select(container)
      .selectAll("div")
      .data(data)
      .enter()
      .append("div")
      .style("width", "0px");

    enterSel.text(function(d) {
      return d.Provincia + " " + d.Percent + "%";
    });
    enterSel
      .transition()
      .delay(0)
      .duration(1300)
      .style("width", function(d) {
        return x(d.Percent) + "px";
      })
      .delay(200)
      .style("color", colorTexto);
    //TODO poner el último a mano
  });
}
<commit_msg> grafica horizontal<commit_after>
var meses={
    'Enero':0,'Febrero':1,'Marzo':2,'Abril':3,'Mayo':4,'Junio':5,'Julio':6,'Agosto':7,'Septiembre':8,'Octubre':9,'Noviembre':10,'Diciembre':11
}
var mesesNuevos={
    "01-Ene-2015":0,"01-Feb-2015":1,"01-Mar-2015":2,"01-Abr-2015":3,"01-May-2015":4,"01-Jun-2015":5,"01-Jul-2015":6,'01-Ago-2015':7,'01-Sep-2015':8,'01-Oct-2015':9,'01-Nov-2015':10,'01-Dic-2015':11
}

function graficaImportExport(container,path){
      var svg = d3.select(container),
        margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        //var parseTime = d3.timeParse("%b");

    var parseRow=function(d) {
          d.Mes = mesesNuevos[d.Mes]
          d.Importado = d.Importado
          d.Exportado = d.Exportado;
          return d;
    }

    var xx = d3.scaleLinear().range([10, width]);
    var yy = d3.scaleLinear().range([ height,0]);

    var xaxis=  d3.axisBottom(xx).ticks(12).tickFormat(function(d){
        return Object.keys(meses)[d]
    })
    //.ticks(d3.timeMonths).tickSize(16, 0)
    //.tickFormat(d3.timeFormat("%B"));
//    xaxis.tickValues(Object.keys(meses));//.tickFormat(d3.timeFormat("%m"));
    var lineImport = d3.line()
      .x(function(d) {  return xx(d.Mes); })
      .y(function(d) { return yy(d.Importado); });

      var lineExport = d3.line()
        .x(function(d) { return xx(d.Mes); })
        .y(function(d) {  return yy(d.Exportado); });

    d3.csv(path, parseRow,function(error, data) {
            mdata=data
            console.log(data)
          if (error) throw error;
          maxImport=d3.max(data,function(d){return parseInt(d.Importado)})
          maxExport=d3.max(data,function(d){return parseInt(d.Exportado)})
          xx.domain([0,11]);
          yy.domain([0,1.1*d3.max([maxImport, maxExport])]);

          // .tickFormat(d3.time.format("%B"))
          g.append("g")
              .attr("transform", "translate(0," + height + ")")
              .call(xaxis )
            .select(".domain")
              .remove();

          g.append("g")
             .call(d3.axisLeft(yy))
            .append("text") //texto
              .attr("fill", "#000")
              .attr("transform", "rotate(-90)")
              .attr("y", 6)
              .attr("dy", "0.71em")
              .attr("text-anchor", "end")
              .text("Toneladas");

          g.append("path")
              .data([data])
              .classed("line import",true).transition()
              .attr("d", lineImport);

          g.append("path")
              .data([data])
              .classed("line export",true).transition()
              .attr("d", lineExport);

              /*d3.selectAll("body").append("div")
              .classed('d3-tooltip',true);*/
/*** import label **/
        g.append("text").text("Importación").attr("transform", function(){
            return "translate(" + xx(data[1].Mes) + "," + (yy(data[11].Importado) -20) + ")";
        })

        var g1 = g.selectAll("g.dotImport") //g1 is the update section
              .data(data)

        var element = g1.enter().append("g").attr("transform", function(d) {
            return "translate(" + xx(d.Mes) + "," + yy(d.Importado) + ")";
        })
        element.classed("dotImport ", true);
        element.append("svg:circle")
        .attr('r',0)
        .transition(300).delay(500)
        .attr('r',5)

/*** export label **/
        g.append("text").text("Exportación").attr("transform", function(){
            return "translate(" + xx(data[1].Mes) + "," + (yy(data[11].Exportado) -20) + ")";
        })
        var g1 = g.selectAll("g.dotExport") //g1 is the update section
              .data(data)

        var element = g1.enter().append("g").attr("transform", function(d) {
            return "translate(" + xx(d.Mes) + "," + yy(d.Exportado) + ")";
        })
        element.classed("dotExport", true);
        element.append("svg:circle")
        .attr('r',0)
        .transition(300).delay(500)
        .attr('r',5)

        element.on("mouseover", function(d,i) {/*
            $(".d3-tooltip").css('top',d3.mouse(svg)[1]+"px")
            $(".d3-tooltip").css('left',d3.mouse(svg)[0]+"px")
            $(".d3-tooltip").show();
            $(".d3-tooltip").html(d.Exportado);*/
        })

        element.on("mouseout", function(d,i) {
            $(".d3-tooltip").hide();
        //    d3.select(this).select("circle")
        })
    });
}

function dibujaGrafico(container, ficheroDeDatos) {
  var colorTexto = "#333";
  var largoGrafico = $(container).width();
  if (ficheroDeDatos === undefined) ficheroDeDatos = "data/grafico.csv";

  d3.csv(ficheroDeDatos, function(error, data) {
    var mdata = data;
    var numbers = [];
    mdata.forEach(function(el) {
      numbers.push(+el.Percent);
    });

    //data = data.slice(0, 3);

    var x = d3
      .scaleLinear()
      .domain([0, 100])
      .range([0, largoGrafico-10]);
     var arrayColores=['#000','#333','#888','#aaa']
    var enterSel = d3
      .select(container)
      .selectAll("div.grafica-barras")
      .data(data)
      .enter()
      .append("div")
      .style("width", function(d) {
        return x(d.Percent) + "px";
      })
      .style('opacity',0)
      .style('background-color',function(d,i){
          return arrayColores[i];
      })
      .classed("grafica-barras",true)

      var enterSel2 = d3
        .select(container)
        .selectAll("div.grafica-texto")
        .data(data)
        .enter()
        .append("div")
        .classed("grafica-texto",true)
        .style("width", function(d) {
          return x(d.Percent) + "px";
        })
        .style('opacity',0)
        enterSel2.transition().delay(1000).style('opacity',1)

    enterSel2.text(function(d) {
      return d.Provincia + " " + d.Percent + "%";
    });
    enterSel
      .transition()
      .delay(0)
      .duration(1000)
      .delay(100)
      .style('opacity',1)

    //TODO poner el último a mano
  });
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Text, Image, View } from 'react-native';
import styles from './styles/GameplayScreenStyle';
import ClickableImage from '../components/ClickableImage';
import { StackNagivator } from 'react-navigation';

export default class GameplayScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
    }
  }

  componentWillMount() {
    console.log('ljsdflkjsdf============================')
  }

  componentDidMount() {
    return fetch('http://localhost:3000/games/'+this.props.navigation.state.params.game_id+'/paths', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        traceable_type: this.props.navigation.state.params.traceable_type,
        traceable_id: this.props.navigation.state.params.traceable_id,
      }),
    })
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        pathInfo: responseJson,
      })
    })
    .catch((error) => {
      console.error(error)
    })
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View>
          <Text>Loading...</Text>
        </View>
      )
    }

    const { navigate } = this.props.navigation;
    let thingObject = this.state.pathInfo;
    return (
      <View>
        <View>
          <Image source={{uri: 'https://image.tmdb.org/t/p/w185/'+this.state.pathInfo.current_traceable.traceable.image_url}} style={{width:40, height:40}} />
        </View>
        <View>
          {
            this.state.pathInfo.possible_paths.map(function(possible_path, index) {
              return (
                <ClickableImage key={index} text={{uri: 'https://image.tmdb.org/t/p/w185/'+possible_path.traceable.image_url}} onPress={() => navigate('GameplayScreen', { game_id: thingObject.game_id, traceable_id: thingObject.current_traceable.traceable.id, traceable_type: thingObject.current_traceable.traceable.type} )} />
              )
            })
          }
        </View>
      </View>
    )
  }
}
<commit_msg>Stable gameplayscreen, need to add win game logic<commit_after>import React, { Component } from 'react';
import { Text, Image, View } from 'react-native';
import styles from './styles/GameplayScreenStyle';
import ClickableImage from '../components/ClickableImage';
import { StackNagivator } from 'react-navigation';

export default class GameplayScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
    }
  }

  componentWillMount() {
    console.log('ljsdflkjsdf============================')
  }

  componentDidMount() {
    return fetch('http://localhost:3000/games/'+this.props.navigation.state.params.game_id+'/paths', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        traceable_type: this.props.navigation.state.params.traceable_type,
        traceable_id: this.props.navigation.state.params.traceable_id,
      }),
    })
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        pathInfo: responseJson,
      })
      console.log(this.state.pathInfo);
    })
    .catch((error) => {
      console.error(error)
    })
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View>
          <Text>Loading...</Text>
        </View>
      )
    }

    const { navigate } = this.props.navigation;
    let thingObject = this.state.pathInfo;
    return (
      <View>
        <View>
          <Image source={{uri: 'https://image.tmdb.org/t/p/w185/'+this.state.pathInfo.current_traceable.traceable.image_url}} style={{width:40, height:40}} />
        </View>
        <View>
          {
            this.state.pathInfo.possible_paths.map(function(possible_path, index) {
              return (
                <ClickableImage key={index} text={{uri: 'https://image.tmdb.org/t/p/w185/'+possible_path.traceable.image_url}} onPress={() => navigate('GameplayScreen', { game_id: thingObject.game_id, traceable_id: possible_path.traceable.id, traceable_type: possible_path.traceable_type} )} />
              )
            })
          }
        </View>
        <Text>{ thingObject.game_id }</Text>
      </View>
    )
  }
}
<|endoftext|>


<commit_before>/*
   Copyright 2014 Xabier Crespo Álvarez

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

	   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

:Author:
	Xabier Crespo Álvarez (xabicrespog@gmail.com)
	Diego Hurtado de Mendoza Pombo (diego.hdmp@gmail.com)
*/

var satnetClient = function() {

	var rpc_url = 'http://172.19.51.170:8000/jrpc/';
	this.rpc = new JsonRPC(rpc_url, { methods:
		['system.login',
		 'system.logout',
		 'communications.gs.storePassiveMessage',
		 'configuration.gs.list'] });

	var kissparser = new kissParser(onReceiveFrameCallback);
	var connectionInfo = null;
	var satnetConnection = {
		serialPort:null,
		baudRate:null,
		groundStation:null
	};

	// Elements in DOM
	var serialPortSel = document.getElementById('serialPortSel');
	var refreshPortsBtn = document.getElementById('refreshPortsBtn');
	var baudRateSel = document.getElementById('baudRateSel');
	var baudRateInp = document.getElementById('baudRateInp');
	var groundStationSel = document.getElementById('groundStationSel');
	var refreshGroundStationsBtn = document.getElementById('refreshGroundStationsBtn');
	var connectBtn = document.getElementById('connectBtn');
	var disconnectBtn = document.getElementById('disconnectBtn');

	this.initialize = function() {
		refreshGS();
		refreshDevices();
	}
	/********************************
	* Event callbacks
	*********************************/
	// Refreshes the list of GS stations in main window. Called after log in
	// from login_handlers
	var refreshGS = function() {
		while (groundStationSel.length > 1) {
			groundStationSel.remove(1);
		}
		satnet.rpc.configuration.gs.list()
			.onSuccess(function(result) {
				terminal.log(result.length + " ground station(s) was(were) found");
				if (!result.length) terminal.log("Please, create a GS through SATNET website");

				for (var i = 0; i < result.length; i++) {
					var option = document.createElement('option');
					option.text = result[i];
					groundStationSel.add(option);
				}
				chrome.storage.local.get(["groundStation"], function (items) {
					// If the GS is available select saved value
					if (items.groundStation) {
						for (i=0 ; i < groundStationSel.length ; i++) {
							if (groundStationSel[i].value == items.groundStation) {
								groundStationSel.selectedIndex = i;
								terminal.log('Ground station ' + items.groundStation + ' found');
								break;
							}
						}
					}
				});

			})
			.onException(jsonRPCerror)
			//.onComplete()
			.execute();
	}

	// Refreshes the list of serial devices in main window
	var refreshDevices = function() {
		chrome.serial.getDevices(function(ports) {
			while (serialPortSel.length > 1) {
				serialPortSel.remove(1);
			}
			terminal.log(ports.length + " serial device(s) was(were) found");
			for (var i = 0; i < ports.length; i++) {
				var option = document.createElement('option');
				option.text = ports[i].path;
				serialPortSel.add(option);
			}
		});
		chrome.storage.local.get(["serialPort", "baudRate"], function (items) {
			// If the port is available select saved value
			if (items.serialPort && items.baudRate) {
				for (i=0 ; i < serialPortSel.length ; i++) {
					if (serialPortSel[i].value == items.serialPort) {
						terminal.log('Serial port ' +items.serialPort + ' found');
						serialPortSel.selectedIndex = i;
						break;
					}
				}
				baudRateSel.style.display = "none";
				baudRateInp.style.display = "block";
				baudRateInp.value = items.baudRate;
			}
		});

	}

	// Callback to deal with 'CONNECT' button
	var onConnect = function(connInfo) {
		if (!connInfo) {
			connectBtn.classList.add('button-error');
			terminal.log('Connection error');
			refreshDevices();
			window.setTimeout(function() {
				connectBtn.classList.remove('button-error');
			}, 1000);
		} else {
			terminal.log('Succesful serial connection (ID ' + connInfo.connectionId + ')');
			terminal.log('Serial port : ' + satnetConnection.serialPort);
			terminal.log('Baud rate : ' + satnetConnection.baudRate);
			terminal.log('Ground Station : ' + satnetConnection.groundStation);
			chrome.storage.local.set({'serialPort': satnetConnection.serialPort,
				'baudRate': satnetConnection.baudRate, 'groundStation': satnetConnection.groundStation }, function() {
   					terminal.log('Connection parameters saved');
   			});

			connectionInfo = connInfo;
			connectBtn.classList.add('button-success');
			connectBtn.innerHTML = 'CONNECTED';
			// Disable parameter changes while connected
			disableElement(connectBtn);
			disableElement(serialPortSel);
			disableElement(refreshPortsBtn);
			disableElement(baudRateSel);
			disableElement(baudRateInp);
			disableElement(groundStationSel);
			disableElement(refreshGroundStationsBtn);

			chrome.serial.onReceive.addListener(onReceiveCallback);
		}
	}

	// Callback to deal with DISCONNECT button
	var onDisconnect = function(result) {
		if (result) {
			closeConnection(connectionInfo.connectionId);
		} else {
			terminal.log('Connection with ID ' + connectionInfo.connectionId + ' could not be closed');
		}
	}

	// Callback to read from serial port
	var onReceiveCallback = function(info) {
		if (info.data && info.connectionId == connectionId) {
			kissparser.update(info.data);
		}
	};

	var onReceiveFrameCallback = function(frame) {
		terminal.log('New frame received: ' + frame);
	};

	// Callback to attend serial port events
	var onReceiveErrorCallback = function(info) {
		closeConnection(info.connectionId);
		getDevices();
	};

	function closeConnection(connectionId) {
		terminal.log('Connection closed (ID: ' + connectionId + ')');
		disconnectBtn.classList.add('pure-button-disabled');
		connectBtn.innerHTML = 'CONNECT';
		connectBtn.classList.remove('button-success');
		// Enable parameter changes
		enableElement(connectBtn);
		enableElement(serialPortSel);
		enableElement(refreshPortsBtn);
		enableElement(baudRateSel);
		enableElement(baudRateInp);
		enableElement(groundStationSel);
		enableElement(refreshGroundStationsBtn);
	}

	function disableElement(element) {
		element.disabled = true;
		element.classList.add('pure-button-disabled');
	}

	function enableElement(element) {
		element.disabled = false;
		element.classList.remove('pure-button-disabled');
	}
	/********************************
	* Event listeners
	*********************************/
	connectBtn.addEventListener('click', function (e) {
		// Check if either the baud rate or the port id is not selected
		if (serialPortSel.selectedIndex == 0) {
			terminal.log('Please, select the TNC serial port');
			return;
		}
		if (!baudRateInp.value.length) {
			terminal.log('Please, select the TNC baud rate');
			return;
		}
		if (groundStationSel.selectedIndex == 0) {
			terminal.log('Please, select a ground station');
			return;
		}

		var path = serialPortSel.options[serialPortSel.selectedIndex].value;
		var baudrate = baudRateInp.value;
		disconnectBtn.classList.remove('pure-button-disabled');
		satnetConnection.serialPort = path;
		satnetConnection.baudRate = Math.round(baudrate);
		satnetConnection.groundStation = groundStationSel.options[groundStationSel.selectedIndex].value;
		chrome.serial.connect(path, {bitrate: Math.round(baudrate), persistent: true}, onConnect);
	});

	// Handling baud rate selection, if the selected option is 'Other'
	// replaces an input field by the select form. Otherwise copies the
	// option to the input to ease the code
	baudRateSel.addEventListener('change', function() {
		if (baudRateSel.selectedIndex == baudRateSel.length-1) {
			baudRateSel.style.display = "none";
			baudRateInp.style.display = "block";
		} else {
			baudRateInp.value = baudRateSel.value;
		}
	});

	disconnectBtn.addEventListener('click', function (e) {
		chrome.serial.disconnect(connectionInfo.connectionId, onDisconnect);
	});

	refreshPortsBtn.addEventListener('click', this.refreshDevices);
	refreshGroundStationsBtn.addEventListener('click', this.refreshGS);

	chrome.serial.onReceiveError.addListener(onReceiveErrorCallback);

}

// Create instance of satnet client on document ready
var satnet;
document.addEventListener("DOMContentLoaded", function(event) {
	satnet = new satnetClient();
	terminal.log('Welcome to SATNet Client!');
});
<commit_msg>Minor fixed<commit_after>/*
   Copyright 2014 Xabier Crespo Álvarez

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

	   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

:Author:
	Xabier Crespo Álvarez (xabicrespog@gmail.com)
	Diego Hurtado de Mendoza Pombo (diego.hdmp@gmail.com)
*/

var satnetClient = function() {

	var rpc_url = 'https://satnet.aero.calpoly.edu/jrpc/';
	var rpc_url = 'http://172.19.51.170:8000/jrpc/';
	this.rpc = new JsonRPC(rpc_url, { methods:
		['system.login',
		 'system.logout',
		 'communications.gs.storePassiveMessage',
		 'configuration.gs.list'] });

	var kissparser = new kissParser(onReceiveFrameCallback);
	var connectionInfo = null;
	var satnetConnection = {
		serialPort:null,
		baudRate:null,
		groundStation:null
	};

	// Elements in DOM
	var serialPortSel = document.getElementById('serialPortSel');
	var refreshPortsBtn = document.getElementById('refreshPortsBtn');
	var baudRateSel = document.getElementById('baudRateSel');
	var baudRateInp = document.getElementById('baudRateInp');
	var groundStationSel = document.getElementById('groundStationSel');
	var refreshGroundStationsBtn = document.getElementById('refreshGroundStationsBtn');
	var connectBtn = document.getElementById('connectBtn');
	var disconnectBtn = document.getElementById('disconnectBtn');

	this.initialize = function() {
		refreshGS();
		refreshDevices();
	}
	/********************************
	* Event callbacks
	*********************************/
	// Refreshes the list of GS stations in main window. Called after log in
	// from login_handlers
	function refreshGS() {
		while (groundStationSel.length > 1) {
			groundStationSel.remove(1);
		}
		satnet.rpc.configuration.gs.list()
			.onSuccess(function(result) {
				terminal.log(result.length + " ground station(s) was(were) found");
				if (!result.length) terminal.log("Please, create a GS through SATNET website");

				for (var i = 0; i < result.length; i++) {
					var option = document.createElement('option');
					option.text = result[i];
					groundStationSel.add(option);
				}
				chrome.storage.local.get(["groundStation"], function (items) {
					// If the GS is available select saved value
					if (items.groundStation) {
						for (i=0 ; i < groundStationSel.length ; i++) {
							if (groundStationSel[i].value == items.groundStation) {
								groundStationSel.selectedIndex = i;
								break;
							}
						}
					}
				});

			})
			.onException(jsonRPCerror)
			//.onComplete()
			.execute();
	}

	// Refreshes the list of serial devices in main window
	function refreshDevices() {
		chrome.serial.getDevices(function(ports) {
			while (serialPortSel.length > 1) {
				serialPortSel.remove(1);
			}
			terminal.log(ports.length + " serial device(s) was(were) found");
			for (var i = 0; i < ports.length; i++) {
				var option = document.createElement('option');
				option.text = ports[i].path;
				serialPortSel.add(option);
			}
		});
		chrome.storage.local.get(["serialPort", "baudRate"], function (items) {
			// If the port is available select saved value
			if (items.serialPort && items.baudRate) {
				for (i=0 ; i < serialPortSel.length ; i++) {
					if (serialPortSel[i].value == items.serialPort) {
						terminal.log('Serial port ' +items.serialPort + ' found');
						serialPortSel.selectedIndex = i;
						break;
					}
				}
				baudRateSel.style.display = "none";
				baudRateInp.style.display = "block";
				baudRateInp.value = items.baudRate;
			}
		});

	}

	// Callback to deal with 'CONNECT' button
	var onConnect = function(connInfo) {
		if (!connInfo) {
			connectBtn.classList.add('button-error');
			terminal.log('Connection error');
			refreshDevices();
			window.setTimeout(function() {
				connectBtn.classList.remove('button-error');
			}, 1000);
		} else {
			terminal.log('Succesful serial connection (ID ' + connInfo.connectionId + ')');
			terminal.log('Serial port : ' + satnetConnection.serialPort);
			terminal.log('Baud rate : ' + satnetConnection.baudRate);
			terminal.log('Ground Station : ' + satnetConnection.groundStation);
			chrome.storage.local.set({'serialPort': satnetConnection.serialPort,
				'baudRate': satnetConnection.baudRate, 'groundStation': satnetConnection.groundStation }, function() {
   					terminal.log('Connection parameters saved');
   			});

			connectionInfo = connInfo;
			connectBtn.classList.add('button-success');
			connectBtn.innerHTML = 'CONNECTED';
			// Disable parameter changes while connected
			disableElement(connectBtn);
			disableElement(serialPortSel);
			disableElement(refreshPortsBtn);
			disableElement(baudRateSel);
			disableElement(baudRateInp);
			disableElement(groundStationSel);
			disableElement(refreshGroundStationsBtn);

			chrome.serial.onReceive.addListener(onReceiveCallback);
		}
	}

	// Callback to deal with DISCONNECT button
	var onDisconnect = function(result) {
		if (result) {
			closeConnection(connectionInfo.connectionId);
		} else {
			terminal.log('Connection with ID ' + connectionInfo.connectionId + ' could not be closed');
		}
	}

	// Callback to read from serial port
	var onReceiveCallback = function(info) {
		if (info.data && info.connectionId == connectionInfo.connectionId) {
			kissparser.update(info.data);
		}
	};

	function onReceiveFrameCallback(frame) {
		terminal.log('New frame received: ' + frame);
	};

	// Callback to attend serial port events
	var onReceiveErrorCallback = function(info) {
		closeConnection(info.connectionId);
		getDevices();
	};

	function closeConnection(connectionId) {
		terminal.log('Connection closed (ID: ' + connectionId + ')');
		disconnectBtn.classList.add('pure-button-disabled');
		connectBtn.innerHTML = 'CONNECT';
		connectBtn.classList.remove('button-success');
		// Enable parameter changes
		enableElement(connectBtn);
		enableElement(serialPortSel);
		enableElement(refreshPortsBtn);
		enableElement(baudRateSel);
		enableElement(baudRateInp);
		enableElement(groundStationSel);
		enableElement(refreshGroundStationsBtn);
	}

	function disableElement(element) {
		element.disabled = true;
		element.classList.add('pure-button-disabled');
	}

	function enableElement(element) {
		element.disabled = false;
		element.classList.remove('pure-button-disabled');
	}
	/********************************
	* Event listeners
	*********************************/
	connectBtn.addEventListener('click', function (e) {
		// Check if either the baud rate or the port id is not selected
		if (serialPortSel.selectedIndex == 0) {
			terminal.log('Please, select the TNC serial port');
			return;
		}
		if (!baudRateInp.value.length) {
			terminal.log('Please, select the TNC baud rate');
			return;
		}
		if (groundStationSel.selectedIndex == 0) {
			terminal.log('Please, select a ground station');
			return;
		}

		var path = serialPortSel.options[serialPortSel.selectedIndex].value;
		var baudrate = baudRateInp.value;
		disconnectBtn.classList.remove('pure-button-disabled');
		satnetConnection.serialPort = path;
		satnetConnection.baudRate = Math.round(baudrate);
		satnetConnection.groundStation = groundStationSel.options[groundStationSel.selectedIndex].value;
		chrome.serial.connect(path, {bitrate: Math.round(baudrate), persistent: true}, onConnect);
	});

	// Handling baud rate selection, if the selected option is 'Other'
	// replaces an input field by the select form. Otherwise copies the
	// option to the input to ease the code
	baudRateSel.addEventListener('change', function() {
		if (baudRateSel.selectedIndex == baudRateSel.length-1) {
			baudRateSel.style.display = "none";
			baudRateInp.style.display = "block";
		} else {
			baudRateInp.value = baudRateSel.value;
		}
	});

	disconnectBtn.addEventListener('click', function (e) {
		chrome.serial.disconnect(connectionInfo.connectionId, onDisconnect);
	});

	refreshPortsBtn.addEventListener('click', refreshDevices);
	refreshGroundStationsBtn.addEventListener('click', refreshGS);

	chrome.serial.onReceiveError.addListener(onReceiveErrorCallback);

}

// Create instance of satnet client on document ready
var satnet;
document.addEventListener("DOMContentLoaded", function(event) {
	satnet = new satnetClient();
	terminal.log('Welcome to SATNet Client!');
});
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

//
// Chromosome ideogram
//

var igv = (function (igv) {

    igv.IdeoPanel = function (parentElement) {

        this.ideograms = {};

        this.div = $('

');
        $(parentElement).append(this.div[0]);

        // ideogram label
        var chromosomeNameDiv = $('

');
        this.div.append(chromosomeNameDiv[0]);

        this.chromosomeNameLabel = $('
')[0];
        $(chromosomeNameDiv).append(this.chromosomeNameLabel);

        // ideogram content
        this.contentDiv = $('

');
        $(this.div).append(this.contentDiv[0]);

        var myself = this;
        this.contentDiv.click(function (e) {

            var xy,
                xPercentage,
                chr,
                chrLength,
                locusLength,
                chrCoveragePercentage,
                locus;

            xy = igv.translateMouseCoordinates(e, myself.contentDiv);
            xPercentage = xy.x / myself.contentDiv.width();

            locusLength = igv.browser.trackBPWidth();
            chr = igv.browser.genome.getChromosome(igv.browser.referenceFrame.chr);
            chrLength = chr.bpLength;
            chrCoveragePercentage = locusLength / chrLength;

            if (xPercentage - (chrCoveragePercentage/2.0) < 0) {
                xPercentage = chrCoveragePercentage/2.0;
                //return;
            }

            if (xPercentage + (chrCoveragePercentage/2.0) > 1.0) {
                xPercentage = 1.0 - chrCoveragePercentage/2.0;
                //return;
            }

            locus = igv.browser.referenceFrame.chr + ":" + igv.numberFormatter(1 + Math.floor((xPercentage - (chrCoveragePercentage/2.0)) * chrLength)) + "-" + igv.numberFormatter(Math.floor((xPercentage + (chrCoveragePercentage/2.0)) * chrLength));
            //console.log("chr length " + igv.numberFormatter(chrLength) + " locus " + locus);

            igv.browser.search(locus, undefined);

        });

        this.contentDiv.css({"left": igv.browser.controlPanelWidth + "px"});

        this.canvas = $('<canvas class="igv-ideogram-canvas"></canvas>')[0];
        $(this.contentDiv).append(this.canvas);
        this.canvas.setAttribute('width', this.contentDiv.width());
        this.canvas.setAttribute('height', this.contentDiv.height());
        this.ctx = this.canvas.getContext("2d");

    };

    igv.IdeoPanel.prototype.resize = function () {

        this.canvas.setAttribute('width', this.div.width());
        this.canvas.setAttribute('height', this.div.height());

        this.ideograms = {};
        this.repaint();
    };

    igv.IdeoPanel.prototype.repaint = function () {

        try {
            var y,
                image,
                bufferCtx,
                chromosome,
                bpPerPixel,
                width,
                widthBP,
                x,
                xBP,
                bpPerPixelIdeogram,
                genome = igv.browser.genome,
                referenceFrame = igv.browser.referenceFrame,
                stainColors = [];

            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

            if (!(genome && referenceFrame && genome.getChromosome(referenceFrame.chr))) {
                return;
            }

            image = this.ideograms[igv.browser.referenceFrame.chr];

            if (!image) {

                image = document.createElement('canvas');
                image.width = this.canvas.width;
                image.height = 13;

                bufferCtx = image.getContext('2d');

                drawIdeogram(bufferCtx, this.canvas.width, image.height);

                this.ideograms[igv.browser.referenceFrame.chr] = image;
            }

            y = (this.canvas.height - image.height) / 2.0;
            this.ctx.drawImage(image, 0, y);

            // Draw red box
            this.ctx.save();

            chromosome = igv.browser.genome.getChromosome(igv.browser.referenceFrame.chr);

            xBP = igv.browser.referenceFrame.start;
            widthBP = this.canvas.width * igv.browser.referenceFrame.bpPerPixel;

            bpPerPixelIdeogram = chromosome.bpLength/this.canvas.width;

            if (widthBP < chromosome.bpLength) {

                x     = Math.floor(                  xBP/bpPerPixelIdeogram );
                width = Math.floor(Math.max(1.0, widthBP/bpPerPixelIdeogram));

                x = Math.max(0, x);
                x = Math.min(this.canvas.width - width, x);

                //console.log("canvas " + this.canvas.width + " xstart " + x + " xend " + (x + width));

                this.ctx.strokeStyle = "red";
                this.ctx.lineWidth = 2;
                this.ctx.strokeRect(x, y, width, image.height + this.ctx.lineWidth - 1);
                this.ctx.restore();
            }

            this.chromosomeNameLabel.innerHTML = referenceFrame.chr;
        } catch (e) {
            console.log("Error painting ideogram: " + e.message);
        }

        function drawIdeogram(bufferCtx, ideogramWidth, ideogramHeight) {

            var ideogramTop = 0;

            if (!genome) return;

            var chromosome = genome.getChromosome(referenceFrame.chr);
            if (!chromosome) return;

            var cytobands = chromosome.cytobands;

            if (cytobands) {

                var center = (ideogramTop + ideogramHeight / 2);

                var xC = [];
                var yC = [];

                var len = cytobands.length;
                if (len == 0) return;

                var chrLength = cytobands[len - 1].end;

                var scale = ideogramWidth / chrLength;

                var lastPX = -1;
                for (var i = 0; i < cytobands.length; i++) {
                    var cytoband = cytobands[i];

                    var start = scale * cytoband.start;
                    var end = scale * cytoband.end;
                    if (end > lastPX) {

                        if (cytoband.type == 'c') { // centermere: "acen"

                            if (cytoband.label.charAt(0) == 'p') {
                                xC[0] = start;
                                yC[0] = ideogramHeight + ideogramTop;
                                xC[1] = start;
                                yC[1] = ideogramTop;
                                xC[2] = end;
                                yC[2] = center;
                            } else {
                                xC[0] = end;
                                yC[0] = ideogramHeight + ideogramTop;
                                xC[1] = end;
                                yC[1] = ideogramTop;
                                xC[2] = start;
                                yC[2] = center;
                            }
                            bufferCtx.fillStyle = "rgb(150, 0, 0)"; //g2D.setColor(Color.RED.darker());
                            bufferCtx.strokeStyle = "rgb(150, 0, 0)"; //g2D.setColor(Color.RED.darker());
                            bufferCtx.polygon(xC, yC, 1, 0);
                            // g2D.fillPolygon(xC, yC, 3);
                        } else {

                            bufferCtx.fillStyle = getCytobandColor(cytoband); //g2D.setColor(getCytobandColor(cytoband));
                            bufferCtx.fillRect(start, ideogramTop, (end - start), ideogramHeight);
                            // context.fillStyle = "Black"; //g2D.setColor(Color.BLACK);
                            // context.strokeRect(start, y, (end - start), height);
                        }
                    }
                }
            }
            bufferCtx.strokeStyle = "black";
            bufferCtx.roundRect(0, ideogramTop, ideogramWidth, ideogramHeight, ideogramHeight / 2, 0, 1);
            //context.strokeRect(margin, y, trackWidth-2*margin, height);
            lastPX = end;

        }

        function getCytobandColor(data) {
            if (data.type == 'c') { // centermere: "acen"
                return "rgb(150, 10, 10)"

            } else {
                var stain = data.stain; // + 4;

                var shade = 230;
                if (data.type == 'p') {
                    shade = Math.floor(230 - stain / 100.0 * 230);
                }
                var c = stainColors[shade];
                if (c == null) {
                    c = "rgb(" + shade + "," + shade + "," + shade + ")";
                    stainColors[shade] = c;
                }
                return c;

            }
        }

    };

    return igv;
})
(igv || {});<commit_msg>Bug fix. Ideogram red navigator box widget now properly positioned and scaled.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

//
// Chromosome ideogram
//

var igv = (function (igv) {

    igv.IdeoPanel = function (parentElement) {

        this.ideograms = {};

        this.div = $('

');
        $(parentElement).append(this.div[0]);

        // ideogram label
        var chromosomeNameDiv = $('

');
        this.div.append(chromosomeNameDiv[0]);

        this.chromosomeNameLabel = $('
')[0];
        $(chromosomeNameDiv).append(this.chromosomeNameLabel);

        // ideogram content
        this.contentDiv = $('

');
        $(this.div).append(this.contentDiv[0]);

        var myself = this;
        this.contentDiv.click(function (e) {

            var xy,
                xPercentage,
                chr,
                chrLength,
                locusLength,
                chrCoveragePercentage,
                locus;

            xy = igv.translateMouseCoordinates(e, myself.contentDiv);
            xPercentage = xy.x / myself.contentDiv.width();

            locusLength = igv.browser.trackBPWidth();
            chr = igv.browser.genome.getChromosome(igv.browser.referenceFrame.chr);
            chrLength = chr.bpLength;
            chrCoveragePercentage = locusLength / chrLength;

            if (xPercentage - (chrCoveragePercentage/2.0) < 0) {
                xPercentage = chrCoveragePercentage/2.0;
                //return;
            }

            if (xPercentage + (chrCoveragePercentage/2.0) > 1.0) {
                xPercentage = 1.0 - chrCoveragePercentage/2.0;
                //return;
            }

            locus = igv.browser.referenceFrame.chr + ":" + igv.numberFormatter(1 + Math.floor((xPercentage - (chrCoveragePercentage/2.0)) * chrLength)) + "-" + igv.numberFormatter(Math.floor((xPercentage + (chrCoveragePercentage/2.0)) * chrLength));
            //console.log("chr length " + igv.numberFormatter(chrLength) + " locus " + locus);

            igv.browser.search(locus, undefined);

        });

        this.contentDiv.css({"left": igv.browser.controlPanelWidth + "px"});

        this.canvas = $('<canvas class="igv-ideogram-canvas"></canvas>')[0];
        $(this.contentDiv).append(this.canvas);
        this.canvas.setAttribute('width', this.contentDiv.width());
        this.canvas.setAttribute('height', this.contentDiv.height());
        this.ctx = this.canvas.getContext("2d");

    };

    igv.IdeoPanel.prototype.resize = function () {

        this.canvas.setAttribute('width', this.div.width());
        this.canvas.setAttribute('height', this.div.height());

        this.ideograms = {};
        this.repaint();
    };

    igv.IdeoPanel.prototype.repaint = function () {

        try {
            var y,
                image,
                bufferCtx,
                chromosome,
                widthPercentage,
                xPercentage,
                width,
                widthBP,
                x,
                xBP,
                genome = igv.browser.genome,
                referenceFrame = igv.browser.referenceFrame,
                stainColors = [];

            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

            if (!(genome && referenceFrame && genome.getChromosome(referenceFrame.chr))) {
                return;
            }

            image = this.ideograms[igv.browser.referenceFrame.chr];

            if (!image) {

                image = document.createElement('canvas');
                image.width = this.canvas.width;
                image.height = 13;

                bufferCtx = image.getContext('2d');

                drawIdeogram(bufferCtx, this.canvas.width, image.height);

                this.ideograms[igv.browser.referenceFrame.chr] = image;
            }

            y = (this.canvas.height - image.height) / 2.0;
            this.ctx.drawImage(image, 0, y);

            // Draw red box
            this.ctx.save();

            chromosome = igv.browser.genome.getChromosome(igv.browser.referenceFrame.chr);

            widthBP = Math.floor(igv.browser.trackBPWidth());
                xBP = igv.browser.referenceFrame.start;

            if (widthBP < chromosome.bpLength) {

                widthPercentage = widthBP/chromosome.bpLength;
                    xPercentage =     xBP/chromosome.bpLength;

                x =     Math.floor(    xPercentage * this.canvas.width);
                width = Math.floor(widthPercentage * this.canvas.width);

                console.log("canvas end " + this.canvas.width + " xEnd " + (x + width));

                x = Math.max(0, x);
                x = Math.min(this.canvas.width - width, x);

                this.ctx.strokeStyle = "red";
                this.ctx.lineWidth = 2;
                this.ctx.strokeRect(x, y, width, image.height + this.ctx.lineWidth - 1);
                this.ctx.restore();
            }

            this.chromosomeNameLabel.innerHTML = referenceFrame.chr;
        } catch (e) {
            console.log("Error painting ideogram: " + e.message);
        }

        function drawIdeogram(bufferCtx, ideogramWidth, ideogramHeight) {

            var ideogramTop = 0;

            if (!genome) return;

            var chromosome = genome.getChromosome(referenceFrame.chr);
            if (!chromosome) return;

            var cytobands = chromosome.cytobands;

            if (cytobands) {

                var center = (ideogramTop + ideogramHeight / 2);

                var xC = [];
                var yC = [];

                var len = cytobands.length;
                if (len == 0) return;

                var chrLength = cytobands[len - 1].end;

                var scale = ideogramWidth / chrLength;

                var lastPX = -1;
                for (var i = 0; i < cytobands.length; i++) {
                    var cytoband = cytobands[i];

                    var start = scale * cytoband.start;
                    var end = scale * cytoband.end;
                    if (end > lastPX) {

                        if (cytoband.type == 'c') { // centermere: "acen"

                            if (cytoband.label.charAt(0) == 'p') {
                                xC[0] = start;
                                yC[0] = ideogramHeight + ideogramTop;
                                xC[1] = start;
                                yC[1] = ideogramTop;
                                xC[2] = end;
                                yC[2] = center;
                            } else {
                                xC[0] = end;
                                yC[0] = ideogramHeight + ideogramTop;
                                xC[1] = end;
                                yC[1] = ideogramTop;
                                xC[2] = start;
                                yC[2] = center;
                            }
                            bufferCtx.fillStyle = "rgb(150, 0, 0)"; //g2D.setColor(Color.RED.darker());
                            bufferCtx.strokeStyle = "rgb(150, 0, 0)"; //g2D.setColor(Color.RED.darker());
                            bufferCtx.polygon(xC, yC, 1, 0);
                            // g2D.fillPolygon(xC, yC, 3);
                        } else {

                            bufferCtx.fillStyle = getCytobandColor(cytoband); //g2D.setColor(getCytobandColor(cytoband));
                            bufferCtx.fillRect(start, ideogramTop, (end - start), ideogramHeight);
                            // context.fillStyle = "Black"; //g2D.setColor(Color.BLACK);
                            // context.strokeRect(start, y, (end - start), height);
                        }
                    }
                }
            }
            bufferCtx.strokeStyle = "black";
            bufferCtx.roundRect(0, ideogramTop, ideogramWidth, ideogramHeight, ideogramHeight / 2, 0, 1);
            //context.strokeRect(margin, y, trackWidth-2*margin, height);
            lastPX = end;

        }

        function getCytobandColor(data) {
            if (data.type == 'c') { // centermere: "acen"
                return "rgb(150, 10, 10)"

            } else {
                var stain = data.stain; // + 4;

                var shade = 230;
                if (data.type == 'p') {
                    shade = Math.floor(230 - stain / 100.0 * 230);
                }
                var c = stainColors[shade];
                if (c == null) {
                    c = "rgb(" + shade + "," + shade + "," + shade + ")";
                    stainColors[shade] = c;
                }
                return c;

            }
        }

    };

    return igv;
})
(igv || {});<|endoftext|>


<commit_before>var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

// this will center the ball horizontally since half of the width of the canvas is right in the middle
var x = canvas.width/2;
// vertically, we will push the ball up 30px from the bottom of the page
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
// starting width and height
var paddleHeight = 10;
var paddleWidth = 75;
// starting x position on canvas
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;

//event listeners that will tell when a key is pressed down/when it is released
document.addEventListener("keydown", keyDownHandler);
document.addEventListener("keyup", keyUpHandler);

// when you press the key down, it stores a keycode for the key that is pressed
  // is then passed as an argument into this function
  // keycode 39 corresponds to the right arrow
function keyDownHandler(e) {
  if(e.keyCode == 39) {
    rightPressed = true;
  }
  else if (e.keyCode == 37) {
    leftPressed = true;
  }
}

function keyUpHandler(e) {
  if(e.keyCode == 39) {
    rightPressed = false;
  }
  else if (e.keyCode == 37) {
    leftPressed = false;
  }
}

function drawBall() {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI*2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}

function drawPaddle() {
  ctx.beginPath();
  ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}

function draw() {
  // clears the canvas before ball is drawn
  ctx.clearRect(0,0, canvas.width, canvas.height);
  // adds 2 on every frame every 10 milliseconds

  //cleaned up function by calling the drawBall function each time
  drawBall();
  drawPaddle();

// is y position + the position of dy (2 in this case) is less than 0
  // if it's less than 0, we know the ball is moving up and off the canvas
  if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
    dy = -dy;
  }
  if(x + dx > canvas.width-ballRadius|| x + dx < ballRadius) {
    dx = -dx;
  }

  // checking if left and right is pressed
  if(rightPressed && paddleX < canvas.width-paddleWidth) {
    paddleX += 7;
  }
  else if(leftPressed && paddleX > 0) {
    paddleX -= 7;
  }

  x += dx;
  y += dy;
}

//first parameter is function to be executed
//second parameter indicates number of milliseconds before execution
setInterval(draw, 10);
<commit_msg>made it possible to lose if the ball hits the bottom of the frame<commit_after>var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

// this will center the ball horizontally since half of the width of the canvas is right in the middle
var x = canvas.width/2;
// vertically, we will push the ball up 30px from the bottom of the page
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
// starting width and height
var paddleHeight = 10;
var paddleWidth = 75;
// starting x position on canvas
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;

//event listeners that will tell when a key is pressed down/when it is released
document.addEventListener("keydown", keyDownHandler);
document.addEventListener("keyup", keyUpHandler);

// when you press the key down, it stores a keycode for the key that is pressed
  // is then passed as an argument into this function
  // keycode 39 corresponds to the right arrow
function keyDownHandler(e) {
  if(e.keyCode == 39) {
    rightPressed = true;
  }
  else if (e.keyCode == 37) {
    leftPressed = true;
  }
}

function keyUpHandler(e) {
  if(e.keyCode == 39) {
    rightPressed = false;
  }
  else if (e.keyCode == 37) {
    leftPressed = false;
  }
}

function drawBall() {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI*2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}

function drawPaddle() {
  ctx.beginPath();
  ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}

function draw() {
  // clears the canvas before ball is drawn
  ctx.clearRect(0,0, canvas.width, canvas.height);
  // adds 2 on every frame every 10 milliseconds

  //cleaned up function by calling the drawBall function each time
  drawBall();
  drawPaddle();

// is y position + the position of dy (2 in this case) is less than 0
  // if it's less than 0, we know the ball is moving up and off the canvas
  if(y + dy < ballRadius) {
    dy = -dy;
  } else if (y + dy > canvas.height-ballRadius) {
    alert("GAME OVER");
    // returns location object that contains information about the url of the document
    document.location.reload();
  }
  if(x + dx > canvas.width-ballRadius|| x + dx < ballRadius) {
    dx = -dx;
  }

  // checking if left and right is pressed
  if(rightPressed && paddleX < canvas.width-paddleWidth) {
    paddleX += 7;
  }
  else if(leftPressed && paddleX > 0) {
    paddleX -= 7;
  }

  x += dx;
  y += dy;
}

//first parameter is function to be executed
//second parameter indicates number of milliseconds before execution
setInterval(draw, 10);
<|endoftext|>