<commit_before>'use strict';

var imageArray = ['imgs/dog.gif', 'imgs/cat.jpg', 'imgs/dog.gif', 'imgs/cat.jpg'];
var altImage = 'imgs/back.png';

function shuffleArray(array){
  for (var i = imageArray.length - 1; i > 0; i--){
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

function buildTable(){
  var iA = 0;
  var table = document.getElementById('game_table');
  var tRow;
  var tData;
  var image;
  for (var r = 0; r < 2; r++){
    tRow = document.createElement('tr');
    for (var c = 0; c < 2; c++){
      tData = document.createElement('td');
      image = document.createElement('img');
      image.setAttribute('faceup', imageArray[iA]);
      image.setAttribute('facedown', altImage);
      image.setAttribute('src', altImage);
      image.setAttribute('index', iA);
      iA += 1;
      tData.appendChild(image);
      tRow.appendChild(tData);
    }
    table.appendChild(tRow);
  }
}
shuffleArray(imageArray);
buildTable();

var countCorrect = 0;
var countTotal = 0;
var picSelector = document.getElementById('game_table');
var choiceArray = [];
var choiceIndexArray = [];
var correctPairs = [];
var firstChoice = null;
picSelector.addEventListener('click', clickHandler);

function clickHandler(event){
  var choiceIndex = event.target.getAttribute('index');
  var faceUp = event.target.getAttribute('faceup');
  var faceDown  = event.target.getAttribute('facedown');
  countTotal += 1;
  event.target.setAttribute('src', faceUp);
  choiceIndexArray.push(choiceIndex);

  if (choiceIndexArray[0] !== choiceIndexArray[1]) {
    choiceArray.push(faceUp);
    if (correctPairs.indexOf(choiceArray[0]) === -1) {
      if (!firstChoice){
        firstChoice = event.target;
      }
      if(choiceArray.length === 2){
        console.log(choiceArray);
        if(choiceArray[0] === choiceArray[1]){
          correctPairs.push(choiceArray[0]);
          choiceArray = [];
          choiceIndexArray = [];
          countCorrect += 1;
          firstChoice = null;
          if (countCorrect === 2) {
            alert('You got them all!');
            window.location = 'about-info.html';
          }
          console.log(true);
          console.log(choiceArray);
        } else{
          function flipCards() {
            event.target.setAttribute('src', faceDown);
            firstChoice.setAttribute('src', faceDown);
            firstChoice = null;
          };
          setTimeout(flipCards, 1000),
          choiceArray = [];
          choiceIndexArray = [];
          console.log(choiceArray);
        }
      }
    }else {
      choiceArray = [];
    }
  }else {
    setTimeout(flipCards, 0),
    alert('please click a separate card, start over');
    choiceArray = [];
    choiceIndexArray = [];
  }
  console.log(countCorrect + 'correct count');
  console.log(countTotal + 'total count');
}
<commit_msg>fixing some of the js and commenting things out<commit_after>'use strict';

var imageArray = ['imgs/alien.jpg', 'imgs/alien.jpg', 'imgs/ghostbuster.jpg', 'imgs/ghostbuster.jpg', 'imgs/darkknight.jpg', 'imgs/darkknight.jpg', 'imgs/rocky.jpg', 'imgs/rocky.jpg', 'imgs/starwars.jpg', 'imgs/starwars.jpg', 'imgs/bladerunner.jpg', 'imgs/bladerunner.jpg'];
var altImage = 'imgs/back.png';

function shuffleArray(array){
  for (var i = imageArray.length - 1; i > 0; i--){
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

function buildTable(){
  var iA = 0;
  var table = document.getElementById('game_table');
  var tRow;
  var tData;
  var image;
  for (var r = 0; r < 2; r++){
    tRow = document.createElement('tr');
    for (var c = 0; c < 6; c++){
      tData = document.createElement('td');
      image = document.createElement('img');
      image.setAttribute('faceup', imageArray[iA]);
      image.setAttribute('facedown', altImage);
      image.setAttribute('src', altImage);
      image.setAttribute('index', iA);
      iA += 1;
      tData.appendChild(image);
      tRow.appendChild(tData);
    }
    table.appendChild(tRow);
  }
}
shuffleArray(imageArray);
buildTable();
// counts correct pairs
var countCorrect = 0;
// counts total clicks
var countTotal = 0;
// selects game table
var picSelector = document.getElementById('game_table');
// creates array which clicked choices will be stored
var choiceArray = [];
// creates array to prevent the same image from being chosen
var choiceIndexArray = [];
// creates array to house correctly answered pairs
var correctPairs = [];
// allows for flipping of cards
var firstChoice = null;
// allows for disabling clicking during timeOut function
var selecting = false;
picSelector.addEventListener('click', clickHandler);

function clickHandler(event){
  //getting attributes the clicked image
  var choiceIndex = event.target.getAttribute('index');
  var faceUp = event.target.getAttribute('faceup');
  var faceDown  = event.target.getAttribute('facedown');
  //stops from selecting image after 2 wrong clicks
  if (selecting){
    return;
  };
  //prevents a null image
  if (faceUp === null){
    return;
  };
  countTotal += 1;
  //beginning flip of clicked photo
  event.target.setAttribute('src', faceUp);
  choiceIndexArray.push(choiceIndex);
  //function to flip cards and allow for setTimout
  function flipCards() {
    selecting = false;
    event.target.setAttribute('src', faceDown);
    firstChoice.setAttribute('src', faceDown);
    firstChoice = null;
    event.target.disable = false;
  };
  //function to stop selecting already correct Pairs
  console.log('click' + event.target);
  //if statements made to determine what will happen upon clicking of photo
  //comparing clicked images
  if (choiceIndexArray[0] !== choiceIndexArray[1]) {
    choiceArray.push(faceUp);
    //comparing if clicked choice is already matched in order to
    //prevent the same correct choices to be clicked again
    if (correctPairs.indexOf(choiceArray[0]) === -1) {
      //determining the first clicked choice and enabling it to switch
      //back if the second choice is wrong
      if (!firstChoice){
        firstChoice = event.target;
      }
      //script after two choices are made
      if(choiceArray.length === 2){
        console.log('choice.length' + choiceArray);
        //script if choices are MATCHING
        if(choiceArray[0] === choiceArray[1]){
          correctPairs.push(choiceArray[0]);
          choiceArray = [];
          choiceIndexArray = [];
          countCorrect += 1;
          firstChoice = null;
          //script after all correct choices are made
          if (countCorrect === 6) {
            function finished(){
              alert('You got them all!');
              window.location = 'about-info.html';
            }
            //timeout to allow seeing the final choice
            setTimeout(finished, 500);
          }
          console.log(true);
          console.log(choiceArray);
          //what will happen if choices are NOT MATCHING
        } else{
          selecting = true;
          setTimeout(flipCards, 1000);
          clickHandler.disable = true;
          choiceArray = [];
          choiceIndexArray = [];
          console.log(choiceArray);
        }
      }
    //else if choice has already been matched
    }else {
      alert('Please make another choice.');
      choiceArray = [];
    }
  //else if same card is picked twice
  }else {
    setTimeout(flipCards, 0),
    alert('please click a separate card, start over');
    choiceArray = [];
    choiceIndexArray = [];
  }
  console.log(countCorrect + 'correct count');
  console.log(countTotal + 'total count');
}
<|endoftext|>


<commit_before>document.addEventListener("DOMContentLoaded", function(){

	var gameOver = false;
	var turn = 0;

	var playerX = {
		name: "X",
		score: 0
	};
	var playerO = {
		name: "O",
		score: 0
	};

	var currentPlayer = playerX;

	var playerXScore = document.getElementById('X');
	var playerOScore = document.getElementById('O');

	var squares = document.getElementsByClassName('square')

	var newGameButton = document.getElementById('new-game-btn')
	newGameButton.addEventListener('click', newGame)

	var resetButton = document.getElementById('reset-btn')
	resetButton.addEventListener('click', resetScores)

	var assortedSquares = [[squares[0], squares[1], squares[2]], [squares[3], squares[4], squares[5]], [squares[6], squares[7], squares[8]]]

	for(var squareNumber = 0; squareNumber < squares.length; squareNumber ++){
		squares[squareNumber].addEventListener('click', makeMove);
	}

	function makeMove(){
		if (gameOver){
			return
		}
		if (checkSquare(this)){
			alert("that square has been taken already, pick another one!")
		}
		else{
			if (turn % 2 == 0){
				marker = "X";
				currentPlayer = playerX;
				playerMarker = makePlayerMarker(marker)
				this.appendChild(playerMarker);
				this.classList.add('taken');
				checkForWinner();
				turn++;
				makeComputerMove();
			}
		}
	}

	function makeComputerMove(){
		if(gameOver){
			return
		}
		var randomSquareIndex = Math.floor(Math.random() * 9)
		while (checkSquare(squares[randomSquareIndex])){
			randomSquareIndex =	Math.floor(Math.random() * 9)
		}
		marker = "O";
		currentPlayer = playerO;
		playerMarker = makePlayerMarker(marker)
		squares[randomSquareIndex].appendChild(playerMarker);
		squares[randomSquareIndex].classList.add('taken');
		checkForWinner();
		turn++;
	}

	function makePlayerMarker(markerValue){
		marker = document.createTextNode(markerValue)
		return marker
	}

	function checkSquare(square){
		if (square.classList.contains('taken')){
			return true
		}
		else{
			return false
		}
	}

	function checkRow(row){
		return checkThreeCells(row)
	}

	function checkColumn(columnNumber){
		var column = [];
		for(var rowNumber = 0; rowNumber < assortedSquares.length; rowNumber++){
			column.push(assortedSquares[rowNumber][columnNumber])
		}
		return checkThreeCells(column)
	}

	function checkLeftDiagonal(){

		var diagonal = [assortedSquares[0][0], assortedSquares[1][1], assortedSquares[2][2]]
		console.log(diagonal)
		return checkThreeCells(diagonal);
		// longer way of creating diagonal
		// var diagonal = [];
		// for (var cellIndex = 0; cellIndex < assortedSquares.length; cellIndex++){
		// 	diagonal.push(assortedSquares[cellIndex][cellIndex])
		// }
	}

	function checkRightDiagonal(){
		var diagonal = [assortedSquares[0][2], assortedSquares[1][1], assortedSquares[2][0]]
		return checkThreeCells(diagonal);
		// longer way of creating diagonal
		// for (var cellIndex = 0; cellIndex < assortedSquares.length; cellIndex++){
		// 	diagonal.push(assortedSquares[cellIndex][assortedSquares.length - 1 - cellIndex])
		// }
	}

	function checkThreeCells(arrayOfThreeCells){
		if(arrayOfThreeCells[0].classList.contains('taken') && arrayOfThreeCells[1].classList.contains('taken') && arrayOfThreeCells[2].classList.contains('taken')){
			if(arrayOfThreeCells[0].innerText == arrayOfThreeCells[1].innerText && arrayOfThreeCells[1].innerText == arrayOfThreeCells[2].innerText){
				return true
			}
		}
		else {
			return false
		}
	}

	function checkForWinner(){
		if(checkLeftDiagonal() || checkRightDiagonal()){
			alert("we have a winner");
			updateWins();
			gameOver = true;
		}
		for (var rowColIndex = 0; rowColIndex < assortedSquares.length; rowColIndex++){
			if(checkRow(assortedSquares[rowColIndex]) || checkColumn(rowColIndex)){
				alert("we have a winner")
				updateWins();
				gameOver = true;
			}
		}
	}

	function newGame(){
		for(var cellIndex = 0; cellIndex < squares.length; cellIndex++){
			squares[cellIndex].innerText = '';
			squares[cellIndex].classList.remove('taken');
		}
		gameOver = false;
		turn = 0;
	}

	function updateWins(){
		currentPlayer.score++;
		playerXScore.innerText = playerX.score;
		playerOScore.innerText = playerO.score;
	}

	function resetScores(){
		playerX.score = 0;
		playerO.score = 0;
		playerXScore.innerText = playerX.score;
		playerOScore.innerText = playerO.score;
		newGame();
	}

});<commit_msg>fix bug, can now tie with computer player and can prevent moves from being made after tie is made<commit_after>document.addEventListener("DOMContentLoaded", function(){

	var gameOver = false;
	var turn = 0;

	var playerX = {
		name: "X",
		score: 0
	};
	var playerO = {
		name: "O",
		score: 0
	};

	var currentPlayer = playerX;

	var playerXScore = document.getElementById('X');
	var playerOScore = document.getElementById('O');

	var squares = document.getElementsByClassName('square')

	var newGameButton = document.getElementById('new-game-btn')
	newGameButton.addEventListener('click', newGame)

	var resetButton = document.getElementById('reset-btn')
	resetButton.addEventListener('click', resetScores)

	var assortedSquares = [[squares[0], squares[1], squares[2]], [squares[3], squares[4], squares[5]], [squares[6], squares[7], squares[8]]]

	for(var squareNumber = 0; squareNumber < squares.length; squareNumber ++){
		squares[squareNumber].addEventListener('click', makeMove);
	}

	function makeMove(){
		if (gameOver){
			return
		}
		if (checkSquare(this)){
			alert("that square has been taken already, pick another one!")
		}
		else{
			if (turn % 2 == 0){
				marker = "X";
				currentPlayer = playerX;
				playerMarker = makePlayerMarker(marker)
				this.appendChild(playerMarker);
				this.classList.add('taken');
				checkForWinner();
				turn++;
				takenSquares = document.getElementsByClassName('square taken')
				if(takenSquares.length !== 9){
				makeComputerMove();
				}
				else{
					gameOver = true;
				}
			}
		}
	}

	function makeComputerMove(){
		if(gameOver){
			return
		}
		var randomSquareIndex = Math.floor(Math.random() * 9)
		while (checkSquare(squares[randomSquareIndex])){
			randomSquareIndex =	Math.floor(Math.random() * 9)
		}
		marker = "O";
		currentPlayer = playerO;
		playerMarker = makePlayerMarker(marker)
		squares[randomSquareIndex].appendChild(playerMarker);
		squares[randomSquareIndex].classList.add('taken');
		checkForWinner();
		turn++;
	}

	function makePlayerMarker(markerValue){
		marker = document.createTextNode(markerValue)
		return marker
	}

	function checkSquare(square){
		if (square.classList.contains('taken')){
			return true
		}
		else{
			return false
		}
	}

	function checkRow(row){
		return checkThreeCells(row)
	}

	function checkColumn(columnNumber){
		var column = [];
		for(var rowNumber = 0; rowNumber < assortedSquares.length; rowNumber++){
			column.push(assortedSquares[rowNumber][columnNumber])
		}
		return checkThreeCells(column)
	}

	function checkLeftDiagonal(){

		var diagonal = [assortedSquares[0][0], assortedSquares[1][1], assortedSquares[2][2]]
		console.log(diagonal)
		return checkThreeCells(diagonal);
		// longer way of creating diagonal
		// var diagonal = [];
		// for (var cellIndex = 0; cellIndex < assortedSquares.length; cellIndex++){
		// 	diagonal.push(assortedSquares[cellIndex][cellIndex])
		// }
	}

	function checkRightDiagonal(){
		var diagonal = [assortedSquares[0][2], assortedSquares[1][1], assortedSquares[2][0]]
		return checkThreeCells(diagonal);
		// longer way of creating diagonal
		// for (var cellIndex = 0; cellIndex < assortedSquares.length; cellIndex++){
		// 	diagonal.push(assortedSquares[cellIndex][assortedSquares.length - 1 - cellIndex])
		// }
	}

	function checkThreeCells(arrayOfThreeCells){
		if(arrayOfThreeCells[0].classList.contains('taken') && arrayOfThreeCells[1].classList.contains('taken') && arrayOfThreeCells[2].classList.contains('taken')){
			if(arrayOfThreeCells[0].innerText == arrayOfThreeCells[1].innerText && arrayOfThreeCells[1].innerText == arrayOfThreeCells[2].innerText){
				return true
			}
		}
		else {
			return false
		}
	}

	function checkForWinner(){
		if(checkLeftDiagonal() || checkRightDiagonal()){
			alert("we have a winner");
			updateWins();
			gameOver = true;
		}
		for (var rowColIndex = 0; rowColIndex < assortedSquares.length; rowColIndex++){
			if(checkRow(assortedSquares[rowColIndex]) || checkColumn(rowColIndex)){
				alert("we have a winner")
				updateWins();
				gameOver = true;
				return
			}
		}
	}

	function newGame(){
		for(var cellIndex = 0; cellIndex < squares.length; cellIndex++){
			squares[cellIndex].innerText = '';
			squares[cellIndex].classList.remove('taken');
		}
		gameOver = false;
		turn = 0;
	}

	function updateWins(){
		currentPlayer.score++;
		playerXScore.innerText = playerX.score;
		playerOScore.innerText = playerO.score;
	}

	function resetScores(){
		playerX.score = 0;
		playerO.score = 0;
		playerXScore.innerText = playerX.score;
		playerOScore.innerText = playerO.score;
		newGame();
	}

});<|endoftext|>


<commit_before>/**
 * Created by Ante Dante on 5/27/2016.
 */
var Physics = require('./node_modules/physicsjs/dist/physicsjs-full.min');

var viewWidth = 1;
var viewHeight = 1;
var cornerRadius = 0.166;
var playerRadius = 0.125;

console.log('game start');

var world = Physics();

module.exports = function(io) {
    Physics(function( world ){

        // set up the world
        var framerate = 16;

        var cornerRadius = 0.1;
        var topLeftCorner = Physics.body('circle', {
            x: 0,
            y: 0,
            radius: cornerRadius,
            treatment: 'static'
        });

        var topRightCorner = Physics.body('circle', {
            x: 1,
            y: 0,
            radius: cornerRadius,
            treatment: 'static'
        });

        var bottomLeftCorner = Physics.body('circle', {
            x: 0,
            y: 1,
            radius: cornerRadius,
            treatment: 'static'
        });

        var bottomRightCorner = Physics.body('circle', {
            x: 1,
            y: 1,
            radius: cornerRadius,
            treatment: 'static'
        });

        world.add(topLeftCorner);
        world.add(topRightCorner);
        world.add(bottomLeftCorner);
        world.add(bottomRightCorner);

        var availablePositions = ['bottom', 'left', 'top', 'right'];
        var playerCount = 0;
        var playerBody = {};
        var players = {};

        playerBody['top'] = Physics.body('circle', {
            x: 0.5,
            y: -0.05,
            radius: playerRadius,
            treatment: 'static'
        });

        playerBody['left'] = Physics.body('circle', {
            x: -0.05,
            y: 0.5,
            radius: playerRadius,
            treatment: 'static'
        });

        playerBody['right'] = Physics.body('circle', {
            x: 1.05,
            y: 0.5,
            radius: playerRadius,
            treatment: 'static'
        });

        playerBody['bottom'] = Physics.body('circle', {
            x: 0.5,
            y: 1.05,
            radius: playerRadius,
            treatment: 'static'
        });

        world.add(playerBody['top']);
        world.add(playerBody['left']);
        world.add(playerBody['right']);
        world.add(playerBody['bottom']);

        // balls constants
        var maxBallsCount = 4;
        var currentBallsCount = 0;
        var ballCreationProbability = 0.1;
        var ballRadius = 0.042;
        var minimumSpeed = 0.00169;
        var ballMass = 1;
        var ball_id = 0;
        var balls = [];
        var reset = false;
        var resetDelay = 200;

        function randomInt (low, high) {
            return Math.floor(Math.random() * (high - low) + low);
        }

        function random (low, high) {
            return Math.random() * (high - low) + low;
        }

        // scores
        var startScore = 0;
        var scoreMax = 7;
        var scores = {'top' : startScore, 'bottom' : startScore, 'left' : startScore, 'right' : startScore};

        var topBot = 'Red Bot';
        var bottomBot = 'Green Bot';
        var leftBot = 'Blue Bot';
        var rightBot = 'Purple Bot';
        var playerPositions = {'bottom' : bottomBot, 'left' : leftBot, 'top' : topBot, 'right' : rightBot};

        // behaviour
        world.add( Physics.behavior('body-impulse-response') );
        world.add( Physics.behavior('body-collision-detection') );
        world.add( Physics.behavior('sweep-prune') );

        // world state
        world.on('step', function(){
            // send world state
            io.sockets.emit('world state', {

                balls : balls.map(function (ball) {
                    return ball.state.pos._;
                }),
                bottomPlayer: playerBody['bottom'].state.pos._,
                topPlayer: playerBody['top'].state.pos._,
                leftPlayer: playerBody['left'].state.pos._,
                rightPlayer: playerBody['right'].state.pos._,
                scores: scores,
                playerNames : playerPositions});

            // balls logic
            // add new balls
            if(reset) {
                resetDelay--;
                if(resetDelay == 0) {
                    reset = false;
                    resetDelay = 200;
                }

            } else if(currentBallsCount < maxBallsCount) {
                if(Math.random() <= ballCreationProbability) {
                    var newBallPosition = randomInt(0, 3);
                    var ballX, ballY;
                    var ballSpeedX, ballSpeedY;
                    switch(newBallPosition) {
                        case 0:
                            // top left
                            ballX = cornerRadius + ballRadius;
                            ballY = cornerRadius + ballRadius;
                            ballSpeedX = 0.0011;
                            ballSpeedY = 0.0016;
                            break;
                        case 1:
                            // top right
                            ballX = 1 - cornerRadius - ballRadius;
                            ballY = cornerRadius + ballRadius;
                            ballSpeedX = -0.0018;
                            ballSpeedY = 0.0019;
                            break;
                        case 2:
                            // bottom right
                            ballX = 1 - cornerRadius - ballRadius;
                            ballY = 1 - cornerRadius - ballRadius;
                            ballSpeedX = -0.0013;
                            ballSpeedY = -0.0019;
                            break;
                        case 3:
                            // bottom left
                            ballX = cornerRadius - ballRadius;
                            ballY = 1 - cornerRadius - ballRadius;
                            ballSpeedX = 0.0014;
                            ballSpeedY = -0.0012;
                            break;
                    }

                    balls.push(Physics.body('circle', {
                        x: ballX,
                        y: ballY,
                        radius: ballRadius,
                        vx: ballSpeedX,
                        vy: ballSpeedY,
                        mass: ballMass,
                        id: ball_id
                    }));

                    world.add(balls[balls.length-1]);
                    ball_id++;
                    currentBallsCount++;
                }
            }

            // Slow issue
            // for(var i = 0; i < balls.length; i++) {
            //     // if(Math.sqrt(Math.pow(balls[i].state.vel.x,2) + Math.pow(balls[i].state.vel.y,2)) < minimumSpeed) {
            //     //     balls[i].state.vel.x += Math.sign(balls[i].state.vel.x) * 0.2 * balls[i].state.vel.x;
            //     //     balls[i].state.vel.y += Math.sign(balls[i].state.vel.y) * 0.2 * balls[i].state.vel.y;
            //     //     console.log('SLOW');
            //     //
            //     // }
            //     console.log('i: ' +  balls[i].state.vel.x + ' ' + balls[i].state.vel.y);
            // }

            // update scores
            for(var i = 0; i < balls.length; i++) {
                if(balls[i].state.pos.x <= 0) {
                    scores['left']++;
                    removeBall(i);
                } else if(balls[i].state.pos.x >= 1) {
                    scores['right']++;
                    removeBall(i);
                } else if(balls[i].state.pos.y <= 0) {
                    scores['top']++;
                    removeBall(i);
                } else if(balls[i].state.pos.y >= 1) {
                    scores['bottom']++;
                    removeBall(i);
                }
            }

            for(var score in scores) {
                if(scores[score] >= scoreMax) {
                    scores['top'] = startScore;
                    scores['right'] = startScore;
                    scores['bottom'] = startScore;
                    scores['left'] = startScore;
                    for(var i = 0; i < balls.length; i++) {
                        removeBall(i);
                    }
                    reset = true;
                    break;
                }
            }
        });

        function removeBall(index) {
            world.remove(balls[index]);
            balls.splice(index,1);
            currentBallsCount--;
        }

        // player interaction
        io.on('connection', function (socket) {

            var playerUsername;
            // new player
            socket.on('newPlayer', function (data) {
                if(playerCount < 4) {
                    playerUsername = data['username'];
                    players[playerUsername] = availablePositions[0];
                    playerPositions[availablePositions[0]] = playerUsername;
                    availablePositions.shift();
                    console.log('New Player: ' + playerUsername + ' || position: ' + players[playerUsername]);
                    socket.emit('positionAssigned', {position : players[playerUsername]});
                    playerCount++;
                } else {
                    console.log('Game is full.')
                }
            });
            // player input
            socket.on('movement', function(data) {
                var dx = 0.015;
                var position = players[data['username']];
                var move = data['move'];
					 var newPosition = [
								playerBody[position].state.pos.x,
								playerBody[position].state.pos.y
                ];
                var changedPosition = 0;
                switch (position) {
                    case 'top':
                        if(move == 'left')
                            newPosition[0] += dx;
                        if(move == 'right')
                            newPosition[0] -= dx;
                        changedPosition = 0;
                        break;
                    case 'left':
                        if(move == 'left')
                            newPosition[1] -= dx;
                        if(move == 'right')
                            newPosition[1] += dx;
                        changedPosition = 1;
                        break;
                    case 'right':
                        if(move == 'left')
                            newPosition[1] += dx;
                        if(move == 'right')
                            newPosition[1] -= dx;
                        changedPosition = 1;
                        break;
                    case 'bottom':
                        if(move == 'left')
                            newPosition[0] -= dx;
                            playerBody[position].state.pos.x -= dx;
                        if(move == 'right')
                            newPosition[0] += dx;
                            playerBody[position].state.pos.x += dx;
                        changedPosition = 0;
                        break;
                }
                newPosition[0] = Math.min(1 - cornerRadius - playerRadius, Math.max(cornerRadius + playerRadius, newPosition[0]));
                newPosition[1] = Math.min(1 - cornerRadius - playerRadius, Math.max(cornerRadius + playerRadius, newPosition[1]));

                if(changedPosition == 0) {
                    playerBody[position].state.pos.x = newPosition[0];
                } else {
                    playerBody[position].state.pos.y = newPosition[1];
                }

            });

            // disconnect logic
            socket.on('disconnect', function () {
                playerCount--;
                switch(players[playerUsername]) {
                    case 'bottom':
                        playerPositions['bottom'] = bottomBot;
                        availablePositions.unshift('bottom');
                        break;
                    case 'left':
                        playerPositions['left'] = leftBot;
                        availablePositions.unshift('left');
                        break;
                    case 'top':
                        playerPositions['top'] = topBot;
                        availablePositions.unshift('top');
                        break;
                    case 'right':
                        playerPositions['right'] = rightBot;
                        availablePositions.unshift('right');
                        break;
                }
            });
        });

        setInterval(function() {
            world.step(world.time)
        }, framerate);

    });

};

<commit_msg>Remove friction from balls<commit_after>/**
 * Created by Ante Dante on 5/27/2016.
 */
var Physics = require('./node_modules/physicsjs/dist/physicsjs-full.min');

var viewWidth = 1;
var viewHeight = 1;
var cornerRadius = 0.166;
var playerRadius = 0.125;

console.log('game start');

var world = Physics();

module.exports = function(io) {
    Physics(function( world ){

        // set up the world
        var framerate = 16;

        var cornerRadius = 0.1;
        var topLeftCorner = Physics.body('circle', {
            x: 0,
            y: 0,
            radius: cornerRadius,
            treatment: 'static'
        });

        var topRightCorner = Physics.body('circle', {
            x: 1,
            y: 0,
            radius: cornerRadius,
            treatment: 'static'
        });

        var bottomLeftCorner = Physics.body('circle', {
            x: 0,
            y: 1,
            radius: cornerRadius,
            treatment: 'static'
        });

        var bottomRightCorner = Physics.body('circle', {
            x: 1,
            y: 1,
            radius: cornerRadius,
            treatment: 'static'
        });

        world.add(topLeftCorner);
        world.add(topRightCorner);
        world.add(bottomLeftCorner);
        world.add(bottomRightCorner);

        var availablePositions = ['bottom', 'left', 'top', 'right'];
        var playerCount = 0;
        var playerBody = {};
        var players = {};

        playerBody['top'] = Physics.body('circle', {
            x: 0.5,
            y: -0.05,
            radius: playerRadius,
            treatment: 'static'
        });

        playerBody['left'] = Physics.body('circle', {
            x: -0.05,
            y: 0.5,
            radius: playerRadius,
            treatment: 'static'
        });

        playerBody['right'] = Physics.body('circle', {
            x: 1.05,
            y: 0.5,
            radius: playerRadius,
            treatment: 'static'
        });

        playerBody['bottom'] = Physics.body('circle', {
            x: 0.5,
            y: 1.05,
            radius: playerRadius,
            treatment: 'static'
        });

        world.add(playerBody['top']);
        world.add(playerBody['left']);
        world.add(playerBody['right']);
        world.add(playerBody['bottom']);

        // balls constants
        var maxBallsCount = 4;
        var currentBallsCount = 0;
        var ballCreationProbability = 0.1;
        var ballRadius = 0.042;
        var minimumSpeed = 0.00169;
        var ballMass = 1;
        var ball_id = 0;
        var balls = [];
        var reset = false;
        var resetDelay = 200;

        function randomInt (low, high) {
            return Math.floor(Math.random() * (high - low) + low);
        }

        function random (low, high) {
            return Math.random() * (high - low) + low;
        }

        // scores
        var startScore = 0;
        var scoreMax = 7;
        var scores = {'top' : startScore, 'bottom' : startScore, 'left' : startScore, 'right' : startScore};

        var topBot = 'Red Bot';
        var bottomBot = 'Green Bot';
        var leftBot = 'Blue Bot';
        var rightBot = 'Purple Bot';
        var playerPositions = {'bottom' : bottomBot, 'left' : leftBot, 'top' : topBot, 'right' : rightBot};

        // behaviour
        world.add( Physics.behavior('body-impulse-response') );
        world.add( Physics.behavior('body-collision-detection') );
        world.add( Physics.behavior('sweep-prune') );

        // world state
        world.on('step', function(){
            // send world state
            io.sockets.emit('world state', {

                balls : balls.map(function (ball) {
                    return ball.state.pos._;
                }),
                bottomPlayer: playerBody['bottom'].state.pos._,
                topPlayer: playerBody['top'].state.pos._,
                leftPlayer: playerBody['left'].state.pos._,
                rightPlayer: playerBody['right'].state.pos._,
                scores: scores,
                playerNames : playerPositions});

            // balls logic
            // add new balls
            if(reset) {
                resetDelay--;
                if(resetDelay == 0) {
                    reset = false;
                    resetDelay = 200;
                }

            } else if(currentBallsCount < maxBallsCount) {
                if(Math.random() <= ballCreationProbability) {
                    var newBallPosition = randomInt(0, 3);
                    var ballX, ballY;
                    var ballSpeedX, ballSpeedY;
                    switch(newBallPosition) {
                        case 0:
                            // top left
                            ballX = cornerRadius + ballRadius;
                            ballY = cornerRadius + ballRadius;
                            ballSpeedX = 0.0011;
                            ballSpeedY = 0.0016;
                            break;
                        case 1:
                            // top right
                            ballX = 1 - cornerRadius - ballRadius;
                            ballY = cornerRadius + ballRadius;
                            ballSpeedX = -0.0018;
                            ballSpeedY = 0.0019;
                            break;
                        case 2:
                            // bottom right
                            ballX = 1 - cornerRadius - ballRadius;
                            ballY = 1 - cornerRadius - ballRadius;
                            ballSpeedX = -0.0013;
                            ballSpeedY = -0.0019;
                            break;
                        case 3:
                            // bottom left
                            ballX = cornerRadius - ballRadius;
                            ballY = 1 - cornerRadius - ballRadius;
                            ballSpeedX = 0.0014;
                            ballSpeedY = -0.0012;
                            break;
                    }

                    balls.push(Physics.body('circle', {
                        x: ballX,
                        y: ballY,
                        radius: ballRadius,
                        vx: ballSpeedX,
                        vy: ballSpeedY,
                        mass: ballMass,
                        id: ball_id,
                        coef: 0
                    }));

                    world.add(balls[balls.length-1]);
                    ball_id++;
                    currentBallsCount++;
                }
            }

            // Slow issue
            // for(var i = 0; i < balls.length; i++) {
            //     // if(Math.sqrt(Math.pow(balls[i].state.vel.x,2) + Math.pow(balls[i].state.vel.y,2)) < minimumSpeed) {
            //     //     balls[i].state.vel.x += Math.sign(balls[i].state.vel.x) * 0.2 * balls[i].state.vel.x;
            //     //     balls[i].state.vel.y += Math.sign(balls[i].state.vel.y) * 0.2 * balls[i].state.vel.y;
            //     //     console.log('SLOW');
            //     //
            //     // }
            //     console.log('i: ' +  balls[i].state.vel.x + ' ' + balls[i].state.vel.y);
            // }

            // update scores
            for(var i = 0; i < balls.length; i++) {
                if(balls[i].state.pos.x <= 0) {
                    scores['left']++;
                    removeBall(i);
                } else if(balls[i].state.pos.x >= 1) {
                    scores['right']++;
                    removeBall(i);
                } else if(balls[i].state.pos.y <= 0) {
                    scores['top']++;
                    removeBall(i);
                } else if(balls[i].state.pos.y >= 1) {
                    scores['bottom']++;
                    removeBall(i);
                }
            }

            for(var score in scores) {
                if(scores[score] >= scoreMax) {
                    scores['top'] = startScore;
                    scores['right'] = startScore;
                    scores['bottom'] = startScore;
                    scores['left'] = startScore;
                    for(var i = 0; i < balls.length; i++) {
                        removeBall(i);
                    }
                    reset = true;
                    break;
                }
            }
        });

        function removeBall(index) {
            world.remove(balls[index]);
            balls.splice(index,1);
            currentBallsCount--;
        }

        // player interaction
        io.on('connection', function (socket) {

            var playerUsername;
            // new player
            socket.on('newPlayer', function (data) {
                if(playerCount < 4) {
                    playerUsername = data['username'];
                    players[playerUsername] = availablePositions[0];
                    playerPositions[availablePositions[0]] = playerUsername;
                    availablePositions.shift();
                    console.log('New Player: ' + playerUsername + ' || position: ' + players[playerUsername]);
                    socket.emit('positionAssigned', {position : players[playerUsername]});
                    playerCount++;
                } else {
                    console.log('Game is full.')
                }
            });
            // player input
            socket.on('movement', function(data) {
                var dx = 0.015;
                var position = players[data['username']];
                var move = data['move'];
					 var newPosition = [
								playerBody[position].state.pos.x,
								playerBody[position].state.pos.y
                ];
                var changedPosition = 0;
                switch (position) {
                    case 'top':
                        if(move == 'left')
                            newPosition[0] += dx;
                        if(move == 'right')
                            newPosition[0] -= dx;
                        changedPosition = 0;
                        break;
                    case 'left':
                        if(move == 'left')
                            newPosition[1] -= dx;
                        if(move == 'right')
                            newPosition[1] += dx;
                        changedPosition = 1;
                        break;
                    case 'right':
                        if(move == 'left')
                            newPosition[1] += dx;
                        if(move == 'right')
                            newPosition[1] -= dx;
                        changedPosition = 1;
                        break;
                    case 'bottom':
                        if(move == 'left')
                            newPosition[0] -= dx;
                            playerBody[position].state.pos.x -= dx;
                        if(move == 'right')
                            newPosition[0] += dx;
                            playerBody[position].state.pos.x += dx;
                        changedPosition = 0;
                        break;
                }
                newPosition[0] = Math.min(1 - cornerRadius - playerRadius, Math.max(cornerRadius + playerRadius, newPosition[0]));
                newPosition[1] = Math.min(1 - cornerRadius - playerRadius, Math.max(cornerRadius + playerRadius, newPosition[1]));

                if(changedPosition == 0) {
                    playerBody[position].state.pos.x = newPosition[0];
                } else {
                    playerBody[position].state.pos.y = newPosition[1];
                }

            });

            // disconnect logic
            socket.on('disconnect', function () {
                playerCount--;
                switch(players[playerUsername]) {
                    case 'bottom':
                        playerPositions['bottom'] = bottomBot;
                        availablePositions.unshift('bottom');
                        break;
                    case 'left':
                        playerPositions['left'] = leftBot;
                        availablePositions.unshift('left');
                        break;
                    case 'top':
                        playerPositions['top'] = topBot;
                        availablePositions.unshift('top');
                        break;
                    case 'right':
                        playerPositions['right'] = rightBot;
                        availablePositions.unshift('right');
                        break;
                }
            });
        });

        setInterval(function() {
            world.step(world.time)
        }, framerate);

    });

};

<|endoftext|>


<commit_before>/*
This is a game by:
Markus "TiByte" Becker   - Lead Developer
Lucas "LFalch"           - Programmer
Aileen                   - Graphic Designer
Kilian "Malloth Rha"     - Musician
Micha                    - Junior Programmer
Using Libraries: Pixi.js and Howler.js
date: 16.04.2016 for LD35
theme: Shapeshift
*/

/*

STRING OF EVENTS:
1. Intro Comic (3 Pictures)
    - socks come to life when unattended
2. Under the bed
    2.1. game
        - avoid hands
    2.2. more story
        - grey sock tells hero to fight sewer monster
3. Sewerfall
    3.1. game
        - falling in the sewer
        - avoid dirt
    3.2. reward (grow arms)
        - if not too dirty
4. Snake game
    4.1. game
        - eat fluff
    4.2. reward (grow bigger)
        - if player ate more than 20 fluff in 30 sec.
5. Plumbing game
    5.1. game
        - turn tiles to connect pipes
    5.2. reward (grow hair)
        - did it in 15 seconds
### Optional ###
0. Platforming game
    0.1. game
    0.2. reward (grow wings)
################
6. Doodle Jump
    6.1. game
        - collect something to gain height
    6.2. more story
        - if won grabbed by sock-hand
        - else falling = losing health
7. Boss fight
    - attack in turns
*/

// Cheat Sheet: https://github.com/mtib/ludum34/blob/master/game.js

// Canvas Size
const WIDTH = 1280;
const HEIGHT = 720;

// Current version
const version = "0.01d"

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: true, transparent: false, resolution: 1});
renderer.backgroundColor = 0x6ec2cb;
document.getElementById("gamediv").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();

// Config goes here:
const fontConfig = {font: "30px 'Arial'", fill: "#000000", align: "left"};
const debugConfig = {font: "20px 'Fira Code',monospace,sans-serif", fill: "#FF0000", align: "left"};
const pointsConfig = {font: "20px monospace", fill: "#FF00FF", align: "right"};
const infoConfig = {font: "60px Arial", fill: "#000000", align: "center"};

const relcenter = {x:0.5,y:0.5};
const enterKey = keyboard(13);

const leftArrow = keyboard(37);
const upArrow = keyboard(38);
const rightArrow = keyboard(39);
const downArrow = keyboard(40);

const aKey = keyboard(65);
const wKey = keyboard(87);
const dKey = keyboard(68);
const sKey = keyboard(83);

const s000bed1 = "./scenes/000/bed.pic1.jpg";
const s000bed2 = "./scenes/000/bed.pic2.jpg";
const s000bed3 = "./scenes/000/bed.pic3.jpg";
const s001bg = "./scenes/001/background.jpg"; // background for game #1
const ssock = "./scenes/001/sock.png"; // normal sock, for use in all? scenes
const s001armo = "./scenes/001/arm.open.png"; // o = open
const s001armg = "./scenes/001/arm.sock.png"; // g = grabbed

const sceneMusic = [ // for the cool kids!
    new Howl({
        src: ['scenes/000/SockventureIntro.ogg'],
        loop: true,
        volume: 0.4,
    }),
    new Howl({
        src: ['scenes/001/SockventureHand.ogg'],
        loop: true,
        volume: 0.4,
    })
];

function Game1Sock() {
    self = this;
    size = 128 // Pixel
    speed = 3 // Pixel / Frame
    this.sprite = new PIXI.Sprite.fromImage(ssock);
    this.sprite.anchor = relcenter;
    this.sprite.width = size;
    this.sprite.height = size;
    this.sprite.position = {x: WIDTH*0.5, y: HEIGHT*0.5};
    this.die = function() {
        cMiddle.removeChild(this.sprite);
    }
    this.move = function() {
        delta = {x:0, y:0};
        if ((rightArrow.isDown || dKey.isDown) && this.sprite.position.x < WIDTH - 100) {
            delta.x += speed;
        }
        if ((leftArrow.isDown || aKey.isDown) && this.sprite.position.x > 100) {
            delta.x -= speed;
        }
        if ((upArrow.isDown || wKey.isDown) && this.sprite.position.y > 230) {
            delta.y -= speed;
        }
        if ((downArrow.isDown || sKey.isDown) && this.sprite.position.y < HEIGHT - 100) {
            delta.y += speed;
        }
        magsqr = Math.sqrt(Math.abs(delta.x) + Math.abs(delta.y))
        if (magsqr == 0) {
            return;
        }
        if (delta.x > 0 && this.sprite.scale.x > 0) {
            this.sprite.scale.x *= -1;
        } else if (delta.x < 0 && this.sprite.scale.x < 0) {
            this.sprite.scale.x *= -1;
        }
        delta.x /= magsqr;
        delta.y /= magsqr;
        this.sprite.position.x += delta.x;
        this.sprite.position.y += delta.y;
    }
    cMiddle.addChild(this.sprite);
}

function State() {
    self = this;
    this.debugText = new PIXI.Text("Version: "+version+"\n<Debug Information>\nState: ",debugConfig);
    this.debugText.position = {x:5,y:5};
    this.score = new PIXI.Text("0", pointsConfig);
    this.score.position = {x: WIDTH - 5, y: 5};
    this.score.anchor = {x: 1, y:0};
    this.debugStateText = new PIXI.Text("0", debugConfig);
    this.debugStateText.position = {x:89,y:45};

    this.infotext = new PIXI.Text("", infoConfig); // eg. "press xxx to skip"

    this.doc = {}; // DestroyOnChange

    cGui.addChild(this.debugText);
    cGui.addChild(this.debugStateText);
    this.number = 0;
    sceneMusic[0].play();
    this.run = function(){
        console.log("default state");
    }

    this.nextState = function(){
        for (var sprite in this.doc) {
            if (this.doc.hasOwnProperty(sprite)) {
                if (this.doc[sprite].die) {
                    this.doc[sprite].die();
                } else {
                    cGui.removeChild(this.doc[sprite])
                    cMiddle.removeChild(this.doc[sprite])
                    cFront.removeChild(this.doc[sprite])
                    cBack.removeChild(this.doc[sprite]);
                }
            }
            delete this.doc[sprite];
        }
        enterKey.press = undefined;

        sceneMusic[this.number++].stop();
        sceneMusic[this.number].play();

        this.switched = true;
        this.debugStateText.text = this.number;
        this.run = this.funcarray[this.number];
    }
    this.introfunc = function(){
        if (this.switched){
            this.infotext.text = "Press <Enter> to skip"
            this.substate = 1;
            this.doc["pic"] = 1;
            this.doc["s000bed1"] = PIXI.Sprite.fromImage(s000bed1);
            this.doc["s000bed2"] = PIXI.Sprite.fromImage(s000bed2);
            this.doc["s000bed3"] = PIXI.Sprite.fromImage(s000bed3);

            this.doc["s000bed1"].width = WIDTH;
            this.doc["s000bed1"].height = HEIGHT;
            this.doc["s000bed2"].width = WIDTH;
            this.doc["s000bed2"].height = HEIGHT;
            this.doc["s000bed3"].width = WIDTH;
            this.doc["s000bed3"].height = HEIGHT;

            cBack.addChild(this.doc["s000bed1"]);

            enterKey.press = function(){
                if (self.number === 0){
                    if (self.doc["pic"] == 3){
                        self.nextState();
                    }else{
                        cBack.removeChild(self.doc["s000bed"+self.doc["pic"]++]);
                        cBack.addChild(self.doc["s000bed"+self.doc["pic"]]);
                    }
                }
            }

            this.switched = false;
        }
    }
    this.switched = true;
    this.underTheBed = function(){
        if (this.switched) {
            this.infotext = "[WASD] to move"
            this.starttime = Date.now()
            this.doc["points"] = this.score;
            this.doc["s001bg"] = PIXI.Sprite.fromImage(s001bg);
            this.doc["s001armo"] = PIXI.Sprite.fromImage(s001armo);
            this.doc["s001armg"] = PIXI.Sprite.fromImage(s001armg);

            this.doc["s001bg"].width = WIDTH;
            this.doc["s001bg"].height = HEIGHT;
            cBack.addChild(this.doc["s001bg"]);
            cGui.addChild(this.doc["points"]);
            this.doc["gamesock"] = new Game1Sock();

            window.setTimeout(function(){this.infotext.text = ""}, 4000);

            this.switched = false;
        }
        this.doc["gamesock"].move();
        this.doc["points"].text = Math.floor((Date.now() - this.starttime) / 1000.0);
    }
    this.funcarray = [this.introfunc, this.underTheBed];

    this.run = this.funcarray[this.number];
}

var gamestate = new State();

/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui
Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

PIXI.loader
    .add(s001bg)
    .add(s001armg)
    .add(s001armo)
    .add(ssock)
    .load(setup);

function setup(){
    // Do setup here
    // Easteregg: eyes!¬
    renderStage();
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    gameLoop();
    renderer.render(stage);
}

// Called before rendering
function gameLoop(){
    // after doing logic:
    gamestate.run()
}

// start game
setup();
<commit_msg>state numbers<commit_after>/*
This is a game by:
Markus "TiByte" Becker   - Lead Developer
Lucas "LFalch"           - Programmer
Aileen                   - Graphic Designer
Kilian "Malloth Rha"     - Musician
Micha                    - Junior Programmer
Using Libraries: Pixi.js and Howler.js
date: 16.04.2016 for LD35
theme: Shapeshift
*/

/*
STRING OF EVENTS:
1. Intro Comic (3 Pictures)
    - socks come to life when unattended
2. Under the bed
    2.1. game
        - avoid hands
    2.2. more story
        - grey sock tells hero to fight sewer monster
3. Sewerfall
    3.1. game
        - falling in the sewer
        - avoid dirt
    3.2. reward (grow arms)
        - if not too dirty
4. Snake game
    4.1. game
        - eat fluff
    4.2. reward (grow bigger)
        - if player ate more than 20 fluff in 30 sec.
5. Plumbing game
    5.1. game
        - turn tiles to connect pipes
    5.2. reward (grow hair)
        - did it in 15 seconds
### Optional ###
0. Platforming game
    0.1. game
    0.2. reward (grow wings)
################
6. Doodle Jump
    6.1. game
        - collect something to gain height
    6.2. more story
        - if won grabbed by sock-hand
        - else falling = losing health
7. Boss fight
    - attack in turns
*/

/*
000 - Intro
001 - Under the bed game
002 - Story (washing machine)
003 - Sewerfall game
004 - Story (Sockbert)
005 - Snake game
006 - Story (Explanation)
007 - Plumbing game
008 - Story (Break out)
009 - Doodle Jump
010 - Story (Getting grabbed)
011 - Boss fight
012 - Thanks for playing

*/

// Cheat Sheet: https://github.com/mtib/ludum34/blob/master/game.js

// Canvas Size
const WIDTH = 1280;
const HEIGHT = 720;

// Current version
const version = "0.01d"

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: true, transparent: false, resolution: 1});
renderer.backgroundColor = 0x6ec2cb;
document.getElementById("gamediv").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();

// Config goes here:
const fontConfig = {font: "30px 'Arial'", fill: "#000000", align: "left"};
const debugConfig = {font: "20px 'Fira Code',monospace,sans-serif", fill: "#FF0000", align: "left"};
const pointsConfig = {font: "20px monospace", fill: "#FF00FF", align: "right"};
const infoConfig = {font: "60px Arial", fill: "#FFFFFF", align: "center", dropShadow: true, dropShadowColor: "#000000"};

const relcenter = {x:0.5,y:0.5};
const enterKey = keyboard(13);

const leftArrow = keyboard(37);
const upArrow = keyboard(38);
const rightArrow = keyboard(39);
const downArrow = keyboard(40);

const aKey = keyboard(65);
const wKey = keyboard(87);
const dKey = keyboard(68);
const sKey = keyboard(83);

const s000bed1 = "./scenes/000/bed.pic1.jpg";
const s000bed2 = "./scenes/000/bed.pic2.jpg";
const s000bed3 = "./scenes/000/bed.pic3.jpg";
const s001bg = "./scenes/001/background.jpg"; // background for game #1
const ssock = "./scenes/001/sock.png"; // normal sock, for use in all? scenes
const s001armo = "./scenes/001/arm.open.png"; // o = open
const s001armg = "./scenes/001/arm.sock.png"; // g = grabbed

