如何让一部分循环在ruby中重复?

时间:2016-09-11 20:12:54

标签: ruby-on-rails ruby artificial-intelligence

我试图在红宝石中编写一个nim游戏,而我已经充分利用了它。我遇到了异常上升时应该做什么的问题,比如用户拿出的对象多于堆中存在的对象而计算机也会这样做。

您可以在下面找到代码。我知道它的写得非常糟糕,但我还在学习。

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

1 个答案:

答案 0 :(得分:1)

您可以将其置于while循环中,等待有效选择......

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