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:

BusyContacts 1.6.4 - Fast, efficient con...
BusyContacts is a contact manager for OS X that makes creating, finding, and managing contacts faster and more efficient. It brings to contact management the same power, flexibility, and sharing... Read more
Steam 4.0 - Multiplayer and communicatio...
Steam is a digital distribution, digital rights management, multiplayer and communications platform developed by Valve Corporation. It is used to distribute a large number of games and related media... Read more
OmniGraffle Pro 7.19.3 - Create diagrams...
OmniGraffle Pro helps you draw beautiful diagrams, family trees, flow charts, org charts, layouts, and (mathematically speaking) any other directed or non-directed graphs. We've had people use... Read more
OmniGraffle 7.19.3 - Create diagrams, fl...
OmniGraffle helps you draw beautiful diagrams, family trees, flow charts, org charts, layouts, and (mathematically speaking) any other directed or non-directed graphs. We've had people use Graffle to... Read more
Hopper Disassembler 5.3.3- - Binary disa...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more
calibre 5.35.0 - Complete e-book library...
Sound Studio 4.10.0 - Robust audio recor...
Sound Studio lets you easily record and professionally edit audio on your Mac. Easily rip vinyls and digitize cassette tapes, or record lectures and voice memos. Prepare for live shows with live... Read more
Sparkle Pro 4.0 - Visual website creator...
Sparkle Pro will change your mind if you thought building websites wasn't for you. Sparkle is the intuitive site builder that lets you create sites for your online portfolio, team or band pages, or... Read more
Dropbox 140.4.1951 - Cloud backup and sy...
Dropbox for Mac is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files... Read more
FotoMagico 6.0.5 - Powerful slideshow cr...
FotoMagico lets you create professional slideshows from your photos and music with just a few, simple mouse clicks. It sports a very clean and intuitive yet powerful user interface. High image... Read more

## Latest Forum Discussions

‘Horizon Chase’ China Spirit DLC Release...
Following the release of the excellent reveal of the Horizon Chase Senna Forever expansion, the game will be getting a new DLC on mobile platforms today. Today, the Horizon Chase China Spirit DLC pack will release on iOS and Android bringing in 9... | Read more »
‘PUZZLED’ from SNK and Hamster Is Out No...
Following ZED BLADE ACA NeoGeo earlier this month, SNK has brought over another game in the ACA NeoGeo series to both iOS and Android in the form of PUZZLED. SNK and Hamster originally brought the series to mobile with Samurai Shodown IV, Alpha... | Read more »
A House Full of Covid – The TouchArcade...
It’s been a rough week as both of our young children tested positive for Covid, and since recording this early on Friday my wife has tested positive now too. Thankfully the kids seemed to recover fairly quickly and are mostly back to normal, and I... | Read more »
TouchArcade Game of the Week: ‘Krispee S...
Krispee Street is a new hidden object game from Frosty Pop that is based on their popular and almost painfully sweet webcomic Krispee. This is one of the latest titles to be added to the Netflix Games catalog, which means you’ll need to log into... | Read more »
Hello gentle readers, and welcome to the SwitchArcade Round-Up for January 21st, 2022. In today’s article, we’ve got a lot of new releases. A lot. There were eight on the schedule when I went to bed last night. There were twenty-four when I woke up... | Read more »
Beta Testers Needed for Huge Version 2.0...
Ya’ll remember Dungeon Raid, right? The phenomenal matching RPG hybrid that launched on mobile more than a decade ago, but was more or less abandoned by its developer only to die a slow death on the App Store before the 32-bit Appocalypse finally... | Read more »
‘Ark Legends’ Gives Players a Chance to...
It’s Airpods and Amazon gift cards galore as Melting Games opens pre-registration for Ark Legends. The upcoming mobile RPG is giving away tons of in-game goodies such as gold, energy, iron core, hero summon chest and rare iron core to players who... | Read more »
‘Nickelodeon Extreme Tennis’ Out Now on...
Nickelodeon Extreme Tennis () from Old Skull Games and Nickelodeon is this week’s new Apple Arcade release. Nickelodeon Extreme Tennis features characters from old and new Nickelodeon shows including SpongeBob, TMNT, and many more. The tennis game... | Read more »
Hello gentle readers, and welcome to the SwitchArcade Round-Up for January 20th, 2022. In today’s article, we’ve got a massive amount of new releases to check out. We’ve got summaries of all of them, from heaven to hell. We also have the lists of... | Read more »
‘Zed Blade ACA NEOGEO’ Review – Well, It...
SNK’s NEOGEO platform played host to a great many classics, both famous and under-the-radar. The Metal Slug games. The King of Fighters series. Magician Lord. Shock Troopers. Sengoku 3. NEO Turf Masters. Fatal Fury. Samurai Shodown. Twinkle Star... | Read more »

