TweetFollow Us on Twitter

Puzzles as Resources
Volume Number:2
Issue Number:3
Column Tag:Developer's Forum

Puzzles as Resources in Aztec C

By David Levner, Sabaki Corp., Product: Polyomino Puzzles

Polyomino Puzzle Resources


Sam Loyd created polyomino puzzles 80 years ago. He didn't have a Macintosh, so he made his puzzles out of cardboard. I am lucky to own a Mac, so I wrote the game MacPoly to draw polyominoes on the screen.

MacPoly stores polyomino puzzles as resources, in a format described in this article. A method for creating these resources is presented, enabling you to add your own puzzles to MacPoly. The method may also be used to create other custom resources.


The word 'polyomino' is a generalization of 'domino'. A domino is made of two squares, and a polyomino many squares. Here are some polyominoes:

Figure 1

An easy puzzle is shown below. The object is to cover the white square (the solution shape) with the four gray pieces. Most polyomino puzzles are much more difficult.

6 x 6 Square

Figure 2

Puzzle Source Files

The first step in creating a puzzle is to enter a puzzle source file. For example, this is the source file I used to generate figure 2:

6 x 6 Square Congratulations! Puzzle by David Levner.


Figure 3

Use a mono-spaced font, like Monaco to make the columns line up, and save the file as text only. The first line of the file contains the puzzle name, followed by a congratulatory message that is displayed when the puzzle is solved. Then begins the puzzle grid.

The grid contains letters that stand for the squares of polyominoes. Lower case letters represent squares that are outside the solution shape, and upper case letters, except 'S', are squares covering the solution (none are shown in this example). Non-alphabetic characters (the dots) are empty spaces that are not part of the solution , and the letter 'S' denotes the squares of the solution that are not covered by any polyominoes.

Solution Source Files

The solution to a puzzle is represented by a very similar source file. The only difference is that there is no congratulatory message.

6 x 6 Square Solution


Figure 4

Puzzle and Solution Resources

A program could read these source files directly, but that would be less efficient than reading resources on the Mac. At the end of this article, a program is listed to convert puzzle and solution source files into resources.

MacPoly's puzzles are divided into 9 categories. Puzzle resources have type SBPn, where n is a digit from 1 to 9, and solutions have type SBSn.

Resource Type Puzzle Type

SBP1 Easy puzzles

SBP2 Rectangles

SBP3 Almost Rectangles

SBP4 Parallelograms

SBP5 Chess Boards

SBP6 Polyominoes

SBP7 Chess Pieces

SBP8 Objects

SBP9 Impossible Puzzles

Figure 5

The puzzle resource for 6 x 6 Square looks like this.

Congratulations! Puzzle by David Levner.


Figure 6

The first line of the puzzle source file becomes the resource name. The second copy of the puzzle grid reserves space to store an arrangement of the pieces saved with MacPoly's save command.

Following the second grid are four nine digit numbers, representing (1) the time spent to arrive at the saved position, in seconds, (2) the number of operations performed to arrive at the saved position (MacPoly allows you to select a piece, drag it, flip it, and spin it), (3) the record time to solve the puzzle, in seconds, and (4) the record (fewest) number of operations to solve a puzzle. Initially, these numbers are set to 0, 0, 999999999, and 999999999. At the end of the resource is a binary zero.

A solution resources differs in several ways: there is no congratulations message or timing information, and only one puzzle grid.

Converting Source Files To Resources

I wrote a C program, called ftor, to convert puzzle source files to resources. Ftor is designed to run under a shell program; it cannot be run from the Macintosh desktop. If you try to recreate ftor, you should run it from the shell supplied with your C compiler.

Most shell programs are modeled on the Bourne shell from the Unix operating system. To use a shell, you type a command, which is interpreted as a program name followed by an argument list. All the C compilers I have seen for the Mac include a shell user interface. On the Amiga, Commodore supplies a shell called the Command Line Interface.

I have listed below some dialogs with the shell. The '$' is a prompt character, signifying that the shell is ready to accept a command. I typed the characters following the '$' to run the program ftor; the line below contains the program's output. In this case, I ran ftor without any arguments to remind me what arguments it expects.

 $ ftor
 usage: ftor TYPE outfile infile1 [infile2 ...]

Ftor's first argument is the four letter type of the resource(s) being created, followed by the output file, and one or more puzzle source files. Each source file is converted to a resource and stored in the output file.

 $ ftor SBP1 Puzzles epz

Assuming that the puzzle source file of figure 3 is named epz, the command above creates a resource called "6 x 6 Square" in the file Puzzles. The Puzzles file must already exist and contain at least one resource.

Ftor Program Source

I used Aztec C to compile and link ftor with the following two commands:

 $ cc ftor.c -o ftor.o
 $ ln -o ftor ftor.o -lc


