Problem when trying to split an array of randomly ordered numbers into two equal parts using Godot/Gdscript

Asked

Viewed 33 times

0

I am currently creating a game in Godot 3.2.3, and in this game I need to create an array that contains numbers from 1 to array.size() (example:[0,1,2,...,30]) and that such numbers are in random order, to be further divided into 2 sub arrays.

The code below demonstrates the process:

func createImageSets(var size):
var arr = Array()
var n = 1
while (n <= size):
    arr.append(n)
    n = n + 1
arr.shuffle()
var half = size/2
study_set = arr.slice(0,half-1)
other_set = arr.slice(half, size-1)
print(study_set)
print(other_set)

Obs: study_set and other_set are variable from script.

When I try to print the sub arrays, I get this result:

[11, 16, 5, 25, 12, 2, 27, 17, 23, 21, 14, 7, 19, 13, 9]
[6, 10, 26, 24, 29, 3, 1, 8, 15, 18, 4, 22, 28, 20, 30]

I realized that every time I run this script, the order of the numbers generated in shuffle() It is the same, as if the method did not create a new instance to generate the shuffle between one execution and another. No matter how many times you run, the result is always these same 2 arrays.

I would like each execution to provide me with different sets of numbers. Could someone help me with this?

1 answer

1


You have to call randomize() before the arr.shuffle().

extends Node2D

var a = [1,2,3,4,5,6,7,8,9]

func _ready():
    randomize()
    a.shuffle()
    for i in range(9):
        print(a[i])

Link for you to test: Here.

Source: QA - godotengine.org

  • Thank you so much for the help. It’s working properly now, and thank you also for the test link, very interesting this platform

Browser other questions tagged

You are not signed in. Login or sign up in order to post.