gpt4 book ai didi

ruby - Ruby 的新手,尝试将数组与嵌套数组进行比较

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:44 25 4
gpt4 key购买 nike

所以我正在构建一个井字游戏,我试图从我的棋盘哈希中提取键,然后将其与数组中的数组进行比较。问题是获胜组合都有 3 个值,但玩家可能需要 4 或 5 步才能获胜,所以我想看看这 4 或 5 个值是否包括其中一个获胜组合(希望这是有意义的)。具体来说,问题出在 winner_check 方法上,有没有办法让这个方法起作用?

def initialize_board
board = {}
(1..9).each {|position| board[position] = ' ' }
board
end

def empty_positions(board)
board.keys.select {|position| board[position] != 'X' && 'O'}
end

def player_turn(board)
puts "Let's play Tic Tac Toe! Pick a position 1-9 and try to beat me."
position = gets.chomp.to_i
board[position] = 'X'
end

def computer_turn(board)
position = empty_positions(board).sample
board[position] = 'O'
end

def winner_check(board)
winning_combos = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]]
winning_combos.each {|combo|}
if board.select { |k,v| v == 'X' }.keys.include?(combo)
puts "You've won! Great job!"
if board.select { |k,v| v == 'O' }.keys.include?(combo)
puts "Looks like the computer outsmarted you, try again!"
elsif
puts "Looks like you've tied, try again!"
end
nil
nil
end

def game_over?(board)
empty_positions(board) == []
end

def draw_board(board)
puts
puts " #{board[1]} | #{board[2]} | #{board[3]} "
puts "---+---+---"
puts " #{board[4]} | #{board[5]} | #{board[6]} "
puts "---+---+---"
puts " #{board[7]} | #{board[8]} | #{board[9]} "
puts
end

board = initialize_board
draw_board(board)

until winner_check(board) || game_over?(board)
player_turn(board)
draw_board(board)
winner_check(board)
computer_turn(board)
draw_board(board)
winner_check(board)
end

最佳答案

我认为你在正确的轨道上,但你有一些语法错误:

winning_combos.each {|combo|}
if board.select { |k,v| v == 'X' }.keys.include?(combo)
puts "You've won! Great job!"
if board.select { |k,v| v == 'O' }.keys.include?(combo)
puts "Looks like the computer outsmarted you, try again!"
elsif
puts "Looks like you've tied, try again!"
end
nil

在第一行,您过早地关闭了您的区 block 。行尾的 } 关闭 block 。

在最后一行,您有文字 nil 的地方,我认为这是您结束 } 的地方。

你还有两个连续的if,应该是if, elsif

更正了语法错误:

winning_combos.each { |combo|

if board.select { |k,v| v == 'X' }.keys.include?(combo)
puts "You've won! Great job!"
elsif board.select { |k,v| v == 'O' }.keys.include?(combo)
puts "Looks like the computer outsmarted you, try again!"
elsif
puts "Looks like you've tied, try again!"
end
}

关于ruby - Ruby 的新手,尝试将数组与嵌套数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26724472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com