Example Code

Magic Square Game Using Arrays and Mouse Events

Code and Documents

Attachment

Download All

Overview:

This example is intended to be a bit of fun, but also show the use of Event structures and (some fairly extensive) array manipulation. Kudos go to cacalderon for the VI used to generate a magic square with De La Loubère's

Method (https://decibel.ni.com/content/docs/DOC-1139), and to Mark.Ridgley for the VI(s) used to obtain an index of an array from a mouse click (https://decibel.ni.com/content/docs/DOC-22434).

Description:

The idea is to construct a 'magic square' from the elements in the selected size array. A 'magic square' has elements where all rows, columns and diagonals add up to the same number.

You are given a shuffled magic square and you must swap nearby elements in order to construct the finished magic square. You can only swap elements which are next to each other in the same row or column. You cannot swap diagonal elements directly but array elements do 'wrap around', so you can swap elements at opposite ends of the same row or column.

The principles of a magic square and their construction can be found at: http://mathworld.wolfram.com/MagicSquare.html

Steps to Execute Code:

  • Start the Main VI and select the array size you want.
  • Click the element you wish to swap, followed by the element you want to swap with.
  • These elements will exchange places if this is considered a valid move.
  • Repeat this process until you have completed the magic square.
  • At any point, you can start again by selecting the size you would like.

Front Panel:

Front panel.png

Regards,
Chris (CLED, CLA, CTA)
Applications Engineering Specialist

Example code from the Example Code Exchange in the NI Community is licensed with the MIT license.

Contributors