/*
** closedoors.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 closedoors()
#else
int closedoors()
#endif
{

/*
** The map as built so far has far too many doors per room.  Close all
** but one door of each room to make a "Bard's Tale I"-like maze.
*/

  int deadwalk;  /* nothing interesting left but the dead cells */
  int doorct, whichdoor;
  int celli, cellj;

#if PROGRESS
  fprintf(stderr,"Close Doors ");
#endif

  deadwalk = dead;

  while (deadwalk != NOPOINTER)
  {

    celli = deadwalk/(mazewidth/2);
    cellj = deadwalk%(mazewidth/2);

    celli = (2*celli) + 1;
    cellj = (2*cellj) + 1;

    doorct = 0;
    if (cmaze[celli - 1][cellj] == HDOOR) doorct++;
    if (cmaze[celli][cellj + 1] == VDOOR) doorct++;
    if (cmaze[celli + 1][cellj] == HDOOR) doorct++;
    if (cmaze[celli][cellj - 1] == VDOOR) doorct++;

    if ( doorct > 1 )
    {
      whichdoor = RANDOM()%doorct; /* keep this one */
      doorct = 0;
      if (cmaze[celli - 1][cellj] == HDOOR)
      {
        if (doorct != whichdoor) cmaze[celli - 1][cellj] = WALL;
        doorct++;
      }
      if (cmaze[celli][cellj + 1] == VDOOR)
      {
        if (doorct != whichdoor) cmaze[celli][cellj + 1] = WALL;
        doorct++;
      }
      if (cmaze[celli + 1][cellj] == HDOOR)
      {
        if (doorct != whichdoor) cmaze[celli + 1][cellj] = WALL;
        doorct++;
      }
      if (cmaze[celli][cellj - 1] == VDOOR)
      {
        if (doorct != whichdoor) cmaze[celli][cellj - 1] = WALL;
        doorct++;
      }
    }
    deadwalk = statlist[deadwalk].next;
  }
}
