You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby实现火柴盒式井字棋AI游戏结束逻辑失效问题求助

井字棋AI游戏结束逻辑故障排查与修复

用Ruby编写井字棋AI基础框架时,遇到一个重复出现的问题:当done数组所有元素都为true(棋盘填满)时,程序没有触发游戏结束逻辑,反而持续要求用户输入,添加测试打印语句也无法输出预期内容。

原代码

game = Array.new(9, " ")
done = Array.new(9, false)
gameplay = true
while gameplay
    input = gets.to_i
    if !done.include?(false)
        puts "game over!"
        gameplay = false
        break
    end
    
    if input < 0 || input > 8
        puts "Put a number from 0 to 8!"
        next
    end
    if(!done[input])
        game[input] = "o"
        done[input] = true
    else
        puts "That spot is filled!"
        next
    end
    while true
        cmove = rand 9
        if done[cmove] == true
            next
        else
            game[cmove] = "x"
            done[cmove] = true
            puts "The computer chose #{cmove}."
            break
        end
    end
    puts "#{game[0]}|#{game[1]}|#{game[2]}"
    puts "#{game[3]}|#{game[4]}|#{game[5]}"
    puts "#{game[6]}|#{game[7]}|#{game[8]}"
end

问题根源

核心问题在于游戏结束的判断逻辑被放在了获取用户输入的语句之后。当棋盘已经填满时,程序会先执行input = gets.to_i,卡住等待用户输入,根本没机会进入if !done.include?(false)的判断分支,自然不会触发游戏结束的逻辑。

修复方案

把游戏结束的判断移到gets.to_i之前,确保每次进入循环时先检查棋盘是否已满,再处理用户输入。同时可以优化电脑落子的逻辑,避免不必要的随机循环。

修改后的代码

game = Array.new(9, " ")
done = Array.new(9, false)
gameplay = true

while gameplay
    # 优先检查游戏是否结束
    if !done.include?(false)
        puts "game over!"
        gameplay = false
        break
    end

    input = gets.to_i
    
    if input < 0 || input > 8
        puts "Put a number from 0 to 8!"
        next
    end
    
    if !done[input]
        game[input] = "o"
        done[input] = true
    else
        puts "That spot is filled!"
        next
    end

    # 优化电脑落子:直接定位第一个空位
    cmove = done.index(false)
    game[cmove] = "x"
    done[cmove] = true
    puts "The computer chose #{cmove}."

    # 打印当前棋盘状态
    puts "#{game[0]}|#{game[1]}|#{game[2]}"
    puts "#{game[3]}|#{game[4]}|#{game[5]}"
    puts "#{game[6]}|#{game[7]}|#{game[8]}"
end

关键修改说明

  • 调整判断顺序:将游戏结束的检查放在获取用户输入之前,确保棋盘填满时直接触发结束逻辑,不再等待用户输入
  • 优化电脑落子:使用done.index(false)直接获取第一个未被占用的位置,替代原有的随机循环逻辑,提升效率同时避免潜在的无限循环风险

内容的提问来源于stack exchange,提问作者Eja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:43:25