This article demonstrates a method for creating custom resources from ascii source files. Owners of MacPoly can create and enter their own puzzles. Puzzles and solutions should be entered in pairs; otherwise the Solve feature of MacPoly will not work properly.

Custom resources are both bad and good: few toolbox functions can manipulate them, but they do exactly what you want. You must write your own code to deal with them, but porting the code to other computers will be easier.

/* The program ftor converts a puzzle source file into a  */
/* resource. Developed with Aztec C version 1.03.  */
/* Copyright Sabaki Corp.,1985, for MacTutor.  */
/* Note that this is not a stand alone application, but */
/* requires the Aztec C system to execute for the */
/* default Mac user interface. */

#include "stdio.h"       /* contains definition of NULL (0L) */
#include "ctype.h"       /* contains definition of isdigit */
#include "quickdraw.h"   /* Quickdraw */
#include "memory.h"      /* Memory manager */
#include "resource.h"    /* Resource manager */


extern int errno;         /* error number variable */


static long long_type;    /* resource type */

static char flag_puzzle;  /* 1 for puzzles, 0 for solutions */


main(argc, argv) /* Entry point. */

int argc;         /* number of arguments */
char *argv[];    /* argument vector, an array of strings */
 int a;           /* argument counter */
 static char usage_msg[] =
 "usage: ftor TYPE outFile inFile1 [inFile2 ...]\n";
 long c4tol();   /* converts four bytes into a long */
 char *ctop(),   /* converts a C string to a PASCAL string */
      *ptoc();   /* converts a PASCAL string to a C string */

 if  (argc < 4)
    { printf(usage_msg); exit(1); }

 long_type = c4tol(argv[1][0], argv[1][1], argv[1][2], argv[1][3]);
 flag_puzzle = (argv[1][2] == 'P');

 close_application_resource_file();   /* For safety's sake. */

 if  (OpenResFile(ctop(argv[2])) < 0) /* Open the output file. */
     printf("File %s open error %d\n", ptoc(argv[2]), ResError());
    }   /* then */

 /* For each input file, add a resource to the output file. */
 for (a = 3; a < argc; a = a + 1)

}  /* main() */


static add_resource(filename)
/* Convert one input file to a resource in the output file. */

char *filename;         /* name of the input file */
 int data_size,         /* length of the text in the source file */
     header_size,       /* length of text before the puzzle grid */
     resource_size, /* length of the resource being created */
     title_size;        /* length of the resource name */
 char *file_data,     /* text read from the source file */
      title[80];      /* resource name */
 Handle res_handle;   /* handle to resource being created */
 Ptr ptr;               /* pointer to the resource being created */

 /* Read the input file.  Note that if the second parameter  */
 /* passed to read_file() points to NULL, then read_file()  */
 /* allocates a block of storage big enough to hold the  */
 /*  input file. */

 file_data = NULL;
 if  (read_file(filename, &file_data) < 0)
    { printf("File %s error %d.\n", filename, errno); exit(1); }

 for (title_size = 0;     /* Determine the size of the title. */
      file_data[title_size] > '\r';
      title_size = title_size + 1)

 /* Copy title to a C string. */
 strncpy(title, file_data, title_size);
 title[title_size] = 0;

 /* Let the length of the title include the \r character. */
 title_size = title_size + 1;

 /* If a resource by this name already exists, remove it. */
 res_handle = GetNamedResource(long_type, ctop(title));
 if  (res_handle != NULL)

 /* Determine the size of the header, the grid, and the */
/*  resource. The header includes the title and the  */
/*  congratulations message. */

 header_size = title_size;
 while  (file_data[header_size] > '\r')
     header_size = header_size + 1;
 header_size = header_size + 1;

 data_size = strlen(file_data);
 resource_size = data_size - title_size + 1;

 /* If it's a puzzle, allow room for a 2nd grid and timing info. */
 if  ( flag_puzzle )
   resource_size = resource_size + data_size - header_size + 40;

 /* Get a new handle for the resource. */
 res_handle = NewHandle((long) resource_size);
 if  (res_handle == NULL)
    { printf("Memory error %d\n", MemError()); exit(1); }

 HLock(res_handle);  /* Make sure  resource doesn't run off. */
 ptr = *res_handle;

 /* Move the header and the puzzle into the resource. */
 strncpy(ptr, &file_data[title_size], data_size - title_size);
 /* Puzzles include a second puzzle grid,  blank timing info. */
 ptr = ptr + data_size - title_size;
 if  ( flag_puzzle )
     strncpy(ptr, &file_data[header_size],
             data_size - header_size);
     ptr = ptr + data_size - header_size;
     strcpy(ptr, "000000000\r000000000\r999999999\r999999999\r");
    } /* then */
   else  ptr[0] = 0;

 /* Add the resource to the output file. */
 AddResource(res_handle, long_type, UniqueID(long_type), title);

 HUnlock(res_handle);   /* Unlock the resource. */
 free(file_data);      /* Free memory allocated by read_file(). */
}  /* static add_resource() */