const sceneMusic = [ // for the cool kids!
    new Howl({
        src: ['scenes/000/SockventureIntro.ogg'],
        loop: true,
        volume: 0.4,
    }),
    new Howl({
        src: ['scenes/001/SockventureHand.ogg'],
        loop: true,
        volume: 0.4,
    })
];

function Game1Sock() {
    self = this;
    size = 128 // Pixel
    speed = 3 // Pixel / Frame
    this.sprite = new PIXI.Sprite.fromImage(ssock);
    this.sprite.anchor = relcenter;
    this.sprite.width = size;
    this.sprite.height = size;
    this.sprite.position = {x: WIDTH*0.5, y: HEIGHT*0.5};
    this.die = function() {
        cMiddle.removeChild(this.sprite);
    }
    this.move = function() {
        delta = {x:0, y:0};
        if ((rightArrow.isDown || dKey.isDown) && this.sprite.position.x < WIDTH - 100) {
            delta.x += speed;
        }
        if ((leftArrow.isDown || aKey.isDown) && this.sprite.position.x > 100) {
            delta.x -= speed;
        }
        if ((upArrow.isDown || wKey.isDown) && this.sprite.position.y > 230) {
            delta.y -= speed;
        }
        if ((downArrow.isDown || sKey.isDown) && this.sprite.position.y < HEIGHT - 100) {
            delta.y += speed;
        }
        magsqr = Math.sqrt(Math.abs(delta.x) + Math.abs(delta.y))
        if (magsqr == 0) {
            return;
        }
        if (delta.x > 0 && this.sprite.scale.x > 0) {
            this.sprite.scale.x *= -1;
        } else if (delta.x < 0 && this.sprite.scale.x < 0) {
            this.sprite.scale.x *= -1;
        }
        delta.x /= magsqr;
        delta.y /= magsqr;
        this.sprite.position.x += delta.x;
        this.sprite.position.y += delta.y;
    }
    cMiddle.addChild(this.sprite);
}

