Shuffle an Array Like a BOSS With This 1 Easy Event!

8
  • 12 favourites

Attached Files

The following files have been attached to this tutorial:

.capx

shufflearray.capx

Download now 169.66 KB

Stats

3,095 visits, 4,443 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Shuffle your deck of cards easily with this ONE event!

Have you ever struggled to RANDOMIZE your array when creating your Construct 2 game?

Here is The Solution to fix your problem forever!

You only need:

- 1 Array

- 1 Line of Code (1 Easy & Simple Event!)

Just this!

How do you do this?

Step 1:

Set the Array Size to 0 (empty the array).

We are only using the X component.

Step 2:

Add Event > System > For.

Select first and last numbers in Array (example: from 1 to 10)

Add Action > Array > Insert.

Select Value: loopindex. Then select Index: int(random(loopindex))

That's all you need! Here is how your event looks:

How does this Magic work?

A good magician never reveals his tricks, hehe. You're lucky this time ;) Let's explain the magic behind this event.

First, we set the array dimension X to zero.

Then we use a For loop. We will insert every number to the array one-by-one.

We insert every number in a random position BETWEEN the already inserted numbers.

The first number is "1". We will insert it into position: random(1). This means in a random position from 0 to 0. Always zero. Our shuffled array is "1".

The second number is "2". We will insert it into: random(2). In other words: index 0 or 1. If random returns 0, the number is inserted at position 0 - our shuffled array is "2,1". If random returns 1, our shuffled array is "1,2".

The next number is "3". It will be inserted either at position 0, 1 or 2. In front of "1,2"/"2,1"; in the middle (like "1,3,2"/"2,3,1"); or behind them. We already have 3 shuffled numbers!

For number "7" or whatever. Before inserting, we already have 1,2,3,4,5,6 randomized. The shuffled array has 6 items. We will insert number "7" in a random position from 0 to 6. In the middle of all those numbers, in front of them or behind all of them.

That's the trick.

Try the Demo!

Try demo online here: http://duquekarl.com/c2/shufflearray/

Want the Source Code?

.CAPX

shufflearray.capx

Download now 169.66 KB

Download .capx attached!

Leave your comments and questions.

Enjoy! :)

  • 13 Comments

  • Order by
Want to leave a comment? Login or Register an account!