long c4tol(c0, c1, c2, c3)
/* Returns a long constructed from the four bytes. */

unsigned char c0, c1, c2, c3;
 return((c0 << 24L) + (c1 << 16L) + (c2 << 8L) + c3);
} /* long c4tol() */


char *ctop(string)
/* Converts a C string to a PASCAL string, which is returned. */

char *string;
 int length;
 char *pstring;

 length = strlen(string);
 for (pstring = &string[length];
      pstring != string;
      pstring = pstring - 1)
     *pstring = *(pstring - 1);
 *string = length;
}  /* char *ctop */

char *ptoc(string)
/* Converts a PASCAL string to a C string, which is returned. */

char *string;
 int i,

 length = *string;
 for (i = 1; i <= length; i = i + 1)
     string[i - 1] = string[i];
 string[length] = 0;
}  /* char *ptoc */

read_file(file_name, data)
/* Reads the data fork of a file. */

char *file_name,  /* name of the file to be read */
     **data;       /* pointer to where the file data should go */
 int fd,           /* file descriptor */
     size;         /* size of the file in bytes */
 extern long lseek();
 extern char *malloc();

 fd = open(file_name, 0);
 if  (fd < 0)
  /* determine the size of the file */
 size = (int) lseek(fd, 0L, 2);
 lseek(fd, 0L, 0);

 if  (*data == NULL)
   *data = malloc(1 + size);  /* leave room for a trailing null */

 if  (*data == NULL)
    { close(fd); return(-1); }  /* malloc failed */

 if  (read(fd, *data, size) != size)
    { close(fd); return(-1); }  /* read failed */

 (*data)[size] = 0;             /* add a trailing null */
}  /* read_file() */


/* Close the application resource file. */

 DetachResource( GetResource('CODE', 1) );
 CloseResFile( CurResFile() );
}             /* close_application_resource_file() */

Community Search:
MacTech Search:

Software Updates via MacUpdate

