簡體   English   中英

Tic-Tac-Toe Loop

[英]Tic-Tac-Toe Loop

我在javascript中制作了一個井字游戲。 我已經列出了一些我認為是基本構建模塊的東西:

var board = [
            0, 0, 0,
            0, 0, 0,
            0, 0, 0
            ];
gameOn = true;
player1Move = true;
counter = 0;
player1 = [];
player2 = [];
var ask = console.log(prompt('where would you like to go?'));

var drawBoard = function(){
    console.log("   A " + (board[0]) + "| B " + (board[1]) + "| C " + (board[2]));
    console.log("  ------------- ");
    console.log("   D " + (board[3]) + "| E " + (board[4]) + "| F " + (board[5]));
    console.log("  ------------- ");
    console.log("   G " + (board[6]) + "| H " + (board[7]) + "| I " + (board[8]));
    console.log("  ------------- ");
};

var solutions = [
    (board[0] && board[1] && board[2]) || (board[3] && board[4] && board[5]) ||
    (board[6] && board[7] && board[8]) || (board[0] && board[3] && board[6]) ||
    (board[1] && board[4] && board[7]) || (board[2] && board[5] && board[8]) ||
    (board[0] && board[4] && board[8]) || (board[2] && board[4] && board[6])
];



while (gameOn === true){
// for loop for game logic
    for (var i = 0 ; i < 9; i++){
      if (player1Move === true) {
        player1.push(ask);
        drawBoard();
        player1Move = false;
      } else if (player1Move === false){
        player2.push(ask);
        drawBoard();
        player1Move = true;
      } else if ((player1 || player2) === solutions){
          gameOn = false;
          console.log((player1 || player2) + "wins!");
      } else {
        gameOn = false;
        console.log("Tie Game!");
      }
    }
}

我知道我的主循環的語法是不正確的。 為什么我不能做目前寫的? 如果你有這個現有的代碼,你會用什么類型的循環設置來完成這個? 對不起,如果這看起來不夠具體,我只是迷失在這一切的邏輯中!

有了這個現有的循環,我想要做的就是通過並提示2個用戶總共9次(因為最大移動= 9)。 一旦有效,我將不斷添加更多游戲邏輯。 為什么我不能得到9次提示? 目前的結果是,它提示我一次,打印出9次板,然后完全打錯。

順便說一句,這只需要在終端窗口中工作。

我盡可能少地改變你的代碼,但有些東西是不同的,我正在逐一解釋。

var board = {
    A: null,
    B: null,
    C: null,
    D: null,
    E: null,
    F: null,
    G: null,
    H: null,
    I: null
};

gameOn = true;
player1Move = true;

var drawBoard = function(){
    console.log("   A " + (board.A || '') + "| B " + (board.B || '') + "| C " + (board.C || ''));
    console.log("  ------------- ");
    console.log("   D " + (board.D || '') + "| E " + (board.E || '') + "| F " + (board.F || ''));
    console.log("  ------------- ");
    console.log("   G " + (board.G || '') + "| H " + (board.H || '') + "| I " + (board.I || ''));
    console.log("  ------------- ");
};

var solutions = function() {
    return (board.A && (board.A == board.B && board.A == board.C))
        || (board.D && (board.D == board.E && board.D == board.F))
        || (board.G && (board.G == board.H && board.G == board.I));
};

drawBoard();
var currentPlayer;

while (gameOn === true){
// for loop for game logic
    for (var i = 0 ; i < 9; i++){
        if (solutions()){
            console.log(currentPlayer + " wins!");
            gameOn = false;
            break;
         }
        //else {
        //    gameOn = false;
        //    console.log("Tie Game!");
        //}
        currentPlayer = 'Player 1';
        if(!player1Move)
            currentPlayer = 'Player 2';

        var ask = prompt(currentPlayer + ': where would you like to go (A or B or C or ..)?');
        if(ask == 'exit') {
            gameOn = false;
            break;
        }

        if (player1Move === true) {
            //player1.push(ask);
            board[ask] = 'X';
            drawBoard();
            player1Move = false;
        } else if (player1Move === false){
            board[ask] = 'O';
            drawBoard();
            player1Move = true;
        }
    }
}

它還沒有完全完成,但之后你可以做的事情,也許你不希望我為你做這一切。

這一切都適用於Chrome控制台。

有一些基本的東西阻礙了你:

  1. var ask = console.log(prompt('where would you like to go?')); 應該是var ask = prompt(currentPlayer + ': where would you like to go?'); - 你的版本填充了ask null。
  2. 這個提示也在錯誤的地方:它需要在循環中,並在drawBoard()之后,以便玩家有東西可以看。
  3. 我已將電路板從一個數組更改為一個對象,因此播放器的答案如“A”直接指向對象字段。 這樣就可以刪除播放器陣列。
  4. 您可以看到, solutions()函數需要完成,並且可能有一種更簡潔的方法。
  5. 我添加了在提示符中寫“退出”的可能性,否則無法提前退出游戲。
  6. 我沒有完成'領帶游戲'! 碼。

確保您了解全局對象,以及window.prompt是什么,以及您的上下文中的console.log 絕對有必要了解適合您環境的調試器。 在Chrome中,它被稱為開發人員工具。

