<commit_before>$(document).ready(function(){
  // game setup
  var turnCount = 0;
  var gameResult = false;
  var humanColor = '#27ae61';
  var computerColor = '#c1392b';
  var user = 'player';

// game tools
  var button = [];
  for (var i = 1; i < 43; i++) {
    button[i] = document.getElementById('canvas'+i);
    button[i].bDisabled = false;
  }

  var ctx = [];
  for (var i = 1; i < 43; i++) ctx[i] = button[i].getContext("2d");

// helper functions
  function buttonId(cell){
    return cell.id.match(/\d/g).join("");
  }

// player turn and initial start to game
  $( "canvas" ).on( "click", function(){
  var cell = (this);
  if( gameResult == false && cell.bDisabled == false){
    var num = buttonId(cell);
    var color = humanColor;
    floatDown(button, num, color, user);
  };

  if (gameResult == false && turnCount < 42){
    setTimeout(function(){
      computerTurn(button, computerColor);
    }, 370);
  };
});

// draws the circle function
function dCircle(button, num, color, user){
  if(button[num].bDisabled == false){
    button[num].bDisabled = true;
    $(button[num]).addClass('bDisabled');
    if(user == 'player') $(button[num]).addClass('player');
    else($(button[num]).addClass('cpu'));

    button[num].style.webkitTransform = "rotateY(180deg)";
    button[num].style.opacity = 0.7;

// delays drawing of circle below
  setTimeout(function(){
    ctx[num].beginPath();
    ctx[num].lineWidth = 1;
    ctx[num].arc(25,25,17,0,Math.PI*2,false);
    ctx[num].fillStyle = color;
    ctx[num].fill();
    ctx[num].strokeStyle = color;
    ctx[num].stroke();
    ctx[num].closePath();
    },350);
    turnCount ++;
  };
};

// Computer turn basic logic below
function computerTurn(button, computerColor){
  var activeButtons = $('canvas').not('.bDisabled');
  var ranIndex = Math.floor(Math.random()*activeButtons.length)
  var selection = activeButtons[ranIndex];
  var cpu = buttonId(selection);

  var color = computerColor;
  if(button[cpu].bDisabled == false){
    floatDown(button, cpu, color);
  }else(computerTurn(computerColor));
};

// function placed dot on the lowest part of the board.
function floatDown(button, num, color, user){
  var nextCell = num;
  while ( button[nextCell].bDisabled == false ){
    if(typeof button[+nextCell + 7] == "object"){
      if(button[+nextCell + 7].bDisabled == true) dCircle(button, nextCell, color, user);
       else (nextCell = +nextCell + 7);
    }else(dCircle(button, nextCell, color, user));
  };
  if(turnCount >6) checkWinner();
};

// Winner function below will review possible solutions and check for a winner.
function checkWinner(){

  setTimeout(function(){
    if(gameResult == false){
      if(turnCount == 42){
        gameResult = true;
        alert("Draw!!");
      };

    var player = $('canvas').filter('.player');
    var cpu = $('canvas').filter('.cpu');

// horizontal check
  for(p = 0; p < player.length; p++){
    var pass = 0;
    for(r = 1; r < 4 ; r++)

    if($(player[p]).hasClass('edge') || $(player[p + 1]).hasClass('edge') || $(player[p + 2]).hasClass('edge')){
      pass = 0;
    }
    else if(player[p].id.match(/\d/g).join("") - player[r].id.match(/\d/g).join("") == -r){
       pass ++;
       if(pass == 3){
        alert('You Won!!');
        gameResult = true;
       };
    }
    else{
       pass = 0;
    };
  };

  var container = [];
  var vertPass = 0

// vertical check

    //   for(p = 0; p < player.length; p++)
    //   {
    //     container[p] = player[p].id.match(/\d/g).join("")
    //   };

    // for(vertNum = 0; vertNum < player.length; vertNum++){
    //   var number = 1;
    //   var column = number;
    //   var nextR = -column * 7
    //   console.log(container)
    //   console.log("---------------")
    //   console.log(container[vertNum]);
    //   console.log(container[column]);
    //   console.log(nextR);
    // if(container[vertNum] - container[column] == nextR){
    //   number++
    //   console.log('passed');
    //   vertPass++
    //   console.log("vert:" + vertPass)
    // };
    //   if(vertPass == 3){
    //     alert("You Win!!")
    //   };

    // }
    };
  }, 500);
};

});

<commit_msg>added additional attempt for horizontal function<commit_after>$(document).ready(function(){
  // game setup
  var turnCount = 0;
  var gameResult = false;
  var humanColor = '#27ae61';
  var computerColor = '#c1392b';
  var user = 'player';

// game tools
  var button = [];
  for (var i = 1; i < 43; i++) {
    button[i] = document.getElementById('canvas'+i);
    button[i].bDisabled = false;
  }

  var ctx = [];
  for (var i = 1; i < 43; i++) ctx[i] = button[i].getContext("2d");

// helper functions
  function buttonId(cell){
    return cell.id.match(/\d/g).join("");
  }

// player turn and initial start to game
  $( "canvas" ).on( "click", function(){
  var cell = (this);
  if( gameResult == false && cell.bDisabled == false){
    var num = buttonId(cell);
    var color = humanColor;
    floatDown(button, num, color, user);
  };

  if (gameResult == false && turnCount < 42){
    setTimeout(function(){
      computerTurn(button, computerColor);
    }, 370);
  };
});

// draws the circle function
function dCircle(button, num, color, user){
  if(button[num].bDisabled == false){
    button[num].bDisabled = true;
    $(button[num]).addClass('bDisabled');
    if(user == 'player') $(button[num]).addClass('player');
    else($(button[num]).addClass('cpu'));

    button[num].style.webkitTransform = "rotateY(180deg)";
    button[num].style.opacity = 0.7;

// delays drawing of circle below
  setTimeout(function(){
    ctx[num].beginPath();
    ctx[num].lineWidth = 1;
    ctx[num].arc(25,25,17,0,Math.PI*2,false);
    ctx[num].fillStyle = color;
    ctx[num].fill();
    ctx[num].strokeStyle = color;
    ctx[num].stroke();
    ctx[num].closePath();
    },350);
    turnCount ++;
  };
};

// Computer turn basic logic below
function computerTurn(button, computerColor){
  var activeButtons = $('canvas').not('.bDisabled');
  var ranIndex = Math.floor(Math.random()*activeButtons.length)
  var selection = activeButtons[ranIndex];
  var cpu = buttonId(selection);

  var color = computerColor;
  if(button[cpu].bDisabled == false){
    floatDown(button, cpu, color);
  }else(computerTurn(computerColor));
};

// function placed dot on the lowest part of the board.
function floatDown(button, num, color, user){
  var nextCell = num;
  while ( button[nextCell].bDisabled == false ){
    if(typeof button[+nextCell + 7] == "object"){
      if(button[+nextCell + 7].bDisabled == true) dCircle(button, nextCell, color, user);
       else (nextCell = +nextCell + 7);
    }else(dCircle(button, nextCell, color, user));
  };
  if(turnCount >6) checkWinner();
};

// Winner function below will review possible solutions and check for a winner.
function checkWinner(){

  setTimeout(function(){
    if(gameResult == false){
      if(turnCount == 42){
        gameResult = true;
        alert("Draw!!");
      };

    // var player = $('canvas').filter('.player');
    // var cpu = $('canvas').filter('.cpu');

// horizontal check
var board = $('canvas');
var playerScore = 0;
var cpuScore = 0;
var token = null;

  for(p = 0; p < 42; p++){
    console.log(p)
    if(playerScore == 3){
      console.log("Final score" + playerScore);
      gameResult = true;
      alert("You Win!");
    }else if(cpuScore == 3){
      gameResult = true;
      alert("You Lose!");
    };
    if($(board[p]).hasClass('bDisabled') == false){
      token = null;
      playerScore = 0;
      cpuScore = 0;
    }else{
        if(token == true && row == Math.floor(p / 7)){
          playerScore++;
          cpuScore = 0;
          console.log("score" + playerScore);
          console.log("first row:" + row);
        }else if(token == false && row == Math.floor(p / 7)){
          cpuScore++;
          playerScore = 0;
        }else{
          token = $(board[p]).hasClass('bDisabled');
          row = Math.floor(p / 7);
          console.log(row)
          console.log("score" + playerScore);
        };
    };

    // var boardCell = board[p].id.match(/\d/g).join("")-1;
    // if(Math.Floor(boardcell/7){

    // }

  //   var pass = 0;
  //   for(r = 1; r < 4 ; r++)

  //   if($(player[p]).hasClass('edge') || $(player[p + 1]).hasClass('edge') || $(player[p + 2]).hasClass('edge')){
  //     pass = 0;
  //   }
  //   else if(player[p].id.match(/\d/g).join("") - player[r].id.match(/\d/g).join("") == -r){
  //      pass ++;
  //      if(pass == 3){
  //       alert('You Won!!');
  //       gameResult = true;
  //      };
  //   }
  //   else{
  //      pass = 0;
  //   };
  };

  var container = [];
  var vertPass = 0

// vertical check

    //   for(p = 0; p < player.length; p++)
    //   {
    //     container[p] = player[p].id.match(/\d/g).join("")
    //   };

    // for(vertNum = 0; vertNum < player.length; vertNum++){
    //   var number = 1;
    //   var column = number;
    //   var nextR = -column * 7
    //   console.log(container)
    //   console.log("---------------")
    //   console.log(container[vertNum]);
    //   console.log(container[column]);
    //   console.log(nextR);
    // if(container[vertNum] - container[column] == nextR){
    //   number++
    //   console.log('passed');
    //   vertPass++
    //   console.log("vert:" + vertPass)
    // };
    //   if(vertPass == 3){
    //     alert("You Win!!")
    //   };

    // }
    };
  }, 500);
};

});

