-1

嗨,有人可以向我解释为什么我的注射在这里不起作用吗?

我在这里正确使用注入吗?出于某种原因,一旦出现这种情况,我的代码就会陷入无限循环(通常是我的游戏中的第五步)

  def cpu_block_player
    winning_combinations = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
    executed = 0
    winning_combinations.each do |combination|
      result_of_combination = ""
      result_of_combination = combination.inject("") {|result, element| result + @board[element]}
      if result_of_combination == "XXe" || result_of_combination == "eXX" || result_of_combination == "XeX"
        executed += 1
        puts executed 
        player_move(@current_turn, result_of_combination.index("e"))     
      end
      break if executed >= 1
   end
4

1 回答 1

1

首先,这类问题更适合Code Review Stack Exchange 站点。

但是,这是我的想法:

查看您的代码时,我的第一个想法是您只有一个大类。为了看到面向对象编程的一些真正优势,我建议将一些代码提取到单独的类中。我绝对可以看到Board类里面有一个Game类,就等着被提取了。

添加到Board类的方法的一些想法:

  • to_s- 这将是您print_board目前方法中的内容,没有print.
  • finished?-- 检查游戏是否“结束”(即有人赢了)。一种winner方法也很有意义。
  • taken?-- 是否有人曾经担任过职位。

您班级中的许多代码Game都将从命名中受益。例如,以这段代码为例:

@current_turn == @player_x ? @current_turn = @player_o : @current_turn = @player_x

弄清楚这段代码的作用并不难,但是在阅读该方法时,确切地知道如何交换当前玩家可能并不重要。player_move你只想知道“此时,我们换了球员”。

提取方法和对象不会让你编写更少的代码,但在我看来它可以让代码更清晰。如果您可以为每一行命名(即,将其提取到方法中),那么弄清楚发生了什么可能会容易得多。

于 2013-07-17T05:02:00.347 回答