【问题标题】:Ruby random array call for each pass in a loop?循环中每次传递的Ruby随机数组调用?
【发布时间】:2011-07-18 16:14:16
【问题描述】:

如何让 Ruby 重新处理每个实例的“atk”变量上的 rand 方法?现在,程序在第一次通过时随机获取一个 atk 数字,然后将其用于程序的其余部分。非常欢迎任何建议!

playerhp = 100
enemyhp = 100
monster = ["Johnny Bravo", "Father Christmas", "Boobzilla", "Lady Gaga", "Derpy-chan"]
m = monster[rand(monster.length)]
melee = [7, 10, 12, 14, 22]
atk = melee[rand(melee.length)]

puts "Your are approached by a horrid looking " + m + "!"
sleep(1)
puts "The " + m + " looks you coldy in the eye and then charges for an attack!"
sleep(1)

while playerhp > 0 do
    puts "The " + m + " has " + enemyhp.to_s + " remaining. What will you do? (type 'attack' or 'defend')"
    action = gets.chomp
        if action == "attack" then
            thisatk = atk.to_i
            enemyhp = enemyhp - thisatk
            puts "You hit the " + m + " for " + thisatk.to_s + " damage!"
        end
        if action == "defend" then
            puts "You crouch in a defensive position!"
        end

    if enemyhp < 1 then
        puts "You completely destroyed that " + m + "! Victory!"
        break   
    end
end

我确信这是你见过的最糟糕的 Ruby 代码,但请记住,这是我使用 Ruby 编写的第一个程序(今天才开始)。我在学习任何语言的第一天就这样做了。

我读书失败……我学习一门语言的唯一方法就是用它制作一个战斗游戏。我发现这是让我进入一个我认可并同时学到很多东西的环境的最佳方式。

【问题讨论】:

  • 你可能希望你的怪物冷冷地直视你的眼睛。 ;-)

标签: ruby variables loops


【解决方案1】:

天啊...我是个白痴。我在循环@_@之外处理了随机化。

对不起,让大家感到尴尬。对于任何有兴趣的人,如果你像我一样愚蠢:

删除了“atk”变量

移动混战[rand(melee.length)] 方法进入循环。

新流程如下所示:

if action == "attack" then
        thisatk = melee[rand(melee.length)]
        enemyhp = enemyhp - thisatk
        puts "You hit the " + m + " for " + thisatk.to_s + " damage!"
    end

如果有人对如何更好地编写特定操作有一些额外的评论,我会全力以赴!!

【讨论】:

  • @tokland:不要使用Array#choice,它在1.9.2中被重命名为Array#sample
  • @Marc,好吧,我使用我拥有的那个 :-) 许多发行版仍然默认提供 Ruby 1.8.7。
  • Array#sample 更干净。感谢您的提示!
猜你喜欢
  • 2016-12-08
  • 1970-01-01
  • 2018-09-08
  • 2012-03-04
  • 2014-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多