TweetFollow Us on Twitter

May 99 Challenge

Volume Number: 15 (1999)
Issue Number: 5
Column Tag: Programmer's Challenge

May 99 Challenge

by Bob Boonstra, Westford, MA

Piper

Every once in a while, good fortune not only comes your way, but actually reaches out of your computer monitor, and grabs you by the throat. I felt a little like that while reading a recent issue of TidBITS. In it was a column by Rick Holzgrafe reflecting on the increasing speed of computers, in which Rick described a program he wrote for a PDP-11/60 to solve a word puzzle. The idea behind the puzzle was to take a phrase and map it onto a rectangular grid, with the objective being to map the phrase into a rectangle of the smallest possible area. The word puzzle looked like a good idea for a Challenge, and Rick and TidBITS agreed to let me use it.

In more detail, the puzzle works like this. To start, you are given a null-terminated string consisting of printable characters. You process the characters in order, ignoring any non-alphabetic characters and ignoring case. The first alphabetic character can be mapped to any square in the grid. The next letter can be mapped to any adjacent square, where adjacent is any of the eight neighboring squares in a horizontal, vertical, or diagonal direction. You may reuse a square if it is adjacent and already has the letter you are mapping. If the same letter occurs twice in a row in the input string, the letters must still be mapped to adjacent (but distinct) squares.

The prototype for the code you should write is:

#if defined(__cplusplus)
extern "C" {
#endif

typedef struct GridPoint {
   long x;
   long y;
} GridPoint;

void Piper (
   char *s,
   GridPoint pt[]
);

#if defined(__cplusplus)
}
#endif

For example, your Piper routine might be provided with the string:

            How much wood would a woodchuck chuck if a woodchuck 
            could chuck wood?

You might place the letters of that string into a 4x14 rectangle like:

                  ULD  ADLU
               HDOAIUCOHWUHOD
               UCOWFKHDOMCWOW
                K   WO

Or, you might compact them into an 4x4 rectangle:

               HWMU
               OOCH
               UDWK
               LAFI

You must return the GridPoint coordinates of where each character is mapped, with pt[i] containing the coordinates of input character s[i]. The origin of your coordinate system should be the cell where the first character is placed. The winner will be the solution that stores the input string in a rectangle of minimal area. Note that you are minimizing rectangle area, not the number of occupied squares. A time penalty of 1% for each second of execution time will be added

This will be a native PowerPC Challenge, using the latest CodeWarrior environment. Solutions may be coded in C, C++, or Pascal.

Three Months Ago Winner

The February Challenge invited readers to write a player for the game of Chinese Checkers. Played on a hexagonal board with six appended triangles, Chinese Checkers pits between 2 and 6 players against one another, with the objective being to move one's pieces from the home triangle to the opposite triangle. In the traditional game, the home triangles are usually 3 or 4 positions on a side; the Challenge extended the game to triangles of up to 64 positions. Pieces can either be moved to an immediately adjacent position or jumped over an adjacent piece. A single piece is permitted to make a sequence of jumps in a single move.

As simple as the game sounds, readers found it to be very difficult, so difficult that no solutions were submitted for the Chinese Checkers Challenge. Which left Yours Truly in something of a difficult spot. I could stop the column at this point, which wouldn't be very interesting for readers, not to mention not very satisfying for the magazine. Or I could write a solution for the Challenge myself, something I haven't done since I retired from Competition four plus years ago. Somewhat against my better judgement, I selected the latter option.

The first thing I noticed in solving the Challenge was that the board coordinate system specified in the problem wasn't very useful in generating a solution. I needed a coordinate system that could be easily rotated in 60-degree increments, enabling my solution to play any of the six possible player positions. After some thought, I came up with a more symmetric coordinate system, called CanonPosition in the code, along with conversion routines ConvertPositionToCanonPosition and ConvertCanonPositionToPosition. The commentary in the code illustrates the coordinate system for a board of size 4. Then I needed a way to evaluate board positions. I decided on a simple metric that summed the distances of all pieces from the apex of their goal triangle. That metric could be improved upon by taking possible jump moves into account. The solution starts by computing all possible moves for our player. It then tries each of those moves, and then recursively calls MakeNextMove to process the next player. It computes and tries all moves for that player, and recurses for the next player. Recursion terminates when kMaxPlys turns have been taken for all players. Positions are evaluated using a min-max technique, where each player selects the position that maximizes his position relative to the best position of the other players.