function State() {
    self = this;
    this.debugText = new PIXI.Text("Version: "+version+"\n<Debug Information>\nState: ",debugConfig);
    this.debugText.position = {x:5,y:5};
    this.score = new PIXI.Text("0", pointsConfig);
    this.score.position = {x: WIDTH - 5, y: 5};
    this.score.anchor = {x: 1, y:0};
    this.debugStateText = new PIXI.Text("0", debugConfig);
    this.debugStateText.position = {x:89,y:45};

    this.infotext = new PIXI.Text("", infoConfig); // eg. "press xxx to skip"
    this.infotext.position = {x: WIDTH/2, y: HEIGHT/2};
    this.infotext.anchor = relcenter;

    this.doc = {}; // DestroyOnChange

    cGui.addChild(this.infotext);
    cGui.addChild(this.debugText);
    cGui.addChild(this.debugStateText);
    this.number = 0;
    sceneMusic[0].play();
    this.run = function(){
        console.log("default state");
    }

    this.nextState = function(){
        for (var sprite in this.doc) {
            if (this.doc.hasOwnProperty(sprite)) {
                if (this.doc[sprite].die) {
                    this.doc[sprite].die();
                } else {
                    cGui.removeChild(this.doc[sprite])
                    cMiddle.removeChild(this.doc[sprite])
                    cFront.removeChild(this.doc[sprite])
                    cBack.removeChild(this.doc[sprite]);
                }
            }
            delete this.doc[sprite];
        }
        enterKey.press = undefined;

        sceneMusic[this.number++].stop();
        sceneMusic[this.number].play();

        this.switched = true;
        this.debugStateText.text = this.number;
        this.run = this.funcarray[this.number];
    }
    this.introfunc = function(){
        if (this.switched){
            this.infotext.text = "Press <Enter> to skip"
            this.substate = 1;
            this.doc["pic"] = 1;
            this.doc["s000bed1"] = PIXI.Sprite.fromImage(s000bed1);
            this.doc["s000bed2"] = PIXI.Sprite.fromImage(s000bed2);
            this.doc["s000bed3"] = PIXI.Sprite.fromImage(s000bed3);

            this.doc["s000bed1"].width = WIDTH;
            this.doc["s000bed1"].height = HEIGHT;
            this.doc["s000bed2"].width = WIDTH;
            this.doc["s000bed2"].height = HEIGHT;
            this.doc["s000bed3"].width = WIDTH;
            this.doc["s000bed3"].height = HEIGHT;

            cBack.addChild(this.doc["s000bed1"]);

            enterKey.press = function(){
                if (self.number === 0){
                    if (self.doc["pic"] == 3){
                        self.nextState();
                    }else{
                        cBack.removeChild(self.doc["s000bed"+self.doc["pic"]++]);
                        cBack.addChild(self.doc["s000bed"+self.doc["pic"]]);
                    }
                }
            }

            this.switched = false;
        }
    }
    this.switched = true;
    this.underTheBed = function(){
        if (this.switched) {
            this.infotext = "[WASD] to move"
            this.starttime = Date.now()
            this.doc["points"] = this.score;
            this.doc["s001bg"] = PIXI.Sprite.fromImage(s001bg);
            this.doc["s001armo"] = PIXI.Sprite.fromImage(s001armo);
            this.doc["s001armg"] = PIXI.Sprite.fromImage(s001armg);

            this.doc["s001bg"].width = WIDTH;
            this.doc["s001bg"].height = HEIGHT;
            cBack.addChild(this.doc["s001bg"]);
            cGui.addChild(this.doc["points"]);
            this.doc["gamesock"] = new Game1Sock();

            window.setTimeout(function(){this.infotext.text = ""}, 4000);

            this.switched = false;
        }
        this.doc["gamesock"].move();
        this.doc["points"].text = Math.floor((Date.now() - this.starttime) / 1000.0);
    }
    this.funcarray = [this.introfunc, this.underTheBed];

    this.run = this.funcarray[this.number];
}

