1

In below javascript a tic tac toe game is rendered:

src:

body {
    text-align: center;
    font-family: Arial, Helvetica, sans-serif;
    }


h2 {
    margin: 0 auto;
    font-size: 35px;
    margin: 10px;
}


.flex-container {
    /* In order to use flex-box we need to first set our display property */
    display: flex;
    /* center the container horizontally */
    justify-content: center;
    /* this will center content vertically */
    align-items: center;
    /* tells the container to align the children in columns rather than rows */
}

.flex-column {
    height: 100%;
    width: 100%;
    flex-direction: column;
    /* tells the container to drop down once it reaches max-width */
}

.flex-wrap {
    flex-wrap: wrap;
    height: 432px;
    width: 432px;
}


.square {
    border: 2px solid rgba(0, 0, 0, .75);
    height: 140px;
    width: 140px;
    font-size: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
}


#reset-button {
    text-align: center;
    font-size: 20px;
    border: 1px solid black;
    height: 55px;
    width: 100px;
    margin: 10px;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <!-- this is how we link up the css -->
    <link href="style.css" rel="stylesheet" type="text/css">
    <!-- And this is how we link up the JS! -->
    <script defer src="main.js"></script>
    <!-- A fun title -->
    <title>Empowering Tic Tac Toe for the Good of Humanity</title>
</head>
<body>
    <h1>Tic-Tac-Toe</h1>
    <h2>It's X's turn!</h2>
    <!-- Many websites are just divs on divs on divs. -->
    <div class="flex-container flex-column">
        <div class="flex-container flex-wrap" id="board">
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        </div>
        <!-- I added a little reset button because our users are going to want to play round after round of our glorious game without ever refreshing the browser! -->
        <button id="reset-button">reset</button>
    </div>
</body>
</html>

/*----- constants -----*/
const winningCombos = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
    ];

/*----- app's state (variables) -----*/

let board;
let turn = 'X';
let win;

/*----- cached element references -----*/

const squares = Array.from(document.querySelectorAll('#board div'));

/*----- event listeners -----*/
document.getElementById('board').addEventListener('click', handleTurn);
const messages = document.querySelector('h2');
document.getElementById('reset-button').addEventListener('click', init);


/*----- functions -----*/

function getWinner() {
    let winner = null;
    winningCombos.forEach(function(combo, index) {
        if (board[combo[0]] && board[combo[0]] === board[combo[1]] && board[combo[0]] === board[combo[2]]) winner = board[combo[0]];
        });
        return winner ? winner : board.includes('') ? null : 'T';
};

function getPosition(playerName) {

    const userAction = async () => {
      const response = await fetch('/', {
        method: 'GET',
        body: '/data/3', // string or object
        headers: {
          'Content-Type': 'application/json'
        }
      });
    const myJson = await response.json(); //extract JSON from the http response
    conole.log('myJson' , myJson)
        // do something with myJson
}

    var client = new HttpClient();
    client.get('/data/3', function(response) {
       console.log('response is'+response)
    });

    console.log('Getting position for player'+playerName)
}

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() {
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );
        anHttpRequest.send( null );
    }
}

function handleTurn() {
    let idx = squares.findIndex(function(square) {
        return square === event.target;
    });
    console.log('Turn is '+turn)

    if(turn == 'X') {
        getPosition('X')
        board[idx] = turn;
        turn = turn === 'X' ? 'O' : 'X';
    }
    else {
        getPosition('O')
        board[idx] = turn;
        turn = turn === 'X' ? 'O' : 'X';
    }
    win = getWinner();
    render();
};

function init() {
    board = [
    '', '', '',
    '', '', '',
    '', '', ''
    ];
    render();
};

function render() {
    board.forEach(function(mark, index) {
    //this moves the value of the board item into the squares[idx]
    squares[index].textContent = mark;
    });
    messages.textContent = win === 'T' ? `That's a tie, queen!` : win ? `${win} wins the game!` : `It's ${turn}'s turn!`;
    };



function wait(ms)
{
    var d = new Date();
    var d2 = null;
    do { d2 = new Date(); }
    while(d2-d < ms);
}

init();

365体育足球滚球比分I'm attempting to send 'X' to all positions spaced 1 second apart:

turn = 'X'
for (i = 0; i <= 8; i++) {
        board[i] = 'X';
        turn = turn === 'X' ? 'O' : 'X';
        console.log(board)
        render();
        wait(1000)
}

'X' is sent to all positions:

but the interval of sending each position 1 second apart is not working, instead the UI 'holds' until the end of the loop and then the board is updated.

How to updated the code so that the board is updated per second as each position is sent within the loop ?

fiddle:

1

Actually, there are two problems that you are facing here.

  1. You don't need to use custom wait function, the wait function is not a really good practice because it will block your execution runtime (since javascript is a single thread language) so your code will eat a huge amount of resources. Instead, you must use native browser API functions like, or which make your code asynchronous and it will prevent blocking your code.

  2. Loops will not wait for custom wait function or even setTimeout or setInterval to complete and they will continue to iterate to your last element. So you need to set different time delays for each to execute them at different times and then use for holding the value of i. So in order to do this, you need to increment your i value exactly after each iteration gets executed. So the best practice for this using while loop over for loop. For more information about loops you can read .


365体育足球滚球比分Finally, in order to make it work, you should replace

turn = 'X'
for (i = 0; i <= 8; i++) {
        board[i] = 'X';
        turn = turn === 'X' ? 'O' : 'X';
        console.log(board)
        render();
        wait(1000)
}

with

turn = 'X'
var i = 0;
while (i < 9) {
  (function(i) {
    setTimeout(function() {
      board[i] = 'X';
      turn = turn === 'X' ? 'O' : 'X';
      console.log(board)
      render();
    }, 1000 * i)
  })(i++)
}

Working demo:

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.