The code could be improved in many ways. Instead of trying all possible positions, it could prune some obviously bad moves in the backward direction. This is complicated by the fact that some good jump multi-moves can include individual jumps that appear to be moving backward. The code might also be improved by evaluating moves by progressive deepening, rather than the depth-first search currently used, and by ordering move evaluation based on the scores at the prior depth. This technique is used in chess programs to prune the move tree to a manageable size. These and other optimizations are left to the reader. :-)

Remember, you can't win if you don't play. To ensure that you have as much time as possible to solve the Challenge, subscribe to the Programmer's Challenge mailing list. To subscribe, see the Challenge web page at <http://www.mactech.com/mactech/progchallenge/>. The Challenge is sent to the list around the 12th of the month before the solutions are due, often in advance of when the physical magazine is delivered.

Here is our sample Chinese Checkers solution:

Chinese Checkers.c
Copyright © 1999 J. Robert Boonstra

/*
*  Example solution for the February 1999 Programmer's Challenge
 *
 *  This solution is provided because no solutions were submitted
 *  for the ChineseCheckers Challenge.  This solution leaves a 
 *  great deal to be desired: it is not optimized, it does not 
 *  prune prospective moves efficiently, and it does not employ
 *  any of the classic alpha-beta techniques for efficiently
 *  selecting a move.
 */

#include <stdio.h>
#include <stdlib.h>
#include <Quickdraw.h>
 
#include "ChineseCheckers.h"

/* Position coordinates specified in problem (size==4)

  0:                           0
  1:                         0   1 
  2:                      -1   0   1 
  3:                    -1   0   1   2
  4:  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6 
  5:    -5  -4  -3  -2  -1   0   1   2   3   4   5   6
  6:      -5  -4  -3  -2  -1   0   1   2   3   4   5  
  7:        -4  -3  -2  -1   0   1   2   3   4   5
  8:          -4  -3  -2  -1   0   1   2   3   4  
  9:        -4  -3  -2  -1   0   1   2   3   4   5
 10:      -5  -4  -3  -2  -1   0   1   2   3   4   5  
 11:    -5  -4  -3  -2  -1   0   1   2   3   4   5   6
 12:  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6 
 13:                    -1   0   1   2
 14:                      -1   0   1 
 15:                         0   1 
 16:                           0
*/

#define kMaxPlys 1
#define kEmpty -1

/* CanonPosition uses units with (0,0) at the middle of the board */
typedef struct CanonPosition {
   long row;
   long col;
} CanonPosition;

/* Canonical position coordinates (size==4)

 -8:                           0
 -7:                        -1   1 
 -6:                      -2   0   2 
 -5:                    -3  -1   1   3
 -4: -12 -10  -8  -6  -4  -2   0   2   4   6   8  10  12 
 -3:   -11  -9  -7  -5  -3  -1   1   3   5   7   9  11
 -2:     -10  -8  -6  -4  -2   0   2   4   6   8  10  
 -1:        -9  -7  -5  -3  -1   1   3   5   7   9
  0:          -8  -6  -4  -2   0   2   4   6   8  
  1:        -9  -7  -5  -3  -1   1   3   5   7   9
  2:     -10  -8  -6  -4  -2   0   2   4   6   8  10  
  3:   -11  -9  -7  -5  -3  -1   1   3   5   7   9  11
  4: -12 -10  -8  -6  -4  -2   0   2   4   6   8  10  12 
  5:                    -3  -1   1   3
  6:                      -2   0   2 
  7:                        -1   1 
  8:                           0
*/

