Tic-Tac-Toe command line The 2019 Stack Overflow Developer Survey Results Are InTic Tac Toe...

Match Roman Numerals

Cooking pasta in a water boiler

Is it a good practice to use a static variable in a Test Class and use that in the actual class instead of Test.isRunningTest()?

Does adding complexity mean a more secure cipher?

Deal with toxic manager when you can't quit

Getting crown tickets for Statue of Liberty

The difference between dialogue marks

I am an eight letter word. What am I?

Did Scotland spend $250,000 for the slogan "Welcome to Scotland"?

What is this sharp, curved notch on my knife for?

Falsification in Math vs Science

Why not take a picture of a closer black hole?

The phrase "to the numbers born"?

Geography at the pixel level

What is preventing me from simply constructing a hash that's lower than the current target?

Dropping list elements from nested list after evaluation

Is it ok to offer lower paid work as a trial period before negotiating for a full-time job?

Can I have a signal generator on while it's not connected?

What does もの mean in this sentence?

How do I free up internal storage if I don't have any apps downloaded?

What could be the right powersource for 15 seconds lifespan disposable giant chainsaw?

How to charge AirPods to keep battery healthy?

Keeping a retro style to sci-fi spaceships?

Is an up-to-date browser secure on an out-of-date OS?



Tic-Tac-Toe command line



The 2019 Stack Overflow Developer Survey Results Are InTic Tac Toe victory checkSQL Tic-Tac-Toe attemptTic-Tac-Toe solverTic Tac Toe in JavaUltimate Tic Tac Toe A.K.A. Tic TacticsTic-Tac-Toe Game (Java)Tic Tac Toe in SwingTic Tac Toe game - object oriented JavaModularized Tic Tac Toe in CSimple text-based tic-tac-toe





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







4












$begingroup$


I created a simple Tic-Tac-Toe. I'm looking for any critiques from a code standpoint: general structure / style / efficiency.



Unfortunately I couldn't get a live demo working because of the dependency on the NodeJS library prompt.



/*  A simple Tic-Tac-Toe game implemented in Javascript V8 3.14.5.9

Players 'X' and 'O' take turn inputing their position on the command line using numbers 1-9

1 | 2 | 3
---------
4 | 5 | 6
---------
7 | 8 | 9

*/


// prompt for nodejs is required: https://github.com/flatiron/prompt
// npm install prompt
var prompt = require('prompt');

var board = {
1: ' ',
2: ' ',
3: ' ',
4: ' ',
5: ' ',
6: ' ',
7: ' ',
8: ' ',
9: ' '
};

function markBoard(position, mark) {
board[position] = mark.toUpperCase();
}

function printBoard() {
console.log('n' +
' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + 'n' +
' ---------n' +
' ' + board[4] + ' | ' + board[5] + ' | ' + board[6] + 'n' +
' ---------n' +
' ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + 'n');

}

function isInt(value) {
var x;
if (isNaN(value)) {
return false;
}
x = parseFloat(value);
return (x | 0) === x;
}

function validateMove(position) {
if (isInt(position) === true && board[position] === ' ') {
return true;
}
return false;
}

// Everyone possible combination of three in a row
var winCombinations = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
[2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]];

// Determins if the passed in player has three in a row
function checkWin(player) {
for (var i = 0; i < winCombinations.length; i++) {
var markCount = 0;
for (var j = 0; j < winCombinations[i].length; j++) {
if (board[winCombinations[i][j]] === player) {
markCount++;
}
if (markCount === 3) {
return true;
}
}
}
return false;
}

function playTurn(player) {

console.log('Your turn player: ' + player);
prompt.start();
prompt.get(['position'], function (err, result) {

if (validateMove(result.position) === true) {
markBoard(result.position, player);
printBoard();
if (checkWin(player) === true) {
console.log('Winner Winner!');
return;
}
if (player === 'X') {
playTurn('O');
} else {
playTurn('X');
}
} else {
console.log('incorrect input please try again...');
playTurn(player);
}
});
}

console.log('Game started: n' +
' 1 | 2 | 3 n' +
' --------- n' +
' 4 | 5 | 6 n' +
' --------- n' +
' 7 | 8 | 9 n');