<|endoftext|>


<commit_before>// NOTE: maybe need to reset these somewhere? For now just going with this
jest.mock('app/services/Firebase', () => {
    return {
        analytics: () => {
            return {
                logEvent: () => {

                }
            };
        }
    };
});

import * as sut from 'app/services/Analytics';
import { AppState } from 'react-native';
import * as AppStateSelectors from 'app/redux/selectors/AppStateSelectors';
import * as ScannedDevicesSelectors from 'app/redux/selectors/ScannedDevicesSelectors';
import * as ConnectedDeviceStatusSelectors from 'app/redux/selectors/ConnectedDeviceStatusSelectors';
import * as SetsSelectors from 'app/redux/selectors/SetsSelectors';

describe('Analytics', () => {
    let params = null;
    const realTron = console.tron;
    const realGetScreenStatus = AppStateSelectors.getScreenStatus;
    const realGetScannedDevices = ScannedDevicesSelectors.getScannedDevices;
    const realGetConnectedDeviceStatus = ConnectedDeviceStatusSelectors.getConnectedDeviceStatus;
    const realGetIsWorkoutEmpty = SetsSelectors.getIsWorkoutEmpty;

    beforeAll(() => {
        console.tron = console.tron = {
            log: () => null,
            display: () => null
        };
    });

    beforeEach(() => {
        params = {};
    });

    afterEach(() => {
        AppStateSelectors.getScreenStatus = realGetScreenStatus;
        ScannedDevicesSelectors.getScannedDevices = realGetScannedDevices;
        ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = realGetConnectedDeviceStatus;
        SetsSelectors.getIsWorkoutEmpty = realGetIsWorkoutEmpty;
    });

    afterAll(() => {
        console.tron = realTron;
    });

    describe('logEventWithAppState', () => {
        describe.skip('is_screen_locked', () => {
            beforeEach(() => {
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            test('false', () => {
                AppStateSelectors.getScreenStatus = () => 'active';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_screen_locked).toBe(false);
            });

            test('true', () => {
                AppStateSelectors.getScreenStatus = () => '';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_screen_locked).toBe(true);
            });
        });

        describe.skip('is_app_active', () => {
            let realAppCurrentState = null;

            beforeEach(() => {
                realAppCurrentState = AppState.currentState;
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            afterEach(() => {
                AppState.currentState = realAppCurrentState;
            });

            test('true if active', () => {
                AppState.currentState = 'active';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_active).toBe(true);
            });

            test('false if inactive', () => {
                AppState.currentState = 'inactive';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_active).toBe(false);
            });

            test('false is background', () => {
                AppState.currentState = 'background';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_active).toBe(false);
            });

            test('undefined otherwise', () => {
                AppState.currentState = 'foobar';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_active).toBeUndefined();
            });
        });

        describe.skip('is_app_in_background', () => {
            let realAppCurrentState = null;

            beforeEach(() => {
                realAppCurrentState = AppState.currentState;
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            afterEach(() => {
                AppState.currentState = realAppCurrentState;
            });

            test('false if active', () => {
                AppState.currentState = 'active';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_in_background).toBe(false);
            });

            test('true if inactive', () => {
                AppState.currentState = 'inactive';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_in_background).toBe(true);
            });

            test('true is background', () => {
                AppState.currentState = 'background';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_in_background).toBe(true);
            });

            test('undefined otherwise', () => {
                AppState.currentState = 'foobar';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_in_background).toBeUndefined();
            });
        });

        describe.skip('is_app_inactive', () => {
            let realAppCurrentState = null;

            beforeEach(() => {
                realAppCurrentState = AppState.currentState;
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            afterEach(() => {
                AppState.currentState = realAppCurrentState;
            });

            test('false if active', () => {
                AppState.currentState = 'active';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_inactive).toBe(false);
            });

            test('true if inactive', () => {
                AppState.currentState = 'inactive';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_inactive).toBe(true);
            });

            test('false is background', () => {
                AppState.currentState = 'background';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_inactive).toBe(false);
            });

            test('undefined otherwise', () => {
                AppState.currentState = 'foobar';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_inactive).toBeUndefined();
            });
        });

        describe('scanned_devices', () => {
            beforeEach(() => {
                AppStateSelectors.getScreenStatus = () => '';
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            test('0', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('');
            });

            test('1', () => {
                ScannedDevicesSelectors.getScannedDevices = () => ['OB 3000'];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('3000');
            });

            test('2', () => {
                ScannedDevicesSelectors.getScannedDevices = () => ['OB 3000', 'OB 3021'];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('30003021');
            });

            test('25', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [
                    'OB 3001', 'OB 3002', 'OB 3003', 'OB 3004', 'OB 3005', 'OB 3006', 'OB 3007', 'OB 3008', 'OB 3009', 'OB 3010',
                    'OB 2001', 'OB 2002', 'OB 2003', 'OB 2004', 'OB 2005', 'OB 2006', 'OB 2007', 'OB 2008', 'OB 2009', 'OB 2010',
                    'OB 1001', 'OB 1002', 'OB 1003', 'OB 1004', 'OB 1005'
                ];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('3001300230033004300530063007300830093010200120022003200420052006200720082009201010011002100310041005');
            });

            test('26', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [
                    'OB 3001', 'OB 3002', 'OB 3003', 'OB 3004', 'OB 3005', 'OB 3006', 'OB 3007', 'OB 3008', 'OB 3009', 'OB 3010',
                    'OB 2001', 'OB 2002', 'OB 2003', 'OB 2004', 'OB 2005', 'OB 2006', 'OB 2007', 'OB 2008', 'OB 2009', 'OB 2010',
                    'OB 1001', 'OB 1002', 'OB 1003', 'OB 1004', 'OB 1005', 'OB 1006'
                ];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('3001300230033004300530063007300830093010200120022003200420052006200720082009201010011002100310041005');
            });
        });

        describe('num_scanned_devices', () => {
            beforeEach(() => {
                AppStateSelectors.getScreenStatus = () => '';
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            test('0', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(0);
            });

            test('1', () => {
                ScannedDevicesSelectors.getScannedDevices = () => ['OB 3000'];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(1);
            });

            test('2', () => {
                ScannedDevicesSelectors.getScannedDevices = () => ['OB 3000', 'OB 3021'];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(2);
            });

            test('25', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [
                    'OB 3001', 'OB 3002', 'OB 3003', 'OB 3004', 'OB 3005', 'OB 3006', 'OB 3007', 'OB 3008', 'OB 3009', 'OB 3010',
                    'OB 2001', 'OB 2002', 'OB 2003', 'OB 2004', 'OB 2005', 'OB 2006', 'OB 2007', 'OB 2008', 'OB 2009', 'OB 2010',
                    'OB 1001', 'OB 1002', 'OB 1003', 'OB 1004', 'OB 1005'
                ];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(25);
            });

            test('26', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [
                    'OB 3001', 'OB 3002', 'OB 3003', 'OB 3004', 'OB 3005', 'OB 3006', 'OB 3007', 'OB 3008', 'OB 3009', 'OB 3010',
                    'OB 2001', 'OB 2002', 'OB 2003', 'OB 2004', 'OB 2005', 'OB 2006', 'OB 2007', 'OB 2008', 'OB 2009', 'OB 2010',
                    'OB 1001', 'OB 1002', 'OB 1003', 'OB 1004', 'OB 1005', 'OB 1006'
                ];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(25);
            });
        });

        describe.skip('is_bluetooth_on', () => {

            beforeEach(() => {
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            test('false if bluetooth off', () => {
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => 'BLUETOOTH_OFF';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_bluetooth_on).toBe(false);
            });

            test('true otherwise', () => {
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => 'foobar';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_bluetooth_on).toBe(true);
            });
        });

        describe('is_workout_in_progress', () => {
            beforeEach(() => {
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
            });

            test('true', () => {
                SetsSelectors.getIsWorkoutEmpty = () => false;

                sut.logEventWithAppState(null, params, null);

                expect(params.is_workout_in_progress).toBe(true);
            });

            test('false', () => {
                SetsSelectors.getIsWorkoutEmpty = () => true;

                sut.logEventWithAppState(null, params, null);

                expect(params.is_workout_in_progress).toBe(false);
            });
        });
    });
});
<commit_msg>Fixed unit tests<commit_after>// NOTE: maybe need to reset these somewhere? For now just going with this
jest.mock('app/services/Firebase', () => {
    return {
        app: () => {
            return {
                analytics: () => {
                    return {
                        logEvent: () => {

                        }
                    };
                }
            }
        }
    };
});

