arrays - 如何检查数组中的数字是否包含在嵌套数组中?
问题描述
我正在开发井字游戏,并想检查玩家的选择是否与包含获胜组合的嵌套数组匹配。
目前,例如,[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 = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]]
def win?(player)
WINNING_COMBOS.each do |x,z,y|
return true if player.include?(x) && player.include?(z) && player.include?(y)
end
false
end
def has_won?
win?(@@player_one) || win?(@@player_two)
end
应该做的工作,没有必要对数组进行排序。
推荐阅读
- java - 如何从java中的对象数组的循环中打印出函数
- shopware - 自定义 cms 元素 SW6
- pandas - 木星笔记本中的 ImportError Pandas - 不查看 venv 包
- javascript - 如何在不改变容器的情况下更改数组值(对象数组内部)?javascript
- php - get_magic_quotes_gpc() 在我的代码中返回未定义
- flutter - Flutter:如何使用 Navigator 堆栈中的数据恢复屏幕
- python - 从python中的数据框中列出两列的python对
- android - 指南百分比变化时的幻灯片动画
- javascript - 你能用javascript操作数据库文件吗?
- xml - 使用 ImportXML 标识多个表