<commit_before>var _ = require('underscore'),
    spawn = require('child_process').spawn,
    exec = require('child_process').exec,
    Game = require('../game/game.js').Game;

function AI(executionCommand, parameters, workingDir, pauseCommand, unpauseCommand, index, addLog) {
    this.process = spawn(executionCommand, parameters, { cwd: workingDir });
    this.pauseCommand = pauseCommand;
    this.unpauseCommand = unpauseCommand;
    this.index = index;
    this.addLog = addLog;
    this.commands = [];
    this.ready = false;
    this.available = true;
    this.timeout = null;
    this.onStdout = function (data) { };
    this.onExit = function () { };

    var self = this;

    this.process.stdout.on('data', function (data) {
        self.addLog('AI' + self.index + '>>' + 'STDOUT: ' + data);
        self.onStdout(data);
    });

    this.process.stderr.on('data', function (data) {
        self.addLog('AI' + self.index + '>>' + 'STDERR: ' + data, self.index);
    });

    this.process.on('close', function (code) {
        self.addLog('AI' + self.index + '>>' + 'Child process exited with code ' + code);
        self.onExit();
    });
}

AI.prototype.setTimer = function (timeLimit) {
    var self = this;
    self.clearTimer();
    self.timeout = setTimeout(function () {
        self.addLog('AI' + self.index + '>>' + 'Killing due to TLE');
        self.process.kill('SIGINT');
    }, timeLimit);
};

AI.prototype.clearTimer = function () {
    clearTimeout(this.timeout);
    this.timeout = null;
};

AI.prototype.pause = function () {
    if (this.pauseCommand) {
        exec(this.pauseCommand);
    }
};

AI.prototype.unpause = function () {
    if (this.unpauseCommand) {
        exec(this.unpauseCommand);
    }
};

function Runner(executionCommands, workingDirs, pauseCommands, unpauseCommands) {
    this.executionCommands = executionCommands;
    var defaultArray = _.map(executionCommands, function () {
        return undefined;
    });
    this.workingDirs = workingDirs || defaultArray;
    this.pauseCommands = pauseCommands || defaultArray;
    this.unpauseCommands = unpauseCommands || defaultArray;
}

Runner.LOG_FOR_EVERYONE = -1;

Runner.prototype.runGame = function (done) {
    var self = this;

    this.done = done;
    var seed = new Date().getTime();
    this.game = new Game(seed);
    this.game.initialize();

    this.gameResult = {
        log: [],
        winner: '',
        replay: {
            seed: seed,
            commands: [],
        },
    };

    this.ais = [];
    for (var i = 0; i < this.game.getNumPlayers() ; i++) {
        var commandAndParameters = this.executionCommands[i].split(' ');
        var command = _.first(commandAndParameters);
        var parameters = _.rest(commandAndParameters);
        this.ais.push(new AI(command, parameters, this.workingDirs[i], this.pauseCommands[i], this.unpauseCommands[i], i, function (message, aiIndex) {
            addLog.call(self, message, aiIndex);
        }));
    }

    _.each(this.ais, function (ai) {
        ai.onStdout = function (data) {
            if (data.toString().trim().toLowerCase() == 'ready' && !ai.ready) {
                ai.ready = true;
                ai.clearTimer();
                onReadyForBeginning.call(self);
            }
        };
        ai.onExit = function () {
            if (ai.available && !ai.ready) {
                onReadyForBeginning.call(self);
            }
            ai.available = false;
            ai.clearTimer();
        }
        ai.setTimer(5000);
    });
};

function onReadyForBeginning() {
    if (isEveryoneReady.call(this, this.ais)) {
        _.each(this.ais, function (ai) {
            var self = this;
            ai.onStdout = function (data) {
                if (ai.available && !ai.ready) {
                    ai.commands = data.toString().trim().split(' ');
                    ai.ready = true;
                    ai.clearTimer();
                    ai.pause();
                    onReady.call(self, ai);
                }
            };
            ai.onExit = function () {
                if (ai.available && !ai.ready) {
                    onReady.call(self, ai);
                }
                ai.available = false;
                ai.clearTimer();
            };
        }, this);

        pauseAIs.call(this);
        beginTurn.call(this);
    }
}

function isEveryoneReady(ais) {
    return _.isEmpty(getUnreadyAIs.call(this));
}

function addLog(logMessage, aiIndex) {
    if (aiIndex === undefined) {
        aiIndex = Runner.LOG_FOR_EVERYONE;
    }
    this.gameResult.log.push({ target: aiIndex, message: logMessage.trim() });
}

function onReady() {
    if (isEveryoneReady.call(this, this.ais)) {
        var commands = _.map(this.ais, function (ai) {
            return ai.available ? ai.commands : [];
        });
        this.game.processTurn(commands);
        addLog.call(this, 'Turn finished. Game status:');
        addLog.call(this, this.game.getStatus());
        addLog.call(this, '');

        if (this.game.isFinished()) {
            finish.call(this);
        } else {
            beginTurn.call(this);
        }
    } else {
        processNextAI.call(this);
    }
}

function beginTurn() {
    addLog.call(this, 'Starting a new turn');

    var availableAIs = getAvailableAIs.call(this);
    if (_.isEmpty(availableAIs)) {
        onReady.call(this);
    } else {
        _.each(availableAIs, function (ai) {
            ai.ready = false;
        }, this);
        processNextAI.call(this);
    }
}

function finish() {
    addLog.call(this, 'Game finished');

    unpauseAIs.call(this);
    _.each(getAvailableAIs.call(this), function (ai) {
        var terminationText = this.game.getTerminationText();
        if (terminationText) {
            ai.process.stdin.write(terminationText);
        }
        ai.onStdout = function () { };
        ai.onExit = function () { };
        ai.setTimer(1000);
    }, this);

    this.gameResult.replay = this.game.getReplay();
    this.gameResult.winner = this.game.getWinner();
    addLog.call(this, 'Winner: ' + this.gameResult.winner);
    this.done();
};

function getAvailableAIs() {
    return _.filter(this.ais, function (ai) {
        return ai.available;
    });
}

function getUnreadyAIs() {
    return _.filter(getAvailableAIs.call(this), function (ai) {
        return !ai.ready;
    });
}

function pauseAIs() {
    _.each(getAvailableAIs.call(this), function (ai) {
        ai.pause();
    }, this);
}

function unpauseAIs() {
    _.each(getAvailableAIs.call(this), function (ai) {
        ai.unpause();
    }, this);
}

function processNextAI() {
    var nextAI = _.first(getUnreadyAIs.call(this));

    addLog.call(this, 'AI' + nextAI.index + '>>' + 'Writing to stdin, waiting for stdout');
    if (this.game.isInitialState()) {
        var initialInformation = this.game.getInitialInformation();
        nextAI.process.stdin.write(initialInformation);
        addLog.call(this, initialInformation);
    }
    var turnInformation = this.game.getTurnInformation(nextAI.index);
    nextAI.process.stdin.write(turnInformation);
    addLog.call(this, turnInformation);

    nextAI.unpause();
    nextAI.setTimer(1000);
}

exports.Runner = Runner;
<commit_msg>Fix: don't consider it available when an AI dies with an error<commit_after>var _ = require('underscore'),
    spawn = require('child_process').spawn,
    exec = require('child_process').exec,
    Game = require('../game/game.js').Game;

function AI(executionCommand, parameters, workingDir, pauseCommand, unpauseCommand, index, addLog) {
    this.process = spawn(executionCommand, parameters, { cwd: workingDir });
    this.pauseCommand = pauseCommand;
    this.unpauseCommand = unpauseCommand;
    this.index = index;
    this.addLog = addLog;
    this.commands = [];
    this.ready = false;
    this.available = true;
    this.timeout = null;
    this.onStdout = function (data) { };
    this.onExit = function () { };

    var self = this;

    this.process.stdout.on('data', function (data) {
        self.addLog('AI' + self.index + '>>' + 'STDOUT: ' + data);
        self.onStdout(data);
    });

    this.process.stderr.on('data', function (data) {
        self.addLog('AI' + self.index + '>>' + 'STDERR: ' + data, self.index);
    });

    this.process.on('close', function (code) {
        self.addLog('AI' + self.index + '>>' + 'Child process exited with code ' + code);
        self.onExit();
    });
}

AI.prototype.setTimer = function (timeLimit) {
    var self = this;
    self.clearTimer();
    self.timeout = setTimeout(function () {
        self.addLog('AI' + self.index + '>>' + 'Killing due to TLE');
        self.process.kill('SIGINT');
    }, timeLimit);
};

AI.prototype.clearTimer = function () {
    clearTimeout(this.timeout);
    this.timeout = null;
};

AI.prototype.pause = function () {
    if (this.pauseCommand) {
        exec(this.pauseCommand);
    }
};

AI.prototype.unpause = function () {
    if (this.unpauseCommand) {
        exec(this.unpauseCommand);
    }
};

function Runner(executionCommands, workingDirs, pauseCommands, unpauseCommands) {
    this.executionCommands = executionCommands;
    var defaultArray = _.map(executionCommands, function () {
        return undefined;
    });
    this.workingDirs = workingDirs || defaultArray;
    this.pauseCommands = pauseCommands || defaultArray;
    this.unpauseCommands = unpauseCommands || defaultArray;
}

Runner.LOG_FOR_EVERYONE = -1;