import * as sut from 'app/services/Analytics';
import { AppState } from 'react-native';
import * as AppStateSelectors from 'app/redux/selectors/AppStateSelectors';
import * as ScannedDevicesSelectors from 'app/redux/selectors/ScannedDevicesSelectors';
import * as ConnectedDeviceStatusSelectors from 'app/redux/selectors/ConnectedDeviceStatusSelectors';
import * as SetsSelectors from 'app/redux/selectors/SetsSelectors';

describe('Analytics', () => {
    let params = null;
    const realTron = console.tron;
    const realGetScreenStatus = AppStateSelectors.getScreenStatus;
    const realGetScannedDevices = ScannedDevicesSelectors.getScannedDevices;
    const realGetConnectedDeviceStatus = ConnectedDeviceStatusSelectors.getConnectedDeviceStatus;
    const realGetIsWorkoutEmpty = SetsSelectors.getIsWorkoutEmpty;

    beforeAll(() => {
        console.tron = console.tron = {
            log: () => null,
            display: () => null
        };
    });

    beforeEach(() => {
        params = {};
    });

    afterEach(() => {
        AppStateSelectors.getScreenStatus = realGetScreenStatus;
        ScannedDevicesSelectors.getScannedDevices = realGetScannedDevices;
        ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = realGetConnectedDeviceStatus;
        SetsSelectors.getIsWorkoutEmpty = realGetIsWorkoutEmpty;
    });

    afterAll(() => {
        console.tron = realTron;
    });

    describe('logEventWithAppState', () => {
        describe.skip('is_screen_locked', () => {
            beforeEach(() => {
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            test('false', () => {
                AppStateSelectors.getScreenStatus = () => 'active';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_screen_locked).toBe(false);
            });

            test('true', () => {
                AppStateSelectors.getScreenStatus = () => '';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_screen_locked).toBe(true);
            });
        });

        describe.skip('is_app_active', () => {
            let realAppCurrentState = null;

            beforeEach(() => {
                realAppCurrentState = AppState.currentState;
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            afterEach(() => {
                AppState.currentState = realAppCurrentState;
            });

            test('true if active', () => {
                AppState.currentState = 'active';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_active).toBe(true);
            });

            test('false if inactive', () => {
                AppState.currentState = 'inactive';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_active).toBe(false);
            });

            test('false is background', () => {
                AppState.currentState = 'background';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_active).toBe(false);
            });

            test('undefined otherwise', () => {
                AppState.currentState = 'foobar';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_active).toBeUndefined();
            });
        });

        describe.skip('is_app_in_background', () => {
            let realAppCurrentState = null;

            beforeEach(() => {
                realAppCurrentState = AppState.currentState;
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            afterEach(() => {
                AppState.currentState = realAppCurrentState;
            });

            test('false if active', () => {
                AppState.currentState = 'active';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_in_background).toBe(false);
            });

            test('true if inactive', () => {
                AppState.currentState = 'inactive';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_in_background).toBe(true);
            });

            test('true is background', () => {
                AppState.currentState = 'background';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_in_background).toBe(true);
            });

            test('undefined otherwise', () => {
                AppState.currentState = 'foobar';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_in_background).toBeUndefined();
            });
        });

        describe.skip('is_app_inactive', () => {
            let realAppCurrentState = null;

            beforeEach(() => {
                realAppCurrentState = AppState.currentState;
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            afterEach(() => {
                AppState.currentState = realAppCurrentState;
            });

            test('false if active', () => {
                AppState.currentState = 'active';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_inactive).toBe(false);
            });

            test('true if inactive', () => {
                AppState.currentState = 'inactive';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_inactive).toBe(true);
            });

            test('false is background', () => {
                AppState.currentState = 'background';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_inactive).toBe(false);
            });

            test('undefined otherwise', () => {
                AppState.currentState = 'foobar';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_app_inactive).toBeUndefined();
            });
        });

        describe('scanned_devices', () => {
            beforeEach(() => {
                AppStateSelectors.getScreenStatus = () => '';
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            test('0', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('');
            });

            test('1', () => {
                ScannedDevicesSelectors.getScannedDevices = () => ['OB 3000'];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('3000');
            });

            test('2', () => {
                ScannedDevicesSelectors.getScannedDevices = () => ['OB 3000', 'OB 3021'];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('30003021');
            });

            test('25', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [
                    'OB 3001', 'OB 3002', 'OB 3003', 'OB 3004', 'OB 3005', 'OB 3006', 'OB 3007', 'OB 3008', 'OB 3009', 'OB 3010',
                    'OB 2001', 'OB 2002', 'OB 2003', 'OB 2004', 'OB 2005', 'OB 2006', 'OB 2007', 'OB 2008', 'OB 2009', 'OB 2010',
                    'OB 1001', 'OB 1002', 'OB 1003', 'OB 1004', 'OB 1005'
                ];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('3001300230033004300530063007300830093010200120022003200420052006200720082009201010011002100310041005');
            });

            test('26', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [
                    'OB 3001', 'OB 3002', 'OB 3003', 'OB 3004', 'OB 3005', 'OB 3006', 'OB 3007', 'OB 3008', 'OB 3009', 'OB 3010',
                    'OB 2001', 'OB 2002', 'OB 2003', 'OB 2004', 'OB 2005', 'OB 2006', 'OB 2007', 'OB 2008', 'OB 2009', 'OB 2010',
                    'OB 1001', 'OB 1002', 'OB 1003', 'OB 1004', 'OB 1005', 'OB 1006'
                ];

                sut.logEventWithAppState(null, params, null);

                expect(params.scanned_devices).toBe('3001300230033004300530063007300830093010200120022003200420052006200720082009201010011002100310041005');
            });
        });

        describe('num_scanned_devices', () => {
            beforeEach(() => {
                AppStateSelectors.getScreenStatus = () => '';
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            test('0', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(0);
            });

            test('1', () => {
                ScannedDevicesSelectors.getScannedDevices = () => ['OB 3000'];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(1);
            });

            test('2', () => {
                ScannedDevicesSelectors.getScannedDevices = () => ['OB 3000', 'OB 3021'];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(2);
            });

            test('25', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [
                    'OB 3001', 'OB 3002', 'OB 3003', 'OB 3004', 'OB 3005', 'OB 3006', 'OB 3007', 'OB 3008', 'OB 3009', 'OB 3010',
                    'OB 2001', 'OB 2002', 'OB 2003', 'OB 2004', 'OB 2005', 'OB 2006', 'OB 2007', 'OB 2008', 'OB 2009', 'OB 2010',
                    'OB 1001', 'OB 1002', 'OB 1003', 'OB 1004', 'OB 1005'
                ];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(25);
            });

            test('26', () => {
                ScannedDevicesSelectors.getScannedDevices = () => [
                    'OB 3001', 'OB 3002', 'OB 3003', 'OB 3004', 'OB 3005', 'OB 3006', 'OB 3007', 'OB 3008', 'OB 3009', 'OB 3010',
                    'OB 2001', 'OB 2002', 'OB 2003', 'OB 2004', 'OB 2005', 'OB 2006', 'OB 2007', 'OB 2008', 'OB 2009', 'OB 2010',
                    'OB 1001', 'OB 1002', 'OB 1003', 'OB 1004', 'OB 1005', 'OB 1006'
                ];

                sut.logEventWithAppState(null, params, null);

                expect(params.num_scanned_devices).toBe(25);
            });
        });

        describe.skip('is_bluetooth_on', () => {

            beforeEach(() => {
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                SetsSelectors.getIsWorkoutEmpty = () => true;
            });

            test('false if bluetooth off', () => {
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => 'BLUETOOTH_OFF';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_bluetooth_on).toBe(false);
            });

            test('true otherwise', () => {
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => 'foobar';

                sut.logEventWithAppState(null, params, null);

                expect(params.is_bluetooth_on).toBe(true);
            });
        });

        describe('is_workout_in_progress', () => {
            beforeEach(() => {
                AppStateSelectors.getScreenStatus = () => '';
                ScannedDevicesSelectors.getScannedDevices = () => [];
                ConnectedDeviceStatusSelectors.getConnectedDeviceStatus = () => '';
            });

            test('true', () => {
                SetsSelectors.getIsWorkoutEmpty = () => false;

                sut.logEventWithAppState(null, params, null);

                expect(params.is_workout_in_progress).toBe(true);
            });

            test('false', () => {
                SetsSelectors.getIsWorkoutEmpty = () => true;

                sut.logEventWithAppState(null, params, null);

                expect(params.is_workout_in_progress).toBe(false);
            });
        });
    });
});
<|endoftext|>