var gamestate = new State();

/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui
Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

PIXI.loader
    .add(s001bg)
    .add(s001armg)
    .add(s001armo)
    .add(ssock)
    .load(setup);

function setup(){
    // Do setup here
    // Easteregg: eyes!¬
    renderStage();
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    gameLoop();
    renderer.render(stage);
}

// Called before rendering
function gameLoop(){
    // after doing logic:
    gamestate.run()
}

// start game
setup();
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
(function($, cloudStack) {
    // Admin dashboard
    cloudStack.sections.dashboard = {
        title: 'label.menu.dashboard',
        show: cloudStack.uiCustom.dashboard,

        adminCheck: function(args) {
            return isAdmin() ? true : false;
        },

        // User dashboard
        user: {
            dataProvider: function(args) {
                var dataFns = {
                    instances: function(data) {
                        var totalInstanceCount = 0;
                        $.ajax({
                            url: createURL("listVirtualMachines"),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: 1
                            },
                            async: false,
                            success: function(json) {
                                if (json.listvirtualmachinesresponse.count != undefined) {
                                    totalInstanceCount = json.listvirtualmachinesresponse.count;
                                }
                            }
                        });

                        var RunningInstanceCount = 0;
                        $.ajax({
                            url: createURL("listVirtualMachines"),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: 1,
                                state: "Running"
                            },
                            async: false,
                            success: function(json) {
                                if (json.listvirtualmachinesresponse.count != undefined) {
                                    RunningInstanceCount = json.listvirtualmachinesresponse.count;
                                }
                            }
                        });

                        var stoppedInstanceCount = 0;
                        $.ajax({
                            url: createURL("listVirtualMachines"),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: 1,
                                state: "Stopped"
                            },
                            async: false,
                            success: function(json) {
                                if (json.listvirtualmachinesresponse.count != undefined) {
                                    stoppedInstanceCount = json.listvirtualmachinesresponse.count;
                                }
                            }
                        });

                        dataFns.account($.extend(data, {
                            runningInstances: RunningInstanceCount,
                            stoppedInstances: stoppedInstanceCount,
                            totalInstances: totalInstanceCount
                        }));
                    },

                    account: function(data) {
                        var user = cloudStack.context.users[0];
                        dataFns.events($.extend(data, {
                            accountID: user.userid,
                            accountName: user.account,
                            userName: user.username,
                            accountType: user.role,
                            accountDomainID: user.domainid
                        }));
                    },

                    events: function(data) {
                        $.ajax({
                            url: createURL('listEvents'),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: (pageSize > 4? 4: pageSize) //if default.page.size > 4, show 4 items only (since space on dashboard is limited)
                                //pageSize: 1 //for testing only
                            },
                            success: function(json) {
                                dataFns.ipAddresses($.extend(data, {
                                    events: json.listeventsresponse.event ? json.listeventsresponse.event : []
                                }));
                            }
                        });
                    },

                    ipAddresses: function(data) {
                        $.ajax({
                            url: createURL('listNetworks'),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: 1,
                                type: 'isolated',
                                supportedServices: 'SourceNat'
                            },
                            success: function(json) {
                                var netTotal = json.listnetworksresponse.count ?
                                    json.listnetworksresponse.count : 0;

                                $.ajax({
                                    url: createURL('listPublicIpAddresses'),
                                    data: {
                                        page: 1,
                                        pageSize: 1
                                    },
                                    success: function(json) {
                                        var ipTotal = json.listpublicipaddressesresponse.count ?
                                            json.listpublicipaddressesresponse.count : 0;

                                        complete($.extend(data, {
                                            netTotal: netTotal,
                                            ipTotal: ipTotal
                                        }));
                                    }
                                });
                            }
                        });
                    }
                };

                var complete = function(data) {
                    args.response.success({
                        data: data
                    });
                };

                dataFns.instances({});
            }
        },

        // Admin dashboard
        admin: {
            zoneDetailView: {
                tabs: {
                    resources: {
                        title: 'label.resources',
                        custom: cloudStack.uiCustom.systemChart('resources')
                    }
                }
            },

            dataProvider: function(args) {
                var dataFns = {
                    zones: function(data) {
                        $.ajax({
                            url: createURL('listZones'),
                            success: function(json) {
                                dataFns.capacity({
                                    zones: json.listzonesresponse.zone
                                });
                            }
                        });
                    },
                    capacity: function(data) {
                        if (window.fetchLatestflag == 1) {
                            data.fetchLastest = true;
                        } else {
                            data.fetchLastest = false;
                        }
                        window.fetchLatestflag = 0;
                        dataFns.alerts(data);
                    },

                    alerts: function(data) {
                        $.ajax({
                            url: createURL('listAlerts'),
                            data: {
                                page: 1,
                                pageSize: (pageSize > 4? 4: pageSize) //if default.page.size > 4, show 4 items only (since space on dashboard is limited)
                            },
                            success: function(json) {
                                var alerts = json.listalertsresponse.alert ?
                                    json.listalertsresponse.alert : [];

                                dataFns.hostAlerts($.extend(data, {
                                    alerts: $.map(alerts, function(alert) {
                                        return {
                                            name: cloudStack.converters.toAlertType(alert.type),
                                            description: alert.description,
                                            sent: cloudStack.converters.toLocalDate(alert.sent)
                                        };
                                    })
                                }));
                            }
                        });
                    },

                    hostAlerts: function(data) {
                        $.ajax({
                            url: createURL('listHosts'),
                            data: {
                                state: 'Alert',
                                page: 1,
                                pageSize: (pageSize > 4? 4: pageSize) //if default.page.size > 4, show 4 items only (since space on dashboard is limited)
                            },
                            success: function(json) {
                                var hosts = json.listhostsresponse.host ?
                                    json.listhostsresponse.host : [];

                                dataFns.zoneCapacity($.extend(data, {
                                    hostAlerts: $.map(hosts, function(host) {
                                        return {
                                            name: host.name,
                                            description: 'message.alert.state.detected'
                                        };
                                    })
                                }));
                            }
                        });
                    },

                    zoneCapacity: function(data) {
                        $.ajax({
                            url: createURL('listCapacity'),
                            data: {
                                fetchLatest: data.fetchLatest,
                                sortBy: 'usage',
                                page: 0,
                                pageSize: (pageSize > 8? 8: pageSize)
                            },
                            success: function(json) {
                                var capacities = json.listcapacityresponse.capacity ?
                                    json.listcapacityresponse.capacity : [];

                                complete($.extend(data, {
                                    zoneCapacities: $.map(capacities, function(capacity) {
                                        if (capacity.podname) {
                                            capacity.zonename = capacity.zonename.concat(', ' + _l('label.pod') + ': ' + capacity.podname);
                                        }

                                        if (capacity.clustername) {
                                            capacity.zonename = capacity.zonename.concat(', ' + _l('label.cluster') + ': ' + capacity.clustername);
                                        }

                                        capacity.zonename.replace('Zone:', _l('label.zone') + ':');

                                        return {
                                            zoneID: capacity.zoneid, // Temporary fix for dashboard
                                            zoneName: capacity.zonename,
                                            type: cloudStack.converters.toCapacityCountType(capacity.type),
                                            percent: parseInt(capacity.percentused),
                                            used: cloudStack.converters.convertByType(capacity.type, capacity.capacityused),
                                            total: cloudStack.converters.convertByType(capacity.type, capacity.capacitytotal)
                                        };
                                    })
                                }));
                            }
                        });
                    }
                };

                var complete = function(data) {
                    args.response.success({
                        data: data
                    });
                };

                dataFns.zones({});
            }
        }
    };
})(jQuery, cloudStack);
<commit_msg>Display 3 items as there is no more space<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

