<commit_before>
var snakeCells = [];
var food;
var initialSnakeLength = 3;
var cellWidth = 10;
var numberOfGameCells = 40;
var gameWidth = numberOfGameCells * cellWidth;
var snakeSpeed = 5;
var game = new Phaser.Game(gameWidth, gameWidth, Phaser.AUTO, 'snake', { preload: preload, create: create, update: update });

var DIRECTION = {
    UP: 1,
    RIGHT: 2,
    DOWN: 3,
    LEFT: 4
};

var direction = DIRECTION.RIGHT;
var inputBuffer = [];
var inputBufferSize = 2;
var upArrowKey;
var rightArrowKey;
var downArrowKey;
var leftArrowKey;

function getAdjacentCellPosition(x, y, size, direction) {
    var newX;
    var newY;
    if (direction == DIRECTION.UP) {
        newY = y - size;
        if (newY < 0) {
            newY = newY + gameWidth;
        }
        return {x:x, y:newY};
    } else if (direction == DIRECTION.RIGHT) {
        newX = x + size;
        if (newX >= gameWidth) {
            newX = newX - gameWidth;
        }
        return {x:newX, y:y};
    } else if (direction == DIRECTION.DOWN) {
        newY = y + size;
        if (newY >= gameWidth) {
            newY = newY - gameWidth;
        }
        return {x:x, y:newY};
    } else if (direction == DIRECTION.LEFT) {
        newX = x - size;
        if (newX < 0) {
            newX = newX + gameWidth;
        }
        return {x:newX, y:y};
    }
}

function moveSnake() {
    var head = snakeCells[0];
    var newDirection = inputBuffer.shift();
    if (!newDirection) {
        newDirection = direction;
    }
    var nextPosition = getAdjacentCellPosition(head.x, head.y, cellWidth, newDirection);
    if (isFoodLocation(nextPosition.x, nextPosition.y)) {
        snakeCells.unshift(game.add.sprite(nextPosition.x, nextPosition.y, 'cell'));
        var foodLocation = createFoodLocation();
        food.x = foodLocation.x;
        food.y = foodLocation.y;
    }

    var last = snakeCells.pop();
    last.x = nextPosition.x;
    last.y = nextPosition.y;
    snakeCells.unshift(last);
    direction = newDirection;
}

function preload() {
    game.load.image('cell', 'images/cell.png');
}

function create() {
    game.stage.backgroundColor = '#ffffff';

    for (var i = initialSnakeLength - 1;i >= 0;--i) {
        snakeCells.push(game.add.sprite(i * cellWidth, 0, 'cell'));
    }
    var foodLocation = createFoodLocation();
    food = game.add.sprite(foodLocation.x, foodLocation.y, 'cell');

    game.time.events.loop(Phaser.Timer.SECOND / snakeSpeed, moveSnake, this);

    upArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.UP);
    upArrowKey.onDown.add(onUpArrowKeyPressed, this);
    rightArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
    rightArrowKey.onDown.add(onRightArrowKeyPressed, this);
    downArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
    downArrowKey.onDown.add(onDownArrowKeyPressed, this);
    leftArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
    leftArrowKey.onDown.add(onLeftArrowKeyPressed, this);
}

function update() {
}

function createFoodLocation() {
    var x = game.rnd.integerInRange(0, numberOfGameCells - 1) * cellWidth;
    var y = game.rnd.integerInRange(0, numberOfGameCells - 1) * cellWidth;
    while (isInsideSnake(x, y)) {
        x = game.rnd.integerInRange(0, numberOfGameCells - 1) * cellWidth;
        y = game.rnd.integerInRange(0, numberOfGameCells - 1) * cellWidth;
    }

    return {x:x, y:y};
}

function isInsideSnake(x, y) {
    var length = snakeCells.length;
    for (var i = 0;i < length;i++) {
        var cell = snakeCells[i];
        if (cell.x === x && cell.y === y) {
            return true;
        }
    }
    return false;
}

function isFoodLocation(x, y) {
    if (food && food.x === x && food.y === y) {
        return true;
    }
    return false;
}

function onUpArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.DOWN) {
        newDirection = DIRECTION.UP;
    }
    if (newDirection && inputBuffer.length < inputBufferSize) {
        inputBuffer.push(newDirection);
    }
}

function onRightArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.LEFT) {
        newDirection = DIRECTION.RIGHT;
    }
    if (newDirection && inputBuffer.length < inputBufferSize) {
        inputBuffer.push(newDirection);
    }
}

function onDownArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.UP) {
        newDirection = DIRECTION.DOWN;
    }
    if (newDirection && inputBuffer.length < inputBufferSize) {
        inputBuffer.push(newDirection);
    }
}

function onLeftArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.RIGHT) {
        newDirection = DIRECTION.LEFT;
    }
    if (newDirection && inputBuffer.length < inputBufferSize) {
        inputBuffer.push(newDirection);
    }
}
<commit_msg>Game restart on self collision<commit_after>var INITIAL_SNAKE_LENGTH = 3;
var CELL_WIDTH = 10;
var NUMBER_OF_GAME_CELLS = 40;
var GAME_WIDTH = NUMBER_OF_GAME_CELLS * CELL_WIDTH;
var INPUT_BUFFER_SIZE = 2;

var DIRECTION = {
    UP: 1,
    RIGHT: 2,
    DOWN: 3,
    LEFT: 4
};

var direction;
var inputBuffer;
var upArrowKey;
var rightArrowKey;
var downArrowKey;
var leftArrowKey;
var snakeCells;
var food;
var snakeSpeed ;

function init() {
    direction = DIRECTION.RIGHT;
    inputBuffer = [];
    snakeCells = [];
    food;
    snakeSpeed = 5;
}

function restart() {
    var length = snakeCells.length;
    for (var i = 0;i < length;i++) {
        snakeCells[i].kill();
    }
    food.kill();
    init();
}

init();

var game = new Phaser.Game(GAME_WIDTH, GAME_WIDTH, Phaser.AUTO, 'snake');

var main = {
    preload: function() {
        game.load.image('cell', 'images/cell.png');
    },

    create: function() {
        game.stage.backgroundColor = '#ffffff';

        for (var i = INITIAL_SNAKE_LENGTH - 1;i >= 0;--i) {
            snakeCells.push(game.add.sprite(i * CELL_WIDTH, 0, 'cell'));
        }
        var foodLocation = createFoodLocation();
        food = game.add.sprite(foodLocation.x, foodLocation.y, 'cell');

        game.time.events.loop(Phaser.Timer.SECOND / snakeSpeed, moveSnake, this);

        upArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.UP);
        upArrowKey.onDown.add(onUpArrowKeyPressed, this);
        rightArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
        rightArrowKey.onDown.add(onRightArrowKeyPressed, this);
        downArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
        downArrowKey.onDown.add(onDownArrowKeyPressed, this);
        leftArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
        leftArrowKey.onDown.add(onLeftArrowKeyPressed, this);
    },

    update: function() {
    }
};

game.state.add('main', main);
game.state.start('main');

function getAdjacentCellPosition(x, y, size, direction) {
    var newX;
    var newY;
    if (direction == DIRECTION.UP) {
        newY = y - size;
        if (newY < 0) {
            newY = newY + GAME_WIDTH;
        }
        return {x:x, y:newY};
    } else if (direction == DIRECTION.RIGHT) {
        newX = x + size;
        if (newX >= GAME_WIDTH) {
            newX = newX - GAME_WIDTH;
        }
        return {x:newX, y:y};
    } else if (direction == DIRECTION.DOWN) {
        newY = y + size;
        if (newY >= GAME_WIDTH) {
            newY = newY - GAME_WIDTH;
        }
        return {x:x, y:newY};
    } else if (direction == DIRECTION.LEFT) {
        newX = x - size;
        if (newX < 0) {
            newX = newX + GAME_WIDTH;
        }
        return {x:newX, y:y};
    }
}

function moveSnake() {
    var head = snakeCells[0];
    var newDirection = inputBuffer.shift();
    if (!newDirection) {
        newDirection = direction;
    }
    var nextPosition = getAdjacentCellPosition(head.x, head.y, CELL_WIDTH, newDirection);
    if (isFoodLocation(nextPosition.x, nextPosition.y)) {
        snakeCells.unshift(game.add.sprite(nextPosition.x, nextPosition.y, 'cell'));
        var foodLocation = createFoodLocation();
        food.x = foodLocation.x;
        food.y = foodLocation.y;
    } else if (isInsideSnake(nextPosition.x, nextPosition.y)) {
        restart();
        game.state.start('main');
        return;
    }

    var last = snakeCells.pop();
    last.x = nextPosition.x;
    last.y = nextPosition.y;
    snakeCells.unshift(last);
    direction = newDirection;
}

function createFoodLocation() {
    var x = game.rnd.integerInRange(0, NUMBER_OF_GAME_CELLS - 1) * CELL_WIDTH;
    var y = game.rnd.integerInRange(0, NUMBER_OF_GAME_CELLS - 1) * CELL_WIDTH;
    while (isInsideSnake(x, y)) {
        x = game.rnd.integerInRange(0, NUMBER_OF_GAME_CELLS - 1) * CELL_WIDTH;
        y = game.rnd.integerInRange(0, NUMBER_OF_GAME_CELLS - 1) * CELL_WIDTH;
    }

    return {x:x, y:y};
}

function isInsideSnake(x, y) {
    var length = snakeCells.length;
    for (var i = 0;i < length;i++) {
        var cell = snakeCells[i];
        if (cell.x === x && cell.y === y) {
            return true;
        }
    }
    return false;
}

function isFoodLocation(x, y) {
    if (food && food.x === x && food.y === y) {
        return true;
    }
    return false;
}

function onUpArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.DOWN) {
        newDirection = DIRECTION.UP;
    }
    if (newDirection && inputBuffer.length < INPUT_BUFFER_SIZE) {
        inputBuffer.push(newDirection);
    }
}

function onRightArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.LEFT) {
        newDirection = DIRECTION.RIGHT;
    }
    if (newDirection && inputBuffer.length < INPUT_BUFFER_SIZE) {
        inputBuffer.push(newDirection);
    }
}

function onDownArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.UP) {
        newDirection = DIRECTION.DOWN;
    }
    if (newDirection && inputBuffer.length < INPUT_BUFFER_SIZE) {
        inputBuffer.push(newDirection);
    }
}

function onLeftArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.RIGHT) {
        newDirection = DIRECTION.LEFT;
    }
    if (newDirection && inputBuffer.length < INPUT_BUFFER_SIZE) {
        inputBuffer.push(newDirection);
    }
}
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs');
var path = require('path');
var moment = require('moment');
var clc = require('cli-color');
var rek = require('rekuire');

module.exports = {
  show: show
};

function show(target, options) {
  var targetPath = resolveDirectory(target);
  var filePath = targetPath + '/dupes.json';
  //TODO: Check if exists
  var resultObject = JSON.parse(fs.readFileSync(filePath));
  if (options.showJson) {
    console.log(resultAge(resultObject));
    console.log(resultOutput(resultObject));
  } else {
    console.log(JSON.stringify(resultObject, null, 3));
  }
}

/////////////////////////////////

function resolveDirectory(dir) { //TODO: duplicate code, combine
  var fullPath = path.resolve(dir || process.cwd());
  if (!(fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory())) {
    console.log(fullPath + ' is not a directory!'); //TODO: This should use the logger
    process.exit();
  }
  return fullPath;
}

function resultAge(resultObject) {
  return 'This file was created on: ' + resultObject.date + '\n' + 'Which is ' + cliTimeAgo(resultObject.unixTimeStamp);
}

function resultOutput(resultObject) { //TODO: duplicate code, combine
  var sets = resultObject.sets; //TODO: Change 'resut' to 'sets'.
  if (sets.length == 0) return '\nThere are no suspected dupes.\n';
  var totalDuplicatesVolume = sets.map(function(set) { return (set.length - 1) * set[0].size; }).reduce(sum, 0);
  var setsByPathOnly = sets.map(function(set) { return set.map(function(file) { return file.path; })});
  var list = setsByPathOnly.map(function(set) { return set.join('\n'); }).join('\n\n');
  var totalRunDuration = resultObject.scanDuration + resultObject.steps.map(function(step) { return step.duration; }).reduce(sum, 0);
  return '\nThese are the suspected dupes:\n\n' + list + '\n\nTotal duplicate volume: ' + totalDuplicatesVolume + ' bytes' + '\nTotal run duration: ' + totalRunDuration.toFixed(3) + ' seconds.';
}

function sum(a, b) {
  return a + b;
}

////////////////////////////////////////////////////////////////////////////////
//TODO: All of this is pasted straight from nsyrc/lib/commands/linksDataUtils.js
//Move to own package:

function ProcessedString(str, funcArray) {
  this.str = str;
  this.length = this.str.length;
  this.funcArray = (funcArray instanceof Array) ? funcArray : [funcArray];
}
ProcessedString.prototype.toString = function() {
  return this.funcArray.filter(Boolean).reduce(function(prev, curr) { return curr(prev); }, this.str);
}
function cliTimeAgo(unixTimeStamp) {
  return new ProcessedString(unixTimeStamp ? moment(unixTimeStamp).fromNow() : "Never", timeAgoColorFunction(unixTimeStamp));
}
function timeAgoColorFunction(unixTimeStamp) {
  var updateStatus = getUpdateStatus(unixTimeStamp);
  if (updateStatus == LinkUpdateStatus.OLD) return clc.red;
  if (updateStatus == LinkUpdateStatus.SEMI) return clc.yellow;
  if (updateStatus == LinkUpdateStatus.NEW) return clc.white;
}
function getUpdateStatus(unixTimeStamp) {
  var secondsAgo = moment().diff(moment(unixTimeStamp || 0)) / 1000;
  if (secondsAgo > 60*60*24*7) { //TODO: this time period (week) should be configurable. //From outside the package!
    return LinkUpdateStatus.OLD;
  } else if (secondsAgo > 60*60*24) { //TODO: this time period (day) should be configurable. //From outside the package!
    return LinkUpdateStatus.SEMI;
  }
  return LinkUpdateStatus.NEW;
}
var LinkUpdateStatus = {
  NEW: 'new',
  SEMI: 'semi',
  OLD: 'old'
}

////////////////////////////////////////////////////////////////////////////////<commit_msg>revented error on missing result file<commit_after>"use strict";

var fs = require('fs');
var path = require('path');
var moment = require('moment');
var clc = require('cli-color');
var rek = require('rekuire');

module.exports = {
  show: show
};

function show(target, options) {
  var targetPath = resolveDirectory(target);
  var filePath = targetPath + '/dupes.json';
  checkFileExists(filePath);
  var resultObject = JSON.parse(fs.readFileSync(filePath)); //TODO: prevent error on file read fail
  if (options.showJson) {
    console.log(resultAge(resultObject));
    console.log(resultOutput(resultObject));
  } else {
    console.log(JSON.stringify(resultObject, null, 3));
  }
}

/////////////////////////////////

function resolveDirectory(dir) { //TODO: duplicate code, combine
  var fullPath = path.resolve(dir || process.cwd());
  if (!(fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory())) {
    console.log(fullPath + ' is not a directory!'); //TODO: This should use the logger
    process.exit();
  }
  return fullPath;
}

function checkFileExists(filePath) {
  if (!fs.existsSync(filePath)) {
    console.log(clc.red(filePath + ' does not exist!')); //TODO: This should use the logger
    process.exit(); //TODO: avoid this
  } else if (!fs.statSync(filePath).isFile()) {
    console.log(clc.red(filePath + ' is not a file!')); //TODO: This should use the logger
    process.exit(); //TODO: avoid This
  }
}

function resultAge(resultObject) {
  return 'This file was created on: ' + resultObject.date + '\n' + 'Which is ' + cliTimeAgo(resultObject.unixTimeStamp);
}

function resultOutput(resultObject) { //TODO: duplicate code, combine
  var sets = resultObject.sets; //TODO: Change 'resut' to 'sets'.
  if (sets.length == 0) return '\nThere are no suspected dupes.\n';
  var totalDuplicatesVolume = sets.map(function(set) { return (set.length - 1) * set[0].size; }).reduce(sum, 0);
  var setsByPathOnly = sets.map(function(set) { return set.map(function(file) { return file.path; })});
  var list = setsByPathOnly.map(function(set) { return set.join('\n'); }).join('\n\n');
  var totalRunDuration = resultObject.scanDuration + resultObject.steps.map(function(step) { return step.duration; }).reduce(sum, 0);
  return '\nThese are the suspected dupes:\n\n' + list + '\n\nTotal duplicate volume: ' + totalDuplicatesVolume + ' bytes' + '\nTotal run duration: ' + totalRunDuration.toFixed(3) + ' seconds.';
}

function sum(a, b) {
  return a + b;
}

////////////////////////////////////////////////////////////////////////////////
//TODO: All of this is pasted straight from nsyrc/lib/commands/linksDataUtils.js
//Move to own package:

function ProcessedString(str, funcArray) {
  this.str = str;
  this.length = this.str.length;
  this.funcArray = (funcArray instanceof Array) ? funcArray : [funcArray];
}
ProcessedString.prototype.toString = function() {
  return this.funcArray.filter(Boolean).reduce(function(prev, curr) { return curr(prev); }, this.str);
}
function cliTimeAgo(unixTimeStamp) {
  return new ProcessedString(unixTimeStamp ? moment(unixTimeStamp).fromNow() : "Never", timeAgoColorFunction(unixTimeStamp));
}
function timeAgoColorFunction(unixTimeStamp) {
  var updateStatus = getUpdateStatus(unixTimeStamp);
  if (updateStatus == LinkUpdateStatus.OLD) return clc.red;
  if (updateStatus == LinkUpdateStatus.SEMI) return clc.yellow;
  if (updateStatus == LinkUpdateStatus.NEW) return clc.white;
}
function getUpdateStatus(unixTimeStamp) {
  var secondsAgo = moment().diff(moment(unixTimeStamp || 0)) / 1000;
  if (secondsAgo > 60*60*24*7) { //TODO: this time period (week) should be configurable. //From outside the package!
    return LinkUpdateStatus.OLD;
  } else if (secondsAgo > 60*60*24) { //TODO: this time period (day) should be configurable. //From outside the package!
    return LinkUpdateStatus.SEMI;
  }
  return LinkUpdateStatus.NEW;
}
var LinkUpdateStatus = {
  NEW: 'new',
  SEMI: 'semi',
  OLD: 'old'
}

////////////////////////////////////////////////////////////////////////////////<|endoftext|>


<commit_before>'use strict';

let minecrafterFont = undefined;

let loadFont = function(myFont) {
    minecrafterFont = myFont;

    initMessages();
};

let messages = [];

let createMessage = function(text) {
    let geometry = new THREE.TextGeometry(text, {
            font: minecrafterFont,
            size: 0.4,
            height: 0.2
        });
    let material = new THREE.MeshLambertMaterial({color: 0x6a6a6b});
    material.opacity = 0;
    material.transparent = true;
    let textM = new THREE.Mesh( geometry, material );

    return textM;
};

let createTotemMessage = function(text) {
    let geometry = new THREE.TextGeometry(text, {
            font: minecrafterFont,
            size: 0.2,
            height: 0.1
        });
    let material = new THREE.MeshLambertMaterial({color: 0xb29060});
    let textM = new THREE.Mesh( geometry, material );

    return textM;
};

let objectFade = function(delta, messages) {
    for (let i = 0; i < messages.length; i++) {
        let deltaOpacity = messages[i].material.wantedOpacity - messages[i].material.opacity;

        if (deltaOpacity > 0.05) {
            messages[i].material.opacity += delta;
        }
        else if (deltaOpacity < -0.05) {
            messages[i].material.opacity -= delta;
        }
        else {
            messages[i].material.opacity = Math.round(messages[i].material.opacity);
        }
    }
};

