# Making a Jigsaw Puzzle: - Part Four: Managing grouped pieces

1
• 15 favourites

### Attached Files

The following files have been attached to this tutorial:

.capx

.capx

.capx

### Stats

5,028 visits, 13,210 views

• Spanish

### Joining groups together

But there is still something we have to do.

Run the app again.Having "joined" pieces 1,2 and 3 inside a group, drag piece 4 to that group and then drag it again. Pieces 3 and 4 It will separate from pieces 2 and 1. Why? We are putting piece 3 into the group of piece 4, but we are not putting the remaining pieces from piece 3's group into that group.

We can solve this by storing group of piece 3 and then assigning a new group to all pieces in that group.

Expand all events if you did not before.

Go to the event with this condition:

Pick All ActualPiece
For Each ActualPiece
System ((ActualPiece.PlaceX=CompareX) & (abs(CompareY- ActualPiece.PlaceY)=1))  ((ActualPiece.PlaceY=CompareY) & (abs(CompareX- ActualPiece.PlaceX)=1)) <>0

Add this condition and move it below the "For Each...":

ActualPiece.Group≠MyGroup

This will prevent us for iterating inside our same group, which could cause an infinite loop.

Add a local variable called "Group2" between the previous event and the event with

System compare distance(ActualPiece.X,ActualPiece.Y,IdealX,IdealY)<5

Now, in the event with "distance(ActualPiece.X,ActualPiece.Y,IdealX,IdealY)<5", add this action:

System => Set Group2 to ActualPiece.Group

This action stores the group of the joined piece in a local variable, so we can select pieces from same group.

System Pick All ActualPiece

This will reset pieces from our selection, so we will search all pieces for pieces inside Group2.

System Pick All ActualPiece

System For each actualpiece
Actualpiece.Group=Group2

This sub-subevent will look for pieces inside Group2. Such pieces are "linked" to the piece we are joining to MyGroup, so we have to join that pieces, also.

Put the following actions inside:
Set ActualPiece.group to Mygroup
Set  ActualPiece.position to (ActualPiece.PlaceX-CompareX)[i]PieceStepX+MyX, (ActualPiece.PlaceY-CompareY)[/i]PieceStepY+MyY

All pieces in the group of the piece we are joining ("linked" to it) will change to current group (will be "linked" to the group we are dropping), and their position will be "aligned" with the group. (Notice the calculations in the "Set Position to..." are the same we used to calculate "IdealX" and "IdealY". We can't use "IdealX, IdealY" because these coordinates are valid for the first "joined" piece only.