I now have it working, this is what it looks like
card1 = {:name => "Celtic guardian", :type => "monster", :atk => 1400,
:def => 1200, :level => 4}
card2 = {:name => "Dark Magician", :type => "monster", :atk => 2500,
:def => 2100, :level => 7}
card3 = {:name => "Spike Seadra", :type => "monster", :atk => 1600, :def
=> 1300, :level => 5}
$deck = [card1,card2,card3]
def draw
draw = rand($deck.size)
puts draw
puts "you drew the card #{$deck[draw][:name]}"
$deck.delete($deck[draw])
I'd rather use Array#delete_at because it is more efficient. Your
solution needs to traverse the whole Array to find the elements to
remove. Yes, in fact it may remove multiple elements!
Array#delete_at just removes a single position.
Btw, you can make the code even simpler and more efficient by doing:
def draw
draw = rand($deck.size)
puts draw
card = $deck.delete_at(draw)
puts "you drew the card #{card[:name]}"
end
This avoids one Array access.
end
3.times do
draw
x = $deck.empty?
if x == true
puts "Game over!"
end
end
Comparing x with true is a bad idea because there are multiple values
for true in Ruby. Generally comparing boolean values or expressions
with boolean constants to get a boolean value is a bad idea because
a) it is superfluous (we do have a boolean value already)
b) it leads to subtle errors which are hard to detect in all languages
which have more than one value representing either boolean state true
and false.
In your case you can simplify to
if $deck.empty?
puts "Game over!"
end
or even
puts "Game over!" if $deck.empty?
Thank you both for answering my beginner questions.
You're welcome.
I hope I will be
able to help people on this forum one day.
Certainly!
Kind regards
robert
···
On Fri, Jan 21, 2011 at 11:16 AM, Josh Rowe <joshua@wired.com.au> wrote:
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/