<commit_before>/// <reference path="GameDraw.js" />
/// <reference path="GameObjects.js" />
var GameEngine = ( function () {
    var board,
        players,
        dices,
        firstDiceThrow,
        currentPlayer,
        hasChosen,
    	indexOfChosenField,
    	indexOfTargetField;

    function start() {
        players = [];
        // playerOneName , playerTwoName - variables containing names from start screen
        players.push(Object.create(GameObjects.Player).init('First', 'white'));
        players.push(Object.create(GameObjects.Player).init('Second', 'black'));

        board = GameObjects.Board.init();

        // dices.rollDices() ; dices.usedNumber(number) ; dices.clearNumbers()
        dices = GameObjects.Dices.init();

        firstDiceThrow = true;

        GameDraw.initGame(board, players);
    }

    function clickedToRollDices() {
        if (firstDiceThrow) {
            firstDiceThrow = false;
            throwFirstDiceToDeterminePlayer();
            currentPlayer = players[0].isOnTurn ? players[0] : players[1];
        }
        if (dices.numbers.length === 0) {
            dices.rollDices();
            currentPlayer = setCurrentPlayerOnTurn();
        }
        GameDraw.updatePlayerNames(currentPlayer)
    }

    function updatePlayGround() {
        GameDraw.updatePlayGround(board);
    }

    function update(pressedField) {
        var canExtract = checkIfPlayerCanExtractPieces(currentPlayer, board);

    		// alert(hasChosen +' ' + indexOfChosenField +' ' +  indexOfTargetField +' ' +  canExtract)

    	if (hasChosen) {
    		indexOfTargetField = getIndexOfPossibleTargetFields(indexOfChosenField, currentPlayer, board, dices.numbers);

    		if (indexOfTargetField.indexOf(pressedField) < 0) {
    			return;
    		}

            board.movePiece (indexOfChosenField, pressedField);

            hasChosen = false;

            checkForPinnedPiece(board);

            dices.usedNumber(Math.abs(pressedField - board[indexOfChosenField]));

            if (dices.numbers.length === 0) {
            	alert ('No more moves. Next player turn');
            	setCurrentPlayerOnTurn();
            }

    	} else {
    		if (!canExtract) {
            	var possibleStartPositions = getIndexOfFieldsWithMovesAvailable(currentPlayer, board, dices.numbers);
            	// alert(possibleStartPositions)
            	if (!possibleStartPositions.length) {
                	alert('No moves');
                	dices.clearNumbers();
                	return;
            	} else if (possibleStartPositions.length === 1) {

                	if (board[possibleStartPositions[0]].pieces.length >= 5) {
                   		board[possibleStartPositions[0]].pieces[4].isChosen = true;
                	} else {
                    	board[possibleStartPositions[0]].pieces[board[possibleStartPositions[0]].pieces.length - 1].isChosen = true;
                	}

                	hasChosen = true;
                	indexOfChosenField = possibleStartPositions[0];
                	// alert(hasChosen + ' ' + indexOfChosenField)

            	} else {
            		if (possibleStartPositions.indexOf(pressedField) > -1) {
            			if (board[pressedField].pieces.length >= 5) {
                   			board[pressedField].pieces[4].isChosen = true;
                		} else {
                    		board[pressedField].pieces[board[pressedField].pieces.length - 1].isChosen = true;
                		}
            		} else {
            			return;
            		}

            		hasChosen = true;
                	indexOfChosenField = pressedField;
                	// alert(hasChosen + ' ' + indexOfChosenField)

            	}

        	} else {
        		// drago tuka move da tegli playera..

        	}
    	}

        updatePlayGround();

        if (!currentPlayer.countOfPieces) {
            alert(currentPlayer.name + ' WINS!!!')
        }
    }

    // Event targets can be document elements, the document itself, window or any other object that supports events.
    //function addListenersToPossibleGameFields(gameFields) {
    //    var i,
    //        len,
    //        currentFieldIndex,
    //        currentField;
    //
    //    for (i = 0, len = gameFields.length; i < len; i += 1) {
    //        currentFieldIndex = gameFields[i];
    //        currentField = board[currentFieldIndex];
    //        currentField.addEventListener('mousedown', selectAndPaintLastPiece(currentField));
    //    }
    //}
    //
    //function selectAndPaintLastPiece(gameField) {
    //    var lengthOfPiecesInField = gameField.pieces.length;
    //    gameField.pieces[lengthOfPiecesInField - 1].isChosen = true;
    //}

    function throwFirstDiceToDeterminePlayer() {
        dices.rollDices();
        if (dices.numbers[dices.numbers.length - 2] > dices.numbers[dices.numbers.length - 1]) {
            players[0].isOnTurn = true;
        } else if (dices.numbers[dices.numbers.length - 2] < dices.numbers[dices.numbers.length - 1]) {
            players[1].isOnTurn = true;
        } else {
            firstDiceThrow = true;
            dices.clearNumbers();
            clickedToRollDices();
        }
    }

    function setCurrentPlayerOnTurn() {
        if (players[0].isOnTurn) {
            players[0].isOnTurn = false;
            players[1].isOnTurn = true;
            return players[0];
        } else {
            players[0].isOnTurn = true;
            players[1].isOnTurn = false;
            return players[1];
        }
    }

    function getDices() {
        return dices;
    }

    return {
        start: start,
        update: update,
        clickedToRollDices: clickedToRollDices,
        dices: getDices
    };
}() );

function getIndexOfFieldsWithMovesAvailable(player, board, numbers) {
    var direction,
        i, j,
        result = [],
        color = player.color,
        index;

    color = color.substring(0, 1).toUpperCase() + color.substring(1);

    if (color.toLowerCase() === 'white') {
        direction = 1;

        if (board[0].pieces.length) {
            for (j = 0; j < numbers.length; j += 1) {
                if (board[0 + numbers[j] * direction]['availableFor' + color]) {
                    return [0];
                }
            }

            return result;
        }
    } else {
        direction = -1;

        if (board[board.length - 1].pieces.length) {
            for (j = 0; j < numbers.length; j += 1) {
                if (board[board.length - 1 + numbers[j] * direction]['availableFor' + color]) {
                    return [board.length - 1];
                }
            }

            return result;
        }
    }

    for (i = 1, len = board.length; i < board.length - 1; i += 1) {
        if (board[i].pieces.length > 0 && board[i].pieces[0].color === color.toLowerCase()) {
            for (j = 0; j < numbers.length; j += 1) {
            	index = i + numbers[j] * direction;
                if (1 < index  && index < 24 && board[index]['availableFor' + color]) {
                    result.push(i);
                    break;
                }
            }
        }
    }

    return result;
}

function getIndexOfPossibleTargetFields(markedIndex, player, board, numbers) {
    // alert(markedIndex + ' ' + numbers)

    var color = player.color,
        i,
        result = [],
        direction;

    if (color === 'white') {
        direction = 1
    } else {
        direction = -1
    }

    color = color.substring(0, 1).toUpperCase() + color.substring(1);

    for (i = 0; i < numbers.length; i++) {
        if (board[markedIndex + numbers[i] * direction]['availableFor' + color]) {
            result.push(markedIndex + numbers[i] * direction);
        }
    }

    return result;
}

function checkForPinnedPiece(board) {
    var i,
        len = board.length;

    for (i = 1; i < len - 1; i += 1) {
        if (board[i].length === 2 && board[i].pieces[0].color !== board[i].pieces[1].color) {
            var shifted = board[i].pieces.shift();
            if (shifted.color === 'white') {
                board[0].push(shifted);
                return;
            } else {
                board[len - 1].push(shifted);
                return;
            }
        }
    }
}

function checkIfPlayerCanExtractPieces(player, board) {
    var color = player.color,
        i,
        count = 0;

    if (color === 'white') {
        for (i = 19; i <= 24; i += 1) {
            if (board[i].pieces.length > 0 && board[i].pieces[0].color === color) {
                count += board[i].pieces.length;
            }
        }
    } else {
        for (i = 1; i <= 6; i += 1) {
            if (board[i].pieces.length > 0 && board[i].pieces[0].color === color) {
                count += board[i].pieces.length;
            }
        }
    }

    return count === player.countOfPieces;
}

