Prechádzať zdrojové kódy

Merge pull request #15563 from poke1024/gdscript-shuffle

Add shuffle() method to Array
Rémi Verschelde 7 rokov pred
rodič
commit
37a6ce5a42
4 zmenil súbory, kde vykonal 22 pridanie a 0 odobranie
  1. 14 0
      core/array.cpp
  2. 1 0
      core/array.h
  3. 2 0
      core/variant_call.cpp
  4. 5 0
      doc/classes/Array.xml

+ 14 - 0
core/array.cpp

@@ -266,6 +266,20 @@ Array &Array::sort_custom(Object *p_obj, const StringName &p_function) {
 	return *this;
 }
 
+void Array::shuffle() {
+
+	const int n = _p->array.size();
+	if (n < 2)
+		return;
+	Variant *data = _p->array.ptrw();
+	for (int i = n - 1; i >= 1; i--) {
+		const int j = Math::rand() % (i + 1);
+		const Variant tmp = data[j];
+		data[j] = data[i];
+		data[i] = tmp;
+	}
+}
+
 template <typename Less>
 _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {
 

+ 1 - 0
core/array.h

@@ -71,6 +71,7 @@ public:
 
 	Array &sort();
 	Array &sort_custom(Object *p_obj, const StringName &p_function);
+	void shuffle();
 	int bsearch(const Variant &p_value, bool p_before = true);
 	int bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before = true);
 	Array &invert();

+ 2 - 0
core/variant_call.cpp

@@ -491,6 +491,7 @@ struct _VariantCall {
 	VCALL_LOCALMEM1(Array, erase);
 	VCALL_LOCALMEM0(Array, sort);
 	VCALL_LOCALMEM2(Array, sort_custom);
+	VCALL_LOCALMEM0(Array, shuffle);
 	VCALL_LOCALMEM2R(Array, bsearch);
 	VCALL_LOCALMEM4R(Array, bsearch_custom);
 	VCALL_LOCALMEM0R(Array, duplicate);
@@ -1636,6 +1637,7 @@ void register_variant_methods() {
 	ADDFUNC0RNC(ARRAY, NIL, Array, pop_front, varray());
 	ADDFUNC0NC(ARRAY, NIL, Array, sort, varray());
 	ADDFUNC2NC(ARRAY, NIL, Array, sort_custom, OBJECT, "obj", STRING, "func", varray());
+	ADDFUNC0NC(ARRAY, NIL, Array, shuffle, varray());
 	ADDFUNC2R(ARRAY, INT, Array, bsearch, NIL, "value", BOOL, "before", varray(true));
 	ADDFUNC4R(ARRAY, INT, Array, bsearch_custom, NIL, "value", OBJECT, "obj", STRING, "func", BOOL, "before", varray(true));
 	ADDFUNC0NC(ARRAY, NIL, Array, invert, varray());

+ 5 - 0
doc/classes/Array.xml

@@ -296,6 +296,11 @@
 				[/codeblock]
 			</description>
 		</method>
+		<method name="shuffle">
+			<description>
+				Shuffle the array such that the items will have a random order.
+			</description>
+		</method>
 	</methods>
 	<constants>
 	</constants>