window.prompt在像jsfiddle這樣的代碼沙箱中,或者在堆棧溢出的bulit-in中都不是很有用。 我建議使用HTML作為您的用戶界面。

function init() {
    trapForm();
    trapInput();
    toggleCurrentUser();
    askUser();
}

var game = [
    [null,null,null],
    [null,null,null],
    [null,null,null]
];

var trapInput = function() {
    //  capture input and use to to create a play in the game
    document.querySelector('#go').addEventListener('click',function(ev) {

        var position = document.querySelector('#square').valueAsNumber;

        if (position < 10 && position > 0) {

            //  render X or O to the HTML
            var td = document.querySelectorAll('#t3 td')[position-1];
            td.innerHTML = currentUser;

            //  modify the corresponding game array
            var row = Math.floor( (position-1) / 3 );
            var col = ( (position+2) % 3) ;
            game[row][col] = currentUser;

            //  this helps us visualize what's happening
            debug(game);
            checkGameStatus();
            toggleCurrentUser();            

        } else {
            debug({"msg":"illegal move"});
        }

    });
};

var trapForm = function() {
    //  prevent form from submitting
    var f = document.querySelector('#f');
    f.addEventListener('submit',function(ev) {
        ev.preventDefault();
        trapInput();
    });
};

 ;(function(window,document,undefined){ "use strict"; function init() { trapForm(); trapInput(); toggleCurrentUser(); askUser(); } var currentUser = 'Y'; var toggleCurrentUser = function(){ if (currentUser === 'X') { currentUser = 'Y'; } else { currentUser = 'X'; } document.querySelector('#currentuser').value = currentUser; }; var isVirginal = function(game) { return game.every(function(row) { return row.every(function(cell) { return (cell === null); }); }); }; var isStaleMate = function(game){ return game.every(function(row){ return row.every(function(cell){ return (cell === 'X' || cell === 'Y'); }); }); }; var horizontalWinner = function(game) { var r = false; return game.some(function(row){ var firstletter = row[0]; if (firstletter === null) { return false; } else { return row.every(function(cell){ return ( cell !== null && cell === firstletter); }); } }); }; var verticalWinner = function(game) { var r = false; for (var i = 0; i < 4; i++) { if (game[0][i] === null) { continue; } if (game[0][i] === game[1][i] && game[1][i] === game[2][i]) { r = game[0][i]; break; } }; return r; }; var diagonalWinner = function(game) { var r = false; if (game[0][0] !== null && (game[0][0] === game[1][1] === game[2][2])) { r = game[0][0]; } if (game[0][2] !== null && (game[0][2] === game[1][1] === game[2][0])) { r = game[0][2]; } return r; }; var checkGameStatus = function(){ var r = 'unknown'; if (isVirginal(game)) { r = 'Virginal Game'; } else { r = 'In Play'; } if (isStaleMate(game)) { r = 'Stale Mate'; } if (diagonalWinner(game)){ r = 'Diagonal Winner: ' + diagonalWinner(game); } if (verticalWinner(game)) { r = 'vertical Winner: ' + verticalWinner(game); } if (horizontalWinner(game)) { r = 'Horizontal Winner: ' + horizontalWinner(game); } document.querySelector('#status').value = r; }; var debug = function(stuff) { document.querySelector('#debug').innerHTML = JSON.stringify(stuff); }; var game = [ [null,null,null], [null,null,null], [null,null,null] ]; var trapInput = function() { // capture input and use to to create a play in the game document.querySelector('#go').addEventListener('click',function(ev) { var position = document.querySelector('#square').valueAsNumber; if (position < 10 && position > 0) { // render X or O to the HTML var td = document.querySelectorAll('#t3 td')[position-1]; td.innerHTML = currentUser; // modify the corresponding game array var row = Math.floor( (position-1) / 3 ); var col = ( (position+2) % 3) ; game[row][col] = currentUser; // this helps us visualize what's happening debug(game); checkGameStatus(); toggleCurrentUser(); } else { debug({"msg":"illegal move"}); } }); }; var trapForm = function() { // prevent form from submitting var f = document.querySelector('#f'); f.addEventListener('submit',function(ev) { ev.preventDefault(); trapInput(); }); }; document.addEventListener('DOMContentLoaded',init); })(window,document); 
 #t3 { font-family: "Courier New"; font-size: xx-large; } #t3 td { border: 1px solid silver; width: 1em; height: 1em; vertical-align: middle; text-align: center; } #f { position: relative; } #f label, input, button { float: left; width: 200px; } #f label, button { clear: left; } hr { clear: both; visibility: hidden; } 
 <form id="f"> <label for="currentuser">Current User</label> <input type="text" readonly id="currentuser" name="currentuser" /> <label for="square">What Square (1-9)?</label> <input type="number" step="1" min="1" max="9" id="square" name="square" /> <label for="status">Game Status</label> <input type="text" readonly id="status" name="status" value="Virgin Game" /> <button type="button" id="go">make move</button> </form> <hr /> <table id="t3"> <tr> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> </tr> </table> <pre id="debug"></pre> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM