【问题标题】:How can I make my tic-tac-toe game end in a tie?如何让我的井字游戏以平局收场?
【发布时间】:2013-12-06 16:36:27
【问题描述】:

我在 Ruby 中创建了一个井字游戏程序。我对允许游戏以平局结束的代码部分有问题。

我编写了一个 if 语句来检查玩家何时赢得游戏。这是我的 else 条件。当我尝试运行程序时出现错误。怎么了?

else 
  while @turn == "x" or "o"
    @square_count -= 1 # I set empty_count to 9 in the initialize of the class 
    # of this program. This would minus 1 from empty) count_each every turn
  end
  if @square_count == 0 #when all the slots are taken, its a tie game
    puts "Tie game!"
    return true  #this makes the program end
  end

我得到的错误是:

tac.rb:89: warning: string literal in condition
tac.rb:88:in `block in check_win': undefined method `-' for nil:NilClass (NoMethodError)
    from tac.rb:77:in `each'
    from tac.rb:77:in `check_win'
    from tac.rb:108:in `<class:Game>'
    from tac.rb:1:in `<main>'

【问题讨论】:

  • 你得到什么错误信息?

标签: ruby


【解决方案1】:

看起来@square_count 可能没有被赋值,所以你可能会得到你指出的错误,因为没有赋值,@square_count 将保持一个 nil 值。

另外,您的 while 语句可能不是您想要的,while 语句当前将始终评估为“真”,因为值为“o”。

【讨论】:

    【解决方案2】:

    替换

    while @turn == "x" or "o"
    

    while @turn == "x" or @turn == "o"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多