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 Synopsis

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.

## Introduction

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.

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.

```..................
.a.a..SSSSSS..b.b.
.aaaa.SSSSSS.bbbb.
.aaa..SSSSSS..bbb.
......SSSSSS......
.c.c..SSSSSS..d.d.
.cccc.SSSSSS.dddd.
.ccc..SSSSSS..ddd.
..................
```

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

```........
.AAABBB.
.AABBBB.
.AAABDB.
.CACDDD.
.CCCCDD.
.CCCDDD.
........
```

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.

```..................
.a.a..SSSSSS..b.b.
.aaaa.SSSSSS.bbbb.
.aaa..SSSSSS..bbb.
......SSSSSS......
.c.c..SSSSSS..d.d.
.cccc.SSSSSS.dddd.
.ccc..........ddd.
..................
..................
.a.a..SSSSSS..b.b.
.aaaa.SSSSSS.bbbb.
.aaa..SSSSSS..bbb.
......SSSSSS......
.c.c..SSSSSS..d.d.
.cccc.SSSSSS.dddd.
.ccc..........ddd.
..................
000000000
000000000
999999999
999999999
\0
```

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
```

## Conclusion

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());
exit(1);
}   /* then */

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

exit(0);
}  /* main() */

/*---------------------------------------------------------------*/

/* 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  */
/* allocates a block of storage big enough to hold the  */
/*  input file. */

file_data = NULL;
{ 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)
RmveResource(res_handle);

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

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 )
{
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. */

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

/*---------------------------------------------------------------*/

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;
return(string);
}  /* char *ctop */

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

char *string;
{
int i,
length;

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

/*---------------------------------------------------------------*/
/* 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)
return(-1);
/* 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 */

close(fd);
(*data)[size] = 0;             /* add a trailing null */
return(0);

/*---------------------------------------------------------------*/

close_application_resource_file()
/* Close the application resource file. */

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

Community Search:
MacTech Search:

Microsoft Office 2016 16.11 - Popular pr...
Microsoft Office 2016 - Unmistakably Office, designed for Mac. The new versions of Word, Excel, PowerPoint, Outlook, and OneNote provide the best of both worlds for Mac users - the familiar Office... Read more
Adobe Photoshop CC 2018 19.1.2 - Profess...
Photoshop CC 2018 is available as part of Adobe Creative Cloud for as little as \$19.99/month (or \$9.99/month if you're a previous Photoshop customer). Adobe Photoshop CC 2018, the industry standard... Read more
Adobe Dreamweaver CC 2018 18.1.0.10155 -...
Dreamweaver CC 2018 is available as part of Adobe Creative Cloud for as little as \$19.99/month (or \$9.99/month if you're a previous Dreamweaver customer). Adobe Dreamweaver CC 2018 allows you to... Read more
Adobe Flash Player 29.0.0.113 - Plug-in...
Adobe Flash Player is a cross-platform, browser-based application runtime that provides uncompromised viewing of expressive applications, content, and videos across browsers and operating systems.... Read more
Drive Genius 5.2.0 - \$79.00
Drive Genius features a comprehensive Malware Scan. Automate your malware protection. Protect your investment from any threat. The Malware Scan is part of the automated DrivePulse utility. DrivePulse... Read more
MegaSeg 6.0.6 - Professional DJ and radi...
MegaSeg is a complete solution for pro audio/video DJ mixing, radio automation, and music scheduling with rock-solid performance and an easy-to-use design. Mix with visual waveforms and Magic... Read more
ffWorks 1.0.7 - Convert multimedia files...
ffWorks (was iFFmpeg), focused on simplicity, brings a fresh approach to the use of FFmpeg, allowing you to create ultra-high-quality movies without the need to write a single line of code on the... Read more
Dash 4.1.5 - Instant search and offline...
Dash is an API documentation browser and code snippet manager. Dash helps you store snippets of code, as well as instantly search and browse documentation for almost any API you might use (for a full... Read more
Evernote 7.0.3 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
jAlbum Pro 15.3 - Organize your digital...
jAlbum Pro has all the features you love in jAlbum, but comes with a commercial license. You can create gorgeous custom photo galleries for the Web without writing a line of code! Beginner-friendly... Read more

## Latest Forum Discussions

All the best games on sale for iPhone an...
It might not have been the greatest week for new releases on the App Store, but don't let that get you down, because there are some truly incredible games on sale for iPhone and iPad right now. Seriously, you could buy anything on this list and I... | Read more »
Everything You Need to Know About The Fo...
In just over a week, Epic Games has made a flurry of announcements. First, they revealed that Fortnite—their ultra-popular PUBG competitor—is coming to mobile. This was followed by brief sign-up period for interested beta testers before sending out... | Read more »
The best games that came out for iPhone...
It's not been the best week for games on the App Store. There are a few decent ones here and there, but nothing that's really going to make you throw down what you're doing and run to the nearest WiFi hotspot in order to download it. That's not to... | Read more »
Death Coming (Games)
Death Coming 1.1.1.536 Device: iOS Universal Category: Games Price: \$1.99, Version: 1.1.1.536 (iTunes) Description: --- Background Story ---You Died. Pure and simple, but death was not the end. You have become an agent of Death: a... | Read more »
Hints, tips, and tricks for Empires and...
Empires and Puzzles is a slick match-stuff RPG that mixes in a bunch of city-building aspects to keep things fresh. And it's currently the Game of the Day over on the App Store. So, if you're picking it up for the first time today, we thought it'd... | Read more »
What You Need to Know About Sam Barlow’s...
Sam Barlow’s follow up to Her Story is #WarGames, an interactive video series that reimagines the 1983 film WarGames in a more present day context. It’s not exactly a game, but it’s definitely still interesting. Here are the top things you should... | Read more »
Pixel Plex Guide - How to Build Better T...
Pixel Plex is the latest city builder that has come to the App Store, and it takes a pretty different tact than the ones that came before it. Instead of being in charge of your own city by yourself, you have to work together with other players to... | Read more »
Fortnite Will Be Better Than PUBG on Mob...
Before last week, if you asked me which game I prefer between Fortnite Battle Royale and PlayerUnknown’s Battlegrounds (PUBG), I’d choose the latter just about 100% of the time. Now that we know that both games are primed to hit our mobile screens... | Read more »
Siege of Dragonspear (Games)
Siege of Dragonspear 2.5.12 Device: iOS Universal Category: Games Price: \$9.99, Version: 2.5.12 (iTunes) Description: Experience the Siege of Dragonspear, an epic Baldur’s Gate tale, filled with with intrigue, magic, and monsters.... | Read more »
7 Wonders Guide - Should You Buy The Lea...
The fantastic mobile version of 7 Wonders just got updated with an expansion that adds Leaders to the game. This new content adds a whole layer of depth to the game, but before you spend \$1.99 to buy it blindly, check out this breakdown of exactly... | Read more »

## Price Scanner via MacPrices.net

B&H drops prices on 15″ MacBook Pros up t...
B&H Photo has dropped prices on new 2017 15″ MacBook Pros, now up to \$300 off MSRP and matching Adorama’s price drop yesterday. Shipping is free, and B&H charges sales tax for NY & NJ... Read more
Apple restocks Certified Refurbished 2017 13″...
Apple has restocked Certified Refurbished 2017 13″ 2.3GHz MacBook Pros for \$200-\$230 off MSRP. A standard Apple one-year warranty is included with each MacBook, models receive new outer cases, and... Read more
13″ Space Gray Touch Bar MacBook Pros on sale...
Adorama has new 2017 13″ Space Gray Touch Bar MacBook Pros on sale for \$150 off MSRP. Shipping is free, and Adorama charges sales tax in NY & NJ only: – 13″ 3.1GHz/256GB Space Gray MacBook Pro (... Read more
Best deal of the year on 15″ Apple MacBook Pr...
Adorama has New 2017 15″ MacBook Pros on sale for up to \$300 off MSRP. Shipping is free, and Adorama charges sales tax in NJ and NY only: – 15″ 2.8GHz Touch Bar MacBook Pro Space Gray (MPTR2LL/A): \$... Read more
Save \$100-\$150+ on 13″ Touch Bar MacBook Pros...
B&H Photo has 13″ Touch Bar MacBook Pros on sale for \$100-\$150 off MSRP. Shipping is free, and B&H charges sales tax for NY & NJ residents only: – 13″ 3.1GHz/256GB Space Gray MacBook Pro... Read more
Current deals on 27″ Apple iMacs, models up t...
B&H Photo has 27″ iMacs on sale for up to \$150 off MSRP. Shipping is free, and B&H charges sales tax for NY & NJ residents only: – 27″ 3.8GHz iMac (MNED2LL/A): \$2149 \$150 off MSRP – 27″ 3... Read more
Thursday Deal: 13″ 2.3GHz MacBook Pro for \$11...
B&H Photo has the 13″ 2.3GHz/128GB Space Gray MacBook Pro on sale for \$100 off MSRP. Shipping is free, and B&H charges sales tax for NY & NJ residents only: – 13-inch 2.3GHz/128GB Space... Read more
How to save \$100-\$190 on 10″ & 12″ iPad P...
Apple is now offering Certified Refurbished 2017 10″ and 12″ iPad Pros for \$100-\$190 off MSRP, depending on the model. An Apple one-year warranty is included with each model, and shipping is free: –... Read more
Silver 12″ 1.3GHz MacBook on sale at B&H...
B&H Photo has the 2017 12″ 1.3GHz Silver MacBook on sale for \$1399.99 including free shipping plus sales tax for NY & NJ residents only. Their price is \$200 off MSRP, and it’s the lowest... Read more
Amazon offers 21″ Apple iMacs for up to \$150...
Amazon 21″ iMacs on sale today for \$50-\$150 off MSRP, depending on the model. Shipping is free: – 21″ 3.4GHz 4K iMac (MNE02LL/A): \$1349.99 \$150 off MSRP – 21″ 3.0GHz iMac (MNDY2LL/A): \$1199 \$100 off... Read more

## Jobs Board

Data Scientist, *Apple* Ecosystem (AMP Anal...
# Data Scientist, Apple Ecosystem (AMP Analytics) Job Number: 113428728 Santa Clara Valley, California, United States Posted: 24-Jan-2018 Weekly Hours: 40.00 **Job Read more
*Apple* Solutions Consultant - Apple (United...
# Apple Solutions Consultant Job Number: 113523441 Orange, CA, California, United States Posted: 21-Feb-2018 Weekly Hours: 40.00 **Job Summary** Are you passionate Read more
*Apple* Professional Learning Specialist - A...
# Apple Professional Learning Specialist Job Number: 113456892 Englewood, NJ, New Jersey, United States Posted: 02-Feb-2018 Weekly Hours: 40.00 **Job Summary** The Read more
*Apple* Retail Online, Senior Financial Anal...
# Apple Retail Online, Senior Financial Analyst Job Number: 57228835 Santa Clara Valley, California, United States Posted: 12-Feb-2018 Weekly Hours: 40.00 **Job Read more
Site Reliability Engineer, *Apple* Pay - Ap...
# Site Reliability Engineer, Apple Pay Job Number: 113356036 Santa Clara Valley, California, United States Posted: 12-Jan-2018 Weekly Hours: 40.00 **Job Summary** Read more