<commit_before>"use strict";

const ccxt = require ('ccxt')
    , WsClient = require ('./WsClient')
    , {
        OrderBook,
        IndexedOrderBook,
        CountedOrderBook,
    } = require ('./OrderBook')
    , functions = require ('./functions')

module.exports = class Exchange extends ccxt.Exchange {
    constructor (options = {}) {
        super (options)
        this.newUpdates = options.newUpdates || false
    }

    inflate (data) {
        return functions.inflate (data)
    }

    inflate64 (data) {
        return functions.inflate64 (data)
    }

    gunzip (data) {
        return functions.gunzip (data)
    }

    orderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new OrderBook (snapshot, depth)
    }

    indexedOrderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new IndexedOrderBook (snapshot, depth)
    }

    countedOrderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new CountedOrderBook (snapshot, depth)
    }

    client (url) {
        this.clients = this.clients || {}
        if (!this.clients[url]) {
            const onMessage = this.handleMessage.bind (this)
            const onError = this.onError.bind (this)
            const onClose = this.onClose.bind (this)
            const onConnected = this.onConnected.bind (this)
            // decide client type here: ws / signalr / socketio
            const wsOptions = this.safeValue (this.options, 'ws', {})
            const options = this.extend (this.streaming, {
                'log': this.log ? this.log.bind (this) : this.log,
                'ping': this.ping ? this.ping.bind (this) : this.ping,
                'verbose': this.verbose,
                'throttle': ccxt.throttle (this.tokenBucket),
            }, wsOptions)
            this.clients[url] = new WsClient (url, onMessage, onError, onClose, onConnected, options)
        }
        return this.clients[url]
    }

    spawn (method, ... args) {
        (method.apply (this, args)).catch ((e) => {
            // todo: handle spawned errors
        })
    }

    delay (timeout, method, ... args) {
        setTimeout (() => {
            this.spawn (method, ... args)
        }, timeout)
    }

    watch (url, messageHash, message = undefined, subscribeHash = undefined, subscription = undefined) {
        //
        // Without comments the code of this method is short and easy:
        //
        //     const client = this.client (url)
        //     const backoffDelay = 0
        //     const future = client.future (messageHash)
        //     const connected = client.connect (backoffDelay)
        //     connected.then (() => {
        //         if (message && !client.subscriptions[subscribeHash]) {
        //             client.subscriptions[subscribeHash] = true
        //             client.send (message)
        //         }
        //     }).catch ((error) => {})
        //     return future
        //
        // The following is a longer version of this method with comments
        //
        const client = this.client (url)
        // todo: calculate the backoff using the clients cache
        const backoffDelay = 0
        //
        //  watchOrderBook ---- future ----+---------------+----→ user
        //                                 |               |
        //                                 ↓               ↑
        //                                 |               |
        //                              connect ......→ resolve
        //                                 |               |
        //                                 ↓               ↑
        //                                 |               |
        //                             subscribe -----→ receive
        //
        const future = client.future (messageHash)
        // we intentionally do not use await here to avoid unhandled exceptions
        // the policy is to make sure that 100% of promises are resolved or rejected
        // either with a call to client.resolve or client.reject with
        //  a proper exception class instance
        const connected = client.connect (backoffDelay)
        // the following is executed only if the catch-clause does not
        // catch any connection-level exceptions from the client
        // (connection established successfully)
        connected.then (() => {
            if (!client.subscriptions[subscribeHash]) {
                client.subscriptions[subscribeHash] = subscription || true
                const options = this.safeValue (this.options, 'ws')
                const cost = this.safeValue (options, 'cost', 1);
                if (message) {
                    if (this.enableRateLimit && client.throttle) {
                        // add cost here |
                        //               |
                        //               V
                        client.throttle (cost).then (() => {
                            client.send (message)
                        }).catch ((e) => { throw e })
                    } else {
                        client.send (message)
                    }
                }
            }
        }).catch ((error) => {
            // we do nothing and don't return a resolvable value from here
            // we leave it in a rejected state to avoid triggering the
            // then-clauses that will follow (if any)
            // removing this catch will raise UnhandledPromiseRejection in JS
            // upon connection failure
        })
        return future
    }

    onConnected (client, message = undefined) {
        // for user hooks
        // console.log ('Connected to', client.url)
    }

    onError (client, error) {
        if ((client.url in this.clients) && (this.clients[client.url].error)) {
            delete this.clients[client.url]
        }
    }

    onClose (client, error) {
        if (client.error) {
            // connection closed due to an error, do nothing
        } else {
            // server disconnected a working connection
            if (this.clients[client.url]) {
                delete this.clients[client.url]
            }
        }
    }

    async close () {
        const clients = Object.values (this.clients || {})
        for (let i = 0; i < clients.length; i++) {
            const client = clients[i]
            delete this.clients[client.url]
            await client.close ()
        }
    }

    findTimeframe (timeframe, timeframes = undefined) {
        timeframes = timeframes || this.timeframes
        const keys = Object.keys (timeframes);
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            if (timeframes[key] === timeframe) {
                return key;
            }
        }
        return undefined;
    }
}
<commit_msg>Exchange.js linting<commit_after>"use strict";

const ccxt = require ('ccxt')
    , WsClient = require ('./WsClient')
    , {
        OrderBook,
        IndexedOrderBook,
        CountedOrderBook,
    } = require ('./OrderBook')
    , functions = require ('./functions');

module.exports = class Exchange extends ccxt.Exchange {
    constructor (options = {}) {
        super (options);
        this.newUpdates = options.newUpdates || false;
    }

    inflate (data) {
        return functions.inflate (data);
    }

    inflate64 (data) {
        return functions.inflate64 (data);
    }

    gunzip (data) {
        return functions.gunzip (data);
    }

    orderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new OrderBook (snapshot, depth);
    }

    indexedOrderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new IndexedOrderBook (snapshot, depth);
    }

    countedOrderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new CountedOrderBook (snapshot, depth);
    }

    client (url) {
        this.clients = this.clients || {};
        if (!this.clients[url]) {
            const onMessage = this.handleMessage.bind (this);
            const onError = this.onError.bind (this);
            const onClose = this.onClose.bind (this);
            const onConnected = this.onConnected.bind (this);
            // decide client type here: ws / signalr / socketio
            const wsOptions = this.safeValue (this.options, 'ws', {});
            const options = this.extend (this.streaming, {
                'log': this.log ? this.log.bind (this) : this.log,
                'ping': this.ping ? this.ping.bind (this) : this.ping,
                'verbose': this.verbose,
                'throttle': ccxt.throttle (this.tokenBucket),
            }, wsOptions);
            this.clients[url] = new WsClient (url, onMessage, onError, onClose, onConnected, options);
        }
        return this.clients[url];
    }

    spawn (method, ... args) {
        (method.apply (this, args)).catch ((e) => {
            // todo: handle spawned errors
        })
    }

    delay (timeout, method, ... args) {
        setTimeout (() => {
            this.spawn (method, ... args)
        }, timeout);
    }

    watch (url, messageHash, message = undefined, subscribeHash = undefined, subscription = undefined) {
        //
        // Without comments the code of this method is short and easy:
        //
        //     const client = this.client (url)
        //     const backoffDelay = 0
        //     const future = client.future (messageHash)
        //     const connected = client.connect (backoffDelay)
        //     connected.then (() => {
        //         if (message && !client.subscriptions[subscribeHash]) {
        //             client.subscriptions[subscribeHash] = true
        //             client.send (message)
        //         }
        //     }).catch ((error) => {})
        //     return future
        //
        // The following is a longer version of this method with comments
        //
        const client = this.client (url);
        // todo: calculate the backoff using the clients cache
        const backoffDelay = 0;
        //
        //  watchOrderBook ---- future ----+---------------+----→ user
        //                                 |               |
        //                                 ↓               ↑
        //                                 |               |
        //                              connect ......→ resolve
        //                                 |               |
        //                                 ↓               ↑
        //                                 |               |
        //                             subscribe -----→ receive
        //
        const future = client.future (messageHash);
        // we intentionally do not use await here to avoid unhandled exceptions
        // the policy is to make sure that 100% of promises are resolved or rejected
        // either with a call to client.resolve or client.reject with
        //  a proper exception class instance
        const connected = client.connect (backoffDelay);
        // the following is executed only if the catch-clause does not
        // catch any connection-level exceptions from the client
        // (connection established successfully)
        connected.then (() => {
            if (!client.subscriptions[subscribeHash]) {
                client.subscriptions[subscribeHash] = subscription || true;
                const options = this.safeValue (this.options, 'ws');
                const cost = this.safeValue (options, 'cost', 1);
                if (message) {
                    if (this.enableRateLimit && client.throttle) {
                        // add cost here |
                        //               |
                        //               V
                        client.throttle (cost).then (() => {
                            client.send (message);
                        }).catch ((e) => { throw e });
                    } else {
                        client.send (message);
                    }
                }
            }
        }).catch ((error) => {
            // we do nothing and don't return a resolvable value from here
            // we leave it in a rejected state to avoid triggering the
            // then-clauses that will follow (if any)
            // removing this catch will raise UnhandledPromiseRejection in JS
            // upon connection failure
        })
        return future;
    }

    onConnected (client, message = undefined) {
        // for user hooks
        // console.log ('Connected to', client.url)
    }

    onError (client, error) {
        if ((client.url in this.clients) && (this.clients[client.url].error)) {
            delete this.clients[client.url];
        }
    }

    onClose (client, error) {
        if (client.error) {
            // connection closed due to an error, do nothing
        } else {
            // server disconnected a working connection
            if (this.clients[client.url]) {
                delete this.clients[client.url];
            }
        }
    }

    async close () {
        const clients = Object.values (this.clients || {});
        for (let i = 0; i < clients.length; i++) {
            const client = clients[i];
            delete this.clients[client.url];
            await client.close ();
        }
    }

    findTimeframe (timeframe, timeframes = undefined) {
        timeframes = timeframes || this.timeframes;
        const keys = Object.keys (timeframes);
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            if (timeframes[key] === timeframe) {
                return key;
            }
        }
        return undefined;
    }
}
<|endoftext|>


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

