### Tic-Tac-Toe：检查一名球员是否赢了

``````class TicTacToe

WINNING_COMBINATIONS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], #Horizontal
[0, 3, 6], [1, 4, 7], [2, 5, 8], #Vertical
[0, 4, 8], [2, 4, 6]] #Diagonal

def initialize
@board = ["", "", "", "", "", "", "", "", ""]
@players = ['player_one', 'player_two']
@current_player = 'player_one'
end

def player_1
@players.first
end

def player_2
@players.last
end

def switch
@current_player = opponent_of(@current_player)
end

def display_board
puts " #{@board[0]} | #{@board[1]} | #{@board[2]} "
puts "-----------"
puts " #{@board[3]} | #{@board[4]} | #{@board[5]} "
puts "-----------"
puts " #{@board[6]} | #{@board[7]} | #{@board[8]} "
end

def move(position)
fail "Please select a space within range." if position < 1 || position > 9
fail "That space is already taken!" unless @board[position-1].empty?
if @current_player == player_1
@board[position-1] = 'o'
else
@board[position-1] = 'x'
end
switch
end

def check_for_winner
#Help!
end

private

def opponent_of(player)
@players.select { |p| p != player }.first
end
end
``````

#### 3 个答案:

``````def check_for_winner
WINNING_COMBINATIONS.each do |combination|
case board.values_at(*combination)
when %w(o o o)
return 'Player 1 wins'
when %w(x x x)
return 'Player 2 wins'
end
end
end
``````

``````def has_winner(board)
WINNING_COMBINATIONS.each do |line|
return true if (line - board) == []
end
return false
end
``````

``````def has_winner(board)
WINNING_COMBINATIONS.any? {|line| (line - board) == [] }
end
``````

``````def has_winner(board)
WINNING_COMBINATIONS.each do |i, j, k|
return true if board[i] == board[j] && board[i] == board[k]
end
false
end
``````