/* PlayerPos is used to store the location of each of a players pieces */
typedef struct PlayerPos {
   CanonPosition pos;
} PlayerPos;

typedef char *CanonBoard;

static long myNumPlayers,myNumPieces,myIndex,myGameSize,
   myPlayerPosition[6],myMinDist;
static PlayerPos *myPositions;

/* global board */
static CanonBoard myBoard;

/* moveIncrement is added to a CanonPosition to find the adjacent square in the
 * six possible directions 0..6, with 0==horizontal right, 1==down right, ...
 * 5==up right
 */
static CanonPosition moveIncrement[6] = 
   { { 0, 2}, { 1, 1}, { 1,-1}, { 0,-2}, {-1,-1}, {-1, 1} };

/* macros to access the board */
#define CanonRowSize(size) (6*(size)+1)
#define CanonBoardPos(row,col) (3*(myGameSize) +    \
         (2*(myGameSize)+(row))*(CanonRowSize(myGameSize)) + (col))
#define CanonBoardVal(board,row,col)          \
         board[CanonBoardPos(row,col)]
#define IsEmpty(board,row,col)             \
         (kEmpty == board[CanonBoardPos(row,col)])

ConvertPositionToCanonPosition
/* Convert coordinates from problem statement to canonical coordinates */
static CanonPosition ConvertPositionToCanonPosition (
            Position *pos, long size) {
   CanonPosition canon;
   canon.row = pos->row - 2 * size;
   if (pos->row == 2 * (int)(pos->row/2)) {
      canon.col = 2 * pos->col;
   } else {
      canon.col = 2 * pos->col - 1;
   }
   return canon;
}

ConvertCanonPositionToPosition
/* Convert canonical coordinates to coordinates from problem statement */
static Position ConvertCanonPositionToPosition (CanonPosition *canon, long size) {
   Position pos;
   pos.row = canon->row + 2 * size;
   if (canon->row == 2 * (int)(canon->row/2)) {
      pos.col = canon->col / 2;
   } else {
      pos.col = (canon->col + 1) / 2;
   }
   return pos;
}

RotateCanonPosition0ToN
/* rotate board by posNum increments of player positions (60 degrees) */
static CanonPosition RotateCanonPosition0ToN(
         CanonPosition oldPos, long posNum) {
   CanonPosition newPos;
   while (posNum<0) posNum+=6;   /* normalize to 0..5 */
   while (posNum>5) posNum-=6;
   switch (posNum) {
   case 0:
      newPos.row = oldPos.row;
      newPos.col = oldPos.col;
      break;
   case 1:
      newPos.row = (oldPos.row + oldPos.col)/2;
      newPos.col = (oldPos.col - 3*oldPos.row)/2;
      break;
   case 2:
      newPos.row =  (oldPos.col - oldPos.row)/2;
      newPos.col = -(oldPos.col + 3*oldPos.row)/2;
      break;
   case 3:
      newPos.row = -oldPos.row;
      newPos.col = -oldPos.col;
      break;
   case 4:
      newPos.row = -(oldPos.row + oldPos.col)/2;
      newPos.col = -(oldPos.col - 3*oldPos.row)/2;
      break;
   case 5:
      newPos.row = -(oldPos.col - oldPos.row)/2;
      newPos.col =  (oldPos.col + 3*oldPos.row)/2;
      break;
   }
   return newPos;
}

MaxColInRow
/* return the max column number in a given row */
static long MaxColInRow(long row, long size) {
   long maxCol;
   if (row<-size) {
      maxCol = row+2*size;
   } else if (row<0) {
      maxCol = 2*size-row;
   } else if (row<=size) {
      maxCol = row+2*size;
   } else /* if (row<=2*size) */ {
      maxCol = 2*size-row;
   }
   return maxCol;
}