var player;
var map;
var ladderMap;
var platforms;
var ladders;
var stoppers;
var npcs;
var rc;
var spaceKey;

function preload() {
    // preload content
    game.load.image('tilesheet', 'assets/tileset.png');
    game.load.image('player', 'assets/player.png');
    game.load.spritesheet('NPC', 'assets/NPC.png', 10, 16);
    game.load.tilemap('map', 'assets/maps/level.json', null, Phaser.Tilemap.TILED_JSON);
}

function create() {
    // create entities
    game.stage.backgroundColor = '#47A3FF';
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.world.setBounds(0, 0, 1920, 1920);
    game.physics.arcade.gravity.y = 600;

    var text = game.add.text(32, 32, 'GREG IS HAPPY', {fontSize:'64px', fill: '#000'});
    text.anchor.set(0.5);
    text.x = game.width / 2;
    text.y = game.height / 4;

    map = game.add.tilemap('map');
    map.addTilesetImage('tileset', 'tilesheet');
    map.setCollisionBetween(1, 4);

    platforms = map.createLayer('Platforms');
    ladders = map.createLayer('Ladders');
    stoppers = map.createLayer('Stoppers');
    stoppers.visible = false;

    cursors = game.input.keyboard.createCursorKeys();
    spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

    npcs = game.add.group();
    npcs.enableBody = true;
    var max = 5;
    var total = 0;
    var tiles = platforms.getTiles(0, 0, platforms.width, platforms.height);
    for (var i in tiles) {
        var tile = tiles[i];
        if (tile.index == 3 && Math.random() > 0.9) {
            npc = new NPC(tile.worldX, 0);
            npc.y = tile.worldY - npc.height;
            npcs.add(npc);
            total += 1;
         }
    }

    player = new Player();
    game.add.existing(player);
    game.camera.follow(player);

    rc = new RageCounter();
    game.add.existing(rc);
}

function update() {
    game.physics.arcade.collide(player, platforms);
    game.physics.arcade.collide(npcs, platforms);

    var total = 0;
    npcs.forEach(function(npc) {
        total += npc.anger;
        game.physics.arcade.overlap(npc, npcs, npcOverlap);
        game.physics.arcade.overlap(player, npc, playerNPCOverlap);
    });

    rc.level = total;
}

function npcOverlap(npc1, npc2) {
    if (npc1.renderOrderID == npc2.renderOrderID) {
        return;
    }
    var rager;
    var victim;
    if (Math.random() <= 0.5) {
        rager = npc1;
        victim = npc2;
    } else {
        rager = npc2;
        victim = npc1;
    }
    // higher anger, higher chance of rage
    var chance = (rager.anger * 0.05) - 0.3;
    if (Math.random() >= chance) {
        rager.rageAt(victim);
    }
}

function playerNPCOverlap(player, npc) {
    if (!spaceKey.isDown) {
        return;
    }

    npc.anger = 0;
}

Player = function() {
    Phaser.Sprite.call(this, game, 0, 0, 'player');
    game.physics.arcade.enable(this);

    this.x = (game.width - this.width) / 2;
};

Player.prototype = Object.create(Phaser.Sprite.prototype);
Player.prototype.constructor = Player;

Player.prototype.update = function() {
    this.body.velocity.x = 0;
    if (cursors.left.isDown) {
        this.body.velocity.x = -350;
    }else if (cursors.right.isDown) {
        this.body.velocity.x = 350;
    }

    if (cursors.up.isDown && this.body.onFloor()) {
        this.body.velocity.y = -300;
    }
};

Player.prototype.beNiceTo = function(npc) {
    // TODO - different levels of "healing"
    npc.rage = 0;
};

NPC = function(x, y) {
    Phaser.Sprite.call(this, game, x, y, 'NPC');
    game.physics.arcade.enable(this);

    this.lastRaged = this.game.time.now - 100;
    this.anger = 0;

    this.body.velocity.x = 50;
    if (Math.random() > 0.5) {
        this.body.velocity.x *= -1;
    }

    this.modifier = Math.random() / 2 + 0.1;
};

NPC.prototype = Object.create(Phaser.Sprite.prototype);
NPC.prototype.contstructor = NPC;

NPC.prototype.update = function() {
    // anger management
    if (this.anger < 9) {
        this.anger += (game.time.physicsElapsed * this.modifier);
    }

    this.frame = Math.round(this.anger);
    if (Math.round(this.anger) > 9) {
        this.frame = 9;
    }

    // edge detection
    var tileX = stoppers.getTileX(this.x + this.body.width/2);
    var tileY = stoppers.getTileY(this.y + this.body.height/2);
    if (this.isEdge(stoppers.index, tileX, tileY)) {
        if (this.game.time.now - this.lastTime < 100) {
            return;
        }

        this.body.velocity.x *= -1;
        this.lastTime = this.game.time.now;
        /*
        if (this.animations.currentAnim.name == 'left') {
            this.animations.play('right');
            return;
        }

        this.animations.play('left');*/
    }
};

NPC.prototype.isEdge = function(index, x, y) {
    var leftTile = map.getTileLeft(index, x, y);
    var rightTile = map.getTileRight(index, x, y);

    if (!leftTile && rightTile) {
        return rightTile.index != -1;
    }

    if (!rightTile && leftTile) {
        return leftTile.index != -1;
    }

    return (leftTile.index != -1) || (rightTile.index != -1);
};

NPC.prototype.rageAt = function(otherNPC) {
    // TODO - implement different levels of rage
    if (this.game.time.now - this.lastRaged < 1000) {
        return;
    }

    otherNPC.anger *= 1.5;
    console.log("RAAAGE");
    this.lastRaged = otherNPC.lastRaged = this.game.time.now;
};

RageCounter = function() {
    Phaser.Text.call(this, game, 0, 0, "RAGE LEVEL: ", {});
    this.level = 0;
    this.fixedToCamera = true;
};

RageCounter.prototype = Object.create(Phaser.Text.prototype);
RageCounter.prototype.contstructor = RageCounter;

RageCounter.prototype.update = function() {
    this.text = "RAGE LEVEL: " + Math.round(this.level);
};

<commit_msg>js/game: give greg some anger states!<commit_after>var game = new Phaser.Game(800, 600, Phaser.CANVAS, '', {preload: preload, create: create, update: update});

var player;
var map;
var ladderMap;
var platforms;
var ladders;
var stoppers;
var npcs;
var rc;
var spaceKey;
var greg;

function preload() {
    // preload content
    game.load.image('tilesheet', 'assets/tileset.png');
    game.load.image('player', 'assets/player.png');
    game.load.spritesheet('NPC', 'assets/NPC.png', 10, 16);
    game.load.tilemap('map', 'assets/maps/level.json', null, Phaser.Tilemap.TILED_JSON);
}

