/*
** makecourts.c  Copyright 1991 Kent Paul Dolan,
**               Mountain View, CA, USA 94039-0755
**
** Written to satisfy an inquiry on USENet's rec.games.programmer newsgroup.
** May be freely used or modified in any non-commercial work.  Copyrighted
** only to prevent patenting by someone else.
*/

#include <stdio.h>
#include "townmaze.h"
#include "townproto.h"

#ifdef __STDC__
void makecourts()
#else
int makecourts()
#endif
{

  int totalcells;
  int chosencell;
  int tries;
  int i;

/*
** Pepper courts around the city interior; keep them apart for algorithmic
** robustness reasons.
*/

#if PROGRESS
  fprintf(stderr,"Courts ");
#endif

  totalcells = ((mazeheight-1)/2 * (mazewidth-1)/2);

  for (i = 0; i < mazecourts; i++)
  {

/*  fprintf(stderr,"Court %d\n",i); */

/*
** Set up to prevent infinite loop from unforseen geometry problems.
*/

   tries = 0;

/*
** Keep looking until a candidate cell is found for this ith court.
*/
    do
    {
      /* not perfectly fair, but good enough for moderate sized mazes. */
      chosencell = RANDOM()%totalcells;

/*    fprintf(stderr,"  chosencell %d\n",chosencell); */

      tries++;

    } while (   (tries <= MAXTRIES)
             && (
                    (interiorcell(chosencell) != (1==1))
                 || (statlist[chosencell].status != ISOLATED)
                 || (statlist[nhbris(chosencell,0)].status != ISOLATED)
                 || (statlist[nhbris(chosencell,1)].status != ISOLATED)
                 || (statlist[nhbris(chosencell,2)].status != ISOLATED)
                 || (statlist[nhbris(chosencell,3)].status != ISOLATED)
                )
            );

    if (tries <= MAXTRIES) makestreet(chosencell,streetnumct++,RANDOM()%4);
  }
  return;
}
