How do I get my reset function to stop counting moves after it is pressed?

Viewed 59

I'm working on a Slider Puzzle and stumbled on a question. I have been trying to make my reset function to stop counting moves on the page when it is pressed but had no luck. My start function starts the counter and ends when the game ends, so how would my counter end counting but still keep the number of moves on display before the user had pressed the reset button?

var gamePiece;
var notify;
var timer;
var spaceY;
var spaceX;
var ticker;
var totalMoves;

function initialize() {
    var puzzleArea = document.getElementById("puzzlearea");
    gamePiece = puzzleArea.getElementsByTagName("div"); //retrieve element within puzzlearea

    for (var i = 0; i < gamePiece.length; i++) //applies features to each puzzle piece 

    {

        gamePiece[i].className = "puzzlepiece"; //setting up the puzzle piece code

        gamePiece[i].style.left = (i % 4 * 100) + "px"; //calculates the position for puzzle pieces from the left of the screen

        gamePiece[i].style.top = (parseInt(i / 4) * 100) + "px"; //calculates the position for puzzle pieces from the top of the screen






        gamePiece[i].onmouseover = function () //applies features when mouse moves over puzzle pieces

        {
            if (checkMove(parseInt(this.innerHTML))) //checks whenever a move is made

            {

                this.style.border = "3px solid red"; //changes to red when a puzzle piece is near an empty space

                this.style.color = "#006600"; //text color changes to green when a puzzle piece is near an empty space

                this.style.textDecoration = "underline"; //underlines the number of the puzzle piece piece
            //console.log(totalMoves);
               

            }
        }


        gamePiece[i].onmouseout = function () //activates whenever mouse moves out of puzzle piece

        {

            this.style.border = "2px solid black"; //reverts to its original size border 

            this.style.color = "#000000"; //reverts to original text color

            this.style.textDecoration = "none"; //reverts to original text state

        }


        gamePiece[i].onclick = function () //activates when mouse clicks on a puzzle piece
        {
            if (checkMove(parseInt(this.innerHTML))) //checks whether or not the puzzle piece can move into an empty space

            {
                swap(this.innerHTML - 1); //moves into an empty space if true
                totalMoves++;
                display();

                if (finish()) //checks when the all the 15 pieces are in its right space

                {

                    win(); //alerts the player that they have won the game
                    
                }
                
                return;
            }
        }
    }
}


spaceX = '300px';
spaceY = '300px';



function checkMove(position) // returns true whenever a piece can be moved into an empty space

{

    if (left(spaceX, spaceY) == (position - 1))

    {
    
             // totalMoves++;   
        return true;
           
        

    }



    if (down(spaceX, spaceY) == (position - 1))

    {
                // totalMoves++;
        return true;
       
        
        

    }



    if (up(spaceX, spaceY) == (position - 1))

    {
                 //totalMoves++;
        return true;
       
        
        

    }



    if (right(spaceX, spaceY) == (position - 1))

    {
                //totalMoves++;
        return true;
        
        
        

    }
    
}


function Notify() //notifies the user 

{

    notify--; //decrements the value of 

    if (notify == 0) //if the value reaches the end then

    {

        var body = document.getElementsByTagName("body"); //retrieves body element in html

        body[0].style.backgroundImage = "none"; //reverts to original page background

        alert("Winner! ... Press Start and Play Again"); //tells the user that they have won the game 

        location.href = "15 Slider Puzzle.html"
        
        return;
        

    } else(notify % 2)

    {

        var body = document.getElementsByTagName("body");

    }

    timer = setTimeout(Notify, 100); //notifies the user for 1 secs
    
}

function win() //notifies user that they have won

{

    var body = document.getElementsByTagName("body");

    notify = 10; //initializes notify variable

    timer = setTimeout(Notify, 10);

}

function finish() //checks when the game reaches its end

{

    var flag = true;

    for (var i = 0; i < gamePiece.length; i++) //for each puzzle piece 
    {

        var top = parseInt(gamePiece[i].style.top);

        var left = parseInt(gamePiece[i].style.left);


        if (left != (i % 4 * 100) || top != parseInt(i / 4) * 100) //checks if each piece matches its left and top position

        {

            flag = false;

            break; //breaks the loop 
           
        }
      
    }
    
    return flag;
}



function left(x, y) //calculates how far to the left a puzzlepiece should position

{

    var cordX = parseInt(x);

    var cordY = parseInt(y);



    if (cordX > 0)

    {

        for (var i = 0; i < gamePiece.length; i++)

        {

            if (parseInt(gamePiece[i].style.left) + 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)

            {

                return i;

            }

        }

    } else

    {

        return -1;

    }

}