NetNewsWire 4.0.0 - RSS and Atom news re...
NetNewsWire is the best way to keep up with the sites and authors you read most regularly. Let NetNewsWire pull down the latest articles, and read them in a distraction-free and Mac-like way. Native... Read more
MacUpdate Desktop 6.0.6 - Search and ins...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more
ForkLift 2.6.5 - Powerful file manager:...
ForkLift is a powerful file manager and ferociously fast FTP client clothed in a clean and versatile UI that offers the combination of absolute simplicity and raw power expected from a well-executed... Read more
Drive Genius 4.1.0 - Powerful system uti...
Drive Genius 4 gives you faster performance from your Mac while also protecting it. The award-winning and improved DrivePulse feature alerts you to hard drive issues before they become major problems... Read more
OnyX 2.9.7 - Maintenance and optimizatio...
OnyX is a multifunctional utility for OS X. It allows you to verify the startup disk and the structure of its System files, to run miscellaneous tasks of system maintenance, to configure the hidden... Read more
DEVONthink Pro 2.8.5 - Knowledge base, i...
DEVONthink Pro is your essential assistant for today's world, where almost everything is digital. From shopping receipts to important research papers, your life often fills your hard drive in the... Read more
Backblaze - Online backup serv...
Backblaze is an online backup service designed from the ground-up for the Mac.With unlimited storage available for $5 per month, as well as a free 15-day trial, peace of mind is within reach with... Read more
Apple Remote Desktop Client 3.8.4 - Clie...
Note: Apple Remote Desktop Client is available only through Software Update (the Updates tab in App Apple Remote Desktop Client is the best way to manage the Mac computers on your network... Read more
Merlin Project - Project man...
Merlin Project is for those of you who are responsible for complex projects. Simple lists of tasks won't suffice. Good planning raises questions about the dependencies of activities on each other,... Read more
Tidy Up 4.1.0 - Find duplicate files and...
Tidy Up is a complete duplicate finder and disk-tidiness utility. With Tidy Up you can search for duplicate files and packages by the owner application, content, type, creator, extension, time... Read more

Carbo - Handwriting in the Digital Age...
Carbo - Handwriting in the Digital Age 1.0 Device: iOS Universal Category: Productivity Price: $3.99, Version: 1.0 (iTunes) Description: | Read more »
The Apple Watch isn't Great as a Fi...
| Read more »
Show the World What You See With
Live broadcasting is getting popular on mobile devices, which is why you can now get, by Infinite Takes. [Read more] | Read more »
PhotoTime's 2.1 Update Adds Apple W...
The latest PhotoTime update is adding even more functionality to the handy photo organizing app. Yep, including Apple Watch support. [Read more] | Read more »
Oh My Glob! Adventure Time Puzzle Quest...
Finn and Jake are taking over D3 Go!'s popular puzzle game series in the upcoming Adventure Time Puzzle Quest. [Read more] | Read more »
Earthcore: Shattered Elements - Tips, Tr...
At first glance, Earthcore: Shattered Elements seems like a rather simple card-battling game. Once you’re introduced to skills that will change quite a bit. Even more so once you start to acquire hero cards. But it’s not so complicated that we... | Read more »
Dungeon999F (Games)
Dungeon999F 1.33 Device: iOS Universal Category: Games Price: $.99, Version: 1.33 (iTunes) Description: "The game you must play at least once in your life!" "The game with potential of million downloads globally!" what the... | Read more »
Mixels Rush - Use Mixes, Maxes and Murps...
Mixels Rush - Use Mixes, Maxes and Murps to Outrun the Nixels 1.0.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.0 (iTunes) Description: Use awesome new Mixels and make crazy combinations to beat the annoying... | Read more »
Battles of the Ancient World II (Games)
Battles of the Ancient World II 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: | Read more »
Sword Of Xolan (Games)
Sword Of Xolan 1.0.4 Device: iOS Universal Category: Games Price: $.99, Version: 1.0.4 (iTunes) Description: Sword of Xolan is an action platformer game that includes the juice of pixel art style. Xolan is a young and brave man who... | Read more »

Price Scanner via

Sale! 16GB iPad mini 3 for $349, save $50
B&H Photo has the 16GB iPad mini 3 WiFi on sale for $349 including free shipping plus NY sales tax only. Their price is $50 off MSRP, and it’s the lowest price available for this model. Read more
Price drop on 2014 15-inch Retina MacBook Pro...
B&H Photo has dropped prices on 2014 15″ Retina MacBook Pros by $200. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1799.99 save $200 - 15″ 2.5GHz... Read more
Will iOS 9 Finally Bring Productivity Friendl...
Ah, the irony. From its original announcement in 2010, Apple has doggedly insisted that the iPad remain “simple,” thus arbitrarily limiting its considerable potential as a content creation and... Read more
13-inch 2.5GHz MacBook Pro (refurbished) avai...
The Apple Store has Apple Certified Refurbished 13″ 2.5GHz MacBook Pros available for $829, or $270 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.... Read more
Mac Pros on sale for up to $260 off MSRP
B&H Photo has Mac Pros on sale for up to $260 off MSRP. Shipping is free, and B&H charges sales tax in NY only: - 3.7GHz 4-core Mac Pro: $2799, $200 off MSRP - 3.5GHz 6-core Mac Pro: $3719.99... Read more
Save up to $600 with Apple refurbished Mac Pr...
The Apple Store has Apple Certified Refurbished Mac Pros available for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more
Apple drops price on refurbished 15-inch 2.2G...
The Apple Store has dropped their price on the Apple Certified Refurbished 2014 15″ 2.2GHz Retina MacBook Pro to $1609, $390 off original MSRP. Apple’s one-year warranty is included, and shipping is... Read more
Apple restocks refurbished Mac minis for up t...
The Apple Store has restocked Apple Certified Refurbished 2014 Mac minis, with models available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: - 1.4GHz... Read more
Cover For iPhone Helps You Create Beautiful P...
Taking photos, editing and sharing them is one of the things most of people do on their iPhones for fun, especially if they’re users of social media. Unfortunately, many iOS photo-editing solutions... Read more
Password Keyboard 1.0 For iOS Handles Logins...
Pfaeffikon, Switzerland based Power APP has introduced Password Keyboard 1.0.0, their new password utility developed for iPhone, iPad and iPod touch devices. Password Keyboard is designed to simplify... Read more

Jobs Board

*Apple* Solutions Consultant - Retail Sales...
**Job Summary** As an Apple Solutions Consultant (ASC) you are the link between our customers and our products. Your role is to drive the Apple business in a retail Read more
*Apple* Solutions Consultant - Retail Sales...
**Job Summary** The ASC is an Apple employee who serves as the Apple business manager and influencer in a hyper-business critical Reseller's store which delivers Read more
Technical Project Manager - *Apple* Pay - A...
**Job Summary** Apple Pay is seeking an experienced technical PM…manage the rollout of features to merchants for the Apple Pay platform in the US Within this role Read more
Senior Payments Security Manager - *Apple*...
**Job Summary** Apple , Inc. is looking for a highly motivated, innovative and hands-on senior payments security manager to join the Apple Pay security team. You will Read more
Project Manager - *Apple* Pay Security - Ap...
**Job Summary** The Apple Pay Security team is seeking a highly organized, results-driven Project Manager to drive the development of Apple Pay Security. If you are Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.