Runner.prototype.runGame = function (done) {
    var self = this;

    this.done = done;
    var seed = new Date().getTime();
    this.game = new Game(seed);
    this.game.initialize();

    this.gameResult = {
        log: [],
        winner: '',
        replay: {
            seed: seed,
            commands: [],
        },
    };

    this.ais = [];
    for (var i = 0; i < this.game.getNumPlayers() ; i++) {
        var commandAndParameters = this.executionCommands[i].split(' ');
        var command = _.first(commandAndParameters);
        var parameters = _.rest(commandAndParameters);
        this.ais.push(new AI(command, parameters, this.workingDirs[i], this.pauseCommands[i], this.unpauseCommands[i], i, function (message, aiIndex) {
            addLog.call(self, message, aiIndex);
        }));
    }

    _.each(this.ais, function (ai) {
        ai.onStdout = function (data) {
            if (data.toString().trim().toLowerCase() == 'ready' && !ai.ready) {
                ai.ready = true;
                ai.clearTimer();
                onReadyForBeginning.call(self);
            }
        };
        ai.onExit = function () {
            ai.clearTimer();
            if (ai.available && !ai.ready) {
                ai.available = false;
                onReadyForBeginning.call(self);
            }
        }
        ai.setTimer(5000);
    });
};

function onReadyForBeginning() {
    if (isEveryoneReady.call(this, this.ais)) {
        _.each(this.ais, function (ai) {
            var self = this;
            ai.onStdout = function (data) {
                if (ai.available && !ai.ready) {
                    ai.commands = data.toString().trim().split(' ');
                    ai.ready = true;
                    ai.clearTimer();
                    ai.pause();
                    onReady.call(self, ai);
                }
            };
            ai.onExit = function () {
                ai.clearTimer();
                if (ai.available && !ai.ready) {
                    ai.available = false;
                    onReady.call(self, ai);
                }
            };
        }, this);

        pauseAIs.call(this);
        beginTurn.call(this);
    }
}

function isEveryoneReady(ais) {
    return _.isEmpty(getUnreadyAIs.call(this));
}

function addLog(logMessage, aiIndex) {
    if (aiIndex === undefined) {
        aiIndex = Runner.LOG_FOR_EVERYONE;
    }
    this.gameResult.log.push({ target: aiIndex, message: logMessage.trim() });
}

function onReady() {
    if (isEveryoneReady.call(this, this.ais)) {
        var commands = _.map(this.ais, function (ai) {
            return ai.available ? ai.commands : [];
        });
        this.game.processTurn(commands);
        addLog.call(this, 'Turn finished. Game status:');
        addLog.call(this, this.game.getStatus());
        addLog.call(this, '');

        if (this.game.isFinished()) {
            finish.call(this);
        } else {
            beginTurn.call(this);
        }
    } else {
        processNextAI.call(this);
    }
}

function beginTurn() {
    addLog.call(this, 'Starting a new turn');

    var availableAIs = getAvailableAIs.call(this);
    if (_.isEmpty(availableAIs)) {
        onReady.call(this);
    } else {
        _.each(availableAIs, function (ai) {
            ai.ready = false;
        }, this);
        processNextAI.call(this);
    }
}

function finish() {
    addLog.call(this, 'Game finished');

    unpauseAIs.call(this);
    _.each(getAvailableAIs.call(this), function (ai) {
        var terminationText = this.game.getTerminationText();
        if (terminationText) {
            ai.process.stdin.write(terminationText);
        }
        ai.onStdout = function () { };
        ai.onExit = function () { };
        ai.setTimer(1000);
    }, this);

    this.gameResult.replay = this.game.getReplay();
    this.gameResult.winner = this.game.getWinner();
    addLog.call(this, 'Winner: ' + this.gameResult.winner);
    this.done();
};

function getAvailableAIs() {
    return _.filter(this.ais, function (ai) {
        return ai.available;
    });
}

function getUnreadyAIs() {
    return _.filter(getAvailableAIs.call(this), function (ai) {
        return !ai.ready;
    });
}

function pauseAIs() {
    _.each(getAvailableAIs.call(this), function (ai) {
        ai.pause();
    }, this);
}

function unpauseAIs() {
    _.each(getAvailableAIs.call(this), function (ai) {
        ai.unpause();
    }, this);
}

function processNextAI() {
    var nextAI = _.first(getUnreadyAIs.call(this));

    addLog.call(this, 'AI' + nextAI.index + '>>' + 'Writing to stdin, waiting for stdout');
    if (this.game.isInitialState()) {
        var initialInformation = this.game.getInitialInformation();
        nextAI.process.stdin.write(initialInformation);
        addLog.call(this, initialInformation);
    }
    var turnInformation = this.game.getTurnInformation(nextAI.index);
    nextAI.process.stdin.write(turnInformation);
    addLog.call(this, turnInformation);

    nextAI.unpause();
    nextAI.setTimer(1000);
}

exports.Runner = Runner;
<|endoftext|>


<commit_before>'use strict';

function create_program(id, shaderlist){
    var program = buffer.createProgram();
    for(var shader in shaderlist){
        buffer.attachShader(
          program,
          shaderlist[shader]
        );
    }
    buffer.linkProgram(program);
    buffer.useProgram(program);

    programs[id] = program;
}

function create_shader(id, type, source){
    var shader = buffer.createShader(type);
    buffer.shaderSource(
      shader,
      source
    );
    buffer.compileShader(shader);

    shaders[id] = shader;
}

function draw(){
    buffer.viewport(
      0,
      0,
      buffer.viewportWidth,
      buffer.viewportHeight
    );
    buffer.clear(buffer.COLOR_BUFFER_BIT | buffer.DEPTH_BUFFER_BIT);

    matrix_identity('camera');
    matrix_rotate(
      'camera',
      [
        degrees_to_radians(camera['rotate-x']),
        degrees_to_radians(camera['rotate-y']),
        degrees_to_radians(camera['rotate-z']),
      ]
    );
    matrix_translate(
      'camera',
      [
        camera['x'],
        camera['y'],
        camera['z'],
      ]
    );

    draw_logic();

    for(var entity in entities){
        matrix_clone(
          'camera',
          'cache'
        );

        matrix_translate(
          'camera',
          [
            -entities[entity]['position']['x'],
            -entities[entity]['position']['y'],
            entities[entity]['position']['z'],
          ]
        );
        matrix_rotate(
          'camera',
          [
            degrees_to_radians(entities[entity]['rotate']['x']),
            degrees_to_radians(entities[entity]['rotate']['y']),
            degrees_to_radians(entities[entity]['rotate']['z']),
          ]
        );

        buffer.bindBuffer(
          buffer.ARRAY_BUFFER,
          entities[entity]['buffer']['color']
        );
        buffer.vertexAttribPointer(
          attributes['vec_vertexColor'],
          4,
          buffer.FLOAT,
          false,
          0,
          0
        );

        buffer.bindBuffer(
          buffer.ARRAY_BUFFER,
          entities[entity]['buffer']['vertex']
        );
        buffer.vertexAttribPointer(
          attributes['vec_vertexPosition'],
          3,
          buffer.FLOAT,
          false,
          0,
          0
        );

        buffer.bindBuffer(
          buffer.ARRAY_BUFFER,
          entities[entity]['buffer']['texture']
        );
        buffer.vertexAttribPointer(
          attributes['vec_texturePosition'],
          2,
          buffer.FLOAT,
          false,
          0,
          0
        );

        buffer.activeTexture(buffer.TEXTURE0);
        buffer.bindTexture(
          buffer.TEXTURE_2D,
          entities[entity]['texture']
        );
        buffer.uniform1i(
          buffer.getUniformLocation(
            programs['shaders'],
            'sampler'
          ),
          0
        );

        buffer.bindBuffer(
          buffer.ARRAY_BUFFER,
          entities[entity]['buffer']['index']
        );

        buffer.uniformMatrix4fv(
          buffer.getUniformLocation(
            programs['shaders'],
            'mat_perspectiveMatrix'
          ),
          0,
          matricies['perspective']
        );
        buffer.uniformMatrix4fv(
          buffer.getUniformLocation(
            programs['shaders'],
            'mat_cameraMatrix'
          ),
          0,
          matricies['camera']
        );

        buffer.drawArrays(
          buffer[entities[entity]['mode']],
          0,
          entities[entity]['vertices'].length / 3
        );

        matrix_copy(
          'cache',
          'camera'
        );
    }

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

function drawloop(){
    draw();
    animationFrame = window.requestAnimationFrame(drawloop);
}

function group_add(group, entitylist){
    if(!(group in groups)){
        groups[group] = {};
    }

    for(var entity in entitylist){
        groups[group][entitylist[entity]] = true;
    }
}

function group_modify(grouplist, todo){
    for(var group in grouplist){
        for(var entity in groups[grouplist[group]]){
            todo(entity);
        }
    }
}

function group_remove(group, entitylist, remove){
    remove = remove || false;

    if(group in groups){
        for(var entity in entitylist){
            delete groups[group][entitylist[entity]];
        }
    }

    if(remove
      && groups[group].length === 0){
        delete groups[group];
    }
}

function init_webgl(){
    resize();

    clearcolor = {
      'alpha': 1,
      'blue': 1,
      'green': 1,
      'red': 1,
    };

    setmode(0);
}

function logicloop(){
    for(var entity in entities){
        if(entities[entity]['logic']){
            entities[entity]['logic']();
        }
    }

    logic();
}

function move_camera(speed, y, strafe){
    strafe = strafe || false;
    var radians = -degrees_to_radians(camera['rotate-y'] - (strafe ? 90 : 0));
    camera['x'] += round(speed * Math.sin(radians), 7);
    camera['y'] += y;
    camera['z'] += round(speed * Math.cos(radians), 7);
}

function new_image(src, todo){
    var image = new Image();
    image.onload = todo || function(){};
    image.src = src;
    return image;
}

function onpointerlockchange(event){
    pointerlock = document.pointerLockElement === document.getElementById('canvas');
};

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;

    buffer.viewportHeight = height;
    buffer.viewportWidth = width;
    buffer.viewport(0, 0, height, width);

    if(typeof resize_logic === 'function'){
        resize_logic();
    }
}

function rotate_camera(x, y, z){
    camera['rotate-x'] = clamp(
      round(
        camera['rotate-x'] + x,
        7
      ),
      0,
      360,
      true
    );
    camera['rotate-y'] = clamp(
      round(
        camera['rotate-y'] + y,
        7
      ),
      0,
      360,
      true
    );
    camera['rotate-z'] = clamp(
      round(
        camera['rotate-z'] + z,
        7
      ),
      0,
      360,
      true
    );
}

function set_clearcolor(color){
    clearcolor = color;
    buffer.clearColor(
      color[0],
      color[1],
      color[2],
      color[3]
    );
}

function setmode(newmode, newgame){
    window.cancelAnimationFrame(animationFrame);
    window.clearInterval(interval);

    camera = {};
    mode = newmode;
    var msperframe = 0;
    newgame = newgame || false;
    programs = {};
    shaders = {};

    if(typeof setmode_logic === 'function'){
        setmode_logic(newgame);

    }else{
        mode = 1;
        newgame = true;
        msperframe = 33;
    }

    // Main menu mode.
    if(mode === 0){
        buffer = 0;
        canvas = 0;

    // Simulation modes.
    }else{
        if(newgame){
            document.body.innerHTML =
              '<canvas id=canvas></canvas><canvas id=buffer></canvas>';

            buffer = document.getElementById('buffer').getContext(
              'webgl',
              {
                'alpha': false,
                'antialias': true,
                'depth': true,
                'preserveDrawingBuffer': false,
                'premultipliedAlpha': false,
                'stencil': false,
              }
            );
            canvas = document.getElementById('canvas').getContext('2d');

            resize();

            set_clearcolor(clearcolor);
            buffer.clearDepth(cleardepth);
            buffer.enable(buffer.CULL_FACE);
            buffer.enable(buffer.DEPTH_TEST);
            buffer.depthFunc(buffer.LEQUAL);

            create_shader(
              'fragment',
              buffer.FRAGMENT_SHADER,
              'precision mediump float;'
              //+ 'varying float float_fogDistance;'
                + 'uniform sampler2D sampler;'
                + 'varying vec4 vec_fragmentColor;'
                + 'varying vec2 vec_textureCoord;'
                + 'void main(void){'
              /*+   'gl_FragColor = mix('
                +     'vec4('
                +       clearcolor['red'] + ','
                +       clearcolor['green'] + ','
                +       clearcolor['blue'] + ','
                +       clearcolor['alpha']
                +     '),'
                +     'vec_fragmentColor,'
                +     'clamp(exp(-0.001 * float_fogDistance * float_fogDistance), 0.0, 1.0)'
                +   ') * vec_fragmentColor;'
              */+   'gl_FragColor = texture2D('
                +     'sampler,'
                +     'vec_textureCoord'
                +   ') * vec_fragmentColor;'
                + '}'
            );
            create_shader(
              'vertex',
              buffer.VERTEX_SHADER,
              'attribute vec3 vec_vertexPosition;'
              //+ 'varying float float_fogDistance;'
                + 'uniform mat4 mat_cameraMatrix;'
                + 'uniform mat4 mat_perspectiveMatrix;'
                + 'varying vec4 vec_fragmentColor;'
                + 'attribute vec4 vec_vertexColor;'
                + 'varying vec2 vec_textureCoord;'
                + 'attribute vec2 vec_texturePosition;'
                + 'void main(void){'
                +   'gl_Position = mat_perspectiveMatrix * mat_cameraMatrix * vec4(vec_vertexPosition, 1.0);'
                +   'vec_fragmentColor = vec_vertexColor;'
              //+   'float_fogDistance = length(gl_Position.xyz);'
                +   'vec_textureCoord = vec_texturePosition;'
                + '}'
            );

            create_program(
              'shaders',
              [
                shaders['fragment'],
                shaders['vertex'],
              ]
            );

            set_vertexattribarray('vec_vertexColor');
            set_vertexattribarray('vec_vertexPosition');
            set_vertexattribarray('vec_texturePosition');
        }

        camera = {
          'rotate-x': 0,
          'rotate-y': 0,
          'rotate-z': 0,
          'x': 0,
          'y': 0,
          'z': 0,
        };
        matricies['camera'] = matrix_create();
        matrix_perspective();

        if(typeof load_level === 'function'){
            load_level(mode);
        }

        if(typeof draw_logic === 'function'){
            animationFrame = window.requestAnimationFrame(drawloop);
        }

        if(typeof logic === 'function'){
            interval = window.setInterval(
              logicloop,
              msperframe || settings['ms-per-frame']
            );
        }
    }

}

function set_buffer(colorData, vertexData, textureData, indexData){
    var colorBuffer = buffer.createBuffer();
    buffer.bindBuffer(
      buffer.ARRAY_BUFFER,
      colorBuffer
    );
    buffer.bufferData(
      buffer.ARRAY_BUFFER,
      new Float32Array(colorData),
      buffer.STATIC_DRAW
    );

    var vertexBuffer = buffer.createBuffer();
    buffer.bindBuffer(
      buffer.ARRAY_BUFFER,
      vertexBuffer
    );
    buffer.bufferData(
      buffer.ARRAY_BUFFER,
      new Float32Array(vertexData),
      buffer.STATIC_DRAW
    );

    var textureBuffer = buffer.createBuffer();
    buffer.bindBuffer(
      buffer.ARRAY_BUFFER,
      textureBuffer
    );
    buffer.bufferData(
      buffer.ARRAY_BUFFER,
      new Float32Array(textureData),
      buffer.STATIC_DRAW
    );

    var indexBuffer = buffer.createBuffer();
    buffer.bindBuffer(
      buffer.ARRAY_BUFFER,
      indexBuffer
    );
    buffer.bufferData(
      buffer.ARRAY_BUFFER,
      new Uint16Array(indexData),
      buffer.STATIC_DRAW
    );

    return {
      'color': colorBuffer,
      'index': indexBuffer,
      'texture': textureBuffer,
      'vertex': vertexBuffer,
    }
}

function set_entity(id, properties){
    properties['position'] = properties['position'] || [
      1, 1, 1, 1,
      1, 1, 1, 1,
      1, 1, 1, 1,
      1, 1, 1, 1,
    ];
    properties['mode'] = properties['mode'] || 'TRIANGLE_FAN';
    properties['position'] = properties['position'] || {
      'x': 0,
      'y': 0,
      'z': 0,
    };
    properties['rotate'] = properties['rotate'] || {
      'x': 0,
      'y': 0,
      'z': 0,
    };
    properties['scale'] = properties['scale'] || {
      'x': 1,
      'y': 1,
      'z': 1
    };

    entities[id] = properties;

    entities[id]['buffer'] = set_buffer(
      entities[id]['color'],
      entities[id]['vertices'],
      [
        0.0, 1.0,
        0.0, 0.0,
        1.0, 0.0,
        1.0, 1.0,
      ],
      entities[id]['index']
    );

    set_texture2d(
      id,
      texture_default
    );
}

function set_texture2d(entityid, image){
    entities[entityid]['texture'] = buffer.createTexture();
    entities[entityid]['image'] = new_image(
      image,
      function(){
          buffer.bindTexture(
            buffer.TEXTURE_2D,
            entities[entityid]['texture']
          );
          buffer.texImage2D(
            buffer.TEXTURE_2D,
            0,
            buffer.RGBA,
            buffer.RGBA,
            buffer.UNSIGNED_BYTE,
            entities[entityid]['image']
          );
          buffer.texParameteri(
            buffer.TEXTURE_2D,
            buffer.TEXTURE_MAG_FILTER,
            buffer.NEAREST
          );
          buffer.texParameteri(
            buffer.TEXTURE_2D,
            buffer.TEXTURE_MIN_FILTER,
            buffer.NEAREST
          );
          buffer.bindTexture(
            buffer.TEXTURE_2D,
            void 0
          );
      }
    );
}

function set_vertexattribarray(attribute){
    attributes[attribute] = buffer.getAttribLocation(
      programs['shaders'],
      attribute
    );
    buffer.enableVertexAttribArray(attributes[attribute]);
}

var animationFrame = 0;
var attributes = {};
var buffer = 0;
var camera = {};
var canvas = 0;
var clearcolor = {};
var cleardepth = 1;
var entities = {};
var groups = {};
var height = 0;
var interval = 0;
var matricies = {};
var mode = 0;
var pointerlock = false;
var programs = {};
var shaders = {};
var texture_debug = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAD1BMVEUAAP8A/wD/AAAAAAD///8hKtLYAAAAIklEQVQoz2NwQQMMTkoQIAgBIiNMwIEBAowhwGSECaAnBwAdPj4tFnzwQgAAAABJRU5ErkJggg==';
var texture_default = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2P8////fwAKAAP+j4hsjgAAAABJRU5ErkJggg==';
var width = 0;
var x = 0;
var y = 0;

document.onpointerlockchange = onpointerlockchange;
window.onresize = resize;
<commit_msg>fixed clearcolor<commit_after>'use strict';

function create_program(id, shaderlist){
    var program = buffer.createProgram();
    for(var shader in shaderlist){
        buffer.attachShader(
          program,
          shaderlist[shader]
        );
    }
    buffer.linkProgram(program);
    buffer.useProgram(program);

    programs[id] = program;
}

function create_shader(id, type, source){
    var shader = buffer.createShader(type);
    buffer.shaderSource(
      shader,
      source
    );
    buffer.compileShader(shader);

    shaders[id] = shader;
}

function draw(){
    buffer.viewport(
      0,
      0,
      buffer.viewportWidth,
      buffer.viewportHeight
    );
    buffer.clear(buffer.COLOR_BUFFER_BIT | buffer.DEPTH_BUFFER_BIT);

    matrix_identity('camera');
    matrix_rotate(
      'camera',
      [
        degrees_to_radians(camera['rotate-x']),
        degrees_to_radians(camera['rotate-y']),
        degrees_to_radians(camera['rotate-z']),
      ]
    );
    matrix_translate(
      'camera',
      [
        camera['x'],
        camera['y'],
        camera['z'],
      ]
    );

    draw_logic();

    for(var entity in entities){
        matrix_clone(
          'camera',
          'cache'
        );

        matrix_translate(
          'camera',
          [
            -entities[entity]['position']['x'],
            -entities[entity]['position']['y'],
            entities[entity]['position']['z'],
          ]
        );
        matrix_rotate(
          'camera',
          [
            degrees_to_radians(entities[entity]['rotate']['x']),
            degrees_to_radians(entities[entity]['rotate']['y']),
            degrees_to_radians(entities[entity]['rotate']['z']),
          ]
        );

        buffer.bindBuffer(
          buffer.ARRAY_BUFFER,
          entities[entity]['buffer']['color']
        );
        buffer.vertexAttribPointer(
          attributes['vec_vertexColor'],
          4,
          buffer.FLOAT,
          false,
          0,
          0
        );

        buffer.bindBuffer(
          buffer.ARRAY_BUFFER,
          entities[entity]['buffer']['vertex']
        );
        buffer.vertexAttribPointer(
          attributes['vec_vertexPosition'],
          3,
          buffer.FLOAT,
          false,
          0,
          0
        );

        buffer.bindBuffer(
          buffer.ARRAY_BUFFER,
          entities[entity]['buffer']['texture']
        );
        buffer.vertexAttribPointer(
          attributes['vec_texturePosition'],
          2,
          buffer.FLOAT,
          false,
          0,
          0
        );

        buffer.activeTexture(buffer.TEXTURE0);
        buffer.bindTexture(
          buffer.TEXTURE_2D,
          entities[entity]['texture']
        );
        buffer.uniform1i(
          buffer.getUniformLocation(
            programs['shaders'],
            'sampler'
          ),
          0
        );

        buffer.bindBuffer(
          buffer.ARRAY_BUFFER,
          entities[entity]['buffer']['index']
        );

        buffer.uniformMatrix4fv(
          buffer.getUniformLocation(
            programs['shaders'],
            'mat_perspectiveMatrix'
          ),
          0,
          matricies['perspective']
        );
        buffer.uniformMatrix4fv(
          buffer.getUniformLocation(
            programs['shaders'],
            'mat_cameraMatrix'
          ),
          0,
          matricies['camera']
        );

        buffer.drawArrays(
          buffer[entities[entity]['mode']],
          0,
          entities[entity]['vertices'].length / 3
        );

        matrix_copy(
          'cache',
          'camera'
        );
    }

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

function drawloop(){
    draw();
    animationFrame = window.requestAnimationFrame(drawloop);
}

function group_add(group, entitylist){
    if(!(group in groups)){
        groups[group] = {};
    }

    for(var entity in entitylist){
        groups[group][entitylist[entity]] = true;
    }
}

function group_modify(grouplist, todo){
    for(var group in grouplist){
        for(var entity in groups[grouplist[group]]){
            todo(entity);
        }
    }
}

function group_remove(group, entitylist, remove){
    remove = remove || false;

    if(group in groups){
        for(var entity in entitylist){
            delete groups[group][entitylist[entity]];
        }
    }

    if(remove
      && groups[group].length === 0){
        delete groups[group];
    }
}

function init_webgl(){
    resize();

    clearcolor = {
      'alpha': 1,
      'blue': 0,
      'green': 0,
      'red': 0,
    };

    setmode(0);
}

function logicloop(){
    for(var entity in entities){
        if(entities[entity]['logic']){
            entities[entity]['logic']();
        }
    }

    logic();
}

function move_camera(speed, y, strafe){
    strafe = strafe || false;
    var radians = -degrees_to_radians(camera['rotate-y'] - (strafe ? 90 : 0));
    camera['x'] += round(speed * Math.sin(radians), 7);
    camera['y'] += y;
    camera['z'] += round(speed * Math.cos(radians), 7);
}

function new_image(src, todo){
    var image = new Image();
    image.onload = todo || function(){};
    image.src = src;
    return image;
}

function onpointerlockchange(event){
    pointerlock = document.pointerLockElement === document.getElementById('canvas');
};

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;

    buffer.viewportHeight = height;
    buffer.viewportWidth = width;
    buffer.viewport(0, 0, height, width);

    if(typeof resize_logic === 'function'){
        resize_logic();
    }
}

function rotate_camera(x, y, z){
    camera['rotate-x'] = clamp(
      round(
        camera['rotate-x'] + x,
        7
      ),
      0,
      360,
      true
    );
    camera['rotate-y'] = clamp(
      round(
        camera['rotate-y'] + y,
        7
      ),
      0,
      360,
      true
    );
    camera['rotate-z'] = clamp(
      round(
        camera['rotate-z'] + z,
        7
      ),
      0,
      360,
      true
    );
}

function set_clearcolor(color){
    clearcolor = color;
    buffer.clearColor(
      color['red'],
      color['green'],
      color['blue'],
      color['alpha']
    );
}

function setmode(newmode, newgame){
    window.cancelAnimationFrame(animationFrame);
    window.clearInterval(interval);

    camera = {};
    mode = newmode;
    var msperframe = 0;
    newgame = newgame || false;
    programs = {};
    shaders = {};

    if(typeof setmode_logic === 'function'){
        setmode_logic(newgame);

    }else{
        mode = 1;
        newgame = true;
        msperframe = 33;
    }

    // Main menu mode.
    if(mode === 0){
        buffer = 0;
        canvas = 0;

    // Simulation modes.
    }else{
        if(newgame){
            document.body.innerHTML =
              '<canvas id=canvas></canvas><canvas id=buffer></canvas>';

            buffer = document.getElementById('buffer').getContext(
              'webgl',
              {
                'alpha': false,
                'antialias': true,
                'depth': true,
                'preserveDrawingBuffer': false,
                'premultipliedAlpha': false,
                'stencil': false,
              }
            );
            canvas = document.getElementById('canvas').getContext('2d');

            resize();

            set_clearcolor(clearcolor);
            buffer.clearDepth(cleardepth);
            buffer.enable(buffer.CULL_FACE);
            buffer.enable(buffer.DEPTH_TEST);
            buffer.depthFunc(buffer.LEQUAL);

            create_shader(
              'fragment',
              buffer.FRAGMENT_SHADER,
              'precision mediump float;'
              //+ 'varying float float_fogDistance;'
                + 'uniform sampler2D sampler;'
                + 'varying vec4 vec_fragmentColor;'
                + 'varying vec2 vec_textureCoord;'
                + 'void main(void){'
              /*+   'gl_FragColor = mix('
                +     'vec4('
                +       clearcolor['red'] + ','
                +       clearcolor['green'] + ','
                +       clearcolor['blue'] + ','
                +       clearcolor['alpha']
                +     '),'
                +     'vec_fragmentColor,'
                +     'clamp(exp(-0.001 * float_fogDistance * float_fogDistance), 0.0, 1.0)'
                +   ') * vec_fragmentColor;'
              */+   'gl_FragColor = texture2D('
                +     'sampler,'
                +     'vec_textureCoord'
                +   ') * vec_fragmentColor;'
                + '}'
            );
            create_shader(
              'vertex',
              buffer.VERTEX_SHADER,
              'attribute vec3 vec_vertexPosition;'
              //+ 'varying float float_fogDistance;'
                + 'uniform mat4 mat_cameraMatrix;'
                + 'uniform mat4 mat_perspectiveMatrix;'
                + 'varying vec4 vec_fragmentColor;'
                + 'attribute vec4 vec_vertexColor;'
                + 'varying vec2 vec_textureCoord;'
                + 'attribute vec2 vec_texturePosition;'
                + 'void main(void){'
                +   'gl_Position = mat_perspectiveMatrix * mat_cameraMatrix * vec4(vec_vertexPosition, 1.0);'
                +   'vec_fragmentColor = vec_vertexColor;'
              //+   'float_fogDistance = length(gl_Position.xyz);'
                +   'vec_textureCoord = vec_texturePosition;'
                + '}'
            );

            create_program(
              'shaders',
              [
                shaders['fragment'],
                shaders['vertex'],
              ]
            );

            set_vertexattribarray('vec_vertexColor');
            set_vertexattribarray('vec_vertexPosition');
            set_vertexattribarray('vec_texturePosition');
        }

        camera = {
          'rotate-x': 0,
          'rotate-y': 0,
          'rotate-z': 0,
          'x': 0,
          'y': 0,
          'z': 0,
        };
        matricies['camera'] = matrix_create();
        matrix_perspective();

        if(typeof load_level === 'function'){
            load_level(mode);
        }

        if(typeof draw_logic === 'function'){
            animationFrame = window.requestAnimationFrame(drawloop);
        }

        if(typeof logic === 'function'){
            interval = window.setInterval(
              logicloop,
              msperframe || settings['ms-per-frame']
            );
        }
    }

}

