如何在Ruby中让循环的一部分重复执行?

我在尝试用Ruby编写一个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

回答:

你可以将它放在一个while循环中,等待有效的选择…

valid_selection = falseuntil 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_selectionend

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注