function create() {
    // create entities
    game.stage.backgroundColor = '#47A3FF';
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.world.setBounds(0, 0, 1920, 1920);
    game.physics.arcade.gravity.y = 600;

    greg = game.add.text(32, 32, 'GREG IS HAPPY', {fontSize:'64px', fill: '#000'});
    greg.anchor.set(0.5);
    greg.x = game.width / 2;
    greg.y = game.height / 4;

    map = game.add.tilemap('map');
    map.addTilesetImage('tileset', 'tilesheet');
    map.setCollisionBetween(1, 4);

    platforms = map.createLayer('Platforms');
    ladders = map.createLayer('Ladders');
    stoppers = map.createLayer('Stoppers');
    stoppers.visible = false;

    cursors = game.input.keyboard.createCursorKeys();
    spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

    npcs = game.add.group();
    npcs.enableBody = true;
    var max = 5;
    var total = 0;
    var tiles = platforms.getTiles(0, 0, platforms.width, platforms.height);
    for (var i in tiles) {
        var tile = tiles[i];
        if (tile.index == 3 && Math.random() > 0.9) {
            npc = new NPC(tile.worldX, 0);
            npc.y = tile.worldY - npc.height;
            npcs.add(npc);
            total += 1;
         }
    }

    player = new Player();
    game.add.existing(player);
    game.camera.follow(player);

    rc = new RageCounter();
    game.add.existing(rc);
}

function update() {
    game.physics.arcade.collide(player, platforms);
    game.physics.arcade.collide(npcs, platforms);

    var total = 0;
    npcs.forEach(function(npc) {
        total += npc.anger;
        game.physics.arcade.overlap(npc, npcs, npcOverlap);
        game.physics.arcade.overlap(player, npc, playerNPCOverlap);
    });

    rc.level = total;

    if (total < 25) {
        greg.text = "GREG IS FURIOUS!";
        // greg is angry!
    } else if (total < 50) {
        greg.text = "GREG IS PULSATING!";
        // greg is displeased!
    } else if (total < 80) {
        greg.text = "GREG IS ANGRY!";
        // greg needs a chill pill;
    } else if (total < 100) {
        greg.text = "GREG IS PLEASED!";
        // greg is getting ANGRY!
    }
}

function npcOverlap(npc1, npc2) {
    if (npc1.renderOrderID == npc2.renderOrderID) {
        return;
    }
    var rager;
    var victim;
    if (Math.random() <= 0.5) {
        rager = npc1;
        victim = npc2;
    } else {
        rager = npc2;
        victim = npc1;
    }
    // higher anger, higher chance of rage
    var chance = (rager.anger * 0.05) - 0.3;
    if (Math.random() >= chance) {
        rager.rageAt(victim);
    }
}

function playerNPCOverlap(player, npc) {
    if (!spaceKey.isDown) {
        return;
    }

    npc.anger = 0;
}

Player = function() {
    Phaser.Sprite.call(this, game, 0, 0, 'player');
    game.physics.arcade.enable(this);

    this.x = (game.width - this.width) / 2;
};

Player.prototype = Object.create(Phaser.Sprite.prototype);
Player.prototype.constructor = Player;

Player.prototype.update = function() {
    this.body.velocity.x = 0;
    if (cursors.left.isDown) {
        this.body.velocity.x = -350;
    }else if (cursors.right.isDown) {
        this.body.velocity.x = 350;
    }

    if (cursors.up.isDown && this.body.onFloor()) {
        this.body.velocity.y = -300;
    }
};

Player.prototype.beNiceTo = function(npc) {
    // TODO - different levels of "healing"
    npc.rage = 0;
};

NPC = function(x, y) {
    Phaser.Sprite.call(this, game, x, y, 'NPC');
    game.physics.arcade.enable(this);

    this.lastRaged = this.game.time.now - 100;
    this.anger = 0;

    this.body.velocity.x = 50;
    if (Math.random() > 0.5) {
        this.body.velocity.x *= -1;
    }

    this.modifier = Math.random() / 2 + 0.1;
};

NPC.prototype = Object.create(Phaser.Sprite.prototype);
NPC.prototype.contstructor = NPC;

NPC.prototype.update = function() {
    // anger management
    if (this.anger < 9) {
        this.anger += (game.time.physicsElapsed * this.modifier) * 0.5;
    }

    this.frame = Math.round(this.anger);
    if (Math.round(this.anger) > 9) {
        this.frame = 9;
    }

    // edge detection
    var tileX = stoppers.getTileX(this.x + this.body.width/2);
    var tileY = stoppers.getTileY(this.y + this.body.height/2);
    if (this.isEdge(stoppers.index, tileX, tileY)) {
        if (this.game.time.now - this.lastTime < 100) {
            return;
        }

        this.body.velocity.x *= -1;
        this.lastTime = this.game.time.now;
        /*
        if (this.animations.currentAnim.name == 'left') {
            this.animations.play('right');
            return;
        }

        this.animations.play('left');*/
    }
};

NPC.prototype.isEdge = function(index, x, y) {
    var leftTile = map.getTileLeft(index, x, y);
    var rightTile = map.getTileRight(index, x, y);

    if (!leftTile && rightTile) {
        return rightTile.index != -1;
    }

    if (!rightTile && leftTile) {
        return leftTile.index != -1;
    }

    return (leftTile.index != -1) || (rightTile.index != -1);
};

NPC.prototype.rageAt = function(otherNPC) {
    // TODO - implement different levels of rage
    if (this.game.time.now - this.lastRaged < 1000) {
        return;
    }

    otherNPC.anger *= 1.5;
    console.log("RAAAGE");
    this.lastRaged = otherNPC.lastRaged = this.game.time.now;
};

RageCounter = function() {
    Phaser.Text.call(this, game, 0, 0, "RAGE LEVEL: ", {});
    this.level = 0;
    this.fixedToCamera = true;
};

RageCounter.prototype = Object.create(Phaser.Text.prototype);
RageCounter.prototype.contstructor = RageCounter;

RageCounter.prototype.update = function() {
    this.text = "RAGE LEVEL: " + Math.round(this.level);
};

<|endoftext|>


<commit_before>"use strict";

const ccxt = require ('ccxt')
    , WsClient = require ('./WsClient')
    , {
        OrderBook,
        IndexedOrderBook,
        CountedOrderBook,
    } = require ('./OrderBook')

module.exports = class Exchange extends ccxt.Exchange {

    orderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new OrderBook (snapshot, depth)
    }

    indexedOrderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new IndexedOrderBook (snapshot, depth)
    }

    countedOrderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new CountedOrderBook (snapshot, depth)
    }

    client (url) {
        this.clients = this.clients || {}
        if (!this.clients[url]) {
            const onMessage = this.handleMessage.bind (this)
            const onError = this.onError.bind (this)
            const onClose = this.onClose.bind (this)
            // decide client type here: ws / signalr / socketio
            const options = this.extend (this.streaming, {
                'ping': this.ping ? this.ping.bind (this) : this.ping,
            })
            this.clients[url] = new WsClient (url, onMessage, onError, onClose, options)
        }
        return this.clients[url]
    }

    async after (future, method, ... args) {
        const result = await future
        // call it as an instance method on this
        return method.call (this, result, ... args)
    }

    async afterDropped (future, method, ... args) {
        // same as above, drop the result
        if (future) {
            await future
        }
        return method.call (this, ... args)
    }

    spawn (method, ... args) {
        (method.apply (this, args)).catch ((e) => {
            // todo: handle spawned errors
        })
    }

    watch (url, messageHash, message = undefined, subscribeHash = undefined, subscription = undefined) {
        //
        // Without comments the code of this method is short and easy:
        //
        //     const client = this.client (url)
        //     const backoffDelay = 0
        //     const future = client.future (messageHash)
        //     const connected = client.connect (backoffDelay)
        //     connected.then (() => {
        //         if (message && !client.subscriptions[subscribeHash]) {
        //             client.subscriptions[subscribeHash] = true
        //             message = this.signMessage (client, messageHash, message)
        //             client.send (message)
        //         }
        //     }).catch ((error) => {})
        //     return future
        //
        // The following is a longer version of this method with comments
        //
        const client = this.client (url)
        // todo: calculate the backoff using the clients cache
        const backoffDelay = 0
        //
        //  watchOrderBook ---- future ----+---------------+----→ user
        //                                 |               |
        //                                 ↓               ↑
        //                                 |               |
        //                              connect ......→ resolve
        //                                 |               |
        //                                 ↓               ↑
        //                                 |               |
        //                             subscribe -----→ receive
        //
        const future = client.future (messageHash)
        // we intentionally do not use await here to avoid unhandled exceptions
        // the policy is to make sure that 100% of promises are resolved or rejected
        // either with a call to client.resolve or client.reject with
        //  a proper exception class instance
        const connected = client.connect (backoffDelay)
        // the following is executed only if the catch-clause does not
        // catch any connection-level exceptions from the client
        // (connection established successfully)
        new FulPromise ()->
        connected.then (() => {
            if (message && !client.subscriptions[subscribeHash]) {
                client.subscriptions[subscribeHash] = subscription || true
                // todo: decouple signing from subscriptions
                message = this.signMessage (client, messageHash, message)
                client.send (message)
            }
        }).catch ((error) => {
            // we do nothing and don't return a resolvable value from here
            // we leave it in a rejected state to avoid triggering the
            // then-clauses that will follow (if any)
            // removing this catch will raise UnhandledPromiseRejection in JS
            // upon connection failure
        })
        return future
    }

    onError (client, error) {
        if ((client.url in this.clients) && (this.clients[client.url].error)) {
            delete this.clients[client.url]
        }
    }

    onClose (client, error) {
        if (client.error) {
            // connection closed due to an error, do nothing
        } else {
            // server disconnected a working connection
            if (this.clients[client.url]) {
                delete this.clients[client.url]
            }
        }
    }

    async close () {
        const clients = Object.values (this.clients || {})
        for (let i = 0; i < clients.length; i++) {
            const client = clients[i]
            delete this.clients[client.url]
            await client.close ()
        }
    }

    signMessage (client, messageHash, message, params = {}) {
        throw new ccxt.NotSupported (this.id + ' signMessage () not implemented yet')
    }
}
<commit_msg>clean<commit_after>"use strict";

