连接四个问题

问题描述

我正在尝试通过查找先前代码解决方案并找出每个部分在做什么以学习如何使用它们的方法来学习编码。 我想成为一名开发人员,但我不想复制并粘贴所有内容,我想真正地了解正在发生的事情,因此我可以自己编写代码。我可以观看100部视频,但是我有问题并且需要帮助,希望外面有人可以帮助我....

我想知道是否有人可以向我解释下面的代码中发生了什么。

 * Player 1 and 2 alternate turns. On each turn,a piece is dropped down a
 * column until a player gets four-in-a-row (horiz,vert,or diag) or until
 * board fills (tie)
 */

class Game {
  constructor(p1,p2,height = 6,width = 7) {
    this.players = [p1,p2];
    this.height = height;
    this.width = width;
    this.currPlayer = p1;
    this.makeBoard();
    this.makeHtmlBoard();
    this.gameOver = false;
  }

  /** makeBoard: create in-JS board structure:
   *   board = array of rows,each row is array of cells  (board[y][x])
   */

**Question: So I believe that this is creating a board and making it empty by looping through it?**
 
 makeBoard() {
    this.board = [];
    for (let y = 0; y < this.height; y++) {
      this.board.push(Array.from({ length: this.width }));
    }
  }

  **Question: Is this grabbing the board element from the HTML Page? board.innerHtml is blank,however
didnt we just make a blank a board? Why do we need this?**

  makeHtmlBoard() {
    const board = document.getElementById('board');
    board.innerHTML = '';

    // make column tops (clickable area
    // for adding a piece to that column)
    const top = document.createElement('tr');
    top.setAttribute('id','column-top');

    // store a reference to the handleClick bound function 
    // so that we can remove the event listener correctly later
    this.handleGameClick = this.handleClick.bind(this);
    
    top.addEventListener("click",this.handleGameClick);

    for (let x = 0; x < this.width; x++) {
      const headCell = document.createElement('td');
      headCell.setAttribute('id',x);
      top.append(headCell);
    }

    board.append(top);

    // make main part of board
    for (let y = 0; y < this.height; y++) {
      const row = document.createElement('tr');
    
      for (let x = 0; x < this.width; x++) {
        const cell = document.createElement('td');
        cell.setAttribute('id',`${y}-${x}`);
        row.append(cell);
      }
    
      board.append(row);
    }
  }

  /** findSpotForCol: given column x,return top empty y (null if filled) */

**Question: I have no idea what this line is doing**

  findSpotForCol(x) {
    for (let y = this.height - 1; y >= 0; y--) {
      if (!this.board[y][x]) {
        return y;
      }
    }
    return null;
  }

  /** placeInTable: update DOM to 
   * place piece into HTML board */

**Question: Im not sure what place in table is doing,however I kNow the second line is creating a DIV on 
the table,third line is styling it,however the last three lines i need help with it.**

  placeInTable(y,x) {
    const piece = document.createElement('div');
    piece.classList.add('piece');
    piece.style.backgroundColor = this.currPlayer.color;
    piece.style.top = -50 * (y + 2);

    const spot = document.getElementById(`${y}-${x}`);
    spot.append(piece);
  }

  /** endGame: announce game end */

  endGame(msg) {
    alert(msg);
    const top = document.querySelector("#column-top");
    top.removeEventListener("click",this.handleGameClick);
  }

  /** handleClick: handle click of column top to play piece */

  handleClick(evt) {
    // get x from ID of clicked cell
    const x = +evt.target.id;

The lines below,I have no idea how I Could even think of this logic,please help.

    ****// get next spot in column (if none,ignore click)
    const y = this.findSpotForCol(x);
    if (y === null) {
      return;**
    }
    // place piece in board and add to HTML table
    this.board[y][x] = this.currPlayer;
    this.placeInTable(y,x);
    // check for tie
    if (this.board.every(row => row.every(cell => cell))) {
      return this.endGame('Tie!');
    }
    // check for win
    if (this.checkForWin()) {
      this.gameOver = true;
      return this.endGame(`The ${this.currPlayer.color} player won!`);
    }
    // switch players
    this.currPlayer =
      this.currPlayer === this.players[0] ? this.players[1] : this.players[0];**
  }

  /** checkForWin: check board cell-by-cell for "does a win start here?" */

  checkForWin() {
    // Check four cells to see if they're all color of current player
    //  - cells: list of four (y,x) cells
    //  - returns true if all are legal coordinates & all match currPlayer
    const _win = cells =>
      cells.every(
        ([y,x]) =>
          y >= 0 &&
          y < this.height &&
          x >= 0 &&
          x < this.width &&
          this.board[y][x] === this.currPlayer
      );

    for (let y = 0; y < this.height; y++) {
      for (let x = 0; x < this.width; x++) {
        // get "check list" of 4 cells (starting here) for each of the different
        // ways to win
        const horiz = [[y,x],[y,x + 1],x + 2],x + 3]];
        const vert = [[y,[y + 1,[y + 2,[y + 3,x]];
        const diagDR = [[y,x + 3]];
        const diagDL = [[y,x - 1],x - 2],x - 3]];

        // find winner (only checking each win-possibility as needed)
        if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {
          return true;
        }
      }
    }
  }
}

class Player {
  constructor(color) {
    this.color = color;
  }
}

document.getElementById('start-game').addEventListener('click',() => {
  let p1 = new Player(document.getElementById('p1-color').value);
  let p2 = new Player(document.getElementById('p2-color').value);
  new Game(p1,p2);
});

解决方法

编程的很大一部分是将问题分解为您可以理解的较小问题。对于初学者来说,此问题的语法和大小可能有些高级。

通常-以下是概述:

  1. 正确
  2. 在javascript中有一个“板”,在HTML中有一个“板”。 javascript是逻辑的,而HTML HTML是用于显示的。这就是为什么您会看到创建两个板的原因
  3. findSpotForCol在给定列中找到最高的未填充位置。这对于您真正深入并尝试自己编写它是一个好问题。当您在连接4中放置令牌时,令牌会到达该列中的最高点,该位置当前尚未填充。 findSpotforCol是做到这一点的算法。
  4. 每个玩家都有自己的颜色。这会将棋子放置在正确的位置,并带有正确的玩家颜色。这将占用我们的JavaScript逻辑板,并在玩家进行移动时使其正确显示在页面上
  5. 没关系,没关系! (“我不知道我怎么能想到这种逻辑”)。考虑一下您在玩connect 4时所做的一切。首先,将检查器放入一列中。它将转到该列中可用的最低点。然后-如果整个董事会都满了,那就平局。然后,您可以检查玩家是否获胜。 (注意-您粘贴的此代码中有一个错误,如果玩家在最后一个检查程序中获胜,则会显示“并列”,因为它首先检查并列)。然后,轮到其他玩家了。

我花了很长时间进行许多初学者练习,以使我理解这样的问题,这种问题正在变得越来越高级,因此不必为审查初学者练习或向其他平台/工具学习而感到难过。 /图书。如果您感到100%不知所措,那不是学习的好地方,您可能应该寻找一个更简单的问题。例如,井字游戏比连接四子游戏要容易一个步骤。