function set_buffer(colorData, vertexData, textureData, indexData){
    var colorBuffer = buffer.createBuffer();
    buffer.bindBuffer(
      buffer.ARRAY_BUFFER,
      colorBuffer
    );
    buffer.bufferData(
      buffer.ARRAY_BUFFER,
      new Float32Array(colorData),
      buffer.STATIC_DRAW
    );

    var vertexBuffer = buffer.createBuffer();
    buffer.bindBuffer(
      buffer.ARRAY_BUFFER,
      vertexBuffer
    );
    buffer.bufferData(
      buffer.ARRAY_BUFFER,
      new Float32Array(vertexData),
      buffer.STATIC_DRAW
    );

    var textureBuffer = buffer.createBuffer();
    buffer.bindBuffer(
      buffer.ARRAY_BUFFER,
      textureBuffer
    );
    buffer.bufferData(
      buffer.ARRAY_BUFFER,
      new Float32Array(textureData),
      buffer.STATIC_DRAW
    );

    var indexBuffer = buffer.createBuffer();
    buffer.bindBuffer(
      buffer.ARRAY_BUFFER,
      indexBuffer
    );
    buffer.bufferData(
      buffer.ARRAY_BUFFER,
      new Uint16Array(indexData),
      buffer.STATIC_DRAW
    );

    return {
      'color': colorBuffer,
      'index': indexBuffer,
      'texture': textureBuffer,
      'vertex': vertexBuffer,
    }
}

function set_entity(id, properties){
    properties['position'] = properties['position'] || [
      1, 1, 1, 1,
      1, 1, 1, 1,
      1, 1, 1, 1,
      1, 1, 1, 1,
    ];
    properties['mode'] = properties['mode'] || 'TRIANGLE_FAN';
    properties['position'] = properties['position'] || {
      'x': 0,
      'y': 0,
      'z': 0,
    };
    properties['rotate'] = properties['rotate'] || {
      'x': 0,
      'y': 0,
      'z': 0,
    };
    properties['scale'] = properties['scale'] || {
      'x': 1,
      'y': 1,
      'z': 1
    };

    entities[id] = properties;

    entities[id]['buffer'] = set_buffer(
      entities[id]['color'],
      entities[id]['vertices'],
      [
        0.0, 1.0,
        0.0, 0.0,
        1.0, 0.0,
        1.0, 1.0,
      ],
      entities[id]['index']
    );

    set_texture2d(
      id,
      texture_default
    );
}

function set_texture2d(entityid, image){
    entities[entityid]['texture'] = buffer.createTexture();
    entities[entityid]['image'] = new_image(
      image,
      function(){
          buffer.bindTexture(
            buffer.TEXTURE_2D,
            entities[entityid]['texture']
          );
          buffer.texImage2D(
            buffer.TEXTURE_2D,
            0,
            buffer.RGBA,
            buffer.RGBA,
            buffer.UNSIGNED_BYTE,
            entities[entityid]['image']
          );
          buffer.texParameteri(
            buffer.TEXTURE_2D,
            buffer.TEXTURE_MAG_FILTER,
            buffer.NEAREST
          );
          buffer.texParameteri(
            buffer.TEXTURE_2D,
            buffer.TEXTURE_MIN_FILTER,
            buffer.NEAREST
          );
          buffer.bindTexture(
            buffer.TEXTURE_2D,
            void 0
          );
      }
    );
}

function set_vertexattribarray(attribute){
    attributes[attribute] = buffer.getAttribLocation(
      programs['shaders'],
      attribute
    );
    buffer.enableVertexAttribArray(attributes[attribute]);
}

var animationFrame = 0;
var attributes = {};
var buffer = 0;
var camera = {};
var canvas = 0;
var clearcolor = {};
var cleardepth = 1;
var entities = {};
var groups = {};
var height = 0;
var interval = 0;
var matricies = {};
var mode = 0;
var pointerlock = false;
var programs = {};
var shaders = {};
var texture_debug = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAD1BMVEUAAP8A/wD/AAAAAAD///8hKtLYAAAAIklEQVQoz2NwQQMMTkoQIAgBIiNMwIEBAowhwGSECaAnBwAdPj4tFnzwQgAAAABJRU5ErkJggg==';
var texture_default = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2P8////fwAKAAP+j4hsjgAAAABJRU5ErkJggg==';
var width = 0;
var x = 0;
var y = 0;

document.onpointerlockchange = onpointerlockchange;
window.onresize = resize;
<|endoftext|>


<commit_before>describe('Battleクラスのテスト', function() {
    describe('ウェイトフェイズ', function() {
        it('素早いキャラクターのターンになる', function() {
            var testData = {};
            testData[1] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ランドーザ',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 150,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var ret = Battle.doWaitPhase();
            var statusArray = Battle.getStatusArray();
            assert.equal('1',ret);
            assert.isTrue(statusArray[1].active>=Battle.MAX_ACTIVE,"アクティブゲージが最大値以上になる");
        });

        it('素早さが同じ場合は、インデックスが若いキャラクターのターンになる',function(){
            var testData = {};
            testData[5] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ゼロブレイバー',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var ret = Battle.doWaitPhase();
            var statusArray = Battle.getStatusArray();
            assert.equal('2',ret);
            assert.isTrue(statusArray[5].active>=Battle.MAX_ACTIVE,"アクティブゲージが最大値以上になる");
            assert.isTrue(statusArray[2].active>=Battle.MAX_ACTIVE,"アクティブゲージが最大値以上になる");

        });
    });

    describe('攻撃', function() {
        it('攻撃側のバッテリーが多いので攻撃がヒットする',function(){
            var testData = {};
            testData[1] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ランドーザ',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 150,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var retWaitPhase = Battle.doWaitPhase();
            var retAtack = Battle.atack({
                atackBattery : 3,
                defenthBattery : 1
            });
            var statusArray = Battle.getStatusArray();
            assert.equal('1',retWaitPhase);
            assert.equal(Battle.ATACK_HIT,retAtack.hit);
            assert.equal(1600,retAtack.damage);
            assert.equal(2,statusArray[1].battery);
            assert.equal(4,statusArray[2].battery);
        });

         it('攻撃・防御側が同じバッテリーを出したので防御判定になりダメージが半減される',function(){
            var testData = {};
            testData[1] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ランドーザ',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 150,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var retWaitPhase = Battle.doWaitPhase();
            var retAtack = Battle.atack({
                atackBattery : 4,
                defenthBattery : 4
            });
            var statusArray = Battle.getStatusArray();
            assert.isTrue('1'===retWaitPhase,'ユーザID1のターンになる');
            assert.isTrue(Battle.ATACK_GUARD===retAtack.hit,'防御判定になる');
            assert.isTrue(2100/2===retAtack.damage,'ダメージが半減される');
            assert.isTrue(1===statusArray[1].battery,'攻撃側バッテリーが減る');
            assert.isTrue(1===statusArray[2].battery,'防御側バッテリーが減る');
        });
    });
}); <commit_msg>戦闘ロジックテストで攻撃判定部分をふやした。<commit_after>describe('Battleクラスのテスト', function() {
    describe('ウェイトフェイズ', function() {
        it('素早いキャラクターのターンになる', function() {
            var testData = {};
            testData[1] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ランドーザ',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 150,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var ret = Battle.doWaitPhase();
            var statusArray = Battle.getStatusArray();
            assert.equal('1',ret,'ユーザID1のターンになる');
            assert.isTrue(statusArray[1].active>=Battle.MAX_ACTIVE,"アクティブゲージが最大値以上になる");
        });

        it('素早さが同じ場合は、インデックスが若いキャラクターのターンになる',function(){
            var testData = {};
            testData[5] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ゼロブレイバー',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var ret = Battle.doWaitPhase();
            var statusArray = Battle.getStatusArray();
            assert.equal('2',ret,'ユーザID2のターンになる');
            assert.isTrue(statusArray[5].active>=Battle.MAX_ACTIVE,"ユーザID5のアクティブゲージが最大値以上になる");
            assert.isTrue(statusArray[2].active>=Battle.MAX_ACTIVE,"ユーザID2のアクティブゲージが最大値以上になる");

        });

        it('自分のターンになったらバッテリーが1回復する',function(){
            var testData = {};
            testData[1] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 3,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ランドーザ',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 150,
                active : 0,
                battery : 2,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var ret = Battle.doWaitPhase();
            var statusArray = Battle.getStatusArray();
            assert.equal('1',ret,'ユーザID1のターンになる');
            assert.equal(4,statusArray[1].battery,'バッテリーが1回復する');
            assert.isTrue(statusArray[1].active>=Battle.MAX_ACTIVE,"アクティブゲージが最大値以上になる");

        });

    });

    describe('攻撃', function() {
        it('攻撃側のバッテリーが多いので攻撃がヒットする',function(){
            var testData = {};
            testData[1] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ランドーザ',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 150,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var retWaitPhase = Battle.doWaitPhase();
            var retAtack = Battle.atack({
                atackBattery : 3,
                defenthBattery : 1
            });
            var statusArray = Battle.getStatusArray();
            assert.equal('1',retWaitPhase);
            assert.equal(Battle.ATACK_HIT,retAtack.hit);
            assert.equal(1600,retAtack.damage);
            assert.equal(2,statusArray[1].battery);
            assert.equal(4,statusArray[2].battery);
        });

         it('攻撃・防御側が同じバッテリーを出したので防御判定になりダメージが半減される',function(){
            var testData = {};
            testData[1] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ランドーザ',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 150,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var retWaitPhase = Battle.doWaitPhase();
            var retAtack = Battle.atack({
                atackBattery : 4,
                defenthBattery : 4
            });
            var statusArray = Battle.getStatusArray();
            assert.equal('1',retWaitPhase,'ユーザID1のターンになる');
            assert.equal(Battle.ATACK_GUARD,retAtack.hit,'防御判定になる');
            assert.equal(2100/2,retAtack.damage,'ダメージが半減される');
            assert.equal(1,statusArray[1].battery,'攻撃側バッテリーが減る');
            assert.equal(1,statusArray[2].battery,'防御側バッテリーが減る');
        });

         it('防御側が多くバッテリーを出したので攻撃ミスになりダメージが0になる',function(){
            var testData = {};
            testData[1] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ランドーザ',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 150,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var retWaitPhase = Battle.doWaitPhase();
            var retAtack = Battle.atack({
                atackBattery : 2,
                defenthBattery : 4
            });
            var statusArray = Battle.getStatusArray();
            assert.equal('1',retWaitPhase,'ユーザID1のターンになる');
            assert.equal(Battle.ATACK_MISS,retAtack.hit,'攻撃ミスになる');
            assert.equal(0,retAtack.damage,'ダメージが0になる');
            assert.equal(3,statusArray[1].battery,'攻撃側バッテリーが減る');
            assert.equal(1,statusArray[2].battery,'防御側バッテリーが減る');
        });

         it('防御側がバッテリーに0を指定したので、クリティカルヒットになる',function(){
            var testData = {};
            testData[1] = {
                name : 'グランブレイバー',
                pictName : 'GranBraver.PNG',
                hp : 3200,
                speed : 230,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name : 'バスターナックル',power : 800},
                    2 : {name : 'バスターナックル',power : 1100},
                    3 : {name : 'バスターナックル',power : 1600},
                    4 : {name : 'バスターナックル',power : 2100},
                    5 : {name : 'バスターナックル',power : 2800}
                }
            };
            testData[2] = {
                name : 'ランドーザ',
                pictName : 'Landozer.PNG',
                hp : 4700,
                speed : 150,
                active : 0,
                battery : 5,
                weapons : {
                    1 : {name:'ブレイクパンチ',power:1200},
                    2 : {name:'ブレイクパンチ',power:1700},
                    3 : {name:'ブレイクパンチ',power:2300},
                    4 : {name:'ブレイクパンチ',power:2900},
                    5 : {name:'ブレイクパンチ',power:3800}
                }
            };

            var Battle = battle({
                statusArray : testData
            });

            var retWaitPhase = Battle.doWaitPhase();
            var retAtack = Battle.atack({
                atackBattery : 5,
                defenthBattery : 0
            });
            var statusArray = Battle.getStatusArray();
            assert.equal('1',retWaitPhase,'ユーザID1のターンになる');
            assert.equal(Battle.ATACK_CRITICAL,retAtack.hit,'クリィカルヒットになる');
            assert.equal(2800*2,retAtack.damage,'ダメージが2倍になる');
            assert.equal(0,statusArray[1].battery,'攻撃側バッテリーが減る');
            assert.equal(5,statusArray[2].battery,'防御側バッテリーが減る');
        });
    });
}); <|endoftext|>


