Shehryar
Shehryar

Reputation: 550

How to make a portion of loop repeat itself in ruby?

I'm trying to code a nim game in ruby and while I have gotten the most of it. I'm facing problems in what to do when exceptions rise such as a user takes out more objects than are present in a heap and the computer does the same.

You can find the code below. I know it's extremely poorly written but I'm still learning.

heap_choice = [3,5,7];
number_of_objects = [9,11,13];
heapSize = heap_choice[rand()*heap_choice.length];
filledHeap = [];

for i in 0..heapSize-1

    filledHeap[i] = number_of_objects[rand()*number_of_objects.length];

   end



 puts "Created #{heapSize} Heaps of Sizes #{filledHeap.join(' ')}";

 puts "Human Player Enter Your Name: ";
 player_name = gets;

 puts "Welcome #{player_name}";
 #variable choice decides whether computer or player goes first
 choice = rand(2);
 if choice === 0 
    puts "Player #{player_name} Will Go First.";
 elsif choice === 1
    puts "Player Computer Will Go First.";
 end    
 # loop to run until all elements of the array are 0
 until filledHeap.all? {|obj| obj === 0}

     if choice === 0

        puts "Player #{player_name} enter the number of objects (Y) to take from heap (X) in order: Y X"
        #y = gets.to_i;
        #x = gets.to_i;
        y, x = gets.split.map(&:to_i)

        filledHeap[x-1] = filledHeap[x-1]-y;

        puts "Player #{player_name} removed #{y} Objects from heap #{x}";
        puts "#{filledHeap}"

        choice = choice + 1;

     elsif choice === 1


        x = rand(heapSize);
        #y = rand(filledHeap.max-1);
        y = rand(filledHeap.max);
        if filledHeap[x] <= 0 
            x = filledHeap.index(filledHeap.max);
            puts "x: #{x}";
            filledHeap[x] = filledHeap[x]-y;
            if filledHeap[x] <= 0
                puts "Player #{player_name} has won!"
                break
            else
                puts "Player Computer removed #{y} Objects from heap #{x+1}";
            end 

        else
            filledHeap[x] = filledHeap[x]-y;
            puts "Player Computer removed #{y} Objects from heap #{x+1}";
        end 

        puts "#{filledHeap}"
        choice = choice - 1;

     end


 end

 puts "Choice: #{choice}";
 choice = 1 - choice;
 if choice === 0
    puts "Player #{player_name} has won!";
 else 
    puts "Player Compuer has won!";

# filledHeap
 end

Upvotes: 0

Views: 145

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

You can put it in a while loop pending a valid selection...

valid_selection = false
until valid_selection
  puts "Player #{player_name} enter the number of objects (Y) to take from heap (X) in order: Y X"
  y, x = gets.split.map(&:to_i)
  valid_selection = true if filled_heap[x-1] >= y
  puts "that's way too much" unless valid_selection
end

Upvotes: 1

Related Questions