IsLegalPosition
/* determine if a row,col coordinate represents a legal position */
static Boolean IsLegalPosition(CanonPosition *pos) {
   long maxCol;
   if ((pos->row<-2*myGameSize) || (pos->row>2*myGameSize)) 
         return false;
   if ((pos->row + pos->col) != 
               2 * (int)((pos->row + pos->col)/2)) 
      return false;
   maxCol = MaxColInRow(pos->row,myGameSize);
   if ((pos->col<-maxCol) || (pos->col>maxCol)) 
      return false;
   return true;
}

MoveFromTo
/* move a piece between positions from and to, does not check legality of move */
static void MoveFromTo(CanonBoard b,CanonPosition *from,CanonPosition *to,long newValue) {
   PlayerPos *p = &myPositions[newValue*myNumPieces];
   long oldValue = CanonBoardVal(b,from->row,from->col);
   int i;
   
   if (oldValue != newValue) {
      DebugStr("\p check err");
   }
   if ( IsLegalPosition(from) && IsLegalPosition(to) ) {
      CanonBoardVal(b,from->row,from->col) = kEmpty;
      CanonBoardVal(b,to->row,to->col) = (char)newValue;
      for (i=0; i<myNumPieces; i++) {
         if (    (p[i].pos.row == from->row) && 
                     (p[i].pos.col == from->col)) {
            p[i].pos.row = to->row;
            p[i].pos.col = to->col;
            break;
         }
      }
   }
}

PositionDistFromGoal
/* return the distance of a given position from a goal postion for player 0 */
static long PositionDistFromGoal (const CanonPosition *a, const CanonPosition *goal) {
   long rowDelta,colDelta;
   rowDelta = a->row - goal->row;
   if (rowDelta<0) rowDelta = -rowDelta;
   colDelta = a->col - goal->col;
   if (colDelta<0) colDelta = -colDelta;
   if (rowDelta>=colDelta) return rowDelta;
   else return rowDelta + (colDelta-rowDelta)/2;
}

PlayerDistFromGoal
/* return the cumulative distance of a player from his goal postion */
static long PlayerDistFromGoal(long player) {
   long cumDist;
   int i;
   CanonPosition goal;
   PlayerPos *p = &myPositions[player*myNumPieces];
   goal.row = -2*myGameSize;
   goal.col = 0;
   goal = 
      RotateCanonPosition0ToN(goal,(myPlayerPosition[player]+3)%6);
   for (i=0, cumDist=0; i<myNumPieces; i++) {
      CanonPosition *cp = &p[i].pos;
      long dist = PositionDistFromGoal(cp,&goal);
      cumDist += dist;
   }
   return cumDist;
}

InitPlayer
/* initialize the positions for a player at a given position */
static void InitPlayer(char *b,PlayerPos *piecePositions, long player, long position,long size) {
   CanonPosition pos,newPos;
   int col,maxCol,pieceCount;
   PlayerPos *piecePos;
   
   pieceCount = 0;
   for (maxCol=0; maxCol<size; maxCol++) {
      pos.row = -2*size+maxCol;
      maxCol = maxCol;
      for (col=-maxCol; col<=maxCol; col+=2) {
         pos.col = col;
         newPos = RotateCanonPosition0ToN(pos,position);
         CanonBoardVal(b,newPos.row,newPos.col) = (char)player;
   piecePos = &piecePositions[myNumPieces*player + pieceCount];
         piecePos->pos = newPos;
         ++pieceCount;
      }
   }
}

/* some variables to record the history of multi-jump moves, to
   prevent them from repeating infinitely */
static CanonPosition gMoveHistoryPos[6*64];
static long gMoveHistoryDirection[6*64];
static long gMoveHistoryCtr = -1;

CalcMove
/* Calculate a move for a given piece for a given player in a given moveDir.
 * Return true there is a legal move.
 * Return doneWithThisDirection==true if there are no more moves in this direction.
 */
