【发布时间】:2019-10-10 20:13:15
【问题描述】:
我正在开发井字游戏,并想检查玩家的选择是否与包含获胜组合的嵌套数组匹配。
此时,例如 [7,8,9] 或 [9,7,8] 或 [1,2,3] 或 [1,3,2] 结束游戏并宣布获胜者,如他们应该。
但是,例如,[1,7,8,6,9] 或 [1,7,3,5,6] 或 [1,4,2,3,9] 将被忽略,获胜者获胜'尽管数组包括获胜组合“7,8,9”和“3,5,7”和“1,2,3”,但不会按预期声明。
提前感谢您的任何建议或帮助。
3x3 网格中的所有获胜组合。
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]]
我有两个玩家数组,@@player_one 和 @@player_two 从@possible_choice 数组中选择数字。
@possible_choice = [1,2,3,4,5,6,7,8,9]
.
.
.
def player_one_turn()
puts "Player One, make your choice:"
p @possible_choice
puts @grid
@@player_one << @possible_choice.delete(gets.chomp.to_i)
p @@player_one
end
我也有has_won?方法
def has_won?
WINNING_COMBOS.include?(@@player_one.sort) ||
WINNING_COMBOS.include?(@@player_two.sort)
end
完整的未完成游戏。请不要介意网格,我还在努力。
class Grid
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]]
attr_accessor :possible_choice
attr_accessor :grid
def initialize
@possible_choice = [1,2,3,4,5,6,7,8,9]
@grid = "
|----|----|----|
| 1 | 2 | 3 |
|----|----|----|
| 4 | 5 | 6 |
|----|----|----|
| 7 | 8 | 9 |
|----|----|----|
"
end
end
class Game < Grid
@@player_one = Array.new
@@player_two = Array.new
def game
puts
puts "*** This is a tic-tac-toe game for two human players. ***"
puts
loop do
player_one_turn()
puts
if has_won?
puts "The game has ended. Player One has won!"
puts
return
end
break if @@player_one.length == 5
player_two_turn()
puts
if has_won?
puts "The game has ended. Player Two has won!"
puts
return
end
end
end
def player_one_turn()
puts "Player One, make your choice:"
p @possible_choice
puts @grid
@@player_one << @possible_choice.delete(gets.chomp.to_i)
p @@player_one
end
def player_two_turn()
puts "Player Two, make your choice:"
p @possible_choice
puts @grid
@@player_two << @possible_choice.delete(gets.chomp.to_i)
p @@player_two
end
def has_won?
WINNING_COMBOS.include?(@@player_one.sort) ||
WINNING_COMBOS.include?(@@player_two.sort)
end
end
new_game = Game.new
new_game.game
【问题讨论】:
-
WINNING_COMBOS.any? { |e| (@@player_one.sort & e).size == 3 }→ 你需要确保奖金中有一个元素,它与玩家的动作完全相交。 -
有一个 3×3 的网格,每个字段都可以是空的,
X或O不是更干净吗?两个@@player_one/@@player_two数组似乎有点多余。
标签: arrays ruby multidimensional-array