let initMessages = function() {

    messages.push(createMessage('I am Tom!'));
    messages[0].position.set(-20,-0,-8);
    messages[0].rotation.y = 3.14/2;
    scene.add(messages[0]);
    eventMap.push(new eventMapItem( 11, 7, () => { showMessage(0) }, undefined));
    eventMap.push(new eventMapItem( 12, 7, () => { showMessage(0) }, undefined));
    eventMap.push(new eventMapItem( 18, 11, undefined, () => { hideMessage(0); showMessage(1); showMessage(2); }));
    eventMap.push(new eventMapItem( 18, 10, undefined, () => { hideMessage(0); showMessage(1); showMessage(2); }));
    eventMap.push(new eventMapItem( 18, 9, undefined, () => { hideMessage(0); showMessage(1); showMessage(2); }));

    messages.push(createMessage('And this is'));
    messages[1].position.set(-24,1.6,-16);
    scene.add(messages[1]);
    messages.push(createMessage('my mind...'));
    messages[2].position.set(-24,1,-16);
    scene.add(messages[2]);
    //eventMap.push(new eventMapItem( 8, 11, () => { showMessage(1); showMessage(2); }, undefined));
    //eventMap.push(new eventMapItem( 8, 12, () => { showMessage(1); showMessage(2); }, undefined));
    eventMap.push(new eventMapItem( 26, 18, undefined, () => { hideMessage(1); hideMessage(2); }));

    messages.push(createMessage('Free Time Forest'));
    messages[3].position.set(-24, 1, -63);
    scene.add(messages[3]);
    showMessage(3);

    messages.push(createMessage('Kazou zone'));
    messages[4].position.set(-5, 2, -52);
    scene.add(messages[4]);
    showMessage(4);

    messages.push(createMessage('Experiment'));
    messages[5].position.set(-20, 1.6, -45);
    messages[5].rotation.y = 3.14/2;
    scene.add(messages[5]);
    showMessage(5);
    messages.push(createMessage('zone'));
    messages[6].position.set(-20, 1, -45);
    messages[6].rotation.y = 3.14/2;
    scene.add(messages[6]);
    showMessage(6);

    messages.push(createMessage('In my'));
    messages[7].position.set(-3.5, -0.5, -61);
    messages[7].rotation.x = -3.14/2;
    scene.add(messages[7]);
    showMessage(7);
    messages.push(createMessage('mind'));
    messages[8].position.set(-3.5, -0.5, -60);
    messages[8].rotation.x = -3.14/2;
    scene.add(messages[8]);
    showMessage(8);

    messages.push(createMessage('Leaving the'));
    messages[9].position.set(-5, 0.6, -64);
    messages[9].rotation.y = 3.14/2;
    scene.add(messages[9]);
    showMessage(9);
    messages.push(createMessage('comfort zone'));
    messages[10].position.set(-5, 0, -64);
    messages[10].rotation.y = 3.14/2;
    scene.add(messages[10]);
    showMessage(10);

    messages.push(createMessage('Is'));
    messages[11].position.set(-4.5, -0.5, -84);
    messages[11].rotation.x = -3.14/2;
    scene.add(messages[11]);
    showMessage(11);
    messages.push(createMessage('easy!'));
    messages[12].position.set(-4.5, -0.5, -83);
    messages[12].rotation.x = -3.14/2;
    scene.add(messages[12]);
    showMessage(12);

    messages.push(createMessage('Learn more'));
    messages[13].position.set(-6, 1.3, -100);
    scene.add(messages[13]);
    showMessage(13);
    messages.push(createMessage('about Tom'));
    messages[14].position.set(-6, 0.7, -100);
    scene.add(messages[14]);
    showMessage(14);
    messages.push(createMessage('here!'));
    messages[15].position.set(-6, 0.1, -100);
    scene.add(messages[15]);
    showMessage(15);

    messages.push(createMessage('The end.'));
    messages[16].position.set(-6, 2.2, -100);
    scene.add(messages[16]);
    showMessage(16);

    messages.push(createMessage('Good for building'));
    messages[17].position.set(-6, -0.5, -86);
    messages[17].rotation.x = -3.14/2;
    messages[17].rotation.z = 3.14/2;
    scene.add(messages[17]);
    showMessage(17);

    messages.push(createMessage('new connections!'));
    messages[18].position.set(-5, -0.5, -86);
    messages[18].rotation.x = -3.14/2;
    messages[18].rotation.z = 3.14/2;
    scene.add(messages[18]);
    showMessage(18);

    eventMap.push(new eventMapItem(2,52,()=>{ startKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(3,52,()=>{ startKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(2,55,()=>{ startKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(3,55,()=>{ startKazouMode(); }, undefined));

    eventMap.push(new eventMapItem(2,51,()=>{ stopKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(3,51,()=>{ stopKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(2,56,()=>{ stopKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(3,56,()=>{ stopKazouMode(); }, undefined));

    createTotem('Skill', 2, -37, -38);
    createTotem('Totems', 2, -34, -38);

    createTotem('Java', 3, -39, -42);
    createTotem('C#', 3, -32, -42);

    createTotem('SPRING', 2, -39, -46);
    createTotem('Javascript', 2.5, -32, -46);

    createTotem('OpenGL/WebGL', 2.5, -39, -50);
    createTotem('NodeJS', 2.5, -32, -50);

    createTotem('Python', 2, -39, -54);
    createTotem('OpenCV', 2, -32, -54);

    createTotem('PHP', 2, -39, -58);
    createTotem('Angular 2', 2, -32, -58);
}

let showMessage = function(id) {
    messages[id].material.wantedOpacity = 1;
}
let hideMessage = function(id) {
    messages[id].material.wantedOpacity = 0;
}
<commit_msg>free time forest -> spare time forest<commit_after>'use strict';

let minecrafterFont = undefined;

let loadFont = function(myFont) {
    minecrafterFont = myFont;

    initMessages();
};

let messages = [];

let createMessage = function(text) {
    let geometry = new THREE.TextGeometry(text, {
            font: minecrafterFont,
            size: 0.4,
            height: 0.2
        });
    let material = new THREE.MeshLambertMaterial({color: 0x6a6a6b});
    material.opacity = 0;
    material.transparent = true;
    let textM = new THREE.Mesh( geometry, material );

    return textM;
};

let createTotemMessage = function(text) {
    let geometry = new THREE.TextGeometry(text, {
            font: minecrafterFont,
            size: 0.2,
            height: 0.1
        });
    let material = new THREE.MeshLambertMaterial({color: 0xb29060});
    let textM = new THREE.Mesh( geometry, material );

    return textM;
};

let objectFade = function(delta, messages) {
    for (let i = 0; i < messages.length; i++) {
        let deltaOpacity = messages[i].material.wantedOpacity - messages[i].material.opacity;

        if (deltaOpacity > 0.05) {
            messages[i].material.opacity += delta;
        }
        else if (deltaOpacity < -0.05) {
            messages[i].material.opacity -= delta;
        }
        else {
            messages[i].material.opacity = Math.round(messages[i].material.opacity);
        }
    }
};

let initMessages = function() {

    messages.push(createMessage('I am Tom!'));
    messages[0].position.set(-20,-0,-8);
    messages[0].rotation.y = 3.14/2;
    scene.add(messages[0]);
    eventMap.push(new eventMapItem( 11, 7, () => { showMessage(0) }, undefined));
    eventMap.push(new eventMapItem( 12, 7, () => { showMessage(0) }, undefined));
    eventMap.push(new eventMapItem( 18, 11, undefined, () => { hideMessage(0); showMessage(1); showMessage(2); }));
    eventMap.push(new eventMapItem( 18, 10, undefined, () => { hideMessage(0); showMessage(1); showMessage(2); }));
    eventMap.push(new eventMapItem( 18, 9, undefined, () => { hideMessage(0); showMessage(1); showMessage(2); }));

    messages.push(createMessage('And this is'));
    messages[1].position.set(-24,1.6,-16);
    scene.add(messages[1]);
    messages.push(createMessage('my mind...'));
    messages[2].position.set(-24,1,-16);
    scene.add(messages[2]);
    //eventMap.push(new eventMapItem( 8, 11, () => { showMessage(1); showMessage(2); }, undefined));
    //eventMap.push(new eventMapItem( 8, 12, () => { showMessage(1); showMessage(2); }, undefined));
    eventMap.push(new eventMapItem( 26, 18, undefined, () => { hideMessage(1); hideMessage(2); }));

    messages.push(createMessage('Spare Time Forest'));
    messages[3].position.set(-24, 1, -63);
    scene.add(messages[3]);
    showMessage(3);

    messages.push(createMessage('Kazou zone'));
    messages[4].position.set(-5, 2, -52);
    scene.add(messages[4]);
    showMessage(4);

    messages.push(createMessage('Experiment'));
    messages[5].position.set(-20, 1.6, -45);
    messages[5].rotation.y = 3.14/2;
    scene.add(messages[5]);
    showMessage(5);
    messages.push(createMessage('zone'));
    messages[6].position.set(-20, 1, -45);
    messages[6].rotation.y = 3.14/2;
    scene.add(messages[6]);
    showMessage(6);

    messages.push(createMessage('In my'));
    messages[7].position.set(-3.5, -0.5, -61);
    messages[7].rotation.x = -3.14/2;
    scene.add(messages[7]);
    showMessage(7);
    messages.push(createMessage('mind'));
    messages[8].position.set(-3.5, -0.5, -60);
    messages[8].rotation.x = -3.14/2;
    scene.add(messages[8]);
    showMessage(8);

    messages.push(createMessage('Leaving the'));
    messages[9].position.set(-5, 0.6, -64);
    messages[9].rotation.y = 3.14/2;
    scene.add(messages[9]);
    showMessage(9);
    messages.push(createMessage('comfort zone'));
    messages[10].position.set(-5, 0, -64);
    messages[10].rotation.y = 3.14/2;
    scene.add(messages[10]);
    showMessage(10);

    messages.push(createMessage('Is'));
    messages[11].position.set(-4.5, -0.5, -84);
    messages[11].rotation.x = -3.14/2;
    scene.add(messages[11]);
    showMessage(11);
    messages.push(createMessage('easy!'));
    messages[12].position.set(-4.5, -0.5, -83);
    messages[12].rotation.x = -3.14/2;
    scene.add(messages[12]);
    showMessage(12);

    messages.push(createMessage('Learn more'));
    messages[13].position.set(-6, 1.3, -100);
    scene.add(messages[13]);
    showMessage(13);
    messages.push(createMessage('about Tom'));
    messages[14].position.set(-6, 0.7, -100);
    scene.add(messages[14]);
    showMessage(14);
    messages.push(createMessage('here!'));
    messages[15].position.set(-6, 0.1, -100);
    scene.add(messages[15]);
    showMessage(15);

    messages.push(createMessage('The end.'));
    messages[16].position.set(-6, 2.2, -100);
    scene.add(messages[16]);
    showMessage(16);

    messages.push(createMessage('Good for building'));
    messages[17].position.set(-6, -0.5, -86);
    messages[17].rotation.x = -3.14/2;
    messages[17].rotation.z = 3.14/2;
    scene.add(messages[17]);
    showMessage(17);

    messages.push(createMessage('new connections!'));
    messages[18].position.set(-5, -0.5, -86);
    messages[18].rotation.x = -3.14/2;
    messages[18].rotation.z = 3.14/2;
    scene.add(messages[18]);
    showMessage(18);

    eventMap.push(new eventMapItem(2,52,()=>{ startKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(3,52,()=>{ startKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(2,55,()=>{ startKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(3,55,()=>{ startKazouMode(); }, undefined));

    eventMap.push(new eventMapItem(2,51,()=>{ stopKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(3,51,()=>{ stopKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(2,56,()=>{ stopKazouMode(); }, undefined));
    eventMap.push(new eventMapItem(3,56,()=>{ stopKazouMode(); }, undefined));

    createTotem('Skill', 2, -37, -38);
    createTotem('Totems', 2, -34, -38);

    createTotem('Java', 3, -39, -42);
    createTotem('C#', 3, -32, -42);

    createTotem('SPRING', 2, -39, -46);
    createTotem('Javascript', 2.5, -32, -46);

    createTotem('OpenGL/WebGL', 2.5, -39, -50);
    createTotem('NodeJS', 2.5, -32, -50);

    createTotem('Python', 2, -39, -54);
    createTotem('OpenCV', 2, -32, -54);

    createTotem('PHP', 2, -39, -58);
    createTotem('Angular 2', 2, -32, -58);
}

let showMessage = function(id) {
    messages[id].material.wantedOpacity = 1;
}
let hideMessage = function(id) {
    messages[id].material.wantedOpacity = 0;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2012 Seamus D'Arcy */

var common    = require('seneca/lib/common');
var Store     = require('seneca').Store;
var dynamodb  = require('dynamodb');
var async     = require('async');

var eyes      = common.eyes; // Used for development only
var _         = common._;
var uuid      = common.uuid;

var ARRAY_TYPE = 'a';
var BOOL_TYPE = 'b';
var DATE_TYPE = 'd';
var OBJECT_TYPE = 'o';
var SENECA_TYPE_COLUMN = 'seneca';

// TODO:
// - API Paging i.e. LastEvaluatedKey

function DynamoDBStore() {

  var self = new Store();
  var parent = self.parent();

  var seneca;

  self.name = 'seneca-dynamodb';

  /** called by seneca to initialise plugin */
  self.init = function(si, opts, cb) {
    parent.init(si, opts, function() {

      // keep a reference to the seneca instance
      seneca = si;

      self.configure(opts, function(err) {
        if(err) {
          return seneca.fail({code: 'entity', store: self.name, error: err}, cb);
        }
        else cb();
      });
    });
  };

  /** create or update an entity */
  self.save$ = function(args, cb) {
    // entity to save
    var ent  = args.ent;
    var update = !!ent.id;
    var table = tablename(ent);

    if( !ent.id ) {
      ent.id = uuid();
    }

    var entp = makeentp(ent);

    if(update) {
      // id received - execute an update

      var updates = {};

      for(var e in entp) {
        if(entp.hasOwnProperty(e) && 'function' != typeof(entp[e]) && e != 'id') {
          updates[e] = {value: entp[e], action: 'PUT'};
        }
      }

      self.connection.updateItem(table, ent.id, null, updates, {}, function(err, res, cap) {
        if(err) {
          return seneca.fail({code: 'save/update', tag: args.tag$, store: self.name, fields: fields, error: err }, cb);
        }
        else {
          seneca.log(args.tag$,'save/update', res);
          cb(null, ent);
        }
      });
    }
    else {
      // no id received - execute an insert
      self.connection.putItem(table, entp, {}, function(err, res, cap) {
        if(err) {
          return seneca.fail({code: 'save/insert', tag: args.tag$, store: self.name, fields: fields, error: err }, cb);
        }
        else {
          seneca.log(args.tag$, 'save/insert', res);
          cb(null, ent);
        }
      });
    }
  };

  /** load the first matching entity */
  self.load$ = function(args, cb) {

    var q = _.clone(args.q);
    var qent = args.qent;

    self.connection.getItem(tablename(qent), qent.id, null, {}, function(err, res, cap) {
      if(err) {
        return seneca.fail({code:'load', tag: args.tag$, store: self.name, error: err}, cb);
      }
      else {
        var fent = makeent(qent, res);
        seneca.log(args.tag$, 'load', res);
        cb(null, fent);
      }
    });
  };

  /** load all matching entities */
  self.list$ = function(args, cb) {

    var qent = args.qent;
    var q = args.q;

    var options = {};
    var filter = {};

    if(!q.all$) { // all$ should only be included if list is called from remove
      for (var param in q) {
         if(q.hasOwnProperty(param)) {
            filter[param] = {eq: q[param]};
         }
      }

      if(!_.isEmpty(filter)) {
        options.filter = filter;
      }
    }

    // TODO: use getItem instead of scan if q contains only id

    self.connection.scan(tablename(qent), options, function(err, res) {
      if(err) {
        return seneca.fail({code:'list', tag: args.tag$, store: self.name, error: err}, cb);
      } else {
        var list = [];
        res.items.forEach(function(item) {
          var ent = makeent(qent, item);
          list.push(ent);
        });
        cb(null, list);
      }
    });
  };

  /** remove all matching entities */
  self.remove$ = function(args, cb) {
    var table = tablename(args.qent);

    // list entities matching args
    self.list$(args, function(err, res) {
      if(err) {
        return seneca.fail({code:'remove/list', tag: args.tag$, store: self.name, error: err}, cb);
      } else {
        // create delete request request for each item
        var deletes = [];
        res.forEach(function(entity) {
          deletes.push(deleteItem(table, entity.id));
        });

        async.parallel(deletes, function(err, res) {
          if(err) {
            return seneca.fail({code:'remove/delete', tag: args.tag$, store: self.name, error: err}, cb);
          } else {
            cb(null);
          }
        });
      }
    });
  };

  /** close connection to data store - called during shutdown */
  self.close$ = function(args, cb) {
    seneca.log(args.tag$, 'close');
    cb();
  };

  self.configure = function(spec, cb) {
    self.spec = spec;

    var conf = 'string' == typeof(spec) ? null : spec;

    self.connection = dynamodb.ddb({
      accessKeyId: conf.accessKeyId,
      secretAccessKey: conf.secretAccessKey,
      endpoint: conf.endpoint
    });

    seneca.log({tag$: 'init'}, 'db open');
    cb(null, self);
  };

  var deleteItem = function(table, id) {
    return function(cb) {
      self.connection.deleteItem(table, id, null, {returnValues: 'ALL_OLD'}, function(err, res, cap) {
        if(err) {
          cb(err);
        } else {
          cb(null, res);
        }
      });
    };
  };

  var makeentp = function(ent) {
    var entp = {};
    var fields = ent.fields$();
    var type = {};

    fields.forEach(function(field) {
      if(_.isArray( ent[field])) {
        type[field] = ARRAY_TYPE;
      } else if(_.isBoolean(ent[field])) {
        type[field] = BOOL_TYPE;
      } else if(_.isDate(ent[field])) {
        type[field] = DATE_TYPE;
      } else if(!_.isArray(ent[field]) && _.isObject(ent[field])) {
        type[field] = OBJECT_TYPE;
      }

      if(_.isBoolean(ent[field]) || _.isObject(ent[field])) {
        entp[field] = JSON.stringify(ent[field]);
      } else {
        entp[field] = ent[field];
      }
    });

    if(!_.isEmpty(type)) {
      entp[SENECA_TYPE_COLUMN] = JSON.stringify(type);
    }
    return entp;
  };

  var makeent = function(ent, row) {
    var entp = {};
    var fields = _.keys(row);
    var senecatype = {};
    var conversion = {};

    if(!_.isUndefined(row[SENECA_TYPE_COLUMN]) && !_.isNull(row[SENECA_TYPE_COLUMN])) {
      senecatype = JSON.parse(row[SENECA_TYPE_COLUMN]);
    }

    conversion[ARRAY_TYPE] = conversion[OBJECT_TYPE] = function(field) { return JSON.parse(field); };
    conversion[DATE_TYPE] = function(field) { return new Date(JSON.parse(field)); };
    conversion[BOOL_TYPE] = function(field) { return Boolean(JSON.parse(field)); };

    fields.forEach(function(field) {
      if(field != SENECA_TYPE_COLUMN) {
        var convert = conversion[senecatype[field]];
        if (convert) {
          entp[field] = convert(row[field]);
        } else {
          entp[field] = row[field];
        }
      }
    });

    return ent.make$(entp);
  };

  var tablename = function(entity) {
    var canon = entity.canon$({object: true});
    return(canon.base ? canon.base + '_' : '') + canon.name;
  };

  function error(args, err, cb) {
    if(err) {
      if(!err.fatal) {
        return false;
      }

      seneca.log(args.tag$, 'error: ' + err);
      seneca.fail({code: 'entity/error', store: self.name }, cb);
      return true;
    }

    return false;
  }

  return self;
}

module.exports = new DynamoDBStore();<commit_msg>Todos, cleanup<commit_after>/* Copyright (c) 2012 Seamus D'Arcy */

/*
 * TODO
 * - Handle API paging e.g. LastEvaluatedKey where number of scanned items exceeds 1MB
 * - load$, list$ - use GetItem instead of Scan if the input contains only an id
 * - Serialization of unsupported types: the basis for makeentp() has been moved to seneca RelationalStore but Boolean is not handled
 * - load$ - support a set of properties as input (use Scan instead of GetItem in this case)
 * - list$ - handle query string as input
 * - load$ - sorting results
 */

var Store     = require('seneca').Store;
var dynamodb  = require('dynamodb');
var async     = require('async');
var _         = require('underscore');
var uuid      = require('node-uuid');

var ARRAY_TYPE = 'a';
var BOOL_TYPE = 'b';
var DATE_TYPE = 'd';
var OBJECT_TYPE = 'o';
var SENECA_TYPE_COLUMN = 'seneca';

function DynamoDBStore() {

  var self = new Store();
  var parent = self.parent();

  var seneca;

  self.name = 'seneca-dynamodb';

  /* called by seneca to initialise plugin */
  self.init = function(si, opts, cb) {
    parent.init(si, opts, function() {

      // keep a reference to the seneca instance
      seneca = si;

      self.configure(opts, function(err) {
        if(err) {
          return seneca.fail({code: 'entity', store: self.name, error: err}, cb);
        }
        else cb();
      });
    });
  };

  /* create or update an entity */
  self.save$ = function(args, cb) {
    // entity to save
    var ent  = args.ent;
    var update = !!ent.id;
    var table = tablename(ent);

    if( !ent.id ) {
      ent.id = uuid();
    }

    var entp = makeentp(ent);

    if(update) {
      // id received - execute an update

      var updates = {};

      for(var e in entp) {
        if(entp.hasOwnProperty(e) && 'function' != typeof(entp[e]) && e != 'id') {
          updates[e] = {value: entp[e], action: 'PUT'};
        }
      }

      self.connection.updateItem(table, ent.id, null, updates, {}, function(err, res, cap) {
        if(err) {
          return seneca.fail({code: 'save/update', tag: args.tag$, store: self.name, fields: fields, error: err }, cb);
        }
        else {
          seneca.log(args.tag$,'save/update', res);
          cb(null, ent);
        }
      });
    }
    else {
      // no id received - execute an insert
      self.connection.putItem(table, entp, {}, function(err, res, cap) {
        if(err) {
          return seneca.fail({code: 'save/insert', tag: args.tag$, store: self.name, fields: fields, error: err }, cb);
        }
        else {
          seneca.log(args.tag$, 'save/insert', res);
          cb(null, ent);
        }
      });
    }
  };

  /* load the first matching entity */
  self.load$ = function(args, cb) {

    var q = _.clone(args.q);
    var qent = args.qent;

    self.connection.getItem(tablename(qent), qent.id, null, {}, function(err, res, cap) {
      if(err) {
        return seneca.fail({code:'load', tag: args.tag$, store: self.name, error: err}, cb);
      }
      else {
        var fent = makeent(qent, res);
        seneca.log(args.tag$, 'load', res);
        cb(null, fent);
      }
    });
  };

  /* load all matching entities */
  self.list$ = function(args, cb) {

    var qent = args.qent;
    var q = args.q;

    var options = {};
    var filter = {};

    if(!q.all$) { // all$ should only be included if list is called from remove
      for (var param in q) {
         if(q.hasOwnProperty(param)) {
            filter[param] = {eq: q[param]};
         }
      }

      if(!_.isEmpty(filter)) {
        options.filter = filter;
      }
    }

    // TODO: use getItem instead of scan if q contains only id

    self.connection.scan(tablename(qent), options, function(err, res) {
      if(err) {
        return seneca.fail({code:'list', tag: args.tag$, store: self.name, error: err}, cb);
      } else {
        var list = [];
        res.items.forEach(function(item) {
          var ent = makeent(qent, item);
          list.push(ent);
        });
        cb(null, list);
      }
    });
  };

  /* remove all matching entities */
  self.remove$ = function(args, cb) {
    var table = tablename(args.qent);

    // list entities matching args
    self.list$(args, function(err, res) {
      if(err) {
        return seneca.fail({code:'remove/list', tag: args.tag$, store: self.name, error: err}, cb);
      } else {
        // create delete request request for each item
        var deletes = [];
        res.forEach(function(entity) {
          deletes.push(deleteItem(table, entity.id));
        });

        async.parallel(deletes, function(err, res) {
          if(err) {
            return seneca.fail({code:'remove/delete', tag: args.tag$, store: self.name, error: err}, cb);
          } else {
            cb(null);
          }
        });
      }
    });
  };

  /* close connection to data store - called during shutdown */
  self.close$ = function(args, cb) {
    seneca.log(args.tag$, 'close');
    cb();
  };

  self.configure = function(spec, cb) {
    self.spec = spec;

    var conf = 'string' == typeof(spec) ? null : spec;

    self.connection = dynamodb.ddb({
      accessKeyId: conf.accessKeyId,
      secretAccessKey: conf.secretAccessKey,
      endpoint: conf.endpoint
    });

    seneca.log({tag$: 'init'}, 'db open');
    cb(null, self);
  };

  /* returns a delete request for the specified table and item id */
  var deleteItem = function(table, id) {
    return function(cb) {
      self.connection.deleteItem(table, id, null, {returnValues: 'ALL_OLD'}, function(err, res, cap) {
        if(err) {
          cb(err);
        } else {
          cb(null, res);
        }
      });
    };
  };

  /* create a persistable entity from the entity object (serialize unsupported types) */
  var makeentp = function(ent) {
    var entp = {};
    var fields = ent.fields$();
    var type = {};

    fields.forEach(function(field) {
      if(_.isArray( ent[field])) {
        type[field] = ARRAY_TYPE;
      } else if(_.isBoolean(ent[field])) {
        type[field] = BOOL_TYPE;
      } else if(_.isDate(ent[field])) {
        type[field] = DATE_TYPE;
      } else if(!_.isArray(ent[field]) && _.isObject(ent[field])) {
        type[field] = OBJECT_TYPE;
      }

      if(_.isBoolean(ent[field]) || _.isObject(ent[field])) {
        entp[field] = JSON.stringify(ent[field]);
      } else {
        entp[field] = ent[field];
      }
    });

    if(!_.isEmpty(type)) {
      entp[SENECA_TYPE_COLUMN] = JSON.stringify(type);
    }
    return entp;
  };

  /* create a new entity from returned persistent entity (deserialize unsupported types) */
  var makeent = function(ent, row) {
    var entp = {};
    var fields = _.keys(row);
    var senecatype = {};
    var conversion = {};

    if(!_.isUndefined(row[SENECA_TYPE_COLUMN]) && !_.isNull(row[SENECA_TYPE_COLUMN])) {
      senecatype = JSON.parse(row[SENECA_TYPE_COLUMN]);
    }

    conversion[ARRAY_TYPE] = conversion[OBJECT_TYPE] = function(field) { return JSON.parse(field); };
    conversion[DATE_TYPE] = function(field) { return new Date(JSON.parse(field)); };
    conversion[BOOL_TYPE] = function(field) { return Boolean(JSON.parse(field)); };

    fields.forEach(function(field) {
      if(field != SENECA_TYPE_COLUMN) {
        var convert = conversion[senecatype[field]];
        if (convert) {
          entp[field] = convert(row[field]);
        } else {
          entp[field] = row[field];
        }
      }
    });

    return ent.make$(entp);
  };

  var tablename = function(entity) {
    var canon = entity.canon$({object: true});
    return(canon.base ? canon.base + '_' : '') + canon.name;
  };

  return self;
}

module.exports = new DynamoDBStore();<|endoftext|>


<commit_before>// Here we're defining our game module. If our project was bigger and
// consisted of multiple files, then we could keep adding our code into
// this module, and the module may or may not exist by the time this file
// is read. That's why this line looks the way it does. We're saying that
// 'game' is equal to the pre-existing game module if it exists, and
// if it doesn't exist, then it's equal to a new empty object. The
// javascript || operator is useful here to bundle this into one line.
// It works because 'null' and 'undefined' and falsey values in javascript.

var game = this.game || {};

/**
 * We're wrapping our code in what's called an IFFE ("iffy"). It stands for
 * Immediately Invoked Function Expression. You'll notice that it's a
 * function wrapped in a pair of parentheses, and followed by '()'. That means
 * that this anonymous function will be called immediately after it is defined.
 * We pass our 'game' module in as an argument as a way to make methods public
 * on that module. An example is the 'init' function.
 */
(function(module) {
    // There are no constants in javascript but we can give ourselves a visual
    // hint that we shouldn't change them by making them all caps.
    var FRAME_RATE = 60;
    var STAGE_WIDTH;
    var STAGE_HEIGHT;
    var BULLET_SPEED = 7;
    var BULLET_RADIUS = 5;
    var PLAYER_RADIUS = 30;
    var ENEMY_RADIUS = 15;
    var ENEMY_SPEED = 1;

    var canvas;
    var stage;
    var player;
    var enemies = [];
    var bullets = [];

    var gameOver = false;

    // =======================================================================
    // INITIALIZATION
    // =======================================================================

    /**
     * This is what will be called to kick off our game.
     */
    module.init = function() {
        // This grabs our canvas element from our page.
        canvas = document.getElementById("js-canvas");

        // Here we create a new stage - it's what holds everything
        // visual in our game.
        stage = new createjs.Stage(canvas);

        // It'll be useful to know the dimensions of our stage late
        STAGE_WIDTH = canvas.width;
        STAGE_HEIGHT = canvas.height;

        // Here we call some subroutines to finish up initialization.
        // We could have written the code here, but it reads nicer this way.
        initPlayer();
        initEvents();
    }

    /**
     * We initialize the player here. He's just going to be a circle in the
     * middle of the stage.
     */
    function initPlayer() {
        // Shapes are vector images in createjs. That means that they scale
        // without degredation.
        player = new createjs.Shape();

        // Here we're saying that we're going make the shape a white circle
        // with a radius of PLAYER_RADIUS at position 0. Objects in createjs
        // all have their own local coordinate system that's separate from the
        // global coordinate system. Drawings should usually center around the
        // origin in the local coordinate system to make it easier to find
        // relative positions later.
        player.graphics.beginFill("white").drawCircle(0, 0, PLAYER_RADIUS);

        // We're putting our player in the center of the stage. These coordiantes
        // are referencing the global coordinate system. You'll notice our y-value
        // is positive here. That's because the origin in almost all game engines
        // is in the top-left corner, with y increasing as you go down. The reason
        // for this is that montiors draw out the lines that make up the screen from
        // top to bottom, left to right. It's confusing at first, but it becomes
        // second nature as you do more game development.
        player.x = STAGE_WIDTH / 2;
        player.y = STAGE_HEIGHT / 2;

        // Here's another important game concept - adding children. Currently, our player
        // isn't in the 'display list' - a list of objects that the stage will render
        // to the canvas. Only children of the stage (and their children) will be drawn.
        // Here, we're adding our player to the stage to be drawn.
        stage.addChild(player);
    }

    function initEvents() {
        // Here we're just listening for when the mouse button clicks down on the stage.
        // When it does, we'll call the mouseDown function we've defined.
        stage.addEventListener("stagemousedown", mouseDown);

        // FPS stands for "Frames Per Second" - it's how often the game screen refreshes.
        // Here, we're telling it to use a constant we've already defined.
        createjs.Ticker.setFPS(FRAME_RATE);

        // RAF is a special browser property that makes games more efficient in modern
        // browsers. Don't worry about it, just know that it's good to turn on.
        createjs.Ticker.useRAF = true;

        // This is adding the event for every time a new frame is rendered. We want to
        // do all of our updating in this 'tock' function, as this is what will be called
        // 60 times per second (or whatever your framerate is).
        createjs.Ticker.addEventListener("tick", tick);

        // Finally, we're just setting a timer to spawn an enemy ever two seconds.
        setInterval(spawnEnemy, 2000);
    }

    // =======================================================================
    // EVENTS
    // =======================================================================

    /**
     * This function is called every time the mouse clicks down on the stage.
     */
    function mouseDown(e) {
        // We're just going to shoot towards the current mouse position. Always use
        // mouseX and mouseY to get your mouse position, as createjs has already made
        // them relative to the top left corner of the canvas instead of absolutely
        // positioned in the window.
        shoot(stage.mouseX, stage.mouseY);
    }

    /**
     * This is our update function. It will be called every 1/60 of a second (or whatever
     * you chose your frameerate to be). It's where we decide what happenns for this next
     * frame.
     */
    function tick(e) {
        // If the game is over, do nothing.
        if (gameOver) {
            return;
        }

        // Run through our list of bullets and call each of their tick
        // functions so they can update themselves.
        for (var i = 0; i < bullets.length; i++) {
            bullets[i].tick(e);
        }

        // Run through our list of enemies and call each of their tick
        // functions so they can update themselves.
        for (var i = 0; i < enemies.length; i++) {
            enemies[i].tick(e);
        }

        // Check for collisions between all of our things.
        checkBulletEnemyCollision();
        checkEnemyHeroCollision();

        // This call is super-important. It tells the stage to update the
        // canvas to reflect the game state. Without it, nothing would happen
        // visually!
        stage.update();
    }

    // =======================================================================
    // GAME FUNCTIONS
    // =======================================================================

    function spawnEnemy() {
        var rad = Math.random() * Math.PI * 2;
        var radius = STAGE_WIDTH/2 + STAGE_HEIGHT/2;
        var x = player.x + Math.cos(rad) * radius;
        var y = player.y + Math.sin(rad) * radius;
        var moveRad = Math.atan2(y - player.y, x - player.x);
        var vx = -Math.cos(moveRad) * ENEMY_SPEED;
        var vy = -Math.sin(moveRad) * ENEMY_SPEED;
        var e = new Enemy(vx, vy);
        e.sprite.x = x;
        e.sprite.y = y;
        enemies.push(e);
        stage.addChild(e.sprite);
    }

    function shoot(x, y) {
        var dx = x - player.x;
        var dy = y - player.y;
        var rad = Math.atan2(dy, dx);

        var vx = Math.cos(rad) * BULLET_SPEED;
        var vy = Math.sin(rad) * BULLET_SPEED;

        var b = new Bullet(vx, vy);
        b.sprite.x = player.x + Math.cos(rad) * PLAYER_RADIUS;
        b.sprite.y = player.y + Math.sin(rad) * PLAYER_RADIUS;
        stage.addChild(b.sprite);
        bullets.push(b);
    }

    function checkBulletEnemyCollision() {
        for (var i = bullets.length - 1; i >= 0; i--) {
            var b = bullets[i];
            for (var j = enemies.length - 1; j >= 0; j--) {
                var e = enemies[j];
                if (circleCollision(b.sprite, BULLET_RADIUS, e.sprite, ENEMY_RADIUS)) {
                    stage.removeChild(e.sprite);
                    enemies.splice(j, 1);

                    stage.removeChild(b.sprite);
                    bullets.splice(i, 1);
                }
            }
        }
    }

    function checkEnemyHeroCollision() {
        for (var i = enemies.length - 1; i >= 0; i--) {
            var e = enemies[i];
            if (circleCollision(player, PLAYER_RADIUS, e.sprite, ENEMY_RADIUS)) {
                gameOver = true;
                alert("Game Over!");
            }
        }
    }

    function circleCollision(sprite1, r1, sprite2, r2) {
        var dx = sprite1.x - sprite2.x;
        var dy = sprite1.y - sprite2.y;
        var dist = Math.sqrt(dx * dx + dy * dy);
        return dist <= r1 + r2;
    }

    // =======================================================================
    // CLASSES
    // =======================================================================

    function Bullet(vx, vy) {
        this.vx = vx;
        this.vy = vy;

        this.sprite = new createjs.Shape();
        this.sprite.graphics.beginFill("blue").drawCircle(0, 0, BULLET_RADIUS);

        this.tick = function(e) {
            this.sprite.x += vx;
            this.sprite.y += vy;
        }
    }

    function Enemy(vx, vy) {
        this.vx = vx;
        this.vy = vy;

        this.sprite = new createjs.Shape();
        this.sprite.graphics.beginFill("red").drawCircle(0, 0, ENEMY_RADIUS);

        this.tick = function(e) {
            this.sprite.x += vx;
            this.sprite.y += vy;

        }
    }

})(game);

window.onload = function() {
    game.init();
}<commit_msg>Commented up the shoot method.<commit_after>// Here we're defining our game module. If our project was bigger and
// consisted of multiple files, then we could keep adding our code into
// this module, and the module may or may not exist by the time this file
// is read. That's why this line looks the way it does. We're saying that
// 'game' is equal to the pre-existing game module if it exists, and
// if it doesn't exist, then it's equal to a new empty object. The
// javascript || operator is useful here to bundle this into one line.
// It works because 'null' and 'undefined' and falsey values in javascript.

var game = this.game || {};

/**
 * We're wrapping our code in what's called an IFFE ("iffy"). It stands for
 * Immediately Invoked Function Expression. You'll notice that it's a
 * function wrapped in a pair of parentheses, and followed by '()'. That means
 * that this anonymous function will be called immediately after it is defined.
 * We pass our 'game' module in as an argument as a way to make methods public
 * on that module. An example is the 'init' function.
 */
(function(module) {
    // There are no constants in javascript but we can give ourselves a visual
    // hint that we shouldn't change them by making them all caps.
    var FRAME_RATE = 60;
    var STAGE_WIDTH;
    var STAGE_HEIGHT;
    var BULLET_SPEED = 7;
    var BULLET_RADIUS = 5;
    var PLAYER_RADIUS = 30;
    var ENEMY_RADIUS = 15;
    var ENEMY_SPEED = 1;

    var canvas;
    var stage;
    var player;
    var enemies = [];
    var bullets = [];

    var gameOver = false;

    // =======================================================================
    // INITIALIZATION
    // =======================================================================

    /**
     * This is what will be called to kick off our game.
     */
    module.init = function() {
        // This grabs our canvas element from our page.
        canvas = document.getElementById("js-canvas");

        // Here we create a new stage - it's what holds everything
        // visual in our game.
        stage = new createjs.Stage(canvas);

        // It'll be useful to know the dimensions of our stage late
        STAGE_WIDTH = canvas.width;
        STAGE_HEIGHT = canvas.height;

        // Here we call some subroutines to finish up initialization.
        // We could have written the code here, but it reads nicer this way.
        initPlayer();
        initEvents();
    }

    /**
     * We initialize the player here. He's just going to be a circle in the
     * middle of the stage.
     */
    function initPlayer() {
        // Shapes are vector images in createjs. That means that they scale
        // without degredation.
        player = new createjs.Shape();

        // Here we're saying that we're going make the shape a white circle
        // with a radius of PLAYER_RADIUS at position 0. Objects in createjs
        // all have their own local coordinate system that's separate from the
        // global coordinate system. Drawings should usually center around the
        // origin in the local coordinate system to make it easier to find
        // relative positions later.
        player.graphics.beginFill("white").drawCircle(0, 0, PLAYER_RADIUS);

        // We're putting our player in the center of the stage. These coordiantes
        // are referencing the global coordinate system. You'll notice our y-value
        // is positive here. That's because the origin in almost all game engines
        // is in the top-left corner, with y increasing as you go down. The reason
        // for this is that montiors draw out the lines that make up the screen from
        // top to bottom, left to right. It's confusing at first, but it becomes
        // second nature as you do more game development.
        player.x = STAGE_WIDTH / 2;
        player.y = STAGE_HEIGHT / 2;

        // Here's another important game concept - adding children. Currently, our player
        // isn't in the 'display list' - a list of objects that the stage will render
        // to the canvas. Only children of the stage (and their children) will be drawn.
        // Here, we're adding our player to the stage to be drawn.
        stage.addChild(player);
    }

    function initEvents() {
        // Here we're just listening for when the mouse button clicks down on the stage.
        // When it does, we'll call the mouseDown function we've defined.
        stage.addEventListener("stagemousedown", mouseDown);

        // FPS stands for "Frames Per Second" - it's how often the game screen refreshes.
        // Here, we're telling it to use a constant we've already defined.
        createjs.Ticker.setFPS(FRAME_RATE);

        // RAF is a special browser property that makes games more efficient in modern
        // browsers. Don't worry about it, just know that it's good to turn on.
        createjs.Ticker.useRAF = true;

        // This is adding the event for every time a new frame is rendered. We want to
        // do all of our updating in this 'tock' function, as this is what will be called
        // 60 times per second (or whatever your framerate is).
        createjs.Ticker.addEventListener("tick", tick);

        // Finally, we're just setting a timer to spawn an enemy ever two seconds.
        setInterval(spawnEnemy, 2000);
    }

    // =======================================================================
    // EVENTS
    // =======================================================================

    /**
     * This function is called every time the mouse clicks down on the stage.
     */
    function mouseDown(e) {
        // We're just going to shoot towards the current mouse position. Always use
        // mouseX and mouseY to get your mouse position, as createjs has already made
        // them relative to the top left corner of the canvas instead of absolutely
        // positioned in the window.
        shoot(stage.mouseX, stage.mouseY);
    }

    /**
     * This is our update function. It will be called every 1/60 of a second (or whatever
     * you chose your frameerate to be). It's where we decide what happenns for this next
     * frame.
     */
    function tick(e) {
        // If the game is over, do nothing.
        if (gameOver) {
            return;
        }

        // Run through our list of bullets and call each of their tick
        // functions so they can update themselves.
        for (var i = 0; i < bullets.length; i++) {
            bullets[i].tick(e);
        }

        // Run through our list of enemies and call each of their tick
        // functions so they can update themselves.
        for (var i = 0; i < enemies.length; i++) {
            enemies[i].tick(e);
        }

        // Check for collisions between all of our things.
        checkBulletEnemyCollision();
        checkEnemyHeroCollision();

        // This call is super-important. It tells the stage to update the
        // canvas to reflect the game state. Without it, nothing would happen
        // visually!g
        stage.update();
    }

    // =======================================================================
    // GAME FUNCTIONS
    // =======================================================================

    /**
     * This function will create a new bullet, position it appropriately,
     * and get it moving towards the mouse cursor.
     */
    function shoot(x, y) {
        // So, the general strategy here is that we first have to find the angle
        // created between the mouse and the player. Once we know this angle,
        // we can use the desired speed we want the bullet to travel to break down
        // the bullet's movement into its respective x and y components. This is all
        // just basic trigonometry.

        // To find the angle, we want to find each leg of the triangle (the x and
        // y differences) and then find the arctan of their ratio. If you draw the
        // triangle out on paper, this will make a lot more sense.
        var dx = x - player.x;
        var dy = y - player.y;
        var theta = Math.atan2(dy, dx);

        // Now that we have our angle, we want to find what the legs of the triangle
        // would be if we had a hypotenuse whose length is the speed of the bullet.
        // This is how much we want the bullet to move in the x and y direction
        // each frame.
        var vx = Math.cos(theta) * BULLET_SPEED;
        var vy = Math.sin(theta) * BULLET_SPEED;

        // Now we just make a bullet and position it (not forgetting to add it
        // to the stage).
        var b = new Bullet(vx, vy);
        b.sprite.x = player.x + Math.cos(theta) * PLAYER_RADIUS;
        b.sprite.y = player.y + Math.sin(theta) * PLAYER_RADIUS;
        stage.addChild(b.sprite);

        // Finally, we store it in an array so we can reference it later.
        bullets.push(b);
    }

    /**
     * This function will put an enemy at a random location off-screen and start
     * him moving towards the player.
     */
    function spawnEnemy() {
        var rad = Math.random() * Math.PI * 2;
        var radius = STAGE_WIDTH/2 + STAGE_HEIGHT/2;
        var x = player.x + Math.cos(rad) * radius;
        var y = player.y + Math.sin(rad) * radius;
        var moveRad = Math.atan2(player.y - y, player.x - x);
        var vx = Math.cos(moveRad) * ENEMY_SPEED;
        var vy = Math.sin(moveRad) * ENEMY_SPEED;
        var e = new Enemy(vx, vy);
        e.sprite.x = x;
        e.sprite.y = y;
        enemies.push(e);
        stage.addChild(e.sprite);
    }

    function checkBulletEnemyCollision() {
        for (var i = bullets.length - 1; i >= 0; i--) {
            var b = bullets[i];
            for (var j = enemies.length - 1; j >= 0; j--) {
                var e = enemies[j];
                if (circleCollision(b.sprite, BULLET_RADIUS, e.sprite, ENEMY_RADIUS)) {
                    stage.removeChild(e.sprite);
                    enemies.splice(j, 1);

                    stage.removeChild(b.sprite);
                    bullets.splice(i, 1);
                }
            }
        }
    }

    function checkEnemyHeroCollision() {
        for (var i = enemies.length - 1; i >= 0; i--) {
            var e = enemies[i];
            if (circleCollision(player, PLAYER_RADIUS, e.sprite, ENEMY_RADIUS)) {
                gameOver = true;
                alert("Game Over!");
            }
        }
    }

    function circleCollision(sprite1, r1, sprite2, r2) {
        var dx = sprite1.x - sprite2.x;
        var dy = sprite1.y - sprite2.y;
        var dist = Math.sqrt(dx * dx + dy * dy);
        return dist <= r1 + r2;
    }

    // =======================================================================
    // CLASSES
    // =======================================================================

    function Bullet(vx, vy) {
        this.vx = vx;
        this.vy = vy;

        this.sprite = new createjs.Shape();
        this.sprite.graphics.beginFill("blue").drawCircle(0, 0, BULLET_RADIUS);

        this.tick = function(e) {
            this.sprite.x += vx;
            this.sprite.y += vy;
        }
    }

    function Enemy(vx, vy) {
        this.vx = vx;
        this.vy = vy;

        this.sprite = new createjs.Shape();
        this.sprite.graphics.beginFill("red").drawCircle(0, 0, ENEMY_RADIUS);

        this.tick = function(e) {
            this.sprite.x += vx;
            this.sprite.y += vy;

        }
    }

})(game);

window.onload = function() {
    game.init();
}<|endoftext|>


<commit_before>var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });
var enemy;

function preload() {
  game.load.image('floor', 'assets/floor.png');
  game.load.image('enemy', 'assets/enemy.png');
}

function create() {
  game.add.sprite(0, 0, 'floor');
  enemy = game.add.sprite(0, 0, 'enemy');
  enemy.anchor.x = enemy.anchor.y = 0.5
  startTravel();
}

function update() {

}

function startTravel() {
	setTimeout(function(){
		var orig = generateOrigPoint(enemy);
		var dest = generateDestPoint(enemy, orig);
		var time = getRandomInt(1500, 2500);
		enemy.x = orig.x;
		enemy.y = orig.y;

		var tween = game.add.tween(enemy).to({x: dest.x, y: dest.y}, time, Phaser.Easing.None, true);
		tween.onComplete.add(startTravel, this);
	}, 500);
}

function generateOrigPoint(target){
	var point = {};
	if (Math.random() >= 0.5){
		point.x = getRandomInt(-target.width, (game.width + target.width));
		point.y = (Math.random() >= 0.5) ? -target.height : (game.height + target.height);
	} else {
		point.y = getRandomInt(-target.height, (game.height + target.height));
		point.x = (Math.random() >= 0.5) ? -target.width : (game.width + target.width);
	}
	return point;
}

function generateDestPoint(target, orig){
	var point = {};
	point.x = 0;
	point.y = 0;
	return point;
}

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}<commit_msg>monster crossing the screen randomly<commit_after>var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });
var enemy;

function preload() {
	game.load.image('floor', 'assets/floor.png');
	game.load.image('enemy', 'assets/enemy.png');
}

function create() {
	game.add.sprite(0, 0, 'floor');
	enemy = game.add.sprite(-150, -150, 'enemy');
	enemy.anchor.x = enemy.anchor.y = 0.5;
	enemy.inputEnabled = true;
	enemy.events.onInputDown.add(enemyClick, this);
	startTravel();
}

function update() {

}

function enemyClick(target){
	if (target.movTween.isPaused){
		target.movTween.resume();
	} else {
		target.movTween.pause();
	}
}

function startTravel() {
	setTimeout(function(){
		var orig = generateOrigPoint(enemy);
		var dest = generateDestPoint(enemy, orig);
		var time = getRandomInt(2000, 2500);
		enemy.x = orig.x;
		enemy.y = orig.y;

		enemy.movTween = game.add.tween(enemy).to({x: dest.x, y: dest.y}, time, Phaser.Easing.None, true);
		enemy.movTween.onComplete.add(startTravel, this);
	}, 500);
}

function generateOrigPoint(target){
	var point = {x:0, y:0, loc:0};
	point.loc = Math.floor(Math.random() * 4);
	return generatePoint(point, target, point.loc);
}

function generateDestPoint(target, orig){
	var point = {x:0, y:0, loc:0, locName:null};
	do {
		point.loc = Math.floor(Math.random() * 4);
	} while (point.loc == orig.loc);
	return generatePoint(point, target, point.loc);
}

function generatePoint(point, target, loc){
	if (point.loc <= 1){
		point.x = getRandomInt(target.width, game.width - target.width);
		point.y = (point.loc == 0)? -target.height : game.height + target.height;
	} else {
		point.x = (point.loc == 2)? -target.width : game.width + target.width;
		point.y = getRandomInt(target.height, game.height - target.height);
	}
	return point;
}

function getRandomInt(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}<|endoftext|>


<commit_before>class Dice extends React.Component {
  constructor() {
    super();
    this.state = {
      words: this.parseInput(decodeURIComponent(location.search.substring(5))),
      div: document.createElement("div")
		};

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  parseInput(input) {
    return input.split('\n\r').map(x => x.split('\n').filter(Boolean));
  }

  image(word) {

  }

  appendWord(text) {
    var p = document.createElement("p");
    p.appendChild(document.createTextNode(text));
    return p;
  }

  appendImg(src) {
    var img = document.createElement("img");
    img.className = 'img';
    img.src = random;
  }

  handleSubmit() {
      var div = this.state.div;
      while (div.hasChildNodes()) {
        div.removeChild(div.lastChild);
      }
      var words = this.state.words;
      for(var i = 0; i < words.length; i++) {
        var random = words[i][Math.floor(Math.random()*(words.length-1))];
        if (this.image(random)) {
          div.appendChild(this.appendImg(random));
        }
        else {
          div.appendChild(this.appendWord(random));
        }
      }
      document.body.appendChild(div);
  }

  render() {
    return (

        <input type="button" value="Throw dice" onClick={this.handleSubmit}/>

    );
  }
}

ReactDOM.render(
  <Dice />,
  document.getElementById('root')
);<commit_msg>Fix bug in word generator<commit_after>class Dice extends React.Component {
  constructor() {
    super();
    this.state = {
      words: this.parseInput(decodeURIComponent(location.search.substring(5))),
      div: document.createElement("div")
		};

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  parseInput(input) {
    return input.split('\n\r').map(x => x.split('\n').filter(Boolean));
  }

  image(word) {

  }

  appendWord(text) {
    var p = document.createElement("p");
    p.appendChild(document.createTextNode(text));
    return p;
  }

  appendImg(src) {
    var img = document.createElement("img");
    img.className = 'img';
    img.src = random;
  }

  handleSubmit() {
      var div = this.state.div;
      while (div.hasChildNodes()) {
        div.removeChild(div.lastChild);
      }
      var words = this.state.words;
      for(var i = 0; i < words.length; i++) {
        var random = words[i][Math.floor(Math.random()*(words[i].length-1))];
        if (this.image(random)) {
          div.appendChild(this.appendImg(random));
        }
        else {
          div.appendChild(this.appendWord(random));
        }
      }
      document.body.appendChild(div);
  }

  render() {
    return (

        <input type="button" value="Throw dice" onClick={this.handleSubmit}/>

    );
  }
}

ReactDOM.render(
  <Dice />,
  document.getElementById('root')
);<|endoftext|>


<commit_before>/**
  @module ember-flexberry-designer
*/

import Ember from 'ember';
import joint from 'npm:jointjs';

import FdUmlElement from '../objects/uml-primitives/fd-uml-element';
import FdUmlLink from '../objects/uml-primitives/fd-uml-link';

/**
  Component for working with the UML diagram through the JointJS.

  @class FdUmlDiagramComponent
  @extends Ember.Component
*/
export default Ember.Component.extend({
  /**
    All primitives of the UML diagram.

    @property primitives
    @type Ember.Array
  */
  primitives: undefined,

  /**
    Created 'Paper' from joint js.

    @property paper
    @type object
  */
  paper: undefined,

  /**
    All elements of the UML diagram.

    @property elements
    @type Ember.Array
  */
  elements: Ember.computed.filter('primitives', p => p instanceof FdUmlElement),

  /**
    All a links of the UML diagram.

    @property links
    @type Ember.Array
  */
  links: Ember.computed.filter('primitives', p => p instanceof FdUmlLink),

  /**
    Indicates that the diagram has primitives.

    @property notEmpty
    @type Boolean
  */
  notEmpty: Ember.computed.notEmpty('primitives'),

  /**
    See [EmberJS API](https://emberjs.com/).

    @method init
  */
  init() {
    this._super(...arguments);

    this.set('graph', new joint.dia.Graph());
  },

  /**
    See [EmberJS API](https://emberjs.com/).

    @method didInsertElement
  */
  didInsertElement() {
    this._super(...arguments);

    let elements = this.get('elements');
    let links = this.get('links');

    let height = '100%';
    let width = '100%';
    if (this.get('notEmpty')) {
      height = Math.max.apply(null, elements.map(e => e.get('y') + e.get('height'))) + 100;
      width = Math.max.apply(null, elements.map(e => e.get('x') + e.get('width'))) + 100;
    }

    let graph = this.get('graph');
    let paper = new joint.dia.Paper({
      el: this.get('element'),
      height: height,
      width: width,
      model: graph,
    });
    paper.options.connectionStrategy = joint.connectionStrategies.pinAbsolute;
    paper.on('blank:pointerclick', this._blankPointerClick, this);
    paper.on('element:pointerclick', this._elementPointerClick, this);
    paper.on('blank:contextmenu', this._blankContextMenu, this);

    graph.addCells(elements.map(e => e.JointJS()));
    graph.addCells(links.map(l => l.JointJS()));
  },

  /**
    Handler event 'blank:pointerclick'.

    @method actions._blankPointerClick
    @param {jQuery.Event} e event.
    @param {Number} x coordinate x.
    @param {Number} y coordinate y.
   */
  _blankPointerClick(e, x, y) {
    let options = { e:e, x:x, y:y };
    let newElement = this.get('blankPointerClick')(options);
    this._addNewElement(newElement);
  },

  /**
    Handler event 'element:pointerclick'.

    @method actions._elementPointerClick
    @param {Object} element selected joint js element.
    @param {jQuery.Event} e event.
    @param {Number} x coordinate x.
    @param {Number} y coordinate y.
   */
  _elementPointerClick(element, e, x, y) {
    let options = { element:element, e:e, x:x, y:y };
    let newElement = this.get('elementPointerClick')(options);
    this._addNewElement(newElement);
  },

  /**
    Handler event 'blank:contextmenu'.

    @method actions._blankContextMenu
    @param {jQuery.Event} e event.
    @param {Number} x coordinate x.
    @param {Number} y coordinate y.
   */
  _blankContextMenu(e, x, y) {
    let options = { e:e, x:x, y:y };
    this.get('blankContextMenu')(options);
  },

  /**
    Add new Element on graph.

    @method actions._addNewElement
    @param {Object} newElement joint js element.
   */
  _addNewElement(newElement) {
    if (!Ember.isNone(newElement)) {
      let graph = this.get('graph');
      graph.addCell([newElement]);
    }
  }
});
<commit_msg>Fix error<commit_after>/**
  @module ember-flexberry-designer
*/

import Ember from 'ember';
import joint from 'npm:jointjs';

import FdUmlElement from '../objects/uml-primitives/fd-uml-element';
import FdUmlLink from '../objects/uml-primitives/fd-uml-link';

/**
  Component for working with the UML diagram through the JointJS.

  @class FdUmlDiagramComponent
  @extends Ember.Component
*/
export default Ember.Component.extend({
  /**
    All primitives of the UML diagram.

    @property primitives
    @type Ember.Array
  */
  primitives: undefined,

  /**
    All elements of the UML diagram.

    @property elements
    @type Ember.Array
  */
  elements: Ember.computed.filter('primitives', p => p instanceof FdUmlElement),

  /**
    All a links of the UML diagram.

    @property links
    @type Ember.Array
  */
  links: Ember.computed.filter('primitives', p => p instanceof FdUmlLink),

  /**
    Indicates that the diagram has primitives.

    @property notEmpty
    @type Boolean
  */
  notEmpty: Ember.computed.notEmpty('primitives'),

  /**
    See [EmberJS API](https://emberjs.com/).

    @method init
  */
  init() {
    this._super(...arguments);

    this.set('graph', new joint.dia.Graph());
  },

  /**
    See [EmberJS API](https://emberjs.com/).

    @method didInsertElement
  */
  didInsertElement() {
    this._super(...arguments);

    let elements = this.get('elements');
    let links = this.get('links');

    let height = '100%';
    let width = '100%';
    if (this.get('notEmpty')) {
      height = Math.max.apply(null, elements.map(e => e.get('y') + e.get('height'))) + 100;
      width = Math.max.apply(null, elements.map(e => e.get('x') + e.get('width'))) + 100;
    }

    let graph = this.get('graph');
    let paper = new joint.dia.Paper({
      el: this.get('element'),
      height: height,
      width: width,
      model: graph,
    });
    paper.options.connectionStrategy = joint.connectionStrategies.pinAbsolute;
    paper.on('blank:pointerclick', this._blankPointerClick, this);
    paper.on('element:pointerclick', this._elementPointerClick, this);
    paper.on('blank:contextmenu', this._blankContextMenu, this);

    graph.addCells(elements.map(e => e.JointJS()));
    graph.addCells(links.map(l => l.JointJS()));
  },

  /**
    Handler event 'blank:pointerclick'.

    @method actions._blankPointerClick
    @param {jQuery.Event} e event.
    @param {Number} x coordinate x.
    @param {Number} y coordinate y.
   */
  _blankPointerClick(e, x, y) {
    let options = { e:e, x:x, y:y };
    let newElement = this.get('blankPointerClick')(options);
    this._addNewElement(newElement);
  },

  /**
    Handler event 'element:pointerclick'.

    @method actions._elementPointerClick
    @param {Object} element selected joint js element.
    @param {jQuery.Event} e event.
    @param {Number} x coordinate x.
    @param {Number} y coordinate y.
   */
  _elementPointerClick(element, e, x, y) {
    let options = { element:element, e:e, x:x, y:y };
    let newElement = this.get('elementPointerClick')(options);
    this._addNewElement(newElement);
  },

  /**
    Handler event 'blank:contextmenu'.

    @method actions._blankContextMenu
    @param {jQuery.Event} e event.
    @param {Number} x coordinate x.
    @param {Number} y coordinate y.
   */
  _blankContextMenu(e, x, y) {
    let options = { e:e, x:x, y:y };
    this.get('blankContextMenu')(options);
  },

  /**
    Add new Element on graph.

    @method actions._addNewElement
    @param {Object} newElement joint js element.
   */
  _addNewElement(newElement) {
    if (!Ember.isNone(newElement)) {
      let graph = this.get('graph');
      graph.addCell([newElement]);
    }
  }
});
<|endoftext|>