// // All events will call GameEngine.Update() and GameDraw.Update().

//// Logic to add
function checkIfPlayerIsMakingNormalMoves(currentActivePlayer, currentPlayerMoves, maximumAllowedMovesInTurn) {
    if (currentPlayerMoves < maximumAllowedMovesInTurn && !currentActivePlayer.hasHitChecker && !currentActivePlayer.canTakeChecker) {
        return true;
    }
    return false;
}

function play() {

    var maximumAllowedMovesInTurn;
    var currentActivePlayer;
    var inactivePlayer;
    var currentPlayerMoves = 0;   // DA SE IZNESAT TEZI PROMENLIVI GORE POSLE

    //FIRST DICE ROLL CHECK
    if (!checkIfDiceHaveBeenThrownBefore(firstDiceThrow)) {
        throwFirstDiceToDeterminePlayer();
    }

    setCurrentPlayerOnTurn(firstPlayerOnTurn); //Will create the current player on turn
    //value,and have a inactivePlayer  value for the one that isnt  on turn at the moment

    //IF NO MOVES AVAILABLE SWITCH PLAYERS WITHOUT THROWING DICE (player hit and all his 6 spaces are currently closed by enemy)
    if (!currentActivePlayer.hasMovesAvailable) {  //LOGIC NEEDS TO BE ADDED,WHEN  HAS MOVES AVAILABLE BECOMES FALSE- IT'S TRUE ON START,BUT CHANGES
        firstPlayerOnTurn = !firstPlayerOnTurn;
        play();
    }

    //THROW DICE
    throwDiceAndCheckMaxMovesForTurn();

    //IF HAS HIT CHECKERS
    while (currentActivePlayer.hasHitChecker) {

        if (!currentActivePlayer.hasHitChecker) {
            break;
        }

        //WHITE PLAYER - player 1
        if (currentActivePlayer.color === 'white') {
            //check if first dice number field is available
            if (board.fields[firstDice.number].availableForWhite) {
                if (board.fields[firstDice.number].length > 0 && board.fields[firstDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[25].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }
            if (board.fields[secondDice.number].availableForWhite) {
                if (board.fields[secondDice.number].length > 0 && board.fields[secondDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[25].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    hasNoMoves = true;
                    break;
                }
            }

        }

        //IF BLACK PLAYER - player 2

        else {
            //check if first dice number field is available
            if (board.fields[firstDice.number].availableForBlack) {
                if (board.fields[firstDice.number].length > 0 && board.fields[firstDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[0].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }
            if (board.fields[secondDice.number].availableForBlack) {
                if (board.fields[secondDice.number].length > 0 && board.fields[secondDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[0].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }

        }

    }

    if (currentPlayerMoves === maximumAllowedMovesInTurn) {
        play();
    }

    //CHECK IF PLAYER IS CURRENTLY TAKING CHECKERS

    if (currentPlayerMoves === maximumAllowedMovesInTurn) {
        play();
    }

    //JUST MOVE CHECKERS
    if (!checkIfPlayerIsMakingNormalMoves(currentActivePlayer, currentPlayerMoves, maximumAllowedMovesInTurn)) { //CHECK IF PLAYER HAS TO END TURN
        firstPlayerOnTurn = !firstPlayerOnTurn;
        play();
    }

    if (currentActivePlayer.color === 'white') {//white player - player1

        var isClickValidForStartPosition = false;

        while (!isClickValidForStartPosition) {
            //wait for mouse click for start position
            //get X and Y of clicked position
            //determine which board.fields place it is
            //check if that position contains his checkers  (isAvailable for white/black)
            //if no -> leave ,the  while loop will repeat itself and await new click for start position
            // if yes =>  isClickValidForStartPosition = true;
            //highlight which board places the checker from the start position can move to
            //wait for click to determine end position
            //get X and Y of clicked position
            //determine which board.fields place it is
            //if it is one of the possible places,considering the start position -> make the move and draw ,
            //else keep highligted and wait correct click for end position
            //currentPlayerMoves++
            //check is all possible moves for this player,for this turn are made and change players if so
        }

    }
    else {  //black player - player 2

    }
    draw();
}
<commit_msg>change current player bug fixed<commit_after>/// <reference path="GameDraw.js" />
/// <reference path="GameObjects.js" />
var GameEngine = ( function () {
    var board,
        players,
        dices,
        firstDiceThrow,
        currentPlayer,
        hasChosen,
    	indexOfChosenField,
    	indexOfTargetField;

    function start() {
        players = [];
        // playerOneName , playerTwoName - variables containing names from start screen
        players.push(Object.create(GameObjects.Player).init('First', 'white'));
        players.push(Object.create(GameObjects.Player).init('Second', 'black'));

        board = GameObjects.Board.init();

        // dices.rollDices() ; dices.usedNumber(number) ; dices.clearNumbers()
        dices = GameObjects.Dices.init();

        firstDiceThrow = true;

        GameDraw.initGame(board, players);
    }

    function clickedToRollDices() {
        if (firstDiceThrow) {
            firstDiceThrow = false;
            throwFirstDiceToDeterminePlayer();
            currentPlayer = players[0].isOnTurn ? players[0] : players[1];
        }
        if (dices.numbers.length === 0) {
            dices.rollDices();
            currentPlayer = setCurrentPlayerOnTurn();
        }
        GameDraw.updatePlayerNames(currentPlayer)
    }

    function updatePlayGround() {
        GameDraw.updatePlayGround(board);
    }

    function update(pressedField) {
        var canExtract = checkIfPlayerCanExtractPieces(currentPlayer, board);

    		// alert(hasChosen +' ' + indexOfChosenField +' ' +  indexOfTargetField +' ' +  canExtract)

    	if (hasChosen) {
    		indexOfTargetField = getIndexOfPossibleTargetFields(indexOfChosenField, currentPlayer, board, dices.numbers);

    		if (indexOfTargetField.indexOf(pressedField) < 0) {
    			return;
    		}

            board.movePiece (indexOfChosenField, pressedField);

            hasChosen = false;

            checkForPinnedPiece(board);

            dices.usedNumber(Math.abs(pressedField - board[indexOfChosenField]));

            if (dices.numbers.length === 0) {
            	alert ('No more moves. Next player turn');
            	setCurrentPlayerOnTurn();
            }

    	} else {
    		if (!canExtract) {
            	var possibleStartPositions = getIndexOfFieldsWithMovesAvailable(currentPlayer, board, dices.numbers);
            	// alert(possibleStartPositions)
            	if (!possibleStartPositions.length) {
                	alert('No moves');
                	dices.clearNumbers();
                	return;
            	} else if (possibleStartPositions.length === 1) {

                	if (board[possibleStartPositions[0]].pieces.length >= 5) {
                   		board[possibleStartPositions[0]].pieces[4].isChosen = true;
                	} else {
                    	board[possibleStartPositions[0]].pieces[board[possibleStartPositions[0]].pieces.length - 1].isChosen = true;
                	}

                	hasChosen = true;
                	indexOfChosenField = possibleStartPositions[0];
                	// alert(hasChosen + ' ' + indexOfChosenField)

            	} else {
            		if (possibleStartPositions.indexOf(pressedField) > -1) {
            			if (board[pressedField].pieces.length >= 5) {
                   			board[pressedField].pieces[4].isChosen = true;
                		} else {
                    		board[pressedField].pieces[board[pressedField].pieces.length - 1].isChosen = true;
                		}
            		} else {
            			return;
            		}

            		hasChosen = true;
                	indexOfChosenField = pressedField;
                	// alert(hasChosen + ' ' + indexOfChosenField)

            	}

        	} else {
        		// drago tuka move da tegli playera..

        	}
    	}

        updatePlayGround();

        if (!currentPlayer.countOfPieces) {
            alert(currentPlayer.name + ' WINS!!!')
        }
    }

    // Event targets can be document elements, the document itself, window or any other object that supports events.
    //function addListenersToPossibleGameFields(gameFields) {
    //    var i,
    //        len,
    //        currentFieldIndex,
    //        currentField;
    //
    //    for (i = 0, len = gameFields.length; i < len; i += 1) {
    //        currentFieldIndex = gameFields[i];
    //        currentField = board[currentFieldIndex];
    //        currentField.addEventListener('mousedown', selectAndPaintLastPiece(currentField));
    //    }
    //}
    //
    //function selectAndPaintLastPiece(gameField) {
    //    var lengthOfPiecesInField = gameField.pieces.length;
    //    gameField.pieces[lengthOfPiecesInField - 1].isChosen = true;
    //}

    function throwFirstDiceToDeterminePlayer() {
        dices.rollDices();
        if (dices.numbers[dices.numbers.length - 2] > dices.numbers[dices.numbers.length - 1]) {
            players[0].isOnTurn = true;
        } else if (dices.numbers[dices.numbers.length - 2] < dices.numbers[dices.numbers.length - 1]) {
            players[1].isOnTurn = true;
        } else {
            firstDiceThrow = true;
            dices.clearNumbers();
            clickedToRollDices();
        }
    }

    function setCurrentPlayerOnTurn() {
        if (players[0].isOnTurn) {
            players[0].isOnTurn = false;
            players[1].isOnTurn = true;
            return players[1];
        } else {
            players[0].isOnTurn = true;
            players[1].isOnTurn = false;
            return players[0];
        }
    }

    function getDices() {
        return dices;
    }

    return {
        start: start,
        update: update,
        clickedToRollDices: clickedToRollDices,
        dices: getDices
    };
}() );

function getIndexOfFieldsWithMovesAvailable(player, board, numbers) {
    var direction,
        i, j,
        result = [],
        color = player.color,
        index;

    color = color.substring(0, 1).toUpperCase() + color.substring(1);

    if (color.toLowerCase() === 'white') {
        direction = 1;

        if (board[0].pieces.length) {
            for (j = 0; j < numbers.length; j += 1) {
                if (board[0 + numbers[j] * direction]['availableFor' + color]) {
                    return [0];
                }
            }

            return result;
        }
    } else {
        direction = -1;

        if (board[board.length - 1].pieces.length) {
            for (j = 0; j < numbers.length; j += 1) {
                if (board[board.length - 1 + numbers[j] * direction]['availableFor' + color]) {
                    return [board.length - 1];
                }
            }

            return result;
        }
    }

    for (i = 1, len = board.length; i < board.length - 1; i += 1) {
        if (board[i].pieces.length > 0 && board[i].pieces[0].color === color.toLowerCase()) {
            for (j = 0; j < numbers.length; j += 1) {
            	index = i + numbers[j] * direction;
                if (1 < index  && index < 24 && board[index]['availableFor' + color]) {
                    result.push(i);
                    break;
                }
            }
        }
    }

    return result;
}

function getIndexOfPossibleTargetFields(markedIndex, player, board, numbers) {
    // alert(markedIndex + ' ' + numbers)

    var color = player.color,
        i,
        result = [],
        direction;

    if (color === 'white') {
        direction = 1
    } else {
        direction = -1
    }

    color = color.substring(0, 1).toUpperCase() + color.substring(1);

    for (i = 0; i < numbers.length; i++) {
        if (board[markedIndex + numbers[i] * direction]['availableFor' + color]) {
            result.push(markedIndex + numbers[i] * direction);
        }
    }

    return result;
}

function checkForPinnedPiece(board) {
    var i,
        len = board.length;

    for (i = 1; i < len - 1; i += 1) {
        if (board[i].length === 2 && board[i].pieces[0].color !== board[i].pieces[1].color) {
            var shifted = board[i].pieces.shift();
            if (shifted.color === 'white') {
                board[0].push(shifted);
                return;
            } else {
                board[len - 1].push(shifted);
                return;
            }
        }
    }
}

function checkIfPlayerCanExtractPieces(player, board) {
    var color = player.color,
        i,
        count = 0;

    if (color === 'white') {
        for (i = 19; i <= 24; i += 1) {
            if (board[i].pieces.length > 0 && board[i].pieces[0].color === color) {
                count += board[i].pieces.length;
            }
        }
    } else {
        for (i = 1; i <= 6; i += 1) {
            if (board[i].pieces.length > 0 && board[i].pieces[0].color === color) {
                count += board[i].pieces.length;
            }
        }
    }

    return count === player.countOfPieces;
}

// // All events will call GameEngine.Update() and GameDraw.Update().

//// Logic to add
function checkIfPlayerIsMakingNormalMoves(currentActivePlayer, currentPlayerMoves, maximumAllowedMovesInTurn) {
    if (currentPlayerMoves < maximumAllowedMovesInTurn && !currentActivePlayer.hasHitChecker && !currentActivePlayer.canTakeChecker) {
        return true;
    }
    return false;
}

function play() {

    var maximumAllowedMovesInTurn;
    var currentActivePlayer;
    var inactivePlayer;
    var currentPlayerMoves = 0;   // DA SE IZNESAT TEZI PROMENLIVI GORE POSLE

    //FIRST DICE ROLL CHECK
    if (!checkIfDiceHaveBeenThrownBefore(firstDiceThrow)) {
        throwFirstDiceToDeterminePlayer();
    }

    setCurrentPlayerOnTurn(firstPlayerOnTurn); //Will create the current player on turn
    //value,and have a inactivePlayer  value for the one that isnt  on turn at the moment

    //IF NO MOVES AVAILABLE SWITCH PLAYERS WITHOUT THROWING DICE (player hit and all his 6 spaces are currently closed by enemy)
    if (!currentActivePlayer.hasMovesAvailable) {  //LOGIC NEEDS TO BE ADDED,WHEN  HAS MOVES AVAILABLE BECOMES FALSE- IT'S TRUE ON START,BUT CHANGES
        firstPlayerOnTurn = !firstPlayerOnTurn;
        play();
    }

    //THROW DICE
    throwDiceAndCheckMaxMovesForTurn();

    //IF HAS HIT CHECKERS
    while (currentActivePlayer.hasHitChecker) {

        if (!currentActivePlayer.hasHitChecker) {
            break;
        }

        //WHITE PLAYER - player 1
        if (currentActivePlayer.color === 'white') {
            //check if first dice number field is available
            if (board.fields[firstDice.number].availableForWhite) {
                if (board.fields[firstDice.number].length > 0 && board.fields[firstDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[25].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }
            if (board.fields[secondDice.number].availableForWhite) {
                if (board.fields[secondDice.number].length > 0 && board.fields[secondDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[25].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    hasNoMoves = true;
                    break;
                }
            }

        }

        //IF BLACK PLAYER - player 2

        else {
            //check if first dice number field is available
            if (board.fields[firstDice.number].availableForBlack) {
                if (board.fields[firstDice.number].length > 0 && board.fields[firstDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[0].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }
            if (board.fields[secondDice.number].availableForBlack) {
                if (board.fields[secondDice.number].length > 0 && board.fields[secondDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[0].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }

        }

    }

    if (currentPlayerMoves === maximumAllowedMovesInTurn) {
        play();
    }

    //CHECK IF PLAYER IS CURRENTLY TAKING CHECKERS

    if (currentPlayerMoves === maximumAllowedMovesInTurn) {
        play();
    }

    //JUST MOVE CHECKERS
    if (!checkIfPlayerIsMakingNormalMoves(currentActivePlayer, currentPlayerMoves, maximumAllowedMovesInTurn)) { //CHECK IF PLAYER HAS TO END TURN
        firstPlayerOnTurn = !firstPlayerOnTurn;
        play();
    }

    if (currentActivePlayer.color === 'white') {//white player - player1

        var isClickValidForStartPosition = false;

        while (!isClickValidForStartPosition) {
            //wait for mouse click for start position
            //get X and Y of clicked position
            //determine which board.fields place it is
            //check if that position contains his checkers  (isAvailable for white/black)
            //if no -> leave ,the  while loop will repeat itself and await new click for start position
            // if yes =>  isClickValidForStartPosition = true;
            //highlight which board places the checker from the start position can move to
            //wait for click to determine end position
            //get X and Y of clicked position
            //determine which board.fields place it is
            //if it is one of the possible places,considering the start position -> make the move and draw ,
            //else keep highligted and wait correct click for end position
            //currentPlayerMoves++
            //check is all possible moves for this player,for this turn are made and change players if so
        }

    }
    else {  //black player - player 2

    }
    draw();
}
<|endoftext|>


<commit_before>import mapValues from 'lodash.mapvalues'
import createReducer from '../utils/create-reducer'
import {
  SELECT_CORPUS,
  FETCH_CORPORA_REQUEST,
  FETCH_CORPORA_SUCCESS,
  FETCH_SERVER_STATUS_SUCCESS,
  FETCH_CORPUS_STATUS_SUCCESS
} from '../actions/corpora'
import {
  FETCH_TAGS_CATEGORIES_SUCCESS,
  ADD_TAGS_CATEGORY_SUCCESS
} from '../actions/tags'

const initialState = {
  // TODO: transform it in a array here?
  list: {}, // [corpusId]: corpus
  selected: null,
  status: null // status of selected corpus
}

export default createReducer(initialState, {
  [FETCH_CORPORA_REQUEST]: (state) => ({
    ...state,
    list: {},
    selected: null
  }),
  [FETCH_CORPORA_SUCCESS]: (state, { corpora }) => ({
    ...state,
    // tagsCategories is maintained internally, it does not come from API,
    // we intiialize it to 'FREETAGS' but the full list will come from a call to fetchTagsCategories
    list: mapValues(corpora, (c) => ({ ...c, tagsCategories: ['FREETAGS'] })),
    selected: null
  }),

  [FETCH_SERVER_STATUS_SUCCESS]: (state, { status }) => ({
    ...state,
    status
  }),

  [FETCH_CORPUS_STATUS_SUCCESS]: (state, { corpus, status }) => ({
    ...state,
    selected: corpus,
    status
  }),

  [SELECT_CORPUS]: (state, { corpus }) => ({
    ...state,
    selected: corpus
  }),

  [FETCH_TAGS_CATEGORIES_SUCCESS]: updateTagsCategories((state, { corpusId, categories }) => {
    const originalCategories = (state.list[corpusId] || {}).tagsCategories || []
    if (categories.join(',') === originalCategories.join(',')) {
      return false
    }

    return ['FREETAGS'].concat(categories.filter((c) => c !== 'FREETAGS'))
  }),

  [ADD_TAGS_CATEGORY_SUCCESS]: updateTagsCategories((state, { corpusId, category }) => {
    const originalCategories = (state.list[corpusId] || {}).tagsCategories || []
    if (originalCategories.indexOf(category) !== -1) {
      return state
    }

    return originalCategories.concat([category])
  })
})

function updateTagsCategories (getTagsCategories) {
  return (state, payload) => {
    const tagsCategories = getTagsCategories(state, payload)
    if (!tagsCategories) {
      return state
    }

    const { corpusId } = payload
    const selected = (state.selected && state.selected.corpus_id === corpusId)
      ? { ...state.selected, tagsCategories }
      : state.selected
    const list = state.list[corpusId]
      ? { ...state.list, [corpusId]: { ...state.list[corpusId], tagsCategories } }
      : state.list

    return {
      ...state,
      selected,
      list
    }
  }
}
<commit_msg>style: indexOf → includes<commit_after>import mapValues from 'lodash.mapvalues'
import createReducer from '../utils/create-reducer'
import {
  SELECT_CORPUS,
  FETCH_CORPORA_REQUEST,
  FETCH_CORPORA_SUCCESS,
  FETCH_SERVER_STATUS_SUCCESS,
  FETCH_CORPUS_STATUS_SUCCESS
} from '../actions/corpora'
import {
  FETCH_TAGS_CATEGORIES_SUCCESS,
  ADD_TAGS_CATEGORY_SUCCESS
} from '../actions/tags'

const initialState = {
  // TODO: transform it in a array here?
  list: {}, // [corpusId]: corpus
  selected: null,
  status: null // status of selected corpus
}

export default createReducer(initialState, {
  [FETCH_CORPORA_REQUEST]: (state) => ({
    ...state,
    list: {},
    selected: null
  }),
  [FETCH_CORPORA_SUCCESS]: (state, { corpora }) => ({
    ...state,
    // tagsCategories is maintained internally, it does not come from API,
    // we intiialize it to 'FREETAGS' but the full list will come from a call to fetchTagsCategories
    list: mapValues(corpora, (c) => ({ ...c, tagsCategories: ['FREETAGS'] })),
    selected: null
  }),

  [FETCH_SERVER_STATUS_SUCCESS]: (state, { status }) => ({
    ...state,
    status
  }),

  [FETCH_CORPUS_STATUS_SUCCESS]: (state, { corpus, status }) => ({
    ...state,
    selected: corpus,
    status
  }),

  [SELECT_CORPUS]: (state, { corpus }) => ({
    ...state,
    selected: corpus
  }),

  [FETCH_TAGS_CATEGORIES_SUCCESS]: updateTagsCategories((state, { corpusId, categories }) => {
    const originalCategories = (state.list[corpusId] || {}).tagsCategories || []
    if (categories.join(',') === originalCategories.join(',')) {
      return false
    }

    return ['FREETAGS'].concat(categories.filter((c) => c !== 'FREETAGS'))
  }),

  [ADD_TAGS_CATEGORY_SUCCESS]: updateTagsCategories((state, { corpusId, category }) => {
    const originalCategories = (state.list[corpusId] || {}).tagsCategories || []
    if (originalCategories.includes(category)) {
      return state
    }

    return originalCategories.concat([category])
  })
})

function updateTagsCategories (getTagsCategories) {
  return (state, payload) => {
    const tagsCategories = getTagsCategories(state, payload)
    if (!tagsCategories) {
      return state
    }

    const { corpusId } = payload
    const selected = (state.selected && state.selected.corpus_id === corpusId)
      ? { ...state.selected, tagsCategories }
      : state.selected
    const list = state.list[corpusId]
      ? { ...state.list, [corpusId]: { ...state.list[corpusId], tagsCategories } }
      : state.list

    return {
      ...state,
      selected,
      list
    }
  }
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import AuthenticatedRoute from 'cargo/mixins/authenticated-route';

export default Ember.Route.extend(AuthenticatedRoute, {
    data: {},

    setupController(controller, model) {
        this._super(controller, model);

        controller.set('fetchingFeed', true);
        controller.set('myCrates', this.get('data.myCrates'));
        controller.set('myFollowing', this.get('data.myFollowing'));

        if (!controller.get('loadingMore')) {
            controller.set('myFeed', []);
            controller.send('loadMore');
        }
    },

    model() {
        return this.session.get('currentUser');
    },

    afterModel(user) {
      let myCrates = this.store.find('crate', {
        user_id: user.get('id')
      });

      let myFollowing = this.store.find('crate', {
        following: 1
      });

      return Ember.RSVP.hash({
        myCrates,
        myFollowing
      }).then((hash) => this.set('data', hash) );
    }
});
<commit_msg>routes/dashboard: Replace deprecated find() with query() call<commit_after>import Ember from 'ember';
import AuthenticatedRoute from 'cargo/mixins/authenticated-route';

export default Ember.Route.extend(AuthenticatedRoute, {
    data: {},

    setupController(controller, model) {
        this._super(controller, model);

        controller.set('fetchingFeed', true);
        controller.set('myCrates', this.get('data.myCrates'));
        controller.set('myFollowing', this.get('data.myFollowing'));

        if (!controller.get('loadingMore')) {
            controller.set('myFeed', []);
            controller.send('loadMore');
        }
    },

    model() {
        return this.session.get('currentUser');
    },

    afterModel(user) {
      let myCrates = this.store.query('crate', {
        user_id: user.get('id')
      });

      let myFollowing = this.store.query('crate', {
        following: 1
      });

      return Ember.RSVP.hash({
        myCrates,
        myFollowing
      }).then((hash) => this.set('data', hash) );
    }
});
<|endoftext|>


<commit_before>'use strict'
let R = require('ramda')
let S = require('underscore.string.fp')
let logger = require('js-logger-aknudsen').get('serverRendering')
let immutable = require('immutable')
let immstruct = require('immstruct')
let ReactDomServer = require('react-dom/server')
let Boom = require('boom')
let url = require('url')

let {normalizePath,} = require('../urlUtils')
let explore = require('../views/explore')
let login = require('../views/login')
let userProfile = require('../views/userProfile/userProfile')
let App = require('../components/app')
let {createRouterState, updateRouterState,} = require('../sharedRouting')
let routeMap = require('../routeMap')
let {getEnvParam,} = require('./environment')

let getInitialRouterState = (request, workshopsUri) => {
  let currentPath = request.path
  logger.debug(`Computing initial router state, path is '${currentPath}'`)
  let navItems = R.map((navItem) => {
    let path = !navItem.isExternal ? normalizePath(navItem.path) : navItem.path
    let isSelected = path === currentPath
    logger.debug(`Nav item '${navItem.text}' is selected: ${isSelected}, ${path}`)
    return R.merge(navItem, {
      path,
      isSelected,
    })
  }, [
    {path: '/', text: 'Explore',},
    {path: '/create', text: 'Create',},
    {path: workshopsUri, text: 'Workshops', isExternal: true,},
    {path: 'http://forums.muzhack.com', text: 'Forums', isExternal: true,},
    {path: '/about', text: 'About',},
  ])
  if (!R.any((navItem) => {return navItem.isSelected}, navItems)) {
    logger.debug(`Defaulting to root nav item being selected`)
    let navItem = R.find((navItem) => {return navItem.path === '/'}, navItems)
    navItem.isSelected = true
  }
  return immutable.fromJS({
    currentPath,
    isLoading: false,
    navItems,
  })
}

let renderIndex = (request, reply) => {
  logger.debug(`Rendering SPA index, user is logged in: ${request.auth.credentials != null}`)
  immstruct.clear()
  let appUri = getEnvParam('APP_URI')
  let appUrlObj = url.parse(appUri)
  let fbAppId = getEnvParam('FB_APP_ID')
  let workshopsUri = `${appUrlObj.protocol}//workshops.${appUrlObj.host}`
  let cursor = immstruct('state', {
    metaHtmlAttributes: {
      'fb:app_id': fbAppId,
      'og:type': 'website',
      'og:title': 'MuzHack',
      'og:description': 'MuzHack is an online hub for the publishing of music hardware projects.',
    },
    search: '',
    appUri,
    login: login.createState(),
    explore: explore.createState(),
    userProfile: userProfile.createState(),
    router: getInitialRouterState(request, workshopsUri),
    loggedInUser: request.auth.isAuthenticated ? request.auth.credentials : null,
    trelloKey: getEnvParam('TRELLO_KEY'),
    stripeKey: getEnvParam('STRIPE_PUBLISHABLE_KEY'),
    gitHubClientId: getEnvParam('GITHUB_CLIENT_ID'),
    fbAppId,
  }).cursor()
  cursor = cursor.mergeDeep({
    router: createRouterState(routeMap),
  })
  return updateRouterState(cursor, request.path, null, request.query)
    .then(([cursor, newState,]) => {
      logger.debug(`Got new state:`, newState)
      cursor = cursor.mergeDeep(R.merge(newState, {
        router: {
          isLoading: false,
        },
      }))
      let initialState = cursor.toJS()
      logger.debug(`Successfully loaded initial state:`, initialState)
      let renderOptions = {
        initialState: JSON.stringify(initialState),
        metaAttributes: R.map(([property, content,]) => {
          return {
            property,
            content,
          }
        }, R.toPairs(initialState.metaHtmlAttributes)),
      }
      if (initialState.router.shouldRenderServerSide) {
        logger.debug(`Rendering on server - current state:`, cursor.toJS())
        let reactHtml = ReactDomServer.renderToString(App(cursor))
        logger.debug(`Finished rendering`)
        reply.view('serverSideIndex', R.merge(renderOptions, {
          reactHtml,
        }))
      } else {
        logger.debug(`Not rendering JavaScript on server side`)
        reply.view('nonServerSideIndex', renderOptions)
      }
    }, (error) => {
      if (error.statusCode === 404 || error.type === 'notFound') {
        logger.debug(`Current route not recognized`)
        reply(Boom.notFound())
      } else {
        logger.error(`Failed to load initial state: '${error}':`, error.stack)
        reply(Boom.badImplementation())
      }
    })
}

module.exports = {
  renderIndex,
}
<commit_msg>Disable Workshops nav item for now<commit_after>'use strict'
let R = require('ramda')
let S = require('underscore.string.fp')
let logger = require('js-logger-aknudsen').get('serverRendering')
let immutable = require('immutable')
let immstruct = require('immstruct')
let ReactDomServer = require('react-dom/server')
let Boom = require('boom')
let url = require('url')

let {normalizePath,} = require('../urlUtils')
let explore = require('../views/explore')
let login = require('../views/login')
let userProfile = require('../views/userProfile/userProfile')
let App = require('../components/app')
let {createRouterState, updateRouterState,} = require('../sharedRouting')
let routeMap = require('../routeMap')
let {getEnvParam,} = require('./environment')

let getInitialRouterState = (request, workshopsUri) => {
  let currentPath = request.path
  logger.debug(`Computing initial router state, path is '${currentPath}'`)
  let navItems = R.map((navItem) => {
    let path = !navItem.isExternal ? normalizePath(navItem.path) : navItem.path
    let isSelected = path === currentPath
    logger.debug(`Nav item '${navItem.text}' is selected: ${isSelected}, ${path}`)
    return R.merge(navItem, {
      path,
      isSelected,
    })
  }, [
    {path: '/', text: 'Explore',},
    {path: '/create', text: 'Create',},
    // TODO: Enable
    // {path: workshopsUri, text: 'Workshops', isExternal: true,},
    {path: 'http://forums.muzhack.com', text: 'Forums', isExternal: true,},
    {path: '/about', text: 'About',},
  ])
  if (!R.any((navItem) => {return navItem.isSelected}, navItems)) {
    logger.debug(`Defaulting to root nav item being selected`)
    let navItem = R.find((navItem) => {return navItem.path === '/'}, navItems)
    navItem.isSelected = true
  }
  return immutable.fromJS({
    currentPath,
    isLoading: false,
    navItems,
  })
}

let renderIndex = (request, reply) => {
  logger.debug(`Rendering SPA index, user is logged in: ${request.auth.credentials != null}`)
  immstruct.clear()
  let appUri = getEnvParam('APP_URI')
  let appUrlObj = url.parse(appUri)
  let fbAppId = getEnvParam('FB_APP_ID')
  let workshopsUri = `${appUrlObj.protocol}//workshops.${appUrlObj.host}`
  let cursor = immstruct('state', {
    metaHtmlAttributes: {
      'fb:app_id': fbAppId,
      'og:type': 'website',
      'og:title': 'MuzHack',
      'og:description': 'MuzHack is an online hub for the publishing of music hardware projects.',
    },
    search: '',
    appUri,
    login: login.createState(),
    explore: explore.createState(),
    userProfile: userProfile.createState(),
    router: getInitialRouterState(request, workshopsUri),
    loggedInUser: request.auth.isAuthenticated ? request.auth.credentials : null,
    trelloKey: getEnvParam('TRELLO_KEY'),
    stripeKey: getEnvParam('STRIPE_PUBLISHABLE_KEY'),
    gitHubClientId: getEnvParam('GITHUB_CLIENT_ID'),
    fbAppId,
  }).cursor()
  cursor = cursor.mergeDeep({
    router: createRouterState(routeMap),
  })
  return updateRouterState(cursor, request.path, null, request.query)
    .then(([cursor, newState,]) => {
      logger.debug(`Got new state:`, newState)
      cursor = cursor.mergeDeep(R.merge(newState, {
        router: {
          isLoading: false,
        },
      }))
      let initialState = cursor.toJS()
      logger.debug(`Successfully loaded initial state:`, initialState)
      let renderOptions = {
        initialState: JSON.stringify(initialState),
        metaAttributes: R.map(([property, content,]) => {
          return {
            property,
            content,
          }
        }, R.toPairs(initialState.metaHtmlAttributes)),
      }
      if (initialState.router.shouldRenderServerSide) {
        logger.debug(`Rendering on server - current state:`, cursor.toJS())
        let reactHtml = ReactDomServer.renderToString(App(cursor))
        logger.debug(`Finished rendering`)
        reply.view('serverSideIndex', R.merge(renderOptions, {
          reactHtml,
        }))
      } else {
        logger.debug(`Not rendering JavaScript on server side`)
        reply.view('nonServerSideIndex', renderOptions)
      }
    }, (error) => {
      if (error.statusCode === 404 || error.type === 'notFound') {
        logger.debug(`Current route not recognized`)
        reply(Boom.notFound())
      } else {
        logger.error(`Failed to load initial state: '${error}':`, error.stack)
        reply(Boom.badImplementation())
      }
    })
}

module.exports = {
  renderIndex,
}
<|endoftext|>


<commit_before>#! /usr/bin/env node

// Ref: http://docopt.org/

/*

Chain commands
Positional arguments
Named arguments
Required arguments
Limit arguments options
Set option type (e.g. string, number)
Set number of options (exact, min, & max)
Nest commands & arguments
Adjust kwarg scope (global / children) (Help and Version classes for globals?)
Allow kwarg booleans without values to be true e.g. --thing false (false becomes the next arg)

Return args descriptor with usefull functions like getIn, command, arg, etc

*/

'use strict';

(function () {

  var jargs = require('../src/index');
  var Command = jargs.Command;
  var KWArg = jargs.KWArg;
  var Flag = jargs.Flag;
  var Arg = jargs.Arg;

  var root = jargs.collect(
    Command(
      'init',
      null,
      Arg(
        'path',
        {required: true, type: 'string'}
      )
    ),
    Command(
      'build',
      null,
      KWArg(
        'config',
        {alias: 'c', type: 'string', default: 'config.json'}
      )
    ),
    Flag(
      'help',
      {alias: 'h', type: 'boolean', description: 'Displays help & usage info'}
    ),
    Flag(
      'version',
      {alias: 'v', type: 'boolean', description: 'Displays version number'}
    )
  );

  /*

  var initCommand = jarg.command('init');

  // command.value is a boolean like a flag, if false it was not called
  if (initCommand.value) {

  }

  */

  var command = root.command();

  if (command.exists()) {
    switch (command.name()) {
      case 'init':
        console.log('init called');
        break;
      default:
        console.log('Unknown command \'' + command.name() + '\'');
    }
  } else {
    if (root.kwarg('output').exists()) {
      console.log(root.kwarg('output').value());
    }

    if (root.flag('verbose').exists()) {
      console.log(root.flag('verbose').value());
    }

    if (root.arg('input').exists()) {
      console.log(root.arg('input').value());
    }
  }
})();
<commit_msg>Update example<commit_after>#! /usr/bin/env node

// Ref: http://docopt.org/

/*

Chain commands
Positional arguments
Named arguments
Required arguments
Limit arguments options
Set option type (e.g. string, number)
Set number of options (exact, min, & max)
Nest commands & arguments
Adjust kwarg scope (global / children) (Help and Version classes for globals?)
Allow kwarg booleans without values to be true e.g. --thing false (false becomes the next arg)

Return args descriptor with usefull functions like getIn, command, arg, etc

*/

'use strict';

(function () {

  var jargs = require('../src/index');
  var Command = jargs.Command;
  // var KWArg = jargs.KWArg;
  var Flag = jargs.Flag;
  var Arg = jargs.Arg;

  var root = jargs.collect(
    Command(
      'init',
      {description: 'Create npm package'}
    ),
    Command(
      'install',
      {alias: 'i', description: 'Install dependencies'},
      Arg(
        'lib'
      ),
      Flag(
        'save',
        {alias: 'S'}
      ),
      Flag(
        'save-dev',
        {alias: 'D'}
      ),
      Flag(
        'save-exact',
        {alias: 'E'}
      ),
      Flag(
        'save-optional',
        {alias: 'O'}
      )
    ),
    Command(
      'run',
      {alias: 'run-scripts', description: 'Run a script in the package'},
      Arg(
        'command'
      )
    ),
    Flag(
      'help',
      {alias: 'h', description: 'Displays help & usage info'}
    ),
    Flag(
      'version',
      {alias: 'v', description: 'Displays version number'}
    )
  );

  if (root.command) {
    switch (root.command.name) {
      case 'init':
        // Do init stuff
        break;
      case 'install':
        // Do install stuff
        break;
      case 'run':
        // Do run stuff
        break;
      default:
        // Should never get here
    }
  } else if (root.flags.help) {
    // Display help
  } else if (root.flags.version) {
    // Display version
  }

})();
<|endoftext|>


<commit_before>(function() {

Dagaz.Model.WIN_CNT = 49;

Dagaz.View.DX       = 0;
Dagaz.View.DY       = 0;
Dagaz.View.MX       = 25;

var cache = [];
var size  = 15;

var isMikul = false;
var isMatiBela = false;

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name == "dakon-extension") {
      if (value == "mikul") isMikul = true;
      if (value == "mati-bela") isMatiBela = true;
  } else {
      checkVersion(design, name, value);
  }
}

var createPiece = function(design, player, value) {
  if (value != 0) {
      if (!_.isUndefined(cache[player]) && !_.isUndefined(cache[player][value])) {
          return cache[player][value];
      }
      var r = Dagaz.Model.createPiece(0, player).setValue(0, value);
      if (_.isUndefined(cache[player])) {
          cache[player] = [];
      }
      cache[player][value] = r;
      return r;
  } else {
      return null;
  }
}

var toReserve = function(design, board, player, move, cnt) {
  var pos = design.navigate(player, 0, 2);
  if ((cnt > 0) && (pos !== null)) {
      piece = board.getPiece(pos);
      if (piece === null) {
          piece = Dagaz.Model.createPiece(0, player);
          piece = piece.setValue(0, cnt);
          move.dropPiece(pos, piece);
      } else {
          cnt += Math.abs(+piece.getValue(0));
          piece = piece.setValue(0, cnt);
          move.movePiece(pos, pos, piece);
      }
  }
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  _.each(board.moves, function(move) {
      var isPool = false;
      var fr = 0;
      if (move.isSimpleMove()) {
          var pos = move.actions[0][0][0];
          var piece = board.getPiece(pos);
          var cnt = Math.abs(+piece.getValue(0));
          if (_.isUndefined(cache[piece.player])) {
              cache[piece.player] = [];
              cache[piece.player][cnt] = piece;
          }
          var result = [];
          result.push(0);
          for (var ix = 1; cnt > 0; cnt--, ix++) {
               pos = design.navigate(board.player, pos, 0);
               if (pos === null) {
                   move.failed = true;
                   return;
               }
               if (ix >= size) {
                   ix = 0;
               }
               piece = board.getPiece(pos);
               if (ix < result.length) {
                   result[ix]++;
               } else {
                   if (piece === null) {
                       result.push(1);
                   } else {
                       result.push(Math.abs(+piece.getValue(0)) + 1);
                   }
               }
          }
          ix--;
          var captured = [];
          isPool = design.inZone(1, board.player, pos);
          if ((result[ix] > 1) || isPool) {
              result[ix] = -result[ix];
          } else {
              if (!isPool && design.inZone(0, board.player, pos)) {
                  pos = design.navigate(board.player, pos, 4);
                  if (pos !== null) {
                      piece = board.getPiece(pos);
                      if ((piece !== null) || (result.length == size)) {
                          captured.push(pos);
                          if (isMatiBela) {
                              fr++;
                              result[ix] = 0;
                          }
                      }
                  }
              }
              // TODO: mikul

          }
          var pos = move.actions[0][0][0];
          for (var ix = 0; ix < result.length; ix++) {
               // TODO: use captured

               var player = board.player;
               if (!design.inZone(0, board.player, pos) && (result[ix] > 0)) {
                   player = design.nextPlayer(player);
               }
               var piece = createPiece(design, player, result[ix]);
               if (result[ix] == 0) {
                   if (ix > 0) {
                       move.capturePiece(pos);
                       if (ix == 1) {
                           move.actions[0][2] = [ Dagaz.Model.createPiece(1, board.player) ];
                       }
                   }
               } else {
                   if (piece !== null) {
                       if (ix == 1) {
                           move.actions[0][2] = [ piece ];
                       } else {
                           if ((ix > 0) && (board.getPiece(pos) !== null)) {
                               move.movePiece(pos, pos, piece);
                           } else {
                               move.dropPiece(pos, piece);
                           }
                       }
                   }
               }
               pos = design.navigate(board.player, pos, 0);
          }
          _.each(captured, function(pos) {
               piece = board.getPiece(pos);
               if (piece !== null) {
                   fr = Math.abs(+piece.getValue(0));
                   move.capturePiece(pos);
               }
          });
          if (!isPool && (fr == 0)) {
               _.each(design.allPositions(), function(pos) {
                    if (design.inZone(1, board.player, pos)) {
                        var piece = board.getPiece(pos);
                        if (piece !== null) {
                            var value = +piece.getValue(0);
                            if (value < 0) {
                                piece = piece.setValue(0, -value);
                                move.movePiece(pos, pos, piece);
                            }
                        }
                    }
               });
          }
          toReserve(design, board, board.player, move, fr);
      }
  });
  var ko = [];
  _.each(design.allPositions(), function(pos) {
      if (design.inZone(1, board.player, pos)) return;
      var piece = board.getPiece(pos);
      if (piece !== null) {
          var value = +piece.getValue(0);
          if ((value !== null) && (value < -1)) {
              ko.push(pos);
          }
      }
  });
  if (ko.length > 0) {
      board.ko = ko;
  }
  CheckInvariants(board);
}

})();
<commit_msg>Dakon (extension)<commit_after>(function() {

Dagaz.Model.WIN_CNT = 49;

Dagaz.View.DX       = 0;
Dagaz.View.DY       = 0;
Dagaz.View.MX       = 25;

var cache = [];
var size  = 15;

var isMikul = false;
var isMatiBela = false;

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name == "dakon-extension") {
      if (value == "mikul") isMikul = true;
      if (value == "mati-bela") isMatiBela = true;
  } else {
      checkVersion(design, name, value);
  }
}

var createPiece = function(design, player, value) {
  if (value != 0) {
      if (!_.isUndefined(cache[player]) && !_.isUndefined(cache[player][value])) {
          return cache[player][value];
      }
      var r = Dagaz.Model.createPiece(0, player).setValue(0, value);
      if (_.isUndefined(cache[player])) {
          cache[player] = [];
      }
      cache[player][value] = r;
      return r;
  } else {
      return null;
  }
}

var addReserve = function(x, y) {
  var r = Math.abs(x) + y;
  if (x < 0) {
      return -r;
  } else {
      return r;
  }
}

var toReserve = function(design, board, player, move, cnt) {
  var pos = design.navigate(player, 0, 2);
  if ((cnt != 0) && (pos !== null)) {
      piece = board.getPiece(pos);
      if (piece === null) {
          piece = Dagaz.Model.createPiece(0, player);
          piece = piece.setValue(0, cnt);
          move.dropPiece(pos, piece);
      } else {
          cnt = addReserve(cnt, Math.abs(+piece.getValue(0)));
          piece = piece.setValue(0, cnt);
          move.movePiece(pos, pos, piece);
      }
  }
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  _.each(board.moves, function(move) {
      var isPool = false;
      var fr = 0;
      if (move.isSimpleMove()) {
          var pos = move.actions[0][0][0];
          if (design.inZone(1, board.player, pos)) {
              move.failed = true;
              return;
          }
          var piece = board.getPiece(pos);
          var cnt = Math.abs(+piece.getValue(0));
          if (_.isUndefined(cache[piece.player])) {
              cache[piece.player] = [];
              cache[piece.player][cnt] = piece;
          }
          var result = [];
          result.push(0);
          for (var ix = 1; cnt > 0; cnt--, ix++) {
               pos = design.navigate(board.player, pos, 0);
               if (pos === null) {
                   move.failed = true;
                   return;
               }
               if (ix >= size) {
                   ix = 0;
               }
               piece = board.getPiece(pos);
               if (ix < result.length) {
                   result[ix]++;
               } else {
                   if (piece === null) {
                       result.push(1);
                   } else {
                       result.push(Math.abs(+piece.getValue(0)) + 1);
                   }
               }
          }
          ix--;
          var captured = [];
          isPool = design.inZone(1, board.player, pos);
          if ((result[ix] > 1) || isPool) {
              result[ix] = -result[ix];
          } else {
              if (!isPool) {
                  if (design.inZone(0, board.player, pos)) {
                      pos = design.navigate(board.player, pos, 4);
                      if (pos !== null) {
                          piece = board.getPiece(pos);
                          if ((piece !== null) || (result.length == size)) {
                              captured.push(pos);
                              if (isMatiBela) {
                                  fr++;
                                  result[ix] = 0;
                              }
                          }
                      }
                  } else {
                      var p = design.navigate(board.player, pos, 0);
                      var q = design.navigate(board.player, pos, 6);
                      if (isMikul && (p !== null) && (q !== null) && (result.length > 1)) {
                          var piece = board.getPiece(p);
                          if (Math.abs(+piece.getValue(0)) == Math.abs(result[ix - 1])) {
                              captured.push(p);
                              captured.push(q);
                              fr++;
                              result[ix] = 0;
                          }
                      }
                  }
              }
          }
          var pos = move.actions[0][0][0];
          for (var ix = 0; ix < result.length; ix++) {
               if (_.indexOf(captured, pos) >= 0) {
                   fr += result[ix];
                   result[ix] = 0;
                   captured = _.without(captured, pos);
               }
               pos = design.navigate(board.player, pos, 0);
          }
          _.each(captured, function(pos) {
               piece = board.getPiece(pos);
               if (piece !== null) {
                   fr += Math.abs(+piece.getValue(0));
                   move.capturePiece(pos);
               }
          });
          var pos = move.actions[0][0][0];
          for (var ix = 0; ix < result.length; ix++) {
               if (design.inZone(1, board.player, pos)) {
                   result[ix] = addReserve(result[ix], fr);
                   fr = 0;
               }
               var player = board.player;
               if (!design.inZone(0, board.player, pos) && (result[ix] > 0)) {
                   player = design.nextPlayer(player);
               }
               var piece = createPiece(design, player, result[ix]);
               if (result[ix] == 0) {
                   if (ix > 0) {
                       move.capturePiece(pos);
                       if (ix == 1) {
                           move.actions[0][2] = [ Dagaz.Model.createPiece(1, board.player) ];
                       }
                   }
               } else {
                   if (piece !== null) {
                       if (ix == 1) {
                           move.actions[0][2] = [ piece ];
                       } else {
                           if ((ix > 0) && (board.getPiece(pos) !== null)) {
                               move.movePiece(pos, pos, piece);
                           } else {
                               move.dropPiece(pos, piece);
                           }
                       }
                   }
               }
               pos = design.navigate(board.player, pos, 0);
          }
          if (!isPool && (fr == 0)) {
               _.each(design.allPositions(), function(pos) {
                    if (design.inZone(1, board.player, pos)) {
                        var piece = board.getPiece(pos);
                        if (piece !== null) {
                            var value = +piece.getValue(0);
                            if (value < 0) {
                                piece = piece.setValue(0, -value);
                                move.movePiece(pos, pos, piece);
                            }
                        }
                    }
               });
          }
          toReserve(design, board, board.player, move, fr);
      }
  });
  var ko = [];
  _.each(design.allPositions(), function(pos) {
      if (design.inZone(1, board.player, pos)) return;
      var piece = board.getPiece(pos);
      if (piece !== null) {
          var value = +piece.getValue(0);
          if ((value !== null) && (value < -1)) {
              ko.push(pos);
          }
      }
  });
  if (ko.length > 0) {
      board.ko = ko;
  }
  CheckInvariants(board);
}

})();
<|endoftext|>


<commit_before>import Ember from "ember";
import config from '../config/environment';
import AjaxPromise from '../utils/ajax-promise';

export default Ember.Service.extend({
  session: Ember.inject.service(),
  logger: Ember.inject.service(),
  messagesUtil: Ember.inject.service("messages"),

  appLoad: function () {
    if (!config.cordova.enabled) {
      return;
    }

    // Based off https://github.com/Telerik-Verified-Plugins/PushNotification/blob/master/Example/www/index.html

    var pushNotification, _this = this;

    function onDeviceReady() {
      if (config.staging && TestFairy) {
        TestFairy.begin('a362fd4ae199930a7a1a1b6daa6f729ac923b506');
      }
      pushNotification = window.plugins.pushNotification;
      if (device.platform == "android" || device.platform == "Android" || device.platform == "amazon-fireos") {
        var opts = {"senderID":config.cordova.GcmSenderId, "ecb":"onNotificationGCM"};
        pushNotification.register(successHandler, errorHandler, opts);
      } else if (device.platform === "iOS") {
        var opts = {"badge": "true", "sound": "true", "alert": "true", "ecb": "onNotificationAPN"};
        pushNotification.register(res => sendToken(res, "aps"), errorHandler, opts);
      } else if (device.platform === "windows") {
        var opts = {"ecb":"noop"};
        pushNotification.register(res => sendToken(res.uri, "wns"), errorHandler, opts);
        WinJS.Application.addEventListener("activated", window.onNotificationWindows, false);
      }
    }

    // handle APNS notifications for iOS
    window.onNotificationAPN = function(e) {
      if (e.foreground === "0") {
        return processTappedNotification(e);
      }

      if (e.badge) {
        pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, e.badge);
      }
    }

    // handle GCM notifications for Android
    window.onNotificationGCM = function(e) {
      switch (e.event) {
        case 'registered':
          if (e.regid.length > 0) {
            sendToken(e.regid, "gcm");
          }
          break;

        case 'message':
          if (e.foreground) {
            // handled by socket.io notification sent at same time (e.payload.message)
          }
          else {
            processTappedNotification(e.payload);
            // otherwise we were launched because the user touched a notification in the notification tray
          }
          break;

        case 'error':
          this.get("logger").error("notification error " + JSON.stringify(e));
          break;

        default:
          this.get("logger").error("unknown notification event " + JSON.stringify(e));
          break;
      }
    }

    // handle WNS notifications for WP8.1
    window.onNotificationWindows = function(e) {
      if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
        processTappedNotification(JSON.parse(e.detail.arguments));
      }
    }

    window.noop = function() {}

    function sendToken(handle, platform) {
      return new AjaxPromise("/auth/register_device", "POST", _this.get("session.authToken"), {handle: handle, platform: platform});
    }

    function successHandler(result) {
    }

    function errorHandler(error) {
      _this.get("logger").error(error);
    }

    function processTappedNotification(payload) {
      var notifications = _this.container.lookup("controller:notifications");
      if (payload.category === "incoming_call") {
        notifications.acceptCall(payload);
      }
      notifications.setRoute(payload);
      notifications.transitionToRoute.apply(notifications, payload.route);
    }

    document.addEventListener('deviceready', onDeviceReady, true);
  }
});
<commit_msg>Fixed for TestFairy check<commit_after>import Ember from "ember";
import config from '../config/environment';
import AjaxPromise from '../utils/ajax-promise';

export default Ember.Service.extend({
  session: Ember.inject.service(),
  logger: Ember.inject.service(),
  messagesUtil: Ember.inject.service("messages"),

  appLoad: function () {
    if (!config.cordova.enabled) {
      return;
    }

    // Based off https://github.com/Telerik-Verified-Plugins/PushNotification/blob/master/Example/www/index.html

    var pushNotification, _this = this;

    function onDeviceReady() {
      if (config.staging && typeof TestFairy != 'undefined') {
        TestFairy.begin('a362fd4ae199930a7a1a1b6daa6f729ac923b506');
      }
      pushNotification = window.plugins.pushNotification;
      if (device.platform == "android" || device.platform == "Android" || device.platform == "amazon-fireos") {
        var opts = {"senderID":config.cordova.GcmSenderId, "ecb":"onNotificationGCM"};
        pushNotification.register(successHandler, errorHandler, opts);
      } else if (device.platform === "iOS") {
        var opts = {"badge": "true", "sound": "true", "alert": "true", "ecb": "onNotificationAPN"};
        pushNotification.register(res => sendToken(res, "aps"), errorHandler, opts);
      } else if (device.platform === "windows") {
        var opts = {"ecb":"noop"};
        pushNotification.register(res => sendToken(res.uri, "wns"), errorHandler, opts);
        WinJS.Application.addEventListener("activated", window.onNotificationWindows, false);
      }
    }

    // handle APNS notifications for iOS
    window.onNotificationAPN = function(e) {
      if (e.foreground === "0") {
        return processTappedNotification(e);
      }

      if (e.badge) {
        pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, e.badge);
      }
    }

    // handle GCM notifications for Android
    window.onNotificationGCM = function(e) {
      switch (e.event) {
        case 'registered':
          if (e.regid.length > 0) {
            sendToken(e.regid, "gcm");
          }
          break;

        case 'message':
          if (e.foreground) {
            // handled by socket.io notification sent at same time (e.payload.message)
          }
          else {
            processTappedNotification(e.payload);
            // otherwise we were launched because the user touched a notification in the notification tray
          }
          break;

        case 'error':
          this.get("logger").error("notification error " + JSON.stringify(e));
          break;

        default:
          this.get("logger").error("unknown notification event " + JSON.stringify(e));
          break;
      }
    }

    // handle WNS notifications for WP8.1
    window.onNotificationWindows = function(e) {
      if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
        processTappedNotification(JSON.parse(e.detail.arguments));
      }
    }

    window.noop = function() {}

    function sendToken(handle, platform) {
      return new AjaxPromise("/auth/register_device", "POST", _this.get("session.authToken"), {handle: handle, platform: platform});
    }

    function successHandler(result) {
    }

    function errorHandler(error) {
      _this.get("logger").error(error);
    }

    function processTappedNotification(payload) {
      var notifications = _this.container.lookup("controller:notifications");
      if (payload.category === "incoming_call") {
        notifications.acceptCall(payload);
      }
      notifications.setRoute(payload);
      notifications.transitionToRoute.apply(notifications, payload.route);
    }

    document.addEventListener('deviceready', onDeviceReady, true);
  }
});
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {Route} from 'react-router';
import createHashHistory from 'history/createHashHistory';
import {ConnectedRouter} from 'react-router-redux';

// import configureRoute from './config.routes';
import configureStore from 'reduxes/store';

import Root from 'containers/Root';

const history = createHashHistory();
const store = configureStore(history);

/**
 * IE polyfill
 */
if (!(Object.setPrototypeOf || {}.__proto__)) {
    var nativeGetPrototypeOf = Object.getPrototypeOf;

    Object.getPrototypeOf = function (object) {
        if (object.__proto__) {
            return object.__proto__;
        } else {
            return nativeGetPrototypeOf.call(Object, object);
        }
    };
}

render(
    <Provider store={store}>
        <ConnectedRouter history={history}>

                <Route path="/" component={Root}/>

        </ConnectedRouter>
    </Provider>,
    document.getElementById('app-container')
);<commit_msg>update react-router to v4<commit_after>'use strict';

import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {Route} from 'react-router';
import createHashHistory from 'history/createHashHistory';
import {ConnectedRouter} from 'react-router-redux';

import configureStore from 'reduxes/store';

import Root from 'containers/Root';

const history = createHashHistory();
const store = configureStore(history);

render(
    <Provider store={store}>
        <ConnectedRouter history={history}>

                <Route path="/" component={Root}/>

        </ConnectedRouter>
    </Provider>,
    document.getElementById('app-container')
);<|endoftext|>


<commit_before>const addController = require('./add')
const editController = require('./edit')
const viewController = require('./view')
const archiveController = require('./archive')
const auditController = require('./audit')
const companiesHouseController = require('./companies-house')
const contactsController = require('./contacts')
const exportsController = require('./exports')
const interactionsController = require('./interactions')
const investmentsController = require('./investments')
const renderCompanyList = require('./list')

module.exports = {
  addController,
  editController,
  viewController,
  archiveController,
  auditController,
  companiesHouseController,
  contactsController,
  exportsController,
  interactionsController,
  investmentsController,
  renderCompanyList,
}
<commit_msg>Remove redundant references<commit_after>const addController = require('./add')
const editController = require('./edit')
const archiveController = require('./archive')
const auditController = require('./audit')
const contactsController = require('./contacts')
const exportsController = require('./exports')
const interactionsController = require('./interactions')
const investmentsController = require('./investments')
const renderCompanyList = require('./list')

module.exports = {
  addController,
  editController,
  archiveController,
  auditController,
  contactsController,
  exportsController,
  interactionsController,
  investmentsController,
  renderCompanyList,
}
<|endoftext|>