static Boolean CalcMove(
         CanonBoard b, long player, long pieceNum, long moveDir, 
         CanonPosition *p1, CanonPosition *p2, 
         Boolean *doneWithThisDirection, long iterationLimit) {
   Boolean legalMove = true;
   if (gMoveHistoryCtr<0) {
      PlayerPos *p = &myPositions[player*myNumPieces];
      *p2 = *p1 = p[pieceNum].pos;
      p2->row += moveIncrement[moveDir].row;
      p2->col += moveIncrement[moveDir].col;
      if (!IsLegalPosition(p2)) legalMove = false;
      else if (IsEmpty(b,p2->row,p2->col)) {
      } else {
         long oldVal = CanonBoardVal(b,p2->row,p2->col);
         p2->row += moveIncrement[moveDir].row;
         p2->col += moveIncrement[moveDir].col;
         if (!IsLegalPosition(p2)) legalMove = false;
         else if (IsEmpty(b,p2->row,p2->col)) {
            if (gMoveHistoryCtr>iterationLimit) 
                        DebugStr("\p limit exceeded");
            gMoveHistoryPos[++gMoveHistoryCtr] = *p1;
            gMoveHistoryDirection[gMoveHistoryCtr] = 6;
            gMoveHistoryPos[++gMoveHistoryCtr] = *p2;
            gMoveHistoryDirection[gMoveHistoryCtr] = -1;
         } else {
            legalMove = false;
         }
      }
   } else {
      CanonPosition pStart,pTemp;
      long newDir;
      ++gMoveHistoryDirection[gMoveHistoryCtr];
      pStart = pTemp = gMoveHistoryPos[gMoveHistoryCtr];
      while (   (gMoveHistoryCtr>=0) && 
                     (gMoveHistoryDirection[gMoveHistoryCtr]>=6) ) {
         gMoveHistoryCtr-;
      }
      if (gMoveHistoryCtr>0) {
         newDir = gMoveHistoryDirection[gMoveHistoryCtr];
         pTemp.row += moveIncrement[newDir].row;
         pTemp.col += moveIncrement[newDir].col;
         if (!IsLegalPosition(&pTemp)) legalMove=false;
         else if (IsEmpty(b,pTemp.row,pTemp.col)) legalMove=false;
         else {
            pTemp.row += moveIncrement[newDir].row;
            pTemp.col += moveIncrement[newDir].col;
            if (!IsLegalPosition(&pTemp)) legalMove=false;
            else if (!IsEmpty(b,pTemp.row,pTemp.col)) legalMove=false;
            else {
               int i;
               for (i=0; i<=gMoveHistoryCtr; i++)
                  if (   (pTemp.row == gMoveHistoryPos[i].row) && 
                           (pTemp.col == gMoveHistoryPos[i].col) )
                      legalMove=false;
               if (legalMove) {
                  gMoveHistoryDirection[++gMoveHistoryCtr] = -1;
                  gMoveHistoryPos[gMoveHistoryCtr] = pTemp;
                  *p1 = gMoveHistoryPos[0];
                  *p2 = pTemp;
               }
            }
         }
      } else {
         legalMove=false;
      }
      
   }
   *doneWithThisDirection = (gMoveHistoryCtr<0);
   return legalMove;
}

/* multiplier to determine how much storage to reserves for moves for each piece */
#define kMemAllocFudge 12

EnumerateMoves
static long EnumerateMoves(CanonBoard b, long player, CanonPosition moveFrom[], CanonPosition moveTo[]) {
   long numMoves = 0;
   int piece,moveDir;
   Boolean legalMove,doneWithThisDirection;
   for (piece=0; piece<myNumPieces; piece++) {
      int pieceCounter=0;
      int firstPieceMoveIndex = numMoves;
      moveDir = 0;
      do {
         legalMove = CalcMove(b,player,piece,moveDir,
               &moveFrom[numMoves],&moveTo[numMoves],
               &doneWithThisDirection,6*myGameSize);
         if (doneWithThisDirection)
            ++moveDir;
         if (!legalMove) continue;
         if (numMoves>=kMemAllocFudge*myNumPieces-1) {
            DebugStr("\pnumMoves limit exceeded");
            break;
         } else {
            int i;
            for (i=firstPieceMoveIndex; i<numMoves; i++)
               if ( (moveTo[i].row==moveTo[numMoves].row) && 
                   (moveTo[i].col==moveTo[numMoves].col) )
                     legalMove = false;
            if (!legalMove) continue;
            ++numMoves;
         }
      } while (moveDir<6);
   }
   return numMoves;
}

