Merge pull request #68625 from BleedingXiko/pick_random
[3.x] Add ability to pick random value from array
This commit is contained in:
commit
4ff9a8a0b4
|
@ -31,6 +31,7 @@
|
|||
#include "array.h"
|
||||
|
||||
#include "core/hashfuncs.h"
|
||||
#include "core/math/math_funcs.h"
|
||||
#include "core/object.h"
|
||||
#include "core/variant.h"
|
||||
#include "core/vector.h"
|
||||
|
@ -407,6 +408,10 @@ Variant Array::pop_front() {
|
|||
}
|
||||
return Variant();
|
||||
}
|
||||
Variant Array::pick_random() const {
|
||||
ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
|
||||
return operator[](Math::rand() % _p->array.size());
|
||||
}
|
||||
|
||||
Variant Array::pop_at(int p_pos) {
|
||||
if (_p->array.empty()) {
|
||||
|
|
|
@ -72,6 +72,7 @@ public:
|
|||
void fill(const Variant &p_value);
|
||||
|
||||
Variant front() const;
|
||||
Variant pick_random() const;
|
||||
Variant back() const;
|
||||
|
||||
Array &sort();
|
||||
|
|
|
@ -578,6 +578,7 @@ struct _VariantCall {
|
|||
VCALL_LOCALMEM2(Array, insert);
|
||||
VCALL_LOCALMEM1(Array, remove);
|
||||
VCALL_LOCALMEM0R(Array, front);
|
||||
VCALL_LOCALMEM0R(Array, pick_random)
|
||||
VCALL_LOCALMEM0R(Array, back);
|
||||
VCALL_LOCALMEM2R(Array, find);
|
||||
VCALL_LOCALMEM2R(Array, rfind);
|
||||
|
@ -1960,6 +1961,7 @@ void register_variant_methods() {
|
|||
ADDFUNC1NC(ARRAY, NIL, Array, remove, INT, "position", varray());
|
||||
ADDFUNC1NC(ARRAY, NIL, Array, erase, NIL, "value", varray());
|
||||
ADDFUNC0R(ARRAY, NIL, Array, front, varray());
|
||||
ADDFUNC0R(ARRAY, NIL, Array, pick_random, varray())
|
||||
ADDFUNC0R(ARRAY, NIL, Array, back, varray());
|
||||
ADDFUNC2R(ARRAY, INT, Array, find, NIL, "what", INT, "from", varray(0));
|
||||
ADDFUNC2R(ARRAY, INT, Array, rfind, NIL, "what", INT, "from", varray(-1));
|
||||
|
|
|
@ -263,6 +263,16 @@
|
|||
Returns the minimum value contained in the array if all elements are of comparable types. If the elements can't be compared, [code]null[/code] is returned.
|
||||
</description>
|
||||
</method>
|
||||
<method name="pick_random">
|
||||
<return type="Variant" />
|
||||
<description>
|
||||
Returns a random value from the target array.
|
||||
[codeblock]
|
||||
var array: Array[int] = [1, 2, 3, 4]
|
||||
print(array.pick_random()) # Prints either of the four numbers.
|
||||
[/codeblock]
|
||||
</description>
|
||||
</method>
|
||||
<method name="pop_at">
|
||||
<return type="Variant" />
|
||||
<argument index="0" name="position" type="int" />
|
||||
|
|
Loading…
Reference in New Issue