function right(x, y) //calculates how far to the right a puzzlepiece should position
{

    var cordX = parseInt(x);

    var cordY = parseInt(y);

    if (cordX < 300)

    {

        for (var i = 0; i < gamePiece.length; i++) {

            if (parseInt(gamePiece[i].style.left) - 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)

            {

                return i;

            }

        }

    } else

    {

        return -1;

    }

}



function up(x, y) //calculates how far up a puzzlepiece should position
{

    var cordX = parseInt(x);

    var cordY = parseInt(y);

    if (cordY > 0)

    {

        for (var i = 0; i < gamePiece.length; i++)

        {

            if (parseInt(gamePiece[i].style.top) + 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)

            {

                return i;

            }

        }

    } else

    {

        return -1;

    }

}



function down(x, y) //calculates how far down a puzzlepiece should position

{

    var cordX = parseInt(x);

    var cordY = parseInt(y);

    if (cordY < 300)

    {

        for (var i = 0; i < gamePiece.length; i++)

        {

            if (parseInt(gamePiece[i].style.top) - 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)

            {

                return i;

            }

        }

    } else

    {

        return -1;

    }

}



function swap(position) //moves the puzzle piece by switching position with an empty space
{

    var temp = gamePiece[position].style.top;

    gamePiece[position].style.top = spaceY;

    spaceY = temp;

    temp = gamePiece[position].style.left;

    gamePiece[position].style.left = spaceX;

    spaceX = temp;

}

function start() //starts the move counter when the button is pressed
{
    totalMoves = 0;
    ticker = document.getElementById("Moves");
}

function display() //helps update the display when a move is successfully made
{
    ticker.innerHTML = totalMoves;
}

function reset()
{
    
}
body {
    background-color: white;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
}

#controls,
#overall,
#puzzlearea {
    width: 400px;
}

#controls {
    padding-top: 10px;
    text-align: center;
}

h1 {
    margin: 10px 0px;
    text-align: center;
}

/* Used to center the puzzle. */
#overall {
    margin-left: auto;
    margin-right: auto;
}

/* The area that holds the 15 puzzle pieces. */
#puzzlearea {
    font-size: 32px;
    height: 400px;
    padding: 0px;
    position: relative;
}

/* This class should be applied to each of the 15 puzzle pieces. */
.puzzlepiece {
    border: 2px solid black;
    height: 96px;
    line-height: 96px;
    position: absolute;
    text-align: center;
    vertical-align: middle;
    width: 96px;
}

/* This class should be applied to a puzzle piece that can be moved. */
.movablepiece:hover {
    border-color: red;
    color: #006600;
    text-decoration: underline;
}
<!DOCTYPE HTML>
<html>
    <title> 15 Slider Puzzle</title>
   
    <link rel="stylesheet" type="text/css" href="15 Slider.css" />
        <script src="15 Slider.js" type="text/javascript"></script>
    <head>
    <body onload = "initialize()">
      <h1>Slider Puzzle</h1>
      <div id="overall">
        <div id="puzzlearea">
          <!-- the following are the fifteen puzzle pieces -->
          <div>1</div>  <div>2</div>  <div>3</div>  <div>4</div>
          <div>5</div>  <div>6</div>  <div>7</div>  <div>8</div>
          <div>9</div>  <div>10</div> <div>11</div> <div>12</div>
          <div>13</div> <div>14</div> <div>15</div>
        </div>
        <div id="controls"></div>
        <button onclick = "start();">Start</button>
        <button onclick = "reset();">Reset</button>
      <br>
    Number Of Moves: <span id="Moves">0</span>
      </div><!--content-->
      <br>
    </head>
</html>

3 Answers

I have added a var hasStopped which will only add moves if its false and if reset is clicked it will set to true which means the swap will still run but moves will not counted as well.

Also, when you clicked start() again the totalMoves will start counting the moves again. If you want that too.

Here is working demo for you: https://jsfiddle.net/usmanmunir/cs4d3qfm/16/

var gamePiece;
var notify;
var timer;
var spaceY;
var spaceX;
var ticker;
var totalMoves;
var hasStopped = false;