MakeNextMove
/* 
 * Recursive routine to explore move tree.
 * MakeNextMove iterates over all possible moves for a player.
 * If ply limit is not yet reached, it recurses by calling for the next player.
 * Ply limit is decreased by 1 when the "me" player is called.
 * Recursion terminates when ply limit is reached.
 * Score is assigned on return based on the perspective of the player making the move.
 * Simple-minded score algorithm is used: 
 *   difference between player score and the best other player score, where
 *   a player's score is the number of spaces he is away from the final state
 * No alpha-beta pruning is employed - search is exhaustive.
 */

static long MakeNextMove(CanonBoard b, long me, long player, long playerDistances[6], long numPlys,
   Boolean firstTime, CanonPosition *from, CanonPosition *to) {
   long theMove,nextPlayer,numMoves,
               bestScore=0x7FFFFFFF, myBestDistance=0x7FFFFFFF;
   CanonPosition pFrom,pTo,bestFrom,bestTo;
   int newPlys;
   CanonPosition *moveFrom,*moveTo;

   /* allocate storage for possible moves */
   moveFrom = (CanonPosition *)
      malloc(kMemAllocFudge*myNumPieces*sizeof(CanonPosition));
   if (0==moveFrom) 
         DebugStr("\pproblem allocation moveFrom memory");
   moveTo = (CanonPosition *)
      malloc(kMemAllocFudge*myNumPieces*sizeof(CanonPosition));
   if (0==moveTo) 
         DebugStr("\pproblem allocation moveTo memory");
   
   /* prime best move with starting move */
   bestFrom = *from;
   bestTo = *to;
   /* enumerate all legal moves for this player */
   numMoves = EnumerateMoves(b,player,moveFrom,moveTo);
   /* examine all of the enumerated moves */
   for (theMove=0; theMove<numMoves; theMove++) {
      long opponent,scoreDifference,minOpponentDistance,
               myDistance,returnedDistances[6];
      int thePlayer;
      pFrom = moveFrom[theMove];
      pTo = moveTo[theMove];
      if (firstTime) {
         *from = pFrom;
         *to = pTo;
      }
      nextPlayer = (player+1)%myNumPlayers;
      newPlys = (player==me) ? numPlys-1 : numPlys;
      
      /* record move in the simulated board */
      MoveFromTo(b,&pFrom,&pTo,player);
      
      myDistance = PlayerDistFromGoal(player);
      
      /* recurse if ply limit not reached */
      if ( (newPlys>=0) && (myDistance>myMinDist) ){
         /* MakeNextMove returns each player's distance from the goal in 
            returnedDistances, and the score from nextPlayer's perspective in 
            returnScore.
            returnScore is ignored except by nonrecursive callers to MakeNextMove 
          */
         long returnScore;
         returnScore = 
               MakeNextMove(b, me, nextPlayer, returnedDistances, 
                           newPlys, false, from, to);
      } else /*if (player==me)*/ {
         /* terminating recursion, calculate position values for each player */
         /* compute distances for all players */
         for (thePlayer=0; thePlayer<myNumPlayers; thePlayer++)
            returnedDistances[thePlayer] = 
                     PlayerDistFromGoal(thePlayer);
      }
      /* compute best opponent score from this player perspective */
      for (thePlayer=0,minOpponentDistance=0x7fffffff; 
                     thePlayer<myNumPlayers; thePlayer++) {
         if (   (thePlayer != player) && 
            (returnedDistances[thePlayer]<minOpponentDistance) ) 
            minOpponentDistance = returnedDistances[thePlayer];
      }
      scoreDifference = 
            returnedDistances[player]-minOpponentDistance;
      /* Save score if it is the best for this player.
         This move is best if
         (1) our distance from goal minus best opponents distance is smallest, or
         (2) goal distance difference is equal, but our absolute distance is smallest, or
         (3) goal distance difference is equal, and coin flip says pick this move 
                                          (commented out) */
      if ( (scoreDifference < bestScore) ||
          ((scoreDifference==bestScore) && 
                  (returnedDistances[player]<myBestDistance)) /*||
((scoreDifference==bestScore) && ((rand()&0x0080)==1))*/ ) {
         bestScore = scoreDifference;
         myBestDistance = returnedDistances[player];
         for (opponent=0; opponent<myNumPlayers; opponent++)
      playerDistances[opponent] = returnedDistances[opponent];
         bestFrom = pFrom;
         bestTo = pTo;
      }
      /* reverse move to clear board for mext move */
      MoveFromTo(b,&pTo,&pFrom,player);
   }
   /* free dynamically allocated move storage */
   free(moveTo);
   free(moveFrom);
   
   /* return best move */
   *from = bestFrom;
   *to = bestTo;

   return bestScore;
}