playTurn('X');









share|improve this question











$endgroup$



















    4












    $begingroup$


    I created a simple Tic-Tac-Toe. I'm looking for any critiques from a code standpoint: general structure / style / efficiency.



    Unfortunately I couldn't get a live demo working because of the dependency on the NodeJS library prompt.



    /*  A simple Tic-Tac-Toe game implemented in Javascript V8 3.14.5.9

    Players 'X' and 'O' take turn inputing their position on the command line using numbers 1-9

    1 | 2 | 3
    ---------
    4 | 5 | 6
    ---------
    7 | 8 | 9

    */


    // prompt for nodejs is required: https://github.com/flatiron/prompt
    // npm install prompt
    var prompt = require('prompt');

    var board = {
    1: ' ',
    2: ' ',
    3: ' ',
    4: ' ',
    5: ' ',
    6: ' ',
    7: ' ',
    8: ' ',
    9: ' '
    };

    function markBoard(position, mark) {
    board[position] = mark.toUpperCase();
    }

    function printBoard() {
    console.log('n' +
    ' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + 'n' +
    ' ---------n' +
    ' ' + board[4] + ' | ' + board[5] + ' | ' + board[6] + 'n' +
    ' ---------n' +
    ' ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + 'n');

    }

    function isInt(value) {
    var x;
    if (isNaN(value)) {
    return false;
    }
    x = parseFloat(value);
    return (x | 0) === x;
    }

    function validateMove(position) {
    if (isInt(position) === true && board[position] === ' ') {
    return true;
    }
    return false;
    }

    // Everyone possible combination of three in a row
    var winCombinations = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
    [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]];

    // Determins if the passed in player has three in a row
    function checkWin(player) {
    for (var i = 0; i < winCombinations.length; i++) {
    var markCount = 0;
    for (var j = 0; j < winCombinations[i].length; j++) {
    if (board[winCombinations[i][j]] === player) {
    markCount++;
    }
    if (markCount === 3) {
    return true;
    }
    }
    }
    return false;
    }

    function playTurn(player) {

    console.log('Your turn player: ' + player);
    prompt.start();
    prompt.get(['position'], function (err, result) {

    if (validateMove(result.position) === true) {
    markBoard(result.position, player);
    printBoard();
    if (checkWin(player) === true) {
    console.log('Winner Winner!');
    return;
    }
    if (player === 'X') {
    playTurn('O');
    } else {
    playTurn('X');
    }
    } else {
    console.log('incorrect input please try again...');
    playTurn(player);
    }
    });
    }

    console.log('Game started: n' +
    ' 1 | 2 | 3 n' +
    ' --------- n' +
    ' 4 | 5 | 6 n' +
    ' --------- n' +
    ' 7 | 8 | 9 n');


    playTurn('X');









    share|improve this question











    $endgroup$















      4












      4








      4


      0



      $begingroup$


      I created a simple Tic-Tac-Toe. I'm looking for any critiques from a code standpoint: general structure / style / efficiency.



      Unfortunately I couldn't get a live demo working because of the dependency on the NodeJS library prompt.



      /*  A simple Tic-Tac-Toe game implemented in Javascript V8 3.14.5.9

      Players 'X' and 'O' take turn inputing their position on the command line using numbers 1-9

      1 | 2 | 3
      ---------
      4 | 5 | 6
      ---------
      7 | 8 | 9

      */


      // prompt for nodejs is required: https://github.com/flatiron/prompt
      // npm install prompt
      var prompt = require('prompt');

      var board = {
      1: ' ',
      2: ' ',
      3: ' ',
      4: ' ',
      5: ' ',
      6: ' ',
      7: ' ',
      8: ' ',
      9: ' '
      };

      function markBoard(position, mark) {
      board[position] = mark.toUpperCase();
      }

      function printBoard() {
      console.log('n' +
      ' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + 'n' +
      ' ---------n' +
      ' ' + board[4] + ' | ' + board[5] + ' | ' + board[6] + 'n' +
      ' ---------n' +
      ' ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + 'n');

      }

      function isInt(value) {
      var x;
      if (isNaN(value)) {
      return false;
      }
      x = parseFloat(value);
      return (x | 0) === x;
      }

      function validateMove(position) {
      if (isInt(position) === true && board[position] === ' ') {
      return true;
      }
      return false;
      }

      // Everyone possible combination of three in a row
      var winCombinations = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
      [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]];

      // Determins if the passed in player has three in a row
      function checkWin(player) {
      for (var i = 0; i < winCombinations.length; i++) {
      var markCount = 0;
      for (var j = 0; j < winCombinations[i].length; j++) {
      if (board[winCombinations[i][j]] === player) {
      markCount++;
      }
      if (markCount === 3) {
      return true;
      }
      }
      }
      return false;
      }

      function playTurn(player) {

      console.log('Your turn player: ' + player);
      prompt.start();
      prompt.get(['position'], function (err, result) {

      if (validateMove(result.position) === true) {
      markBoard(result.position, player);
      printBoard();
      if (checkWin(player) === true) {
      console.log('Winner Winner!');
      return;
      }
      if (player === 'X') {
      playTurn('O');
      } else {
      playTurn('X');
      }
      } else {
      console.log('incorrect input please try again...');
      playTurn(player);
      }
      });
      }

      console.log('Game started: n' +
      ' 1 | 2 | 3 n' +
      ' --------- n' +
      ' 4 | 5 | 6 n' +
      ' --------- n' +
      ' 7 | 8 | 9 n');


      playTurn('X');









      share|improve this question











      $endgroup$




      I created a simple Tic-Tac-Toe. I'm looking for any critiques from a code standpoint: general structure / style / efficiency.



      Unfortunately I couldn't get a live demo working because of the dependency on the NodeJS library prompt.



      /*  A simple Tic-Tac-Toe game implemented in Javascript V8 3.14.5.9

      Players 'X' and 'O' take turn inputing their position on the command line using numbers 1-9

      1 | 2 | 3
      ---------
      4 | 5 | 6
      ---------
      7 | 8 | 9

      */


      // prompt for nodejs is required: https://github.com/flatiron/prompt
      // npm install prompt
      var prompt = require('prompt');

      var board = {
      1: ' ',
      2: ' ',
      3: ' ',
      4: ' ',
      5: ' ',
      6: ' ',
      7: ' ',
      8: ' ',
      9: ' '
      };

      function markBoard(position, mark) {
      board[position] = mark.toUpperCase();
      }

      function printBoard() {
      console.log('n' +
      ' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + 'n' +
      ' ---------n' +
      ' ' + board[4] + ' | ' + board[5] + ' | ' + board[6] + 'n' +
      ' ---------n' +
      ' ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + 'n');

      }

      function isInt(value) {
      var x;
      if (isNaN(value)) {
      return false;
      }
      x = parseFloat(value);
      return (x | 0) === x;
      }

      function validateMove(position) {
      if (isInt(position) === true && board[position] === ' ') {
      return true;
      }
      return false;
      }

      // Everyone possible combination of three in a row
      var winCombinations = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
      [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]];

      // Determins if the passed in player has three in a row
      function checkWin(player) {
      for (var i = 0; i < winCombinations.length; i++) {
      var markCount = 0;
      for (var j = 0; j < winCombinations[i].length; j++) {
      if (board[winCombinations[i][j]] === player) {
      markCount++;
      }
      if (markCount === 3) {
      return true;
      }
      }
      }
      return false;
      }

      function playTurn(player) {

      console.log('Your turn player: ' + player);
      prompt.start();
      prompt.get(['position'], function (err, result) {

      if (validateMove(result.position) === true) {
      markBoard(result.position, player);
      printBoard();
      if (checkWin(player) === true) {
      console.log('Winner Winner!');
      return;
      }
      if (player === 'X') {
      playTurn('O');
      } else {
      playTurn('X');
      }
      } else {
      console.log('incorrect input please try again...');
      playTurn(player);
      }
      });
      }

      console.log('Game started: n' +
      ' 1 | 2 | 3 n' +
      ' --------- n' +
      ' 4 | 5 | 6 n' +
      ' --------- n' +
      ' 7 | 8 | 9 n');


      playTurn('X');






      javascript node.js console tic-tac-toe






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 30 '15 at 17:37









      Jamal

      30.6k11121227




      30.6k11121227










      asked Jun 30 '15 at 16:32









      abaldwin99abaldwin99

      15026




      15026






















          3 Answers
          3






          active

          oldest

          votes


















          5












          $begingroup$

          This code was very well organized and was extremely easy to follow along.





          Looks to me that board is just a 1-based array.



          It would be easier (and it makes more sense) to use an array, instead of an object.



          But don't change how you are asking the user for input. You want to translate the user input one number back, so if the user enters "1" for box number 1, just subtract 1 from the integer version of the input and then pass it to markBoard.



          if (validateMove(result.position) === true) {
          markBoard(result.position - 1, player);
          printBoard();




          In your markBoard function, there is no point in calling .toUpperCase as the player variable passed in from playTurn is already a capital letter.





          You are making validateMove too complicated. Just do:



          return isInt(position) && board[position] === ' ';


          If the expression evaluates to true, it will return true. If it evaluates to false, it will return false.



          Note: I omitted the === true because JavaScript automatically checks for something to equal true.





          It doesn't look like you have anything to check if the user enters an invalid number.



          I would add something to the end of validateMove to check to make sure that the option is in bounds.



          Here is what I came up with:



          return isInt(position) && board[position] === ' ' && (position >= 0 && position <= 8);


          It would be >= 1 && <= 9 if you continued to use the object instead of the array for storing squares of the board





          This might help your efficiency:



          Try moving this conditional from checkWin



          if (markCount === 3) {
          return true;
          }


          Outside of the inner for loop so you aren't doing a conditional check with each iteration.





          In checkWin, you do a lot of looping. In each loop, you are destroying and re-making variables as they exit and leave the scope (the loop).



          This is very optimal. To help this, move the declarations of markCount, i, and j to the very top of the function (before the loops). You can set them to 0 when they are needed.



          Here is what I am saying:



          function checkWin(player) {
          var i, j, markCount
          for (i = 0; i < winCombinations.length; i++) {
          markCount = 0;
          for (j = 0; j < winCombinations[i].length; j++) {
          if (board[winCombinations[i][j]] === player) {
          markCount++;
          }
          if (markCount === 3) {
          return true;
          }
          }
          }
          return false;
          }


          Notice how I removed the vars?





          I'm a little confused by what your isInt function is trying to accomplish.



          To make it simpler, just run isNaN on the position. It will return NaN (which acts like false in a conditional) if the user entered a string, rather than a number.






          share|improve this answer









          $endgroup$













          • $begingroup$
            Cheers. Good stuff. validateMove does check that the option is within bounds but isn't obvious. If the board position is a space then that position is valid. (Not already taken and between 1-9) I think a comment is needed to explain. The isInt function was taken from here:stackoverflow.com/questions/14636536/…
            $endgroup$
            – abaldwin99
            Jul 1 '15 at 16:56












          • $begingroup$
            For checkWin doesn't JavaScript already hoist var i, j, markCount to the top of the function?
            $endgroup$
            – Bemmu
            Apr 25 '17 at 6:14





















          3












          $begingroup$

          This is great. Your validation can be handled for you by prompt, though, e.g.



            const positionQuery = `${player}'s turn. choose a position 1-9`
          const position = {
          properties: {
          [positionQuery]: {
          pattern: /^[1-9]{1}$/,
          message: 'Choose a position 1-9',
          required: true
          }
          }
          }
          prompt.start()
          prompt.get([positionQuery], (err, result) => {
          ...
          }





          share|improve this answer









          $endgroup$





















            0












            $begingroup$

            🚗🏎🚚🚨🚨🚔🚍🚒🚑🚜🚜🚜🚜🏍🚒🚒🚒🚒🚒🚒🚒🚒🚒🚒🏍🏍





            share








            New contributor




            Alex Spahr of peal city is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






            $endgroup$














              Your Answer





              StackExchange.ifUsing("editor", function () {
              return StackExchange.using("mathjaxEditing", function () {
              StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
              StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
              });
              });
              }, "mathjax-editing");

              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "196"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f95249%2ftic-tac-toe-command-line%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              5












              $begingroup$

              This code was very well organized and was extremely easy to follow along.





              Looks to me that board is just a 1-based array.



              It would be easier (and it makes more sense) to use an array, instead of an object.



              But don't change how you are asking the user for input. You want to translate the user input one number back, so if the user enters "1" for box number 1, just subtract 1 from the integer version of the input and then pass it to markBoard.



              if (validateMove(result.position) === true) {
              markBoard(result.position - 1, player);
              printBoard();




              In your markBoard function, there is no point in calling .toUpperCase as the player variable passed in from playTurn is already a capital letter.





              You are making validateMove too complicated. Just do:



              return isInt(position) && board[position] === ' ';


              If the expression evaluates to true, it will return true. If it evaluates to false, it will return false.



              Note: I omitted the === true because JavaScript automatically checks for something to equal true.





              It doesn't look like you have anything to check if the user enters an invalid number.



              I would add something to the end of validateMove to check to make sure that the option is in bounds.



              Here is what I came up with:



              return isInt(position) && board[position] === ' ' && (position >= 0 && position <= 8);


              It would be >= 1 && <= 9 if you continued to use the object instead of the array for storing squares of the board





              This might help your efficiency:



              Try moving this conditional from checkWin



              if (markCount === 3) {
              return true;
              }


              Outside of the inner for loop so you aren't doing a conditional check with each iteration.





              In checkWin, you do a lot of looping. In each loop, you are destroying and re-making variables as they exit and leave the scope (the loop).



              This is very optimal. To help this, move the declarations of markCount, i, and j to the very top of the function (before the loops). You can set them to 0 when they are needed.



              Here is what I am saying:



              function checkWin(player) {
              var i, j, markCount
              for (i = 0; i < winCombinations.length; i++) {
              markCount = 0;
              for (j = 0; j < winCombinations[i].length; j++) {
              if (board[winCombinations[i][j]] === player) {
              markCount++;
              }
              if (markCount === 3) {
              return true;
              }
              }
              }
              return false;
              }


              Notice how I removed the vars?





              I'm a little confused by what your isInt function is trying to accomplish.



              To make it simpler, just run isNaN on the position. It will return NaN (which acts like false in a conditional) if the user entered a string, rather than a number.






              share|improve this answer









              $endgroup$













              • $begingroup$
                Cheers. Good stuff. validateMove does check that the option is within bounds but isn't obvious. If the board position is a space then that position is valid. (Not already taken and between 1-9) I think a comment is needed to explain. The isInt function was taken from here:stackoverflow.com/questions/14636536/…
                $endgroup$
                – abaldwin99
                Jul 1 '15 at 16:56












              • $begingroup$
                For checkWin doesn't JavaScript already hoist var i, j, markCount to the top of the function?
                $endgroup$
                – Bemmu
                Apr 25 '17 at 6:14


















              5












              $begingroup$

              This code was very well organized and was extremely easy to follow along.





              Looks to me that board is just a 1-based array.



              It would be easier (and it makes more sense) to use an array, instead of an object.



              But don't change how you are asking the user for input. You want to translate the user input one number back, so if the user enters "1" for box number 1, just subtract 1 from the integer version of the input and then pass it to markBoard.



              if (validateMove(result.position) === true) {
              markBoard(result.position - 1, player);
              printBoard();




              In your markBoard function, there is no point in calling .toUpperCase as the player variable passed in from playTurn is already a capital letter.





              You are making validateMove too complicated. Just do:



              return isInt(position) && board[position] === ' ';


              If the expression evaluates to true, it will return true. If it evaluates to false, it will return false.



              Note: I omitted the === true because JavaScript automatically checks for something to equal true.





              It doesn't look like you have anything to check if the user enters an invalid number.



              I would add something to the end of validateMove to check to make sure that the option is in bounds.



              Here is what I came up with:



              return isInt(position) && board[position] === ' ' && (position >= 0 && position <= 8);


              It would be >= 1 && <= 9 if you continued to use the object instead of the array for storing squares of the board





              This might help your efficiency:



              Try moving this conditional from checkWin



              if (markCount === 3) {
              return true;
              }


              Outside of the inner for loop so you aren't doing a conditional check with each iteration.





              In checkWin, you do a lot of looping. In each loop, you are destroying and re-making variables as they exit and leave the scope (the loop).



              This is very optimal. To help this, move the declarations of markCount, i, and j to the very top of the function (before the loops). You can set them to 0 when they are needed.



              Here is what I am saying:



              function checkWin(player) {
              var i, j, markCount
              for (i = 0; i < winCombinations.length; i++) {
              markCount = 0;
              for (j = 0; j < winCombinations[i].length; j++) {
              if (board[winCombinations[i][j]] === player) {
              markCount++;
              }
              if (markCount === 3) {
              return true;
              }
              }
              }
              return false;
              }


              Notice how I removed the vars?





              I'm a little confused by what your isInt function is trying to accomplish.



              To make it simpler, just run isNaN on the position. It will return NaN (which acts like false in a conditional) if the user entered a string, rather than a number.






              share|improve this answer









              $endgroup$













              • $begingroup$
                Cheers. Good stuff. validateMove does check that the option is within bounds but isn't obvious. If the board position is a space then that position is valid. (Not already taken and between 1-9) I think a comment is needed to explain. The isInt function was taken from here:stackoverflow.com/questions/14636536/…
                $endgroup$
                – abaldwin99
                Jul 1 '15 at 16:56












              • $begingroup$
                For checkWin doesn't JavaScript already hoist var i, j, markCount to the top of the function?
                $endgroup$
                – Bemmu
                Apr 25 '17 at 6:14
















              5












              5








              5





              $begingroup$

              This code was very well organized and was extremely easy to follow along.





              Looks to me that board is just a 1-based array.



              It would be easier (and it makes more sense) to use an array, instead of an object.



              But don't change how you are asking the user for input. You want to translate the user input one number back, so if the user enters "1" for box number 1, just subtract 1 from the integer version of the input and then pass it to markBoard.



              if (validateMove(result.position) === true) {
              markBoard(result.position - 1, player);
              printBoard();




              In your markBoard function, there is no point in calling .toUpperCase as the player variable passed in from playTurn is already a capital letter.





              You are making validateMove too complicated. Just do:



              return isInt(position) && board[position] === ' ';


              If the expression evaluates to true, it will return true. If it evaluates to false, it will return false.



              Note: I omitted the === true because JavaScript automatically checks for something to equal true.





              It doesn't look like you have anything to check if the user enters an invalid number.



              I would add something to the end of validateMove to check to make sure that the option is in bounds.



              Here is what I came up with:



              return isInt(position) && board[position] === ' ' && (position >= 0 && position <= 8);


              It would be >= 1 && <= 9 if you continued to use the object instead of the array for storing squares of the board





              This might help your efficiency:



              Try moving this conditional from checkWin



              if (markCount === 3) {
              return true;
              }


              Outside of the inner for loop so you aren't doing a conditional check with each iteration.





              In checkWin, you do a lot of looping. In each loop, you are destroying and re-making variables as they exit and leave the scope (the loop).



              This is very optimal. To help this, move the declarations of markCount, i, and j to the very top of the function (before the loops). You can set them to 0 when they are needed.



              Here is what I am saying:



              function checkWin(player) {
              var i, j, markCount
              for (i = 0; i < winCombinations.length; i++) {
              markCount = 0;
              for (j = 0; j < winCombinations[i].length; j++) {
              if (board[winCombinations[i][j]] === player) {
              markCount++;
              }
              if (markCount === 3) {
              return true;
              }
              }
              }
              return false;
              }


              Notice how I removed the vars?





              I'm a little confused by what your isInt function is trying to accomplish.



              To make it simpler, just run isNaN on the position. It will return NaN (which acts like false in a conditional) if the user entered a string, rather than a number.






              share|improve this answer









              $endgroup$



              This code was very well organized and was extremely easy to follow along.





              Looks to me that board is just a 1-based array.



              It would be easier (and it makes more sense) to use an array, instead of an object.



              But don't change how you are asking the user for input. You want to translate the user input one number back, so if the user enters "1" for box number 1, just subtract 1 from the integer version of the input and then pass it to markBoard.



              if (validateMove(result.position) === true) {
              markBoard(result.position - 1, player);
              printBoard();




              In your markBoard function, there is no point in calling .toUpperCase as the player variable passed in from playTurn is already a capital letter.





              You are making validateMove too complicated. Just do:



              return isInt(position) && board[position] === ' ';


              If the expression evaluates to true, it will return true. If it evaluates to false, it will return false.



              Note: I omitted the === true because JavaScript automatically checks for something to equal true.





              It doesn't look like you have anything to check if the user enters an invalid number.



              I would add something to the end of validateMove to check to make sure that the option is in bounds.



              Here is what I came up with:



              return isInt(position) && board[position] === ' ' && (position >= 0 && position <= 8);


              It would be >= 1 && <= 9 if you continued to use the object instead of the array for storing squares of the board





              This might help your efficiency:



              Try moving this conditional from checkWin



              if (markCount === 3) {
              return true;
              }


              Outside of the inner for loop so you aren't doing a conditional check with each iteration.





              In checkWin, you do a lot of looping. In each loop, you are destroying and re-making variables as they exit and leave the scope (the loop).



              This is very optimal. To help this, move the declarations of markCount, i, and j to the very top of the function (before the loops). You can set them to 0 when they are needed.



              Here is what I am saying:



              function checkWin(player) {
              var i, j, markCount
              for (i = 0; i < winCombinations.length; i++) {
              markCount = 0;
              for (j = 0; j < winCombinations[i].length; j++) {
              if (board[winCombinations[i][j]] === player) {
              markCount++;
              }
              if (markCount === 3) {
              return true;
              }
              }
              }
              return false;
              }


              Notice how I removed the vars?





              I'm a little confused by what your isInt function is trying to accomplish.



              To make it simpler, just run isNaN on the position. It will return NaN (which acts like false in a conditional) if the user entered a string, rather than a number.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jul 1 '15 at 0:14









              SirPythonSirPython

              12k32891




              12k32891












              • $begingroup$
                Cheers. Good stuff. validateMove does check that the option is within bounds but isn't obvious. If the board position is a space then that position is valid. (Not already taken and between 1-9) I think a comment is needed to explain. The isInt function was taken from here:stackoverflow.com/questions/14636536/…
                $endgroup$
                – abaldwin99
                Jul 1 '15 at 16:56












              • $begingroup$
                For checkWin doesn't JavaScript already hoist var i, j, markCount to the top of the function?
                $endgroup$
                – Bemmu
                Apr 25 '17 at 6:14




















              • $begingroup$
                Cheers. Good stuff. validateMove does check that the option is within bounds but isn't obvious. If the board position is a space then that position is valid. (Not already taken and between 1-9) I think a comment is needed to explain. The isInt function was taken from here:stackoverflow.com/questions/14636536/…
                $endgroup$
                – abaldwin99
                Jul 1 '15 at 16:56












              • $begingroup$
                For checkWin doesn't JavaScript already hoist var i, j, markCount to the top of the function?
                $endgroup$
                – Bemmu
                Apr 25 '17 at 6:14


















              $begingroup$
              Cheers. Good stuff. validateMove does check that the option is within bounds but isn't obvious. If the board position is a space then that position is valid. (Not already taken and between 1-9) I think a comment is needed to explain. The isInt function was taken from here:stackoverflow.com/questions/14636536/…
              $endgroup$
              – abaldwin99
              Jul 1 '15 at 16:56






              $begingroup$
              Cheers. Good stuff. validateMove does check that the option is within bounds but isn't obvious. If the board position is a space then that position is valid. (Not already taken and between 1-9) I think a comment is needed to explain. The isInt function was taken from here:stackoverflow.com/questions/14636536/…
              $endgroup$
              – abaldwin99
              Jul 1 '15 at 16:56














              $begingroup$
              For checkWin doesn't JavaScript already hoist var i, j, markCount to the top of the function?
              $endgroup$
              – Bemmu
              Apr 25 '17 at 6:14






              $begingroup$
              For checkWin doesn't JavaScript already hoist var i, j, markCount to the top of the function?
              $endgroup$
              – Bemmu
              Apr 25 '17 at 6:14















              3












              $begingroup$

              This is great. Your validation can be handled for you by prompt, though, e.g.



                const positionQuery = `${player}'s turn. choose a position 1-9`
              const position = {
              properties: {
              [positionQuery]: {
              pattern: /^[1-9]{1}$/,
              message: 'Choose a position 1-9',
              required: true
              }
              }
              }
              prompt.start()
              prompt.get([positionQuery], (err, result) => {
              ...
              }





              share|improve this answer









              $endgroup$


















                3












                $begingroup$

                This is great. Your validation can be handled for you by prompt, though, e.g.



                  const positionQuery = `${player}'s turn. choose a position 1-9`
                const position = {
                properties: {
                [positionQuery]: {
                pattern: /^[1-9]{1}$/,
                message: 'Choose a position 1-9',
                required: true
                }
                }
                }
                prompt.start()
                prompt.get([positionQuery], (err, result) => {
                ...
                }





                share|improve this answer









                $endgroup$
















                  3












                  3








                  3





                  $begingroup$

                  This is great. Your validation can be handled for you by prompt, though, e.g.



                    const positionQuery = `${player}'s turn. choose a position 1-9`
                  const position = {
                  properties: {
                  [positionQuery]: {
                  pattern: /^[1-9]{1}$/,
                  message: 'Choose a position 1-9',
                  required: true
                  }
                  }
                  }
                  prompt.start()
                  prompt.get([positionQuery], (err, result) => {
                  ...
                  }





                  share|improve this answer









                  $endgroup$



                  This is great. Your validation can be handled for you by prompt, though, e.g.



                    const positionQuery = `${player}'s turn. choose a position 1-9`
                  const position = {
                  properties: {
                  [positionQuery]: {
                  pattern: /^[1-9]{1}$/,
                  message: 'Choose a position 1-9',
                  required: true
                  }
                  }
                  }
                  prompt.start()
                  prompt.get([positionQuery], (err, result) => {
                  ...
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Apr 25 '17 at 3:36









                  Ari FrankelAri Frankel

                  311




                  311























                      0












                      $begingroup$

                      🚗🏎🚚🚨🚨🚔🚍🚒🚑🚜🚜🚜🚜🏍🚒🚒🚒🚒🚒🚒🚒🚒🚒🚒🏍🏍





                      share








                      New contributor




                      Alex Spahr of peal city is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.






                      $endgroup$


















                        0












                        $begingroup$

                        🚗🏎🚚🚨🚨🚔🚍🚒🚑🚜🚜🚜🚜🏍🚒🚒🚒🚒🚒🚒🚒🚒🚒🚒🏍🏍





                        share








                        New contributor




                        Alex Spahr of peal city is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                        Check out our Code of Conduct.






                        $endgroup$
















                          0












                          0








                          0





                          $begingroup$

                          🚗🏎🚚🚨🚨🚔🚍🚒🚑🚜🚜🚜🚜🏍🚒🚒🚒🚒🚒🚒🚒🚒🚒🚒🏍🏍





                          share








                          New contributor




                          Alex Spahr of peal city is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






                          $endgroup$



                          🚗🏎🚚🚨🚨🚔🚍🚒🚑🚜🚜🚜🚜🏍🚒🚒🚒🚒🚒🚒🚒🚒🚒🚒🏍🏍






                          share








                          New contributor




                          Alex Spahr of peal city is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.








                          share


                          share






                          New contributor




                          Alex Spahr of peal city is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.









                          answered 54 secs ago









                          Alex Spahr of peal cityAlex Spahr of peal city

                          1




                          1




                          New contributor




                          Alex Spahr of peal city is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.





                          New contributor





                          Alex Spahr of peal city is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






                          Alex Spahr of peal city is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f95249%2ftic-tac-toe-command-line%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

                              How do i solve the “ No module named 'mlxtend' ” issue on Jupyter?

                              Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...