function initialize() {
  var puzzleArea = document.getElementById("puzzlearea");
  gamePiece = puzzleArea.getElementsByTagName("div"); //retrieve element within puzzlearea

  for (var i = 0; i < gamePiece.length; i++) //applies features to each puzzle piece 

  {

    gamePiece[i].className = "puzzlepiece"; //setting up the puzzle piece code

    gamePiece[i].style.left = (i % 4 * 100) + "px"; //calculates the position for puzzle pieces from the left of the screen

    gamePiece[i].style.top = (parseInt(i / 4) * 100) + "px"; //calculates the position for puzzle pieces from the top of the screen






    gamePiece[i].onmouseover = function() //applies features when mouse moves over puzzle pieces

    {
      if (checkMove(parseInt(this.innerHTML))) //checks whenever a move is made

      {

        this.style.border = "3px solid red"; //changes to red when a puzzle piece is near an empty space

        this.style.color = "#006600"; //text color changes to green when a puzzle piece is near an empty space

        this.style.textDecoration = "underline"; //underlines the number of the puzzle piece piece
        //console.log(totalMoves);


      }
    }


    gamePiece[i].onmouseout = function() //activates whenever mouse moves out of puzzle piece

    {

      this.style.border = "2px solid black"; //reverts to its original size border 

      this.style.color = "#000000"; //reverts to original text color

      this.style.textDecoration = "none"; //reverts to original text state

    }


    gamePiece[i].onclick = function() //activates when mouse clicks on a puzzle piece
    {
      if (checkMove(parseInt(this.innerHTML))) //checks whether or not the puzzle piece can move into an empty space

      {
        swap(this.innerHTML - 1); //moves into an empty space if true
        if (!hasStopped) {
          totalMoves++;
          display();
        }
        if (finish()) //checks when the all the 15 pieces are in its right space

        {

          win(); //alerts the player that they have won the game

        }

        return;
      }
    }
  }
}


spaceX = '300px';
spaceY = '300px';



function checkMove(position) // returns true whenever a piece can be moved into an empty space

{

  if (left(spaceX, spaceY) == (position - 1))

  {

    // totalMoves++;   
    return true;



  }



  if (down(spaceX, spaceY) == (position - 1))

  {
    // totalMoves++;
    return true;




  }



  if (up(spaceX, spaceY) == (position - 1))

  {
    //totalMoves++;
    return true;




  }



  if (right(spaceX, spaceY) == (position - 1))

  {
    //totalMoves++;
    return true;




  }

}


function Notify() //notifies the user 

{

  notify--; //decrements the value of 

  if (notify == 0) //if the value reaches the end then

  {

    var body = document.getElementsByTagName("body"); //retrieves body element in html

    body[0].style.backgroundImage = "none"; //reverts to original page background

    alert("Winner! ... Press Start and Play Again"); //tells the user that they have won the game 

    location.href = "15 Slider Puzzle.html"

    return;


  } else(notify % 2)

  {

    var body = document.getElementsByTagName("body");

  }

  timer = setTimeout(Notify, 100); //notifies the user for 1 secs

}

function win() //notifies user that they have won

{

  var body = document.getElementsByTagName("body");

  notify = 10; //initializes notify variable

  timer = setTimeout(Notify, 10);

}

function finish() //checks when the game reaches its end

{

  var flag = true;

  for (var i = 0; i < gamePiece.length; i++) //for each puzzle piece 
  {

    var top = parseInt(gamePiece[i].style.top);

    var left = parseInt(gamePiece[i].style.left);


    if (left != (i % 4 * 100) || top != parseInt(i / 4) * 100) //checks if each piece matches its left and top position

    {

      flag = false;

      break; //breaks the loop 

    }

  }

  return flag;
}



function left(x, y) //calculates how far to the left a puzzlepiece should position

{

  var cordX = parseInt(x);

  var cordY = parseInt(y);



  if (cordX > 0)

  {

    for (var i = 0; i < gamePiece.length; i++)

    {

      if (parseInt(gamePiece[i].style.left) + 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)

      {

        return i;

      }

    }

  } else

  {

    return -1;

  }

}



function right(x, y) //calculates how far to the right a puzzlepiece should position
{

  var cordX = parseInt(x);

  var cordY = parseInt(y);

  if (cordX < 300)

  {

    for (var i = 0; i < gamePiece.length; i++) {

      if (parseInt(gamePiece[i].style.left) - 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)

      {

        return i;

      }

    }

  } else

  {

    return -1;

  }

}



function up(x, y) //calculates how far up a puzzlepiece should position
{

  var cordX = parseInt(x);

  var cordY = parseInt(y);

  if (cordY > 0)

  {

    for (var i = 0; i < gamePiece.length; i++)

    {

      if (parseInt(gamePiece[i].style.top) + 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)

      {

        return i;

      }

    }

  } else

  {

    return -1;

  }

}