// number of items to display on dashboards
dashboardItemsToDisplay = 3;

(function($, cloudStack) {
    // Admin dashboard
    cloudStack.sections.dashboard = {
        title: 'label.menu.dashboard',
        show: cloudStack.uiCustom.dashboard,

        adminCheck: function(args) {
            return isAdmin() ? true : false;
        },

        // User dashboard
        user: {
            dataProvider: function(args) {
                var dataFns = {
                    instances: function(data) {
                        var totalInstanceCount = 0;
                        $.ajax({
                            url: createURL("listVirtualMachines"),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: 1
                            },
                            async: false,
                            success: function(json) {
                                if (json.listvirtualmachinesresponse.count != undefined) {
                                    totalInstanceCount = json.listvirtualmachinesresponse.count;
                                }
                            }
                        });

                        var RunningInstanceCount = 0;
                        $.ajax({
                            url: createURL("listVirtualMachines"),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: 1,
                                state: "Running"
                            },
                            async: false,
                            success: function(json) {
                                if (json.listvirtualmachinesresponse.count != undefined) {
                                    RunningInstanceCount = json.listvirtualmachinesresponse.count;
                                }
                            }
                        });

                        var stoppedInstanceCount = 0;
                        $.ajax({
                            url: createURL("listVirtualMachines"),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: 1,
                                state: "Stopped"
                            },
                            async: false,
                            success: function(json) {
                                if (json.listvirtualmachinesresponse.count != undefined) {
                                    stoppedInstanceCount = json.listvirtualmachinesresponse.count;
                                }
                            }
                        });

                        dataFns.account($.extend(data, {
                            runningInstances: RunningInstanceCount,
                            stoppedInstances: stoppedInstanceCount,
                            totalInstances: totalInstanceCount
                        }));
                    },

                    account: function(data) {
                        var user = cloudStack.context.users[0];
                        dataFns.events($.extend(data, {
                            accountID: user.userid,
                            accountName: user.account,
                            userName: user.username,
                            accountType: user.role,
                            accountDomainID: user.domainid
                        }));
                    },

                    events: function(data) {
                        $.ajax({
                            url: createURL('listEvents'),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: (pageSize > dashboardItemsToDisplay? dashboardItemsToDisplay: pageSize) //if default.page.size > dashboardItemsToDisplay, show dashboardItemsToDisplay items only (since space on dashboard is limited)
                                //pageSize: 1 //for testing only
                            },
                            success: function(json) {
                                dataFns.ipAddresses($.extend(data, {
                                    events: json.listeventsresponse.event ? json.listeventsresponse.event : []
                                }));
                            }
                        });
                    },

                    ipAddresses: function(data) {
                        $.ajax({
                            url: createURL('listNetworks'),
                            data: {
                                listAll: true,
                                page: 1,
                                pageSize: 1,
                                type: 'isolated',
                                supportedServices: 'SourceNat'
                            },
                            success: function(json) {
                                var netTotal = json.listnetworksresponse.count ?
                                    json.listnetworksresponse.count : 0;

                                $.ajax({
                                    url: createURL('listPublicIpAddresses'),
                                    data: {
                                        page: 1,
                                        pageSize: 1
                                    },
                                    success: function(json) {
                                        var ipTotal = json.listpublicipaddressesresponse.count ?
                                            json.listpublicipaddressesresponse.count : 0;

                                        complete($.extend(data, {
                                            netTotal: netTotal,
                                            ipTotal: ipTotal
                                        }));
                                    }
                                });
                            }
                        });
                    }
                };

                var complete = function(data) {
                    args.response.success({
                        data: data
                    });
                };

                dataFns.instances({});
            }
        },

        // Admin dashboard
        admin: {
            zoneDetailView: {
                tabs: {
                    resources: {
                        title: 'label.resources',
                        custom: cloudStack.uiCustom.systemChart('resources')
                    }
                }
            },

            dataProvider: function(args) {
                var dataFns = {
                    zones: function(data) {
                        $.ajax({
                            url: createURL('listZones'),
                            success: function(json) {
                                dataFns.capacity({
                                    zones: json.listzonesresponse.zone
                                });
                            }
                        });
                    },
                    capacity: function(data) {
                        if (window.fetchLatestflag == 1) {
                            data.fetchLastest = true;
                        } else {
                            data.fetchLastest = false;
                        }
                        window.fetchLatestflag = 0;
                        dataFns.alerts(data);
                    },

                    alerts: function(data) {
                        $.ajax({
                            url: createURL('listAlerts'),
                            data: {
                                page: 1,
                                pageSize: (pageSize > dashboardItemsToDisplay? dashboardItemsToDisplay: pageSize) //if default.page.size > dashboardItemsToDisplay, show dashboardItemsToDisplay items only (since space on dashboard is limited)
                            },
                            success: function(json) {
                                var alerts = json.listalertsresponse.alert ?
                                    json.listalertsresponse.alert : [];

                                dataFns.hostAlerts($.extend(data, {
                                    alerts: $.map(alerts, function(alert) {
                                        return {
                                            name: cloudStack.converters.toAlertType(alert.type),
                                            description: alert.description,
                                            sent: cloudStack.converters.toLocalDate(alert.sent)
                                        };
                                    })
                                }));
                            }
                        });
                    },

                    hostAlerts: function(data) {
                        $.ajax({
                            url: createURL('listHosts'),
                            data: {
                                state: 'Alert',
                                page: 1,
                                pageSize: (pageSize > dashboardItemsToDisplay? dashboardItemsToDisplay: pageSize) //if default.page.size > dashboardItemsToDisplay, show dashboardItemsToDisplay items only (since space on dashboard is limited)
                            },
                            success: function(json) {
                                var hosts = json.listhostsresponse.host ?
                                    json.listhostsresponse.host : [];

                                dataFns.zoneCapacity($.extend(data, {
                                    hostAlerts: $.map(hosts, function(host) {
                                        return {
                                            name: host.name,
                                            description: 'message.alert.state.detected'
                                        };
                                    })
                                }));
                            }
                        });
                    },

                    zoneCapacity: function(data) {
                        $.ajax({
                            url: createURL('listCapacity'),
                            data: {
                                fetchLatest: data.fetchLatest,
                                sortBy: 'usage',
                                page: 0,
                                pageSize: (pageSize > 8? 8: pageSize)
                            },
                            success: function(json) {
                                var capacities = json.listcapacityresponse.capacity ?
                                    json.listcapacityresponse.capacity : [];

                                complete($.extend(data, {
                                    zoneCapacities: $.map(capacities, function(capacity) {
                                        if (capacity.podname) {
                                            capacity.zonename = capacity.zonename.concat(', ' + _l('label.pod') + ': ' + capacity.podname);
                                        }

                                        if (capacity.clustername) {
                                            capacity.zonename = capacity.zonename.concat(', ' + _l('label.cluster') + ': ' + capacity.clustername);
                                        }

                                        capacity.zonename.replace('Zone:', _l('label.zone') + ':');

                                        return {
                                            zoneID: capacity.zoneid, // Temporary fix for dashboard
                                            zoneName: capacity.zonename,
                                            type: cloudStack.converters.toCapacityCountType(capacity.type),
                                            percent: parseInt(capacity.percentused),
                                            used: cloudStack.converters.convertByType(capacity.type, capacity.capacityused),
                                            total: cloudStack.converters.convertByType(capacity.type, capacity.capacitytotal)
                                        };
                                    })
                                }));
                            }
                        });
                    }
                };

                var complete = function(data) {
                    args.response.success({
                        data: data
                    });
                };

                dataFns.zones({});
            }
        }
    };
})(jQuery, cloudStack);
<|endoftext|>


