0
function aiPick() {
    let aiCell = null;
    while (aiCell == null) {
      let aiColIndex = Math.floor(Math.random() * 7)
      console.log(aiColIndex)
      aiCell = getFirstOpenCellForColumn(aiColIndex) 
      console.log(typeof(aiCell))
      console.log(getClassListArray(aiCell))
    }
    aiCell.classList.add('red')
    checkStatusOfGame(aiCell)
    yellowIsNext = !yellowIsNext
    aiClassList = getClassListArray(aiCell)
    aiColClass = aiClassList.find(className => className.includes('col'));
    let aiColIndex = parseInt(aiColClass[4], 10);
    clearColorFromTop(aiColIndex)
}

我正在为 Connect Four 游戏开发一个对手。我让它随机选择七列中的一列,然后该函数将通过向 thatgetFirstOpenCellForColumn添加一个类来标记第一个打开的单元格。reddiv

然后,代码会检查移动是否与玩家获胜checkStatusOfGame(aiCell)并交换玩家并移除显示在游戏板外部列顶部的用作“选择器”的令牌。

我正在寻找一种方法让计算机在列中的最后一个空间被占用时生成一个新的随机数来选择一列。我认为这会做到这一点,因为当计算机选择一个完整的列时,它会给我这个错误消息:

script.js:39 Uncaught TypeError: Cannot read properties of null (reading 'classList')
    at getClassListArray (script.js:39)
    at aiPick (script.js:274)
    at HTMLDivElement.handleCellClick (script.js:258)

但它似乎并没有回到选择一个随机数,而是简单地跳到yellowIsNext = !yellowIsNext这样我现在放置计算机的红色令牌而不是我的黄色令牌。

基本上,我希望代码

  1. 选择一个随机数
  2. 将令牌放在与该数字对应的列中
  3. 如果该列已满,请返回#1

你知道为什么这不起作用吗?还有另一种写while循环的方法,还是let aiCell = null不正确?

谢谢!

4

0 回答 0