add ability to pick random value from array

(cherry picked from commit 9f4dbf415d)

Co-authored-by: BleedingXiko <66162192+BleedingXiko@users.noreply.github.com>
This commit is contained in:
Nonunknown 2022-10-15 09:43:16 -03:00 committed by Rémi Verschelde
parent d80396db03
commit eb5b297fef
No known key found for this signature in database
GPG key ID: C3336907360768E1
4 changed files with 18 additions and 0 deletions

View file

@ -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()) {

View file

@ -72,6 +72,7 @@ public:
void fill(const Variant &p_value);
Variant front() const;
Variant pick_random() const;
Variant back() const;
Array &sort();

View file

@ -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));

View file

@ -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" />