9

我在一个介绍性的软件开发课程上,我的作业是创建一个石头剪刀布程序,它接受两个参数(石头、纸)等,并返回获胜的 arg。

现在如果我可以使用条件,我会快速解决这个问题,但是作业说我们需要知道的一切都在 ruby​​ 教科书的前三章中,而这些章节不包括条件!没有它们是否有可能创建这个程序?还是他只是希望我们足智多谋并使用条件句?不过,这是一个非常简单的条件分配......我想我可能会在这里遗漏一些东西。

编辑:我正在考虑那个 chmod 数值系统,并认为通过那个加法系统可能有一个解决方案......

4

8 回答 8

11

这是一个只使用哈希的:

RULES = {
  :rock     => {:rock => :draw, :paper => :paper, :scissors => :rock},
  :paper    => {:rock => :paper, :paper => :draw, :scissors => :scissors},
  :scissors => {:rock => :rock, :paper => :scissors, :scissors => :draw}
}

def play(p1, p2)
  RULES[p1][p2]
end

puts play(:rock, :paper)        # :paper
puts play(:scissors, :rock)     # :rock
puts play(:scissors, :scissors) # :draw
于 2012-09-14T07:59:50.117 回答
8
def winner(p1, p2)
  wins = {rock: :scissors, scissors: :paper, paper: :rock}
  {true => p1, false => p2}[wins[p1] == p2]
end

获胜者(:rock, :rock) # => :rock d'oh! – 托克兰

根据@sarnold,将此作为学生的练习:)。

于 2012-06-06T23:14:00.817 回答
3

我非常怀疑您是否见过数组/集合的交叉点,所以只是为了好玩:

def who_wins(p1, p2)
  win_moves = {"rock" => "paper", "paper" => "scissors", "scissors" => "rock"}
  ([p1, p2] & win_moves.values_at(p1, p2)).first
end

who_wins("rock", "paper") # "paper"
who_wins("scissors", "rock") # "rock"
who_wins("scissors", "scissors") # nil
于 2012-06-06T23:18:06.203 回答
2

一个简单的哈希来拯救:

def tell_me(a1, a2)
  input = [a1 , a2].sort.join('_').to_sym
  rules = { :paper_rock => "paper", :rock_scissor => "rock", :paper_scissor => "scissor"}
  rules[input]
end
于 2012-06-06T23:12:06.607 回答
1

我只是认为最简单的解决方案必须是这样的:

@results = {
  'rock/paper' => 'paper',
  'rock/scissors' => 'rock',
  'paper/scissors' => 'scissors',
  'paper/rock' => 'paper',
  'scissors/paper' => 'scissors',
  'scissors/rock' => 'rock'
}

def winner p1, p2
  @results["#{p1}/#{p2}"]
end
于 2012-06-07T00:42:43.953 回答
1
WINNAHS = [[:rock, :scissors], [:scissors, :paper], [:paper, :rock]]

def winner(p1, p2)
  (WINNAHS.include?([p1,p2]) && p1) || (WINNAHS.include?([p2,p1]) && p2) || :tie
end

winner(:rock, :paper)        #=> :paper 
winner(:scissors, :paper)    #=> :scissors 
winner(:scissors, :scissors) #=> :tie 
于 2015-08-21T02:40:43.447 回答
0

我对 ruby​​ 了解不多,但我很久以前通过使用每个值(例如,R = 1、P = 2、S=3)解决了这样的问题。

实际上,我只是在考虑到这一点后用谷歌搜索,有人使用 array解决了 python中的问题。

于 2012-06-06T23:10:38.630 回答
0

pguardiario 的上述解决方案可以根据以下内容进行修改,以显示 (1) 哪个玩家获胜(而不是选择获胜的对象)和 (2) 平局时的结果:

def rps(p1, p2)
   @results = {
   'rock/paper' => "Player 2 won!",
   'rock/scissors' => "Player 1 won!",
   'paper/scissors' => "Player 2 won!",
   'paper/rock' => "Player 1 won!",
   'scissors/paper' => "Player 1 won!",
   'scissors/rock' => "Player 2 won!",
   'rock/rock' => "Draw!",
   'scissors/scissors' => "Draw!",
   'paper/paper' => "Draw!"
   }

   @results["#{p1}/#{p2}"]
end

rps("rock", "rock")     => "Draw!"
rps("rock", "scissors") => "Player 1 won!"
rps("rock", "paper")    => "Player 2 won!"

...ETC

于 2016-05-16T14:57:14.383 回答