纸,剪刀,红宝石中的摇滚游戏.当一个数组更改数据时,它会更改另一个数组的数据 (¿?)



这是我的代码:

class RockPaperScissors
   # Exceptions this class can raise:
  class NoSuchStrategyError < StandardError
  end
  def self.winner(player1, player2)
    if ((player1[1] == 'R') && (player2[1] == 'S') ||
        (player1[1] == 'S') && (player2[1] == 'P') ||
        (player1[1] == 'P') && (player2[1] == 'R'))
      return player1
    elsif ((player1[1] == 'R') && (player2[1] == 'P') ||
        (player1[1] == 'S') && (player2[1] == 'R') ||
        (player1[1] == 'P') && (player2[1] == 'S'))
      return player2
    elsif ((player1[1] == 'R') && (player2[1] == 'R') ||
        (player1[1] == 'S') && (player2[1] == 'S') ||
        (player1[1] == 'P') && (player2[1] == 'P'))
      return player1
    end
  end
  def self.tournament_winner(tournament)
    player1 = Array.new
    player2 = Array.new
    nextround = Array.new
    while tournament.length != 1 do
      tournament.each_with_index {|item, index|
        if (index%2!=0)
          player2[0] = item[0]
          player2[1] = item[1]
        elsif (index%2 ==0)
          player1[0] = item[0]
          player1[1] = item[1]
        else
          puts 'bananas'
        end
        if (index%2!=0)
          nextround[(index-1)/2] = winner(player1, player2)
        end
      }
      tournament=nextround
    end
    return tournament
  end
end

RockPaperScissors.tournament_winner([["num1", "R"], ["num2", "P"], ["num3", "P"], ["num4", "R"]])

好吧,最后一行是执行启动。这个代码制作了一个石头、剪刀布的比赛。它接受每个角色及其攻击的数组数组作为输入,并且必须返回包含冠军及其攻击的数组。

锦标赛是 num1 vs num2 (num2 胜), 和 num3 vs num4 (num3 胜)。然后决赛是 Num2 vs Num3,在这个马厩中,队友赢得了数组中的第一个人 (Num2)。

这似乎过于复杂,因为代码必须处理任意数量的字符,只要它们的数量是 base2(2、4、8、16 个字符......等)。

我的问题是下一个(调试代码,你会看到)。当它更改数组"Player1"或"Player2"的值时,它也会更改数组"下一轮"中的值,即使它不在该行中!

这是不应该发生的!

顺便说一下,我正在学习Ruby,所以这可能是一个非常愚蠢的失败。

为什么这必须是真的?

"这似乎过于复杂,因为代码必须处理任意数量的字符,只要它们的数量是base2(2,4,8,16个字符......,等等)。

与其让 player1 和 player2 成为数组,我会将它们重写为类 player 的实例。然后在 Player 类中编写方法,以便可以调用 player1.hand,它会返回'S' || 'R' || 'P'

这样,您就可以存储玩家在玩家对象上有多少胜利,

我会研究了解更多的事情

  • 案例/当语句

  • 特殊初始化方法

  • attrs_accessor(用于使数据跨类可访问)

  • 模块

我也看到它完成了,我可能错了,但通常你不会把类放在类中。

最新更新