function down(x, y) //calculates how far down a puzzlepiece should position

{

  var cordX = parseInt(x);

  var cordY = parseInt(y);

  if (cordY < 300)

  {

    for (var i = 0; i < gamePiece.length; i++)

    {

      if (parseInt(gamePiece[i].style.top) - 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)

      {

        return i;

      }

    }

  } else

  {

    return -1;

  }

}



function swap(position) //moves the puzzle piece by switching position with an empty space
{

  var temp = gamePiece[position].style.top;

  gamePiece[position].style.top = spaceY;

  spaceY = temp;

  temp = gamePiece[position].style.left;

  gamePiece[position].style.left = spaceX;

  spaceX = temp;

}

function start() //starts the move counter when the button is pressed
{
  totalMoves = 0;
  hasStopped = false
  ticker = document.getElementById("Moves");
}

function display() //helps update the display when a move is successfully made
{
  ticker.innerHTML = totalMoves;
}

function reset() {
  hasStopped = true
}
body {
  background-color: white;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 14px;
}

#controls,
#overall,
#puzzlearea {
  width: 400px;
}

#controls {
  padding-top: 10px;
  text-align: center;
}

h1 {
  margin: 10px 0px;
  text-align: center;
}


/* Used to center the puzzle. */

#overall {
  margin-left: auto;
  margin-right: auto;
}


/* The area that holds the 15 puzzle pieces. */

#puzzlearea {
  font-size: 32px;
  height: 400px;
  padding: 0px;
  position: relative;
}


/* This class should be applied to each of the 15 puzzle pieces. */

.puzzlepiece {
  border: 2px solid black;
  height: 96px;
  line-height: 96px;
  position: absolute;
  text-align: center;
  vertical-align: middle;
  width: 96px;
}


/* This class should be applied to a puzzle piece that can be moved. */

.movablepiece:hover {
  border-color: red;
  color: #006600;
  text-decoration: underline;
}
<!DOCTYPE HTML>
<html>
<title> 15 Slider Puzzle</title>

<link rel="stylesheet" type="text/css" href="15 Slider.css" />
<script src="15 Slider.js" type="text/javascript"></script>

<head>

  <body onload="initialize()">
    <h1>Slider Puzzle</h1>
    <div id="overall">
      <div id="puzzlearea">
        <!-- the following are the fifteen puzzle pieces -->
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
        <div>7</div>
        <div>8</div>
        <div>9</div>
        <div>10</div>
        <div>11</div>
        <div>12</div>
        <div>13</div>
        <div>14</div>
        <div>15</div>
      </div>
      <div id="controls"></div>
      <button onclick="start();">Start</button>
      <button onclick="reset();">Reset</button>
      <br> Number Of Moves: <span id="Moves">0</span>
    </div>
    <!--content-->
    <br>
</head>

</html>

Use this as a demo https://jsfiddle.net/ugonnaezema/0gpeo1sj/2/

Initialize a new variable to check if the reset button has been pressed

var isResetPressed = false;

Set isResetPressed to false when initialize is called, then check if the reset button is pressed

function initialize() {
    var puzzleArea = document.getElementById("puzzlearea");
    gamePiece = puzzleArea.getElementsByTagName("div"); //retrieve element within puzzlearea
    isResetPressed = false;

    for (var i = 0; i < gamePiece.length; i++) //applies features to each puzzle piece 

    {
      ...

        gamePiece[i].onclick = function () //activates when mouse clicks on a puzzle piece
        {
            if (checkMove(parseInt(this.innerHTML))) //checks whether or not the puzzle piece can move into an empty space

            {
                swap(this.innerHTML - 1); //moves into an empty space if true

                if (isResetPressed)
                {
                    totalMoves = totalMoves;
                }
                else 
                {
                        totalMoves++;
                }

                display();

                if (finish()) //checks when the all the 15 pieces are in its right space

                {

                    win(); //alerts the player that they have won the game
                    
                }
                
                return;
            }
        }

     ...

Set up the reset function as follows


function reset()
{
    display();
    isResetPressed = true;
}

Ok, in your reset function, pop the current moves into a temp variable and display that, then totalMovves = 0;

You could either manually change the display to use the old value:

ticker.innerHTML = totalMoves;
totalMoves = 0;

But I would do this by altering the Display function to look like below:

function display(var moves = totalMoves) //helps update the display when a move is successfully made
{
    ticker.innerHTML = moves;
}

Or you could simply change the order of your commands

function reset(){
  display();
  totalMoves = 0;
}
Related