FindBestMove
/* find best move for player me from this position on the board */
static long FindBestMove(CanonBoard b, long me, long numPlys, CanonPosition *from, CanonPosition *to) {
   long playerDistances[6];

   return MakeNextMove(b,me,me,playerDistances,numPlys,true,from,to);
}

InitChineseCheckers
void InitChineseCheckers(
   long numPlayers,      /* 2..6  */
   long gameSize, /* base of home triangle, 3..63, you have size*(size+1)/2 pieces */
   long playerPosition[6],   /* 0..5, entries 0..numPlayers-1 are valid */
   long yourIndex /* 0..numPlayers-1, your position is playerPosition[yourIndex] */
) {
   int i,numPositions;
   /* allocate memory for board */
   numPositions = 6*(1+gameSize)*4*(1+gameSize);
   myBoard = (char *)malloc(numPositions*sizeof(char));
   if (myBoard==0) DebugStr("\p could not allocate board");
   myNumPieces = gameSize*(gameSize+1)/2;
   myPositions = (PlayerPos *)
               malloc(6*myNumPieces*sizeof(PlayerPos));
   if (myPositions==0) 
               DebugStr("\p could not allocate myPositions");

   /* copy parameters */
   for (i=0;i<6; i++) myPlayerPosition[i] = playerPosition[i];
   myIndex = yourIndex;
   myNumPlayers = numPlayers;
   myGameSize = gameSize;
   /* initialize board */
   for (i=0; i<numPositions; i++) myBoard[i] = kEmpty;
   for (i=0; i<numPlayers; i++) {
      InitPlayer(myBoard,myPositions,i,playerPosition[i],gameSize);
   }
   
   /* calculate distance metric at goal position */
   for (i=1, myMinDist=0; i<gameSize; i++) myMinDist += i*(i+1);
}

YourMove
void YourMove(
   Position *fromPos,   /* originating position */
   Position *toPos   /* destination position */
) {
   CanonPosition from,to;
   long numPlys = kMaxPlys;
   FindBestMove(myBoard,myIndex,numPlys,&from,&to);
   MoveFromTo(myBoard,&from,&to,myIndex);
   *fromPos = ConvertCanonPositionToPosition(&from,myGameSize);
   *toPos = ConvertCanonPositionToPosition(&to,myGameSize);
}

OpponentMove
void OpponentMove(
   long opponent,   /* index in playerPosition[] of the player making move */
   Position fromPos,   /* originating position */
   Position toPos      /* destination position */
) {
   CanonPosition from,to;
   from = ConvertPositionToCanonPosition(&fromPos,myGameSize);
   to =   ConvertPositionToCanonPosition(&toPos,myGameSize);
   MoveFromTo(myBoard,&from,&to,opponent);
}

TermChineseCheckers
void TermChineseCheckers(void) {
   free (myPositions);
   free (myBoard);
}
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.