const ccxt = require ('ccxt')
    , WsClient = require ('./WsClient')
    , {
        OrderBook,
        IndexedOrderBook,
        CountedOrderBook,
    } = require ('./OrderBook')

module.exports = class Exchange extends ccxt.Exchange {

    orderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new OrderBook (snapshot, depth)
    }

    indexedOrderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new IndexedOrderBook (snapshot, depth)
    }

    countedOrderBook (snapshot = {}, depth = Number.MAX_SAFE_INTEGER) {
        return new CountedOrderBook (snapshot, depth)
    }

    client (url) {
        this.clients = this.clients || {}
        if (!this.clients[url]) {
            const onMessage = this.handleMessage.bind (this)
            const onError = this.onError.bind (this)
            const onClose = this.onClose.bind (this)
            // decide client type here: ws / signalr / socketio
            const options = this.extend (this.streaming, {
                'ping': this.ping ? this.ping.bind (this) : this.ping,
            })
            this.clients[url] = new WsClient (url, onMessage, onError, onClose, options)
        }
        return this.clients[url]
    }

    async after (future, method, ... args) {
        const result = await future
        // call it as an instance method on this
        return method.call (this, result, ... args)
    }

    async afterDropped (future, method, ... args) {
        // same as above, drop the result
        if (future) {
            await future
        }
        return method.call (this, ... args)
    }

    spawn (method, ... args) {
        (method.apply (this, args)).catch ((e) => {
            // todo: handle spawned errors
        })
    }

    watch (url, messageHash, message = undefined, subscribeHash = undefined, subscription = undefined) {
        //
        // Without comments the code of this method is short and easy:
        //
        //     const client = this.client (url)
        //     const backoffDelay = 0
        //     const future = client.future (messageHash)
        //     const connected = client.connect (backoffDelay)
        //     connected.then (() => {
        //         if (message && !client.subscriptions[subscribeHash]) {
        //             client.subscriptions[subscribeHash] = true
        //             message = this.signMessage (client, messageHash, message)
        //             client.send (message)
        //         }
        //     }).catch ((error) => {})
        //     return future
        //
        // The following is a longer version of this method with comments
        //
        const client = this.client (url)
        // todo: calculate the backoff using the clients cache
        const backoffDelay = 0
        //
        //  watchOrderBook ---- future ----+---------------+----→ user
        //                                 |               |
        //                                 ↓               ↑
        //                                 |               |
        //                              connect ......→ resolve
        //                                 |               |
        //                                 ↓               ↑
        //                                 |               |
        //                             subscribe -----→ receive
        //
        const future = client.future (messageHash)
        // we intentionally do not use await here to avoid unhandled exceptions
        // the policy is to make sure that 100% of promises are resolved or rejected
        // either with a call to client.resolve or client.reject with
        //  a proper exception class instance
        const connected = client.connect (backoffDelay)
        // the following is executed only if the catch-clause does not
        // catch any connection-level exceptions from the client
        // (connection established successfully)
        connected.then (() => {
            if (message && !client.subscriptions[subscribeHash]) {
                client.subscriptions[subscribeHash] = subscription || true
                // todo: decouple signing from subscriptions
                message = this.signMessage (client, messageHash, message)
                client.send (message)
            }
        }).catch ((error) => {
            // we do nothing and don't return a resolvable value from here
            // we leave it in a rejected state to avoid triggering the
            // then-clauses that will follow (if any)
            // removing this catch will raise UnhandledPromiseRejection in JS
            // upon connection failure
        })
        return future
    }

    onError (client, error) {
        if ((client.url in this.clients) && (this.clients[client.url].error)) {
            delete this.clients[client.url]
        }
    }

    onClose (client, error) {
        if (client.error) {
            // connection closed due to an error, do nothing
        } else {
            // server disconnected a working connection
            if (this.clients[client.url]) {
                delete this.clients[client.url]
            }
        }
    }

    async close () {
        const clients = Object.values (this.clients || {})
        for (let i = 0; i < clients.length; i++) {
            const client = clients[i]
            delete this.clients[client.url]
            await client.close ()
        }
    }

    signMessage (client, messageHash, message, params = {}) {
        throw new ccxt.NotSupported (this.id + ' signMessage () not implemented yet')
    }
}
<|endoftext|>


<commit_before>'use strict';

//Dice type arrays
var orangeDiceArray = [];
var blueDiceArray = [];
var grayDiceArray = [];
var maxRounds = 0;
var roundCount = 0;
var maxMauls = 5;
var photosToWin = 0;
var mauledFlag = false;

//Generic die constructor
function Die(maul, photo, footprint) {
  this.maul = maul;
  this.photo = photo;
  this.footprint = footprint;
  this.lastRoll = '';
}

//Method for generating random number
Die.prototype.randomNumber = function() {
  var baseNumber = Math.floor(Math.random() * (6) + 1);
  return baseNumber;
};

//Orange die constructor (hardest)
function Orange() {}
Orange.prototype = new Die(3,1,2);
//Blue die constructor (easiest)
function Blue() {}
Blue.prototype = new Die(1,3,2);
//Gray die constructor (medium)
function Gray() {}
Gray.prototype = new Die(2,2,2);

//Roll method for the orange dice
Orange.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2 || random === 3) {
    result = 'claw.png';
  } else if (random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};
//Roll method for the blue dice
Blue.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1) {
    result = 'claw.png';
  } else if (random === 2 || random === 3 || random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};
//Roll method for the gray dice
Gray.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2) {
    result = 'claw.png';
  } else if (random === 3 || random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};

//iffy to populate the dice arrays on page load
(function populateDieArrays(){
  for(var die = 0; die < 4; die++){
    var orange = new Orange();
    var blue = new Blue();
    var gray = new Gray();

    orangeDiceArray.push(orange);
    blueDiceArray.push(blue);
    grayDiceArray.push(gray);
  }
})();

//does the initial roll for a round.
function startRound(){
  for(var die = 0; die < 4; die++){
    orangeDiceArray[die].roll();
    blueDiceArray[die].roll();
    grayDiceArray[die].roll();
  }
  //call to render images to page
  renderDice();
  countMaul();
}

//renders the dice pool
function renderDice(){
  var orangeWrapper = document.getElementById('orange-dice');
  var grayWrapper = document.getElementById('gray-dice');
  var blueWrapper = document.getElementById('blue-dice');

  orangeWrapper.innerHTML = null;
  grayWrapper.innerHTML = null;
  blueWrapper.innerHTML = null;

  for(var die = 0; die < 4; die++){
    var orangeDie = document.createElement('img');
    var grayDie = document.createElement('img');
    var blueDie = document.createElement('img');

    orangeDie.classList.add(orangeDiceArray[die].lastRoll.split('.')[0]);
    grayDie.classList.add(grayDiceArray[die].lastRoll.split('.')[0]);
    blueDie.classList.add(blueDiceArray[die].lastRoll.split('.')[0]);

    orangeDie.src = '../images/' + orangeDiceArray[die].lastRoll;
    grayDie.src = '../images/' + grayDiceArray[die].lastRoll;
    blueDie.src = '../images/' + blueDiceArray[die].lastRoll;

    orangeWrapper.appendChild(orangeDie);
    grayWrapper.appendChild(grayDie);
    blueWrapper.appendChild(blueDie);
  }
}