<commit_before>// ITERATORS.

// this method is going to help me create ITERATORS out of a normal object ot to turn a normal
// oject into an iterator.

class Name extends Array {

    constructor (...names) {
        super(...names);
        this.names = [...names];
    }

    static get [Symbol.iterable]()  {return this.names;}

}

var name = new Name("Johnny", "Jared", "Juma", "Jeffrey", "Jade")
console.log(name[0]);
for (let i of name) {
    console.log(i);
}
var mapped = name.map(function (x) {
    return x + "s.";
})
var reduced = name.reduce((p, n) => p + " " + n)
console.log(reduced);
console.log(mapped);
<commit_msg>all about the new symbols addition<commit_after>// ITERATORS.

// this method is going to help me create ITERATORS out of a normal object ot to turn a normal
// oject into an iterator.
/*
Symbols are a new primitive. Just like the Number, String, and Boolean primitives, Symbols have a Symbol function which can be used to create them. Unlike the other primitives, Symbols do not have a literal syntax (e.g how Strings have '') - the only way to make them is with the Symbol constructor-not-constructor-thingy:

In addition to that, Symbols do not show up on an Object using for in, for of or Object.getOwnPropertyNames - the only way to get the Symbols within an Object is Object.getOwnPropertySymbols:

Symbols are completely unique…

By default, each new Symbol has a completely unique value. If you create a symbol (var mysym = Symbol()) it creates a completely new value inside the JavaScript engine. If you don’t have the reference for the Symbol, you just can’t use it. This also means two symbols will never equal the same value, even if they have the same description
*/