<commit_before>'use strict';

var feedbackUrl = 'http://localhost';
var gateHost = 'http://localhost:8084';
var bakeryDetailUrl = 'http://localhost:8087';

window.spinnakerSettings = {
  defaultProviders: ['aws', 'gce', 'azure', 'cf', 'kubernetes', 'titan'],
  feedbackUrl: feedbackUrl,
  gateUrl: gateHost,
  bakeryDetailUrl: bakeryDetailUrl,
  pollSchedule: 30000,
  defaultTimeZone: 'America/New_York', // see http://momentjs.com/timezone/docs/#/data-utilities/
  providers: {
    azure: {
      defaults: {
        account: 'azure-test',
        region: 'West US'
      },
    },
    aws: {
      defaults: {
        account: 'test',
        region: 'us-east-1'
      },
      defaultSecurityGroups: ['nf-datacenter-vpc', 'nf-infrastructure-vpc', 'nf-datacenter', 'nf-infrastructure'],
      loadBalancers: {
        // if true, VPC load balancers will be created as internal load balancers if the selected subnet has a purpose
        // tag that starts with "internal"
        inferInternalFlagFromSubnet: false,
      },
    },
    gce: {
      defaults: {
        account: 'my-google-account',
        region: 'us-central1',
        zone: 'us-central1-f',
      },
    },
    titan: {
      defaults: {
        account: 'titustest',
        region: 'us-east-1'
      },
    },
    kubernetes: {
      defaults: {
        account: 'my-kubernetes-account',
        namespace: 'default',
        proxy: 'localhost:8001'
      },
    }
  },
  notifications: {
    email: {
      enabled: true,
    },
    hipchat: {
      enabled: true,
      botName: 'Skynet T-800'
    },
    sms: {
      enabled: true,
    },
    slack: {
      enabled: true,
      botName: 'spinnakerbot'
    }
  },
  whatsNew: {
    gistId: '32526cd608db3d811b38',
    fileName: 'news.md',
  },
  feature: {
    pipelines: true,
    jobs: true,
    notifications: false,
    fastProperty: false,
    vpcMigrator: false,
    clusterDiff: false,
    roscoMode: false,
    netflixMode: false,
    infrastructureStages: false, // Should 'createLoadBalancer' be a pipeline stage? (no).
  },
};
<commit_msg>adds auth endpoint to k8s/simple settings.js (#1437)<commit_after>'use strict';

var feedbackUrl = 'http://localhost';
var gateHost = 'http://localhost:8084';
var bakeryDetailUrl = 'http://localhost:8087';
var authEndpoint = gateHost + '/auth/user';

window.spinnakerSettings = {
  defaultProviders: ['aws', 'gce', 'azure', 'cf', 'kubernetes', 'titan'],
  feedbackUrl: feedbackUrl,
  gateUrl: gateHost,
  authEndpoint: authEndpoint,
  bakeryDetailUrl: bakeryDetailUrl,
  pollSchedule: 30000,
  defaultTimeZone: 'America/New_York', // see http://momentjs.com/timezone/docs/#/data-utilities/
  providers: {
    azure: {
      defaults: {
        account: 'azure-test',
        region: 'West US'
      },
    },
    aws: {
      defaults: {
        account: 'test',
        region: 'us-east-1'
      },
      defaultSecurityGroups: ['nf-datacenter-vpc', 'nf-infrastructure-vpc', 'nf-datacenter', 'nf-infrastructure'],
      loadBalancers: {
        // if true, VPC load balancers will be created as internal load balancers if the selected subnet has a purpose
        // tag that starts with "internal"
        inferInternalFlagFromSubnet: false,
      },
    },
    gce: {
      defaults: {
        account: 'my-google-account',
        region: 'us-central1',
        zone: 'us-central1-f',
      },
    },
    titan: {
      defaults: {
        account: 'titustest',
        region: 'us-east-1'
      },
    },
    kubernetes: {
      defaults: {
        account: 'my-kubernetes-account',
        namespace: 'default',
        proxy: 'localhost:8001'
      },
    }
  },
  notifications: {
    email: {
      enabled: true,
    },
    hipchat: {
      enabled: true,
      botName: 'Skynet T-800'
    },
    sms: {
      enabled: true,
    },
    slack: {
      enabled: true,
      botName: 'spinnakerbot'
    }
  },
  whatsNew: {
    gistId: '32526cd608db3d811b38',
    fileName: 'news.md',
  },
  feature: {
    pipelines: true,
    jobs: true,
    notifications: false,
    fastProperty: false,
    vpcMigrator: false,
    clusterDiff: false,
    roscoMode: false,
    netflixMode: false,
    infrastructureStages: false, // Should 'createLoadBalancer' be a pipeline stage? (no).
  },
};
<|endoftext|>


<commit_before>'use strict'

// server.js
var express = require('express');
var morgan = require('morgan');
var multer = require('multer');
var cors = require('cors');
var fs = require('fs');
var path = require('path');
var md5File = require('md5-file');

var config = require('config');

var Util = require('./util.js');

var app = express();

// config
const schDirectory = config.get('App.uploader.dirs.schematics');
const isDebug = config.get('Server.Debug');
if (isDebug) console.log("Server is Debug(Develop) Mode.");

// ミドルウェア
morgan.token('remote-addr', function (req, res) {
  var ffHeaderValue = req.headers['x-forwarded-for'];
  return ffHeaderValue || req.connection.remoteAddress;
});
app.use(morgan('[:date[clf]] :remote-addr :remote-user ":method :url HTTP/:http-version" :status - :response-time ms'));
const upload = multer({ dest: 'schematics' });

const corsOptions = {
  optionsSuccessStatus: 200
}
if (isDebug) corsOptions.origin = config.get('Server.AccessOriginURL');
app.use(cors(corsOptions));

// rootはアクセスできましぇん
app.get('/', (req, res) => {
  res.status(404).end();
});

// GETリクエストのハンドリング
app.get('/+schematics', (req, res) => {
  fs.readdir(schDirectory, (err, files) => {
    if (err) res.json({status: "error", message: err.Error});
    else {
      const filenames = files.filter(fn => fn.endsWith('.schematic'));

      const asyncReadInfos = [];
      for (var i = 0; i < filenames.length; i++) {
        asyncReadInfos.push( Util.readSchematicJSON(filenames[i].replace(/.schematic$/, '')) );
      }

      Promise.all(asyncReadInfos)
      .then((results) => res.json(results));
    }
  });
});

app.get('/+schematics/:sch_name', (req, res) => {
  const target = Util.getSchemFilePath(req.params.sch_name);
  if (fs.existsSync(target)) {
    Promise.resolve(Util.readSchematicJSON(target))
    .then((data) => res.json(data))
    .catch((err) => res.status(403).json({ status: 'read error', error: err }));
  } else res.status(404).end();
});

app.get('/+schematics/:sch_name/download', (req, res) => {
  const target = Util.getSchemFilePath(req.params.sch_name);
  if (fs.existsSync(target)) res.download(target);
  else res.status(404).end();
});

// POSTリクエストのハンドリング
app.post('/+schematics/upload', upload.single('sch_file'), function (req, res, next) {
  if (req.file && req.body.title) {
    const sch_name = path.basename(req.file.originalname, '.schematic');
    const upload_name = Util.getSchemFilePath(sch_name);

    // TODO: md5で上書きチェックを追加
    // TODO: 削除キーで上書きロックを追加
    Promise.resolve(new Promise((resolve, reject) => {
      fs.rename(req.file.path, upload_name, (err) => {
        if (err) reject(err);
        else resolve();
      });
    }))
    .then(() => new Promise((resolve) => {
      // infoディレクトリが無かったら作成
      const dir = config.get('App.uploader.dirs.infoFiles');
      if (fs.existsSync(dir)) fs.mkdir(dir, (err) => resolve());
    }))
    .then(() => new Promise((resolve, reject) => {
      // その他情報をメモする
      const fileInfo = {
        title: req.body.title,
        original_name: req.file.originalname,
        description: req.body.description,
        delete_key: req.body.delete_key,
        upload_date: Date.now()
      };

      fs.writeFile(Util.getInfoFilePath(sch_name), JSON.stringify(fileInfo),
        (err) => {
          if (err) reject(err);
          else resolve({ status: 'success', info: fileInfo });
        });
    }))
    .then((result) => res.json(result))
    .catch((err) => res.status(500).json({
      status: 'error', message: err.error
    }));

  } else {
    res.status(400).json({ status: "error", message: "Invalid API Syntax"});
  }
});

// TODO: deleteメソッドの実装
// 削除キーが一致、もしくは未設定の場合に削除実行
app.delete('/+schematics/:sch_name', (req, res) => {
  console.log("delete => " + req.params.sch_name);
  res.status(400).json({ status: "error", message: "Invalid API Syntax"});
});

app.listen(config.get('Server.Port'), () => {
  console.log("server has started.");
});

<commit_msg>削除APIの実装<commit_after>'use strict'

// server.js
var express = require('express');
var morgan = require('morgan');
var multer = require('multer');
var cors = require('cors');
var fs = require('fs');
var path = require('path');
var md5File = require('md5-file');

var config = require('config');

var Util = require('./util.js');

var app = express();

// config
const schDirectory = config.get('App.uploader.dirs.schematics');
const isDebug = config.get('Server.Debug');
if (isDebug) console.log("Server is Debug(Develop) Mode.");

// ミドルウェア
morgan.token('remote-addr', function (req, res) {
  var ffHeaderValue = req.headers['x-forwarded-for'];
  return ffHeaderValue || req.connection.remoteAddress;
});
app.use(morgan('[:date[clf]] :remote-addr :remote-user ":method :url HTTP/:http-version" :status - :response-time ms'));
const uploader = multer({ dest: 'schematics' });

const corsOptions = {
  optionsSuccessStatus: 200
}
if (isDebug) corsOptions.origin = config.get('Server.AccessOriginURL');
app.use(cors(corsOptions));

// rootはアクセスできましぇん
app.get('/', (req, res) => {
  res.status(404).end();
});

// GETリクエストのハンドリング
app.get('/+schematics', (req, res) => {
  fs.readdir(schDirectory, (err, files) => {
    if (err) res.json({status: "error", message: err.Error});
    else {
      const filenames = files.filter(fn => fn.endsWith('.schematic'));

      const asyncReadInfos = [];
      for (var i = 0; i < filenames.length; i++) {
        asyncReadInfos.push( Util.readSchematicJSON(filenames[i].replace(/.schematic$/, '')) );
      }

      Promise.all(asyncReadInfos)
      .then((results) => res.json(results));
    }
  });
});

app.get('/+schematics/:sch_name', (req, res) => {
  const target = Util.getSchemFilePath(req.params.sch_name);
  if (fs.existsSync(target)) {
    Promise.resolve(Util.readSchematicJSON(target))
    .then((data) => res.json(data))
    .catch((err) => res.status(403).json({ status: 'read error', error: err }));
  } else res.status(404).end();
});

app.get('/+schematics/:sch_name/download', (req, res) => {
  const target = Util.getSchemFilePath(req.params.sch_name);
  if (fs.existsSync(target)) res.download(target);
  else res.status(404).end();
});

// POSTリクエストのハンドリング
app.post('/+schematics/upload', uploader.single('sch_file'), function (req, res, next) {
  if (req.file && req.body.title) {
    const sch_name = path.basename(req.file.originalname, '.schematic');
    const upload_name = Util.getSchemFilePath(sch_name);

    // TODO: md5で上書きチェックを追加
    // TODO: 削除キーで上書きロックを追加
    Promise.resolve(new Promise((resolve, reject) => {
      fs.rename(req.file.path, upload_name, (err) => {
        if (err) reject(err);
        else resolve();
      });
    }))
    .then(() => new Promise((resolve) => {
      // infoディレクトリが無かったら作成
      const dir = config.get('App.uploader.dirs.infoFiles');
      if (fs.existsSync(dir)) fs.mkdir(dir, (err) => resolve());
    }))
    .then(() => new Promise((resolve, reject) => {
      // その他情報をメモする
      const fileInfo = {
        title: req.body.title,
        original_name: req.file.originalname,
        description: req.body.description,
        delete_key: req.body.delete_key,
        upload_date: Date.now()
      };

      fs.writeFile(Util.getInfoFilePath(sch_name), JSON.stringify(fileInfo),
        (err) => {
          if (err) reject(err);
          else resolve({ status: 'success', info: fileInfo });
        });
    }))
    .then((result) => res.json(result))
    .catch((err) => res.status(500).json({
      status: 'error', message: err.error
    }));

  } else {
    res.status(400).json({ status: "error", message: "Invalid API Syntax"});
  }
});

// 削除キーが一致、もしくは未設定の場合に削除実行
app.delete('/+schematics/:sch_name', uploader.single('delete_key'), (req, res) => {
  console.log("delete => " + req.params.sch_name);

  Util.canDeleteFileOfSchematic(req.params.sch_name, req.body.delete_key)
  .then((canDelete) => {
    console.log("delete check => " + canDelete);
    // 削除キーチェックに引っかかった場合はrejectしてcatchへ飛ばす
    if (!canDelete) return Promise.reject({ Error: "Delete key does not match", Status: 403 });
  })
  .then(Util.readSchematicJSON(req.params.sch_name))
  .then((fileInfo) => new Promise((resolve, reject) => {
    // 削除処理1
    fs.unlink(Util.getSchemFilePath(req.params.sch_name), (err) => {
      if (err) reject(err);
      else resolve(fileInfo);
    });
  }))
  .then((fileInfo) => new Promise((resolve, reject) => {
    // 削除処理2
    fs.unlink(Util.getInfoFilePath(req.params.sch_name), (err) => {
      if (err) reject(err);
      else resolve(fileInfo);
    });
  }))
  .then((fileInfo) => {
    // 削除完了レスポンス
    res.json({ status: 'success', fileInfo });
  })
  .catch((err) => {
    // エラー返答
    let stcode = 400;
    if (err.Status) stcode = err.Status;
    res.status(stcode).json({ status: "error", message: err.Error });
  })
});

app.listen(config.get('Server.Port'), () => {
  console.log("server has started.");
});

<|endoftext|>


<commit_before>(function () {
  "use strict";

  angular
    .module('mnHttp', ["mnPendingQueryKeeper"])
    .factory('mnHttpInterceptor', mnHttpFactory)
    .config(function ($httpProvider) {
      $httpProvider.interceptors.push('mnHttpInterceptor');
    });

  function mnHttpFactory(mnPendingQueryKeeper, $q, $httpParamSerializerJQLike, $timeout) {
    var myHttpInterceptor = {
      request: request,
      response: response,
      responseError: responseError
    };

    return myHttpInterceptor;

    function request(config) {
      if (config.url.indexOf(".html") !== -1 || config.doNotIntercept) {
        return config;
      } else {
        return intercept(config);
      }
    }
    function intercept(config) {
      var pendingQuery = {
        config: _.clone(config)
      };
      var mnHttpConfig = config.mnHttp || {};
      delete config.mnHttp;
      if (config.method.toLowerCase() === "post" && mnHttpConfig.cancelPrevious) {
        var queryInFly = mnPendingQueryKeeper.getQueryInFly(config);
        queryInFly && queryInFly.canceler();
      }
      var canceler = $q.defer();
      var timeoutID;
      var timeout = config.timeout;
      var isCleared;

      function clear() {
        if (isCleared) {
          return;
        }
        isCleared = true;
        timeoutID && $timeout.cancel(timeoutID);
        mnPendingQueryKeeper.removeQueryInFly(pendingQuery);
      }

      function cancel(reason) {
        return function () {
          canceler.resolve(reason);
          clear();
        };
      }

      switch (config.method.toLowerCase()) {
        case 'post':
        case 'put':
          config.headers = config.headers || {};
          if (!mnHttpConfig.isNotForm) {
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
            if (!angular.isString(config.data)) {
              config.data = $httpParamSerializerJQLike(config.data);
            }
          }
        break;
      }

      config.timeout = canceler.promise;
      config.clear = clear;

      pendingQuery.canceler = cancel("cancelled");
      pendingQuery.group = mnHttpConfig.group;
      mnPendingQueryKeeper.push(pendingQuery);

      if (timeout) {
        timeoutID = $timeout(cancel("timeout"), timeout);
      }
      return config;
    }

    function clearOnResponse(response) {
      if (response.config.clear && angular.isFunction(response.config.clear)) {
        response.config.clear();
        delete response.config.clear;
      }
    }

    function response(response) {
      clearOnResponse(response);
      return response;
    }
    function responseError(response) {
      clearOnResponse(response);
      return $q.reject(response);
    }
  }

})();
<commit_msg>MB-23244: encode form data in accordance with x-www-form-urlencoded...<commit_after>(function () {
  "use strict";

  angular
    .module('mnHttp', ["mnPendingQueryKeeper"])
    .factory('mnHttpInterceptor', mnHttpFactory)
    .config(function ($httpProvider) {
      $httpProvider.interceptors.push('mnHttpInterceptor');
    });

  function mnHttpFactory(mnPendingQueryKeeper, $q, $httpParamSerializerJQLike, $timeout) {
    var myHttpInterceptor = {
      request: request,
      response: response,
      responseError: responseError
    };

    return myHttpInterceptor;

    function request(config) {
      if (config.url.indexOf(".html") !== -1 || config.doNotIntercept) {
        return config;
      } else {
        return intercept(config);
      }
    }
    function intercept(config) {
      var pendingQuery = {
        config: _.clone(config)
      };
      var mnHttpConfig = config.mnHttp || {};
      delete config.mnHttp;
      if (config.method.toLowerCase() === "post" && mnHttpConfig.cancelPrevious) {
        var queryInFly = mnPendingQueryKeeper.getQueryInFly(config);
        queryInFly && queryInFly.canceler();
      }
      var canceler = $q.defer();
      var timeoutID;
      var timeout = config.timeout;
      var isCleared;

      function clear() {
        if (isCleared) {
          return;
        }
        isCleared = true;
        timeoutID && $timeout.cancel(timeoutID);
        mnPendingQueryKeeper.removeQueryInFly(pendingQuery);
      }

      function cancel(reason) {
        return function () {
          canceler.resolve(reason);
          clear();
        };
      }

      switch (config.method.toLowerCase()) {
        case 'post':
        case 'put':
          config.headers = config.headers || {};
          if (!mnHttpConfig.isNotForm) {
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
            if (!angular.isString(config.data)) {
              config.data = jQueryLikeParamSerializer(config.data);
            }
          }
        break;
      }

      config.timeout = canceler.promise;
      config.clear = clear;

      pendingQuery.canceler = cancel("cancelled");
      pendingQuery.group = mnHttpConfig.group;
      mnPendingQueryKeeper.push(pendingQuery);

      if (timeout) {
        timeoutID = $timeout(cancel("timeout"), timeout);
      }
      return config;
    }

    function serializeValue(v) {
      if (angular.isObject(v)) {
        return angular.isDate(v) ? v.toISOString() : angular.toJson(v);
      }
      return v;
    }
    //function is borrowed from the Angular source code because we want to
    //use $httpParamSerializerJQLik but with properly encoded params via
    //encodeURIComponent since it uses correct application/x-www-form-urlencoded
    //encoding algorithm, in accordance with
    //https://www.w3.org/TR/html5/forms.html#url-encoded-form-data
    function jQueryLikeParamSerializer(params) {
      if (!params) {
        return '';
      }
      var parts = [];
      serialize(params, '', true);
      return parts.join('&');

      function serialize(toSerialize, prefix, topLevel) {
        if (toSerialize === null || angular.isUndefined(toSerialize)) {
          return;
        }
        if (angular.isArray(toSerialize)) {
          angular.forEach(toSerialize, function (value, index) {
            serialize(value, prefix + '[' + (angular.isObject(value) ? index : '') + ']');
          });
        } else if (angular.isObject(toSerialize) && !angular.isDate(toSerialize)) {
          angular.forEach(toSerialize, function (value, key) {
            serialize(value, prefix +
                (topLevel ? '' : '[') +
                key +
                (topLevel ? '' : ']'));
          });
        } else {
          parts.push(encodeURIComponent(prefix) + '=' + encodeURIComponent(serializeValue(toSerialize)));
        }
      }
    }

    function clearOnResponse(response) {
      if (response.config.clear && angular.isFunction(response.config.clear)) {
        response.config.clear();
        delete response.config.clear;
      }
    }

    function response(response) {
      clearOnResponse(response);
      return response;
    }
    function responseError(response) {
      clearOnResponse(response);
      return $q.reject(response);
    }
  }

})();
<|endoftext|>


<commit_before>var _ = require('lodash');

require('coffee-script');
require('coffee-script/register');

// Various assurances that in running tests, we don't accidentally run them
// on the production DB.

// 1. Make sure there are no environmental variables for COCO_ in place

var allowedKeys = [
  'COCO_TRAVIS_TEST'
];

var cocoKeysPresent = _.any(_.keys(process.env), function(envKey) {
  return envKey.indexOf('COCO_') >= 0 && !_.contains(allowedKeys, envKey);
});
if (cocoKeysPresent) {
  throw Error('Stopping server tests because COCO_ environmental variables are present.');
}

// 2. Clear environmental variables anyway
process.env = {};

// 3. Check server_config
global.testing = true;
var config = require('../../server_config');
if(config.mongo.host !== 'localhost') {
  throw Error('Stopping server tests because mongo host is not localhost.');
}

// 4. Check database string
var database = require('../../server/commons/database');
var dbString = 'mongodb://localhost:27017/coco_unittest';
if (database.generateMongoConnectionString() !== dbString) {
  throw Error('Stopping server tests because db connection string was not as expected.');
}

//jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 120; // for long Stripe tests
require('../server/common'); // Make sure global testing functions are set up

var initialized = false;
beforeEach(function(done) {
  if (initialized) {
    return done();
  }

  var async = require('async');
  async.series([
    function(cb) {
      // Start the server
      var server = require('../../server');
      server.startServer(cb);
    },
    function(cb) {
      // 5. Check actual database
      var User = require('../../server/models/User');
      User.find({}).count(function(err, count) {
        // For this to serve as a line of defense against testing with the
        // production DB, tests must be run with
        expect(err).toBeNull();
        expect(count).toBeLessThan(100);
        if(err || count >= 100) {
          // the only way to be sure we don't keep going with the tests
          process.exit(1);
        }
        GLOBAL.mc.lists.subscribe = _.noop;
        cb()
      });
    },
    function(cb) {
      // Clear db
      var mongoose = require('mongoose');
      mongoose.connection.db.command({dropDatabase:1}, function(err, result) {
        if (err) { console.log(err); }
        cb(err);
      });
    },
    function(cb) {
      // Initialize products
      request = require('../server/request');
      request.get(getURL('/db/products'), function(err, res, body) {
        expect(err).toBe(null);
        expect(res.statusCode).toBe(200);
        cb(err);
      });
    }
  ],
  function(err) {
    if (err) {
      process.exit(1);
    }
    initialized = true;
    done();
  });
});
<commit_msg>Make jasmine server test timeout longer<commit_after>var _ = require('lodash');

require('coffee-script');
require('coffee-script/register');

// Various assurances that in running tests, we don't accidentally run them
// on the production DB.

// 1. Make sure there are no environmental variables for COCO_ in place

var allowedKeys = [
  'COCO_TRAVIS_TEST'
];

var cocoKeysPresent = _.any(_.keys(process.env), function(envKey) {
  return envKey.indexOf('COCO_') >= 0 && !_.contains(allowedKeys, envKey);
});
if (cocoKeysPresent) {
  throw Error('Stopping server tests because COCO_ environmental variables are present.');
}

// 2. Clear environmental variables anyway
process.env = {};

// 3. Check server_config
global.testing = true;
var config = require('../../server_config');
if(config.mongo.host !== 'localhost') {
  throw Error('Stopping server tests because mongo host is not localhost.');
}

// 4. Check database string
var database = require('../../server/commons/database');
var dbString = 'mongodb://localhost:27017/coco_unittest';
if (database.generateMongoConnectionString() !== dbString) {
  throw Error('Stopping server tests because db connection string was not as expected.');
}

jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 10; // for long Stripe tests
require('../server/common'); // Make sure global testing functions are set up

var initialized = false;
beforeEach(function(done) {
  if (initialized) {
    return done();
  }

  var async = require('async');
  async.series([
    function(cb) {
      // Start the server
      var server = require('../../server');
      server.startServer(cb);
    },
    function(cb) {
      // 5. Check actual database
      var User = require('../../server/models/User');
      User.find({}).count(function(err, count) {
        // For this to serve as a line of defense against testing with the
        // production DB, tests must be run with
        expect(err).toBeNull();
        expect(count).toBeLessThan(100);
        if(err || count >= 100) {
          // the only way to be sure we don't keep going with the tests
          process.exit(1);
        }
        GLOBAL.mc.lists.subscribe = _.noop;
        cb()
      });
    },
    function(cb) {
      // Clear db
      var mongoose = require('mongoose');
      mongoose.connection.db.command({dropDatabase:1}, function(err, result) {
        if (err) { console.log(err); }
        cb(err);
      });
    },
    function(cb) {
      // Initialize products
      request = require('../server/request');
      request.get(getURL('/db/products'), function(err, res, body) {
        expect(err).toBe(null);
        expect(res.statusCode).toBe(200);
        cb(err);
      });
    }
  ],
  function(err) {
    if (err) {
      process.exit(1);
    }
    initialized = true;
    done();
  });
});
<|endoftext|>