## Price Scanner via MacPrices.net

Verizon’s 2022 iPad promo: \$100-\$310 off any...
Verizon has cellular-capable iPads on sale for \$100-\$310 off MSRP when purchased with an Unlimited service plan. Sale price is applied to your account monthly over a 24 or 30 month period, depending... Read more
Sunday Sale: Apple AirPods are on sale for up...
Amazon has Apple AirPods on sale for \$10-\$100 off MSRP today, depending on the model. All are in stock today with free delivery: – AirPods Max headphones (Blue): \$449 \$100 off MSRP – AirPods Max... Read more
These Apple resellers are offering 13″ M1 Mac...
Apple resellers are offering discounts on 13″ MacBook Pros with M1 Apple Silicon processors ranging up to \$150 off MSRP. Here’s where to get one today: (1): Apple’s 13″ MacBook Pros with M1 Apple... Read more
Amazon lowers prices on select 13″ M1 MacBook...
Amazon has select Apple 13″ M1 MacBook Airs on sale for \$150 off MSRP this weekend, starting at only \$849. Their prices are the lowest available for new MacBook Airs today. Stock may come and go, so... Read more
Apple has 13″ M1 MacBook Airs back in stock s...
Apple has restocked a full line of 13″ M1 MacBook Airs, Certified Refurbished, starting at only \$849 and up to \$190 off original MSRP. These are the cheapest M1-powered MacBooks for sale today at... Read more
In stock and on sale! 16″ 10-Core M1 Pro MacB...
Amazon has new 16″ 10-Core/512GB M1 Pro MacBook Pros in stock today and on sale for \$50 off MSRP including free shipping. Their prices are the lowest available for new M1 Pro 16″ MacBook Pro from any... Read more
Deal Alert!: 14″ M1 Pro with 10-Core CPU in s...
Amazon has the new 14″ M1 Pro MacBook Pro with a 10-Core CPU and 16-Core GPU in stock today and on sale for \$2299.99 including free shipping. Their price is \$200 off Apple’s standard MSRP, and it’s... Read more
Apple has 24-inch M1 iMacs (8-Core CPU/8-Core...
Apple has restocked a wide array of 24-inch M1 iMacs with 8-Core CPUs and 8-Core GPUs in their Certified Refurbished store. Models are available starting at only \$1269 and range up to \$260 off... Read more
Select 24″ M1 iMacs are on sale for \$100 off...
Sales of Apple’s new 24″ M1 iMacs have been rare since its introduction, perhaps due to global supply issues. However, B&H is offering a \$100 discount on select 24″ iMacs, and they’re in stock... Read more
M1 Mac minis are back in stock today at Apple...
Apple has M1-powered Mac minis available in their Certified Refurbished section starting at only \$589 and up to \$140 off MSRP. Each mini comes with Apple’s one-year warranty, and shipping is free: –... Read more

## Jobs Board

Registered Nurse (RN) Employee Health PSJH -...
…is calling for a Registered Nurse (RN) Employee Health PSJH to our location in Apple Valley, CA.** We are seeking a Registered Nurse (RN) Employee Health PSJH to be Read more
Systems Administrator - Pearson (United State...
…and troubleshoot Windows operating systems (workstation and server), laptop computers, Apple iPads, Chromebooks and printers** + **Administer and troubleshoot all Read more
IT Assistant Level 1- IT Desktop Support Anal...
…providing tier-1 or better IT help desk support in a large Windows and Apple environment * Experience using IT Service Desk Management Software * Knowledge of IT Read more
Human Resources Business Partner PSJH - Provi...
…**is calling a** **Human Resources Business Partner, PSJH** **to our location in Apple Valley, CA.** **Applicants that meet qualifications will receive a text with Read more
Manager Community Health Investment Programs...
…is calling a Manager Community Health Investment Programs PSJH to our location in Apple Valley, CA.** **Qualified candidates will be invited to do a self-paced video Read more