def attack_roll
if roll_d20 > AC
print “Attack roll is #{roll_d20} vs. AC #{AC}. Hit!”
else roll_d20 <= AC
print “Attack roll is #{roll_d20} vs. AC #{AC}. Miss!”
end
end
10.times do print attack_roll end
i want to use the result of roll_d20 and compare it to the value AC but
it doesn’t print the correct Hit! or Miss! what am i doing wrong?
irb(main):025:0> def attack_roll
irb(main):026:1> if roll_d20 > AC
irb(main):027:2> puts “#{roll_d20} vs. #{AC} Hit!”
irb(main):028:2> else roll_d20 <= AC
irb(main):029:2> puts “#{roll_d20} vs. #{AC} Miss!”
irb(main):030:2> end
irb(main):031:1> end
=> nil
irb(main):032:0> print attack_roll
16 vs. 10 Miss!
=> nil
class Attack
def roll
to_hit = $d20.roll_d20
hit_or_miss = to_hit > AC ? “Hit!” : “Miss!”
puts "Attack roll is #{to_hit} vs. AC #{AC}. " + hit_or_miss
end
end
AC = 10
$d20 = D20.new
attack1 = Attack.new
puts attack1.roll
FIXED IT! i may be a beginner but i figured it out. should have been
using classes from the start, silly me.
FIXED IT! i may be a beginner but i figured it out. should have been
using classes from the start, silly me.
Awesome that you found a solution! The problem with your initial try
wasn’t that you weren’t using classes though, it was that you weren’t
saving the value returned from your function.
def roll_d20
1 + rand(20)
end
def attack_roll
if roll_d20 > AC
print “Attack roll is #{roll_d20} vs. AC #{AC}. Hit!”
else roll_d20 <= AC
print “Attack roll is #{roll_d20} vs. AC #{AC}. Miss!”
end
end
10.times do print attack_roll end
In the code above, each time the string “roll_d20” happens in the body
of attack_roll, it’s calling the function and returning a new number
since functions in ruby return the value of their last statement.
So it looked like the output was wrong because what you were printing
was a new number instead of the number being compared.
In your new code, you assign the result of the roll to a variable
(which, btw, is done in a bit of an odd way, it’s very uncommon to
want a variable from outside a class to be accessed within it directly
like $d20 is, but don’t worry you’re on the right path), and that
variable is then compared. You could modify your old code to work
the same way (and I suggest you do, it’s always good to apply new
knowledge to old stuff).
Keep reading and coding and learning, and you’ll be on top of things in
no time!
should have been using classes from the start, silly me.
Not necessarily. Classes useful for organizing anything non-trivial,
but for something this small, you don’t need them. (Assuming you
weren’t going to make these just parts of something larger.) This
isn’t Java, after all.
i’ve always wanted to learn how to program and so i’m trying to. i’m
going to use ruby to emulate to d20 game system, hopefully making my own
open source game in the end. thanks for all of the help from you guys i
understand a little better now.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.