Example Code

A Prettier Tic Tac Toe game with matrix scoring logic

Code and Documents

Attachment

A two-player tic tac toe game with continuous scoring logic.

tictac1.png

The user interface is a set of 9 booleans each with independent event structures where the input is appended to a matrix.  A local variable "player" is used to toggle between players for each registered move.  Each move is appended to the scoring matrix, each boolean input corresponding to either a 1 or -1 for the two respective players.  For example, the scoring matrix of a partially completed game would read:

[  1  0 -1 ]

[ -1  1  0 ]

[  1  0 -1 ]

This matrix is sent to a scoring subVI which sequentially works through each horizontal and vertical row, and then the two diagonals.  This is where it was convenient to use LabVIEW's matrix functions to isolate each row and then send the row or set of rows to the scorerow2 subVI.  The scores are cascaded so that a winner could be found in any of the rows and make it up to the final output string.  Additionally, the boolean output from scorer2 serves as a flag to prompt a dialog in the driver VI to reset or close the application.

tictac2.png

At the heart of code is the subVI that scores each row.  Notice that the constant input changes the for loop iterations, so that for the vertical and horizontal rows it can go through all 3 at once, but it can also handle the diagonals by themselves.  I made use of the for loops conditional terminal so that the loop could stop execution if it found a winner - probably not necessary since this is such a lightweight application.

tictac3.png

Finally, the application builder was used to export the project as an executable so even people without LabVIEW can play!

Find the project, commented VI's, and executable in the attached zip!

Joey S.
Senior Product Manager, Software
National Instruments

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

Contributors