function countMaul() {
  var clawCounter = 0;
  for(var die = 0; die < 4; die++) {
    if(orangeDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
    if(grayDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
    if(blueDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
  }
  if(clawCounter >= maxMauls) {
    var maulMessage = document.createElement('p');
    maulMessage.textContent = 'You\'ve been mauled by Sasquatch. Click End Turn to continue.'
    document.getElementById('Die-Title').appendChild(maulMessage);
    document.getElementById('Keep-Rolling').disabled = true;
    mauledFlag = true;
  }
}

//function that handles Keep-Rolling event
function handleKeepRolling() {
  for (var die = 0; die < 4; die++) {
    if (orangeDiceArray[die].lastRoll === 'tracks.jpg') {
      orangeDiceArray[die].roll();
    }
    if (grayDiceArray[die].lastRoll === 'tracks.jpg') {
      grayDiceArray[die].roll();
    }
    if (blueDiceArray[die].lastRoll === 'tracks.jpg') {
      blueDiceArray[die].roll();
    }
  }
  renderDice();
  countMaul();
}

// var maxRounds = 0;
// var roundCount = 0;
// var maxMauls = 5;
// var photosToWin = 0;
function handleDifficulty(event) {
  event.preventDefault();
  var difficultyForm = document.getElementsByClassName('difficulty-submission');
  for (var i = 0; i < difficultyForm.length; i++) {
    difficultyForm[i].disabled = true;
    // console.log(difficultyForm[i]);
  }
  var difficultyChosen = document.getElementById('select-difficulty').value;
  if (difficultyChosen === 'easy') {
    maxRounds = 3;
    photosToWin = 5;
  } else if (difficultyChosen === 'medium') {
    maxRounds = 3;
    photosToWin = 7;
  } else {
    maxRounds = 2;
    photosToWin = 7;
  }
  startRound();
  document.getElementById('End-Turn').disabled = false;
  document.getElementById('Keep-Rolling').disabled = false;
}

//adds event listener to submit button to choose difficulty
document.getElementById('difficulty').addEventListener('submit', handleDifficulty);

//adds event listener to Keep-Rolling button
document.getElementById('Keep-Rolling').addEventListener('click', handleKeepRolling);
<commit_msg>Adding a function to count cameras and an array to keep track of score, and adding the End Turn event handler/listener.<commit_after>'use strict';

//Dice type arrays
var orangeDiceArray = [];
var blueDiceArray = [];
var grayDiceArray = [];
var maxRounds = 0;
var roundCount = 0;
var maxMauls = 5;
var photosToWin = 0;
var mauledFlag = false;
var scoreArray = [];

//Generic die constructor
function Die(maul, photo, footprint) {
  this.maul = maul;
  this.photo = photo;
  this.footprint = footprint;
  this.lastRoll = '';
}

//Method for generating random number
Die.prototype.randomNumber = function() {
  var baseNumber = Math.floor(Math.random() * (6) + 1);
  return baseNumber;
};

//Orange die constructor (hardest)
function Orange() {}
Orange.prototype = new Die(3,1,2);
//Blue die constructor (easiest)
function Blue() {}
Blue.prototype = new Die(1,3,2);
//Gray die constructor (medium)
function Gray() {}
Gray.prototype = new Die(2,2,2);

//Roll method for the orange dice
Orange.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2 || random === 3) {
    result = 'claw.png';
  } else if (random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};
//Roll method for the blue dice
Blue.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1) {
    result = 'claw.png';
  } else if (random === 2 || random === 3 || random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};
//Roll method for the gray dice
Gray.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2) {
    result = 'claw.png';
  } else if (random === 3 || random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};

//iffy to populate the dice arrays on page load
(function populateDieArrays(){
  for(var die = 0; die < 4; die++){
    var orange = new Orange();
    var blue = new Blue();
    var gray = new Gray();

    orangeDiceArray.push(orange);
    blueDiceArray.push(blue);
    grayDiceArray.push(gray);
  }
})();

//does the initial roll for a round.
function startRound(){
  var dieTitleContainer = document.getElementById('Die-Title');
  for(var die = 0; die < 4; die++){
    orangeDiceArray[die].roll();
    blueDiceArray[die].roll();
    grayDiceArray[die].roll();
  }
  if(dieTitleContainer.children[1]){
    dieTitleContainer.removeChild(dieTitleContainer.children[1]);
    document.getElementById('Keep-Rolling').disabled = false;
  }
  //call to render images to page
  renderDice();
  countMaul();
}

//renders the dice pool
function renderDice(){
  var orangeWrapper = document.getElementById('orange-dice');
  var grayWrapper = document.getElementById('gray-dice');
  var blueWrapper = document.getElementById('blue-dice');

  orangeWrapper.innerHTML = null;
  grayWrapper.innerHTML = null;
  blueWrapper.innerHTML = null;

  for(var die = 0; die < 4; die++){
    var orangeDie = document.createElement('img');
    var grayDie = document.createElement('img');
    var blueDie = document.createElement('img');

    orangeDie.classList.add(orangeDiceArray[die].lastRoll.split('.')[0]);
    grayDie.classList.add(grayDiceArray[die].lastRoll.split('.')[0]);
    blueDie.classList.add(blueDiceArray[die].lastRoll.split('.')[0]);

    orangeDie.src = '../images/' + orangeDiceArray[die].lastRoll;
    grayDie.src = '../images/' + grayDiceArray[die].lastRoll;
    blueDie.src = '../images/' + blueDiceArray[die].lastRoll;

    orangeWrapper.appendChild(orangeDie);
    grayWrapper.appendChild(grayDie);
    blueWrapper.appendChild(blueDie);
  }
}

//function to determine if player has been mauled.
function countMaul() {
  var clawCounter = 0;
  for(var die = 0; die < 4; die++) {
    if(orangeDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
    if(grayDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
    if(blueDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
  }
  if(clawCounter >= maxMauls) {
    var maulMessage = document.createElement('p');
    maulMessage.textContent = 'You\'ve been mauled by Sasquatch. Click End Turn to continue.';
    document.getElementById('Die-Title').appendChild(maulMessage);
    document.getElementById('Keep-Rolling').disabled = true;
    mauledFlag = true;
  }
}

//function to count cameras
function countCamera(){
  var cameraCounter = 0;
  for(var die = 0; die < 4; die++){
    if(orangeDiceArray[die].lastRoll === 'camera.png'){
      cameraCounter++;
    }
    if(grayDiceArray[die].lastRoll === 'camera.png'){
      cameraCounter++;
    }
    if(blueDiceArray[die].lastRoll === 'camera.png'){
      cameraCounter++;
    }
  }
  scoreArray.push(cameraCounter);
}

//function that handles Keep-Rolling event
function handleKeepRolling() {
  for (var die = 0; die < 4; die++) {
    if (orangeDiceArray[die].lastRoll === 'tracks.jpg') {
      orangeDiceArray[die].roll();
    }
    if (grayDiceArray[die].lastRoll === 'tracks.jpg') {
      grayDiceArray[die].roll();
    }
    if (blueDiceArray[die].lastRoll === 'tracks.jpg') {
      blueDiceArray[die].roll();
    }
  }
  renderDice();
  countMaul();
}

//function that handles difficulty Selection and Game Start
function handleDifficulty(event) {
  event.preventDefault();
  var difficultyForm = document.getElementsByClassName('difficulty-submission');
  for (var i = 0; i < difficultyForm.length; i++) {
    difficultyForm[i].disabled = true;
    // console.log(difficultyForm[i]);
  }
  var difficultyChosen = document.getElementById('select-difficulty').value;
  if (difficultyChosen === 'easy') {
    maxRounds = 3;
    photosToWin = 5;
  } else if (difficultyChosen === 'medium') {
    maxRounds = 3;
    photosToWin = 7;
  } else {
    maxRounds = 2;
    photosToWin = 7;
  }
  startRound();
  document.getElementById('End-Turn').disabled = false;
  document.getElementById('Keep-Rolling').disabled = false;
}

//function that handles End-Turn
function handleEndTurn(){
  if(mauledFlag !== true){
    countCamera();
    //call the status board render function.
  } else {
    scoreArray.push(0);
    mauledFlag = false;
  }
  if(roundCount < maxRounds){
    startRound();
  }else{
    // Trigger End game logic
  }
}

//adds event listener to submit button to choose difficulty
document.getElementById('difficulty').addEventListener('submit', handleDifficulty);

//adds event listener to Keep-Rolling button
document.getElementById('Keep-Rolling').addEventListener('click', handleKeepRolling);

//adds event listener to End-Turn button
document.getElementById('End-Turn').addEventListener('click', handleEndTurn);
<|endoftext|>


<commit_before>import React from 'react'
import loadGif from './load.gif'
import loadSvg from './load.svg'

const smilSupport = () => {
    return !window ? true : window.document.createElementNS(
        'http://www.w3.org/2000/svg',
        'animate'
      ).toString().indexOf('SVG') >-1;
}

export default () => (

)
<commit_msg>Fix loader<commit_after>import React from 'react'
import loadGif from './load.gif'
import loadSvg from './load.svg'

const smilSupport = () => {
    return typeof(window) === 'undefined' ? true : window.document.createElementNS(
        'http://www.w3.org/2000/svg',
        'animate'
      ).toString().indexOf('SVG') >-1;
}

export default () => (

)
<|endoftext|>