我正在尝试显示获胜阵列

时间:2016-07-15 05:07:46

标签: ruby

我正在尝试在if和elsif语句之后显示获胜数组,但我不知道如何正确显示已被if和elsif语句检查后被选为胜利者的数组。 / p>

   # Helper Method
    def position_taken?(board, index)
   !(board[index].nil? || board[index] == " ")
   end


 # Define your WIN_COMBINATIONS constant
 WIN_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]
   ]
#board = [" ", "X", "O"]
def won?(board)
WIN_COMBINATIONS.each do |win_combination|

win_index_1 = win_combination[0]
position_1 = board[win_index_1]

win_index_2 = win_combination[1]
position_2 = board[win_index_2]

win_index_3 = win_combination[2]
position_3 = board[win_index_3]
#is position 1, 2 , and 3 all equal to X or O?
#if so return win_combination
if    position_1 == "X" && position_2 == "X"  && position_3 == "X"
  win_combination 
elsif position_1 == "O" && position_2 == "O" && position_3 == "O"
  win_combination 
  else
    false
   end
 end
   end

2 个答案:

答案 0 :(得分:0)

你能试试吗?

def won?(board)
  winner = nil
  WIN_COMBINATIONS.each do |win_combination|
    win_index_1 = win_combination[0]
    position_1 = board[win_index_1]

    win_index_2 = win_combination[1]
    position_2 = board[win_index_2]

    win_index_3 = win_combination[2]
    position_3 = board[win_index_3]

    if position_1 == "X" && position_2 == "X"  && position_3 == "X"
      winner = win_combination
    elsif position_1 == "O" && position_2 == "O" && position_3 == "O"
      winner = win_combination 
    end

    break if winner
  end

  return winner
end

答案 1 :(得分:0)

def won?(board)
  WIN_COMBINATIONS.detect do |win_combination|
    [[?X], [?O]].include? win_combination.map(&board.method(:[])).uniq
  end
end

虽然这个代码看起来对新手来说有点神秘,但它相当干净透明。我们在这里做什么:

  1. 使用Enumerable#detect来检测获胜者组合。
  2. 为了检查状况,我们随后:
    1. Array#map目前的胜利组合登上(这是你的六行win_index_N = ...基本上做的;
    2. 在结果数组中,我们获取唯一的项目,如果且只有所有三个符号相同,结果将为'O''X'