class Name extends Array{

    constructor (...names) {
        super(...names)
        this.names = [...names];
    }

    *[Symbol.iterator](){
        for (let i of this.names) {
            yield i;
        }
    }

    [Symbol.species](cb){
        return this;
    }

    get [Symbol.toStringTag]() {
        return 'Names';
    }

}

var name = new Name("Johnny", "Jared", "Juma", "Jeffrey", "Jade")
console.log(name.toString());
console.log(name[0]);
for (let i of name) {
    console.log(i);
}

var mapped = name.map(function (x) {
    return x + "s.";
})

var reduced = name.reduce((p, n) => p + " " + n)
console.log(reduced);
console.log(mapped);

var object = {
    name: "Forest Whittaker",

    age: 20,

    year: 1996,

    self: "Me",

    call(){return this.name + " " + this.age},

    get length(){
        var count = 0;
        for (let i in this) {
            count++;
        }
        return count;
    },

    get keys(){
        var array = [];
        for (let i in this) {
            array.push(i);
        }
        return array;
    },

    *[Symbol.iterator](){
        for (let i in this) {
            yield [i , this[i]];
        }
    },

}

console.log(object.length);
console.log(object.keys);
for (let [a, b] of object) {
    console.log(a + " " + b);
}

var iter = [...object]
console.log(iter);

// extending symbols

var userSym = Symbol("user");
class Users {
    constructor(name) {
        this[userSym] = name || "No name";
        let age = 15;
    }
    get name(){return this[userSym];}
}

var user = new Users();
console.log(user);

// some well know symbols

/*
Symbol.hasInstance: instanceof

Symbol.hasInstance is a Symbol which drives the behaviour of instanceof. When an ES6 compliant engine sees the instanceof operator in an expression it calls upon Symbol.hasInstance. For example, lho instanceof rho would call rho[Symbol.hasInstance](lho) (where rho is the right hand operand and lho is the left hand operand). It’s then up to the method to determine if it inherits from that particular instance, you could implement this like so
*/

class MyClass {
    constructor () {

    }

    [Symbol.hasInstance](lho) {
        return lho instanceof this;
    }
}

var mc = new MyClass()
console.log([] instanceof MyClass);
console.log(mc instanceof MyClass);

/*
Symbol.isConcatSpreadable

Symbol.isConcatSpreadable is a pretty specific Symbol - driving the behaviour of Array#concat. You see, Array#concat can take multiple arguments, which - if arrays - will themselves be flattened (or spread) as part of the concat operation. Consider the following code:
*/
var x = [1, 2].concat([3, 4], [5, 6], 7, 8);
console.log(x, [1, 2, 3, 4, 5, 6, 7, 8]);

/*
As of ES6 the way Array#concat will determine if any of its arguments are spreadable will be with Symbol.isConcatSpreadable. This is more used to say that the class you have made that extends Array won’t be particularly good for Array#concat, rather than the other way around:
*/

class ArrayIsh extends Array {
    get [Symbol.isConcatSpreadable]() {
        return true;
    }
}
class Collection extends Array {
    get [Symbol.isConcatSpreadable]() {
        return false;
    }
}
var arrayIshInstance = new ArrayIsh();
arrayIshInstance[0] = 3;
arrayIshInstance[1] = 4;
var collectionInstance = new Collection();
collectionInstance[0] = 5;
collectionInstance[1] = 6;
var spreadableTest = [1,2].concat(arrayIshInstance).concat(collectionInstance);
console.log(spreadableTest, [1, 2, 3, 4, "<Collection>"]);
/*
Symbol.match

This is another Symbol specific to a function. String#match function will now use this to determine if the given value can be used to match against it. So, you can provide your own matching implementation to use, rather than using Regular Expressions:
*/
class MyMatcher {
    constructor(value) {
        this.value = value;
    }
    [Symbol.match](string) {
        var index = string.indexOf(this.value);
        if (index === -1) {
            return null;
        }
        return [this.value];
    }
}
var fooMatcher = 'foobar'.match(new MyMatcher('foo'));
var barMatcher = 'foobar'.match(new MyMatcher('bar'));
console.log(fooMatcher, ['foo']);
console.log(barMatcher, ['bar']);

/*
Symbol.replace

Just like Symbol.match, Symbol.replace has been added to allow custom classes, where you’d normally use Regular Expressions, for String#replace:
*/
class MyReplacer {
    constructor(value) {
        this.value = value;
    }
    [Symbol.replace](string, replacer) {
        var index = string.indexOf(this.value);
        if (index === -1) {
            return string;
        }
        if (typeof replacer === 'function') {
            replacer = replacer.call(undefined, this.value, string);
        }
        return `${string.slice(0, index)}${replacer}${string.slice(index + this.value.length)}`;
    }
}
var fooReplaced = 'foobar'.replace(new MyReplacer('foo'), 'baz');
var barMatcher = 'foobar'.replace(new MyReplacer('bar'), function () { return 'baz' });
console.log(fooReplaced, 'bazbar');
console.log(barMatcher, 'foobaz');

/*
Symbol.search

Yup, just like Symbol.match and Symbol.replace, Symbol.search exists to prop up String#search - allowing for custom classes instead of Regular Expressions:
*/
class MySearch {
    constructor(value) {
        this.value = value;
    }
    [Symbol.search](string) {
        return string.indexOf(this.value);
    }
}
var fooSearch = 'foobar'.search(new MySearch('foo'));
var barSearch = 'foobar'.search(new MySearch('bar'));
var bazSearch = 'foobar'.search(new MySearch('baz'));
console.log(fooSearch, 0);
console.log(barSearch, 3);
console.log(bazSearch, -1);

/*
Symbol.split

Ok, last of the String symbols - Symbol.split is for String#split. Use like so:
*/

class MySplitter {
    constructor(value) {
        this.value = value;
    }
    [Symbol.split](string) {
        var index = string.indexOf(this.value);
        if (index === -1) {
            return string;
        }
        return [string.substr(0, index), string.substr(index + this.value.length)];
    }
}
var fooSplitter = 'foobar'.split(new MySplitter('foo'));
var barSplitter = 'foobar'.split(new MySplitter('bar'));
console.log(fooSplitter, ['', 'bar']);
console.log(barSplitter, ['foo', '']);
<|endoftext|>


<commit_before>import "./main.css"
import F from "ramda"
import React, { DOM as E } from "react"
import createReactClass from "create-react-class"
import { PropTypes as T } from "prop-types"
import ReactDOM from "react-dom"
import PopoverClass from "../../lib"

const Popover = React.createFactory(PopoverClass)

const Row = React.createFactory(createReactClass({
  displayName: "row",
  propTypes: {
    children: T.number,
  },
  getInitialState () {
    return {
      isOpen: false,
    }
  },
  toggle (toState = null) {
    this.setState({ isOpen: toState === null ? !this.state.isOpen : toState })
  },
  render () {
    const { isOpen } = this.state
    return (
      Popover({
        isOpen,
        body: "!",
        children: (
          E.div({
            className: "Row",
            onMouseOver: () => this.toggle(true),
            onMouseOut: () => this.toggle(false),
            children: this.props.children,
          })
        )
      })
    )
  }
}))

const Main = React.createClass({
  render () {
    return (
      E.div({
        id: "app",
        children: (
          F.range(0,51).map((i) => Row({}, i))
        )
      })
    )
  },
})

window.React = React
window.ReactDOM = ReactDOM
window.Main = Main
<commit_msg>patch: fix last instance of React.createClass<commit_after>import "./main.css"
import F from "ramda"
import React, { DOM as E } from "react"
import createReactClass from "create-react-class"
import { PropTypes as T } from "prop-types"
import ReactDOM from "react-dom"
import PopoverClass from "../../lib"

const Popover = React.createFactory(PopoverClass)

const Row = React.createFactory(createReactClass({
  displayName: "row",
  propTypes: {
    children: T.number,
  },
  getInitialState () {
    return {
      isOpen: false,
    }
  },
  toggle (toState = null) {
    this.setState({ isOpen: toState === null ? !this.state.isOpen : toState })
  },
  render () {
    const { isOpen } = this.state
    return (
      Popover({
        isOpen,
        body: "!",
        children: (
          E.div({
            className: "Row",
            onMouseOver: () => this.toggle(true),
            onMouseOut: () => this.toggle(false),
            children: this.props.children,
          })
        )
      })
    )
  }
}))

const Main = createReactClass({
  render () {
    return (
      E.div({
        id: "app",
        children: (
          F.range(0,51).map((i) => Row({}, i))
        )
      })
    )
  },
})

window.React = React
window.ReactDOM = ReactDOM
window.Main = Main
<|endoftext|>