コード例 #1
0
void DFSBoard::FillRowbyFillStart(int nowr, vector<int>& fillStart){//or directly fill
  int limitNum = lim_row[nowr].size();
  for(int i = 0; i < limitNum; i++)
    for(int j = fillStart[i]; j < fillStart[i]+lim_row[nowr][i].l; j++)
      fillGrid(nowr, j, BLACK);
  for(int i = 0; i < c; i++)
    if(b[nowr][i] == SPACE)
      fillGrid(nowr, i, WHITE);
  printBoard("FillRowbyFillStart");
}
コード例 #2
0
int	readOneGrid(char *grid, int *check, bool start)
{
  char	buff[22];
  int	loop;
  int	i;

  memset(buff, 0, 22);
  i = 0;
  loop = 0;
  while (loop < 11 && (*check = read(0, buff, 21)) > 0)
    {
      if (checkGrid(buff, i, loop))
	return (1);
      if (i < 9 && fillGrid(buff, grid + 9 * i))
	return (1);
      if (loop++ > 0)
	++i;
    }
  if (loop == 11)
    {
      if (!start && printf("####################\n") < 0)
	return (1);
      return (2);
    }
  return (0);
}
コード例 #3
0
ファイル: gol.c プロジェクト: jeroen51/Game-of-life
int main() {
	signal(SIGINT, finish);
	initscr();
	refresh();

	int grid[GRID_SIZE][GRID_SIZE];

	fillGrid(grid);

	printGrid(grid);

	int i;
	for(i = 0; i < LENGTH; ++i) {
		struct timespec requestedTime, elapsedTime;
		requestedTime.tv_sec = 0;
		requestedTime.tv_nsec = SPEED * 1000 * 1000 - 1; //has to be lower than 9 billion

		while((requestedTime.tv_sec + requestedTime.tv_nsec) > 0)
		{
		   nanosleep(&requestedTime, &elapsedTime);
		   requestedTime.tv_sec = elapsedTime.tv_sec;
		   requestedTime.tv_nsec = elapsedTime.tv_nsec;
		}
		iterateGrid(grid);
		printGrid(grid);
	}

	//TODO: use ncurses to manage "windows" in output. ("http://invisible-island.net/ncurses/ncurses-intro.html#curses")
	return 0;
}
コード例 #4
0
ファイル: SampleEntry.cpp プロジェクト: drkvogel/retrasst
void __fastcall TfrmRetrieveMain::btnLocateClick( TObject *Sender ) {
	StoreDAO dao;
	std::map < int, const GridEntry* > boxes;
	Screen->Cursor = crSQLWait;
	progress->Position = 0;
	progress->Max = rows.size( );
	for( std::vector < GridEntry > ::iterator ge = rows.begin( ); ge != rows.end( ); ++ge ) {
		int boxID = ge->bid;
		auto found = boxes.find( boxID );
		if( found != boxes.end( ) ) {
			ge->copyLocation( *( found->second ) );
		} else {
			ROSETTA result;
			if( dao.findBox( boxID, result ) ) {
				ge->copyLocation( result );
				fillGrid( );
			}
			boxes[ boxID ] = &( *ge );
		}
		progress->StepIt( );
		Application->ProcessMessages( );
	}
	updateDisplay( );
	Screen->Cursor = crDefault;
}
コード例 #5
0
//main controls the population of the grid
int main(void){
  int *grid = malloc(sizeof(int) * TEST_SPIRAL_SIZE * TEST_SPIRAL_SIZE);
  memset(grid, 0, sizeof(int) * TEST_SPIRAL_SIZE * TEST_SPIRAL_SIZE);
  fillGrid(grid, TEST_SPIRAL_SIZE);
  //printGrid(grid, TEST_SPIRAL_SIZE);

  printf("sum of %d square spiral is: %d\n", TEST_SPIRAL_SIZE, sumDiagonals(grid, TEST_SPIRAL_SIZE));
}
コード例 #6
0
ファイル: SampleEntry.cpp プロジェクト: drkvogel/retrasst
void __fastcall TfrmRetrieveMain::AddClick( TObject *Sender ) {
	if( !OpenDialog1->Execute( ) ) {
		return;
	}
	Screen->Cursor = crSQLWait;
	progress->Position = 0;
	std::unique_ptr < TStrings > lines( new TStringList );
	lines->LoadFromFile( OpenDialog1->FileName );
	progress->Max = lines->Count;
	std::unique_ptr < TStrings > fields( new TStringList );
	bool expectPos = (rgDestOrder->ItemIndex == FROM_FILE);
	bool finished = false;
	for( int line = 0; line < lines->Count; ) {
		fields->CommaText = lines->Strings[ line ++ ];
		int pos;
		String warning;
		switch( fields->Count ) {
			case 0:
				continue;
			case 1:
				if( expectPos ) {
					warning = "No position";
				} else {
					pos = rows.size() + 1;
				}
				break;
			case 2:
				if( expectPos ) {
					pos = fields->Strings[ 1 ].ToIntDef( -1 );
					if( pos < 1 ) {
						warning = "Invalid position";
					}
					break;
				}
			default:
				warning = "Extra characters";
		}

		if( warning.IsEmpty() ) {
			warning = addCryovials( fields->Strings[ 0 ], pos );
		}
		if( !warning.IsEmpty() ) {
			warning = warning + " on line " + String( line );
			if( Application->MessageBox( warning.c_str(), L"Warning", MB_OKCANCEL | MB_ICONWARNING) != IDOK ) {
				rows.clear( );
				break;
			}
		}
		progress->StepIt( );
		fillGrid( );
		Application->ProcessMessages( );
	}
	Screen->Cursor = crDefault;
	sortList.clear( );
	updateDisplay();
}
コード例 #7
0
bool DFSBoard::tryFillRowbyFillStartHeuristic(int nowr, vector<int>& fillStart){//or directly fill
  int limitNum = lim_row[nowr].size();
  for(int i = 0; i < limitNum; i++)
    for(int j = fillStart[i]; j < fillStart[i]+lim_row[nowr][i].l; j++)
      fillGrid(nowr, j, BLACK);
  for(int i = 0; i < c; i++)
    if(b[nowr][i] == SPACE)
      fillGrid(nowr, i, WHITE);

  tryFailed = false;
  while(!isAllSolved() && !tryFailed)
    if(!doHeuristicInOneLine())
      break;
  if(tryFailed){//find contradiction when updating heuristic
    printf("try fill: failed, rewind %d\n", nowr);
    Rewind(nowr);
    return false;
  }
  puts("dfs with heursitic success");
  return true;
}
コード例 #8
0
ファイル: GridOps.hpp プロジェクト: jwscook/solver
static
void
fillGrid(Grid<GridT>& grid,
         const Dimensions<DIM>& dimensions,
         const std::array<int, DIM>& numberOfUnknownsPerDim)
{
    for (uint i = 0; i < DIM; ++i) {
        fillGrid(grid,
                 dimensions.dimension(i),
                 numberOfUnknownsPerDim[i]);
    }

}
コード例 #9
0
ファイル: Spiral.cpp プロジェクト: Elegy/ProjectEuler
Spiral::Spiral(int size, Rotation rotation)
: Matrix(size, size)
, rotation(rotation)
{
    visited = new bool*[size];
    for(int i = 0; i < size; ++i)
    {
        visited[i] = new bool[size];
        memset(visited[i], 0, sizeof(bool) * size);
    }
    
    fillGrid();
}
コード例 #10
0
// Testing grid.c
int TEST_fillGrid()
{
  cell grid[H][W];
  initGrid(grid);
  fillGrid(grid);
  if(grid[rand()%H][rand()%W].background->ispassable!=passable){
    printf("%25s %s\n",__func__, FAIL );
    return ERROR;
  }
  else{
    printf("%25s %s\n",__func__, PASS );
    return SUCCESS;
  }
}
コード例 #11
0
int TEST_newBulb(){
  cell grid[H][W];
  int x=0, y=0;
  entity *bulb=newBulb(grid, x, y);
  initGrid(grid);
  fillGrid(grid);
  if(bulb->ispassable!=1 || bulb->x!=x || bulb->y !=y){
    printf("%25s %s\n",__func__, FAIL );
    return ERROR;
  }
  else{
    printf("%25s %s\n",__func__, PASS );
    return SUCCESS;
  }
}
コード例 #12
0
int TEST_getNeighbour()
{
  int x=5, y=5;
  direction dir=LEFT;
  cell grid[H][W], *testCell;
  initGrid(grid);
  fillGrid(grid);
  testCell=getNeighbour(x, y, dir, grid);
  if(testCell->background!=grid[y][x-1].background){
    printf("%25s %s\n",__func__, FAIL );
    return ERROR;
  }
  else{
    printf("%25s %s\n",__func__, PASS );
    return SUCCESS;
  }
}
コード例 #13
0
int TEST_directionsTrans()
{
  int x,y;
  cell grid[H][W];
  initGrid(grid);
  fillGrid(grid);
  x=grid[5][1].background->x;
  y=grid[5][0].background->y;
  directionsTrans(LEFT, &x, &y);
  if(x!=grid[5][0].background->x){
    printf("%25s %s\n",__func__, FAIL );
    return ERROR;
  }
  else{
    printf("%25s %s\n",__func__, PASS );
    return SUCCESS;
  }
}
コード例 #14
0
ファイル: SampleEntry.cpp プロジェクト: drkvogel/retrasst
void TfrmRetrieveMain::updateDisplay( ) {
	lbSortCols->Clear( );
	for( const Column & ci : sortList.columns ) {
		AnsiString order = ci.ascending ? " ascending" : " descending";
		lbSortCols->Items->Add( ci.label.c_str( ) + order );
	}
	if( rows.empty( ) ) {
		grdSamples->RowCount = 2;
	} else {
		fillGrid( );
	}
	for( int row = rows.size( ) + 1; row < grdSamples->RowCount; row++ ) {
		for( int col = 0; col < COL_COUNT; col++ ) {
			grdSamples->Cells[ col ][ row ] = " ";
		}
	}
	enableButtons( );
}
コード例 #15
0
ファイル: Source.cpp プロジェクト: chrischiu41/Game-Centre
/*
plays round of tic tac toe, two turns
Parameters: grid, ordername and ordersymbol (2 arrays)
Return Type: index of name/symbol
*/
int round_TTT(char grid[][COLUMN_SIZE], char ordersymbol[], char ordername[][MAX_NAME_LENGTH])
{
	int result;
	int index = 0;
	int position;
	char copyname[MAX_NAME_LENGTH];
	char name;
	int empty_space;
	int count = 0;

	do
	{
		adding_apos_s(index, ordername, copyname);
		printf("%s: ", copyname);
		do
		{
			scanf("%d", &position);
			empty_space = fillGrid(position, ordersymbol[index], grid);
			count++;
			if (empty_space == FALSE)
			{
				printf("Invalid move. Enter another number: ");
				count--;
			}
		} while (empty_space == FALSE);

		if (index == 0)
			index++;
		else
			index = 0;
		if (count == 9)
			index = TIE;
	} while (!winRound(grid, ordersymbol, ordername, count));

	return index;
}
コード例 #16
0
int quizGame(Display *d)
{
  char rand_word[LENGTH], shuffle_word[LENGTH], original_word[LENGTH];
  char hintWord[HINTLENGTH];
  int i, word_size, j, yinit = 9, xinit, cnt=0, in, printHint=0, resetsent = 0;
  int hintNum=0;
  cell grid[H][W];
  entity *player, *door1, *door2, *rbutton, *hbutton;

  initGrid(grid);
  hintNum=enc_getWord(rand_word);
  enc_getHint(hintWord, hintNum-1);
  word_size = strlen(rand_word);
  rand_word[word_size]='\0';

  // here we make sure the word always apears in the middle
  xinit = (W/2) - (word_size/2);
  strcpy(shuffle_word, rand_word);
  enc_shuffle(shuffle_word, word_size);
  strcpy(original_word, shuffle_word);
  player = grid[8][3].foreground = newEntity(passable,P_R1,3,8);
  door1 = grid[7][W-4].background = newEntity(impassable,DOORCLOSED,W-4,7);
  door2 = grid[7][3].background = newEntity(impassable,DOORCLOSED,3,7);

  /* place the word in the grid */
  for (j=0; j<word_size; j++){
    enc_newLetter(grid, xinit+j, yinit, shuffle_word[j]);
  }
  makeBoundariesquizGame(grid);
  rbutton = grid[7][1].background = newEntity(impassable, RESETBUTTON,7,1);
  hbutton = grid[7][16].background = newEntity(impassable, HINTBUTTON,7,16);
  fillGrid(grid);   /* layer of floortiles */

  encGameDraw(d, grid, printHint, hintWord, resetsent, grid[yinit][player->x].background->type);

  /* MAIN LOOP */
  while(in!=10){

    in=input(d);

    if (grid[player->y][player->x].background == door1|| grid[player->y][player->x].background == door2) {
      freeEntityMem(grid);  /* free memory */
      return 0;
    }
    resetsent = 0;
    changeEntity(rbutton, RESETBUTTON);
    if( (in > 0) && (in < 5) ){ /*checks for arrowkeys */
      move(&grid[player->y][player->x],player->x,player->y,(direction)in,grid);
      printGrid(grid);
    }
    if (in == 9) { /*checks for spacebar */
      if(grid[player->y][player->x].background->type == DARROW) {// "$" is now the down arrow symbol
        enc_updateLetter(grid, player->y, player->x);
        Mix_PlayChannel( -1, d->zap, 0 );
        }
      else if(grid[player->y][player->x].background->type == UARROW) {
        enc_updateLetter(grid, player->y, player->x);
        Mix_PlayChannel( -1, d->zap, 0 );
      }
      else if(grid[player->y-1][player->x].background->type == RESETBUTTON) {
        for (i=0; i<word_size; i++){
          enc_newLetter(grid, xinit+i, yinit, original_word[i]);
        }
        resetsent = 1;
        changeEntity(rbutton, RBUTTON_PR);
        Mix_PlayChannel( -1, d->zap, 0 );
      }
      else if(grid[player->y-1][player->x].background == hbutton) {
        printHint = !printHint;
        if (hbutton->type == HINTBUTTON) {
          changeEntity(hbutton, HBUTTON_PR);
        }
        else {
          changeEntity(hbutton, HINTBUTTON);
        }
        Mix_PlayChannel( -1, d->zap, 0 );
      }
    }
    enc_updateWord(grid, yinit, xinit, shuffle_word);
    if(strcmp(shuffle_word, rand_word)==0){
      changeEntity(door1, DOOROPEN);
      changePassable(door1,passable);
      changeEntity(door2, DOOROPEN);
      changePassable(door2,passable);
    }
    printGrid(grid);
    encGameDraw(d, grid, printHint, hintWord, resetsent, grid[yinit][player->x].background->type);
    cnt++;
  }
  freeEntityMem(grid);  /* free memory */
  return 1;
}
コード例 #17
0
/* Inserts controls into layouts
   This is sub-optimal in the OO way, as controls's code still
   depends on Layout classes. We should use layout inserters [friend]
   classes, but it's unlikely we had to deal with a different layout.*/
void ConfigControl::insertInto( QBoxLayout *layout )
{
    QGridLayout *sublayout = new QGridLayout();
    fillGrid( sublayout, 0 );
    layout->addLayout( sublayout );
}
コード例 #18
0
void MainWindow::on_pushButton_clicked()
{
    QString nombre=QFileDialog::getOpenFileName(this,"File",QDir::currentPath(),"*.txt");

    fillGrid(nombre);
}
コード例 #19
0
int main(void)
{
  Display *d = newDisplay();
  cell grid[H][W];
  entity *player, *door1, *door2;
  int in,gamesPlayed[2];
  srand(time(NULL));
  gamesPlayed[0]=gamesPlayed[1]=0;

  mediaLoad(d);
  intro(d);
  initGrid(grid);
   // place player
  player = grid[10][2].foreground = newEntity(passable,P_R1 ,2,10);
   // Creates the boundary walls
  makeBoundariesLobby(grid);

  door1 = grid[4][W-6].background = newEntity(passable,DOORINVIS, W-6,4);
  door2 = grid[7][W-11].background = newEntity(passable,DOORINVIS ,W-11,7);

  /* layer of floortiles -
  must be the last entity placement*/
  fillGrid(grid);


  while(in!=10){
    if(gamesPlayed[0]!=MAXPLAYTIMES||gamesPlayed[1]!=MAXPLAYTIMES){
      lobbyDraw(d, grid);
      in=input(d);
      if( (in > 0) && (in < 5) ){ /*checks for arrowkeys */
        move(&grid[player->y][player->x],player->x,player->y,(direction)in,grid);
        printGrid(grid);
      }
    }
    else{
          GameOver(d,&in);
          if(in!=10){
          gamesPlayed[0]=gamesPlayed[1]=0;
        }
        else{
          /*in==10 the same as d->finished=true;*/
          in=10;
          d->finished=(SDL_bool)true;
        }
    }
    if (grid[player->y][player->x].background == door1&&gamesPlayed[0]<MAXPLAYTIMES) {
      bgame(d);
      gamesPlayed[0]++;
      move(&grid[player->y][player->x],player->x,player->y,DOWN,grid);
      changeEntity(player, P_DOWN1);
    }
    if (grid[player->y][player->x].background == door2&&gamesPlayed[1]<MAXPLAYTIMES) {
      quizGame(d);
      gamesPlayed[1]++;
      move(&grid[player->y][player->x],player->x,player->y,DOWN,grid);
      changeEntity(player, P_DOWN1);
    }
  }
  freeEntityMem(grid);  /* free memory */
  closeDisplay(d);
  d->finished=(SDL_bool)true;
  fprintf(OUTPUT, "\n\n");
  return(0);
}
コード例 #20
0
void ossimTiledElevationDatabase::mapRegion()
{
   static const char M[] = "ossimTiledElevationDatabase::mapRegion";
   
   if ( m_entries.size() && ( m_requestedRect.isLonLatNan() == false ) )
   {
      ossimRefPtr<ossimOrthoImageMosaic> mosaic = new ossimOrthoImageMosaic();
      std::vector<ossimTiledElevationEntry>::iterator i = m_entries.begin();
      while ( i != m_entries.end() )
      {
         mosaic->connectMyInputTo( (*i).m_sic.get() );
         ++i;
      }

      // Compute the requested rectangle in view space.
      ossimRefPtr<ossimImageGeometry> geom = mosaic->getImageGeometry();
      if ( geom.valid() )
      {
         ossimDpt ulDpt;
         ossimDpt lrDpt;
         geom->worldToLocal(m_requestedRect.ul(), ulDpt);
         geom->worldToLocal(m_requestedRect.lr(), lrDpt);

         // Expand out to fall on even view coordinates.
         ulDpt.x = std::floor(ulDpt.x);
         ulDpt.y = std::floor(ulDpt.y);
         lrDpt.x = std::ceil(lrDpt.x);
         lrDpt.y = std::floor(lrDpt.y);

         // Get new(expanded) corners in ground space.
         ossimGpt ulGpt;
         ossimGpt lrGpt;
         geom->localToWorld(ulDpt, ulGpt);
         geom->localToWorld(lrDpt, lrGpt);
         theGroundRect = ossimGrect(ulGpt, lrGpt);
            
         // Expanded requested rect in view space.
         ossimIpt ulIpt = ulDpt;
         ossimIpt lrIpt = lrDpt;
         const ossimIrect VIEW_RECT(ulIpt, lrIpt);

         // Get the data.
         ossimRefPtr<ossimImageData> data = mosaic->getTile(VIEW_RECT, 0);
         if ( data.valid() )
         {
            // Initialize the grid:
            const ossimIpt SIZE( data->getWidth(), data->getHeight() );
            const ossimDpt ORIGIN(ulGpt.lon, lrGpt.lat); // SouthWest corner
            const ossimDpt SPACING( (lrGpt.lon-ulGpt.lon)/(SIZE.x-1),
                                    (ulGpt.lat-lrGpt.lat)/(SIZE.y-1) );
            if ( !m_grid ) m_grid = new ossimDblGrid();
            m_grid->initialize(SIZE, ORIGIN, SPACING, ossim::nan());

            if ( traceDebug() )
            {
               ossimNotify(ossimNotifyLevel_DEBUG)
                  << M
                  << "\nrequested view rect: " << VIEW_RECT
                  << "\nexpanded ground rect: " << theGroundRect
                  << "\norigin:  " << ORIGIN
                  << "\nsize:    " << SIZE
                  << "\nspacing: " << SPACING << std::endl;
            }

            // Fill the grid:
            switch( data->getScalarType() )
            {
               case OSSIM_SINT16:
               {
                  fillGrid(ossim_sint16(0), data);
                  break;
               }
               case OSSIM_SINT32:
               {
                  fillGrid(ossim_sint32(0), data);
                  break;
               }
               case OSSIM_FLOAT32:
               {
                  fillGrid(ossim_float32(0), data);
                  break;
               }
               case OSSIM_FLOAT64:
               {
                  fillGrid(ossim_float64(0), data);
                  break;
               }
               case OSSIM_UINT8:
               case OSSIM_SINT8:
               case OSSIM_USHORT11:
               case OSSIM_UINT16:
               case OSSIM_UINT32:
               case OSSIM_NORMALIZED_DOUBLE:
               case OSSIM_NORMALIZED_FLOAT:
               case OSSIM_SCALAR_UNKNOWN:
               default:
               {
                  std::string errMsg = M;
                  errMsg += " ERROR:\nUnhandled scalar type: ";
                  errMsg += data->getScalarTypeAsString().string();
                  throw ossimException(errMsg);
               }
            }
            
         } // if ( data.valid() )

      } // if ( geom.valid() )

   } // if ( m_entries.size() && ...
}
コード例 #21
0
void ConfigControl::insertIntoExistingGrid( QGridLayout *l, int line )
{
    fillGrid( l, line );
}
コード例 #22
0
ファイル: Grid.c プロジェクト: AlexMooney/Brogue
boolean getQualifyingPathLocNear(short *retValX, short *retValY,
                                 short x, short y,
                                 boolean hallwaysAllowed,
                                 unsigned long blockingTerrainFlags,
                                 unsigned long blockingMapFlags,
                                 unsigned long forbiddenTerrainFlags,
                                 unsigned long forbiddenMapFlags,
                                 boolean deterministic) {
    short **grid, **costMap;
    short loc[2];
    
    // First check the given location to see if it works, as an optimization.
    if (!cellHasTerrainFlag(x, y, blockingTerrainFlags | forbiddenTerrainFlags)
        && !(pmap[x][y].flags & (blockingMapFlags | forbiddenMapFlags))
        && (hallwaysAllowed || passableArcCount(x, y) <= 1)) {
        
        *retValX = x;
        *retValY = y;
        return true;
    }
    
    // Allocate the grids.
    grid = allocGrid();
    costMap = allocGrid();
    
    // Start with a base of a high number everywhere.
    fillGrid(grid, 30000);
    fillGrid(costMap, 1);
    
    // Block off the pathing blockers.
    getTerrainGrid(costMap, PDS_FORBIDDEN, blockingTerrainFlags, blockingMapFlags);
    if (blockingTerrainFlags & (T_OBSTRUCTS_DIAGONAL_MOVEMENT | T_OBSTRUCTS_PASSABILITY)) {
        getTerrainGrid(costMap, PDS_OBSTRUCTION, T_OBSTRUCTS_DIAGONAL_MOVEMENT, 0);
    }
    
    // Run the distance scan.
    grid[x][y] = 1;
    costMap[x][y] = 1;
    dijkstraScan(grid, costMap, true);
    findReplaceGrid(grid, 30000, 30000, 0);
    
    // Block off invalid targets that aren't pathing blockers.
    getTerrainGrid(grid, 0, forbiddenTerrainFlags, forbiddenMapFlags);
    if (!hallwaysAllowed) {
        getPassableArcGrid(grid, 2, 10, 0);
    }
    
    // Get the solution.
    randomLeastPositiveLocationInGrid(grid, retValX, retValY, deterministic);
    
//    dumpLevelToScreen();
//    displayGrid(grid);
//    if (coordinatesAreInMap(*retValX, *retValY)) {
//        hiliteCell(*retValX, *retValY, &yellow, 100, true);
//    }
//    temporaryMessage("Qualifying path selected:", true);
    
    freeGrid(grid);
    freeGrid(costMap);
    
    // Fall back to a pathing-agnostic alternative if there are no solutions.
    if (*retValX == -1 && *retValY == -1) {
        if (getQualifyingLocNear(loc, x, y, hallwaysAllowed, NULL,
                                 (blockingTerrainFlags | forbiddenTerrainFlags),
                                 (blockingMapFlags | forbiddenMapFlags),
                                 false, deterministic)) {
            *retValX = loc[0];
            *retValY = loc[1];
            return true; // Found a fallback solution.
        } else {
            return false; // No solutions.
        }
    } else {
        return true; // Found a primary solution.
    }
}
コード例 #23
0
void run()
{
    display *d = newDisplay();
    Button *buttons[NUM_BUTTONS];
    int i, j, stop = 0, leave = 1, which_alien, money = 0, which_screen = 0;
    char result, **compare, *input_instruction;
    int user_input, wins = 0;
    compare = createAndFillArraywiththeInstuctions(ALIENS, INSTRUCTION);
    input_instruction = (char*)calloc(1, ALIENS);
    errorForAllocation(input_instruction);
    buttons[0] = createButton(940, 580, 40, 70, "WORKS");//x,y,w,h
    buttons[1] = createButton(280, 430, 40, 70, "WORKS");
    Text grid;
    fillGrid(grid);
    Cursor *cursor = malloc(sizeof(Cursor));
    cursor->r = 0;  //------------------------------------
    cursor->c = 0;
    //---------------------------
    Money *moneyP = malloc(sizeof(Money));
    moneyP->moneyNum = 5;

    while (!stop  && wins < GAMES) {
        drawEnity(d, 0, 0, 0);
        result = getEvent(d, buttons);
        if (result == QUIT) {
            stop = 1;;
        }
        user_input = 0;

        printf("in main");
        fflush(stdout);
        i = POSITION1, j = POSITION2; //aline location 
        which_alien = rand() % 4 + 1;
        delayUntilNextAlien(1000);
        //Animation loop with logic
        while ((i > POSITION2 || j < POSITION1) && !stop) {
            drawFrame(d, buttons);
            result = getEvent(d, buttons);
            drawEnity(d, which_screen, 0, 0);
            drawGrid(d, grid, cursor->r, cursor->c);
            DrawMoney(moneyP, d);
            
            if (result == QUIT) {
                stop = 1;;
            }
            else if (result == ENTER) {
                // if (strcmp(&input_instruction[which_alien], compare[i]) == 0) {
                money += 100;
                leave = 1;
                wins++;
                // };
            }
            if (i > POSITION2 && result != QUIT) {
                drawEnity(d, which_alien, 300, i);
                i--;
                leave = 0;
            }
            if (leave == 0 && i == POSITION2 && result != QUIT) {
                drawEnity(d, which_alien, 300, POSITION2);
                result = getEvent(d, buttons);
                if (result == CLICK1) {
                    leave = 1;
                }
                else if (result == HINT) {
                    writeTextToSurface(d, "PLEASW WORK!!!", 255, 255, 255);
                    drawEnity(d, which_alien + ALIENS, 100, 200);
                }
            }
            if (isalpha(result)) {
                input_instruction[user_input] = result;
                if (user_input < ALIENS) {
                    user_input++;
                }
                else {
                    printf("You are trying to write something to long\n");
                }
            }
            else if (result == DEL) {
                if (user_input >= 0) {
                    user_input--;
                }
            }
            if (j < POSITION1 && leave == 1 && result != QUIT) {
                drawEnity(d, which_alien, 300, j);
                j++;
                result = getEvent(d, buttons);
            }
            if (result == QUIT) {
                stop = 1;;
            }
            else if ((result != NONE )&&( result!=CLICK1 )&&(result!=HINT)) { action(grid, cursor, result); }
        }
    }
    QuitGame(d);
}
コード例 #24
0
ファイル: Grid.c プロジェクト: AlexMooney/Brogue
// Loads up **grid with the results of a cellular automata simulation.
void createBlobOnGrid(short **grid,
                      short *retMinX, short *retMinY, short *retWidth, short *retHeight,
                      short roundCount,
                      short minBlobWidth, short minBlobHeight,
					  short maxBlobWidth, short maxBlobHeight, short percentSeeded,
					  char birthParameters[9], char survivalParameters[9]) {
    
	short i, j, k;
	short blobNumber, blobSize, topBlobNumber, topBlobSize;
    
    short topBlobMinX, topBlobMinY, topBlobMaxX, topBlobMaxY, blobWidth, blobHeight;
	//short buffer2[maxBlobWidth][maxBlobHeight]; // buffer[][] is already a global short array
	boolean foundACellThisLine;
	
	// Generate blobs until they satisfy the minBlobWidth and minBlobHeight restraints
	do {
		// Clear buffer.
        fillGrid(grid, 0);
		
		// Fill relevant portion with noise based on the percentSeeded argument.
		for(i=0; i<maxBlobWidth; i++) {
			for(j=0; j<maxBlobHeight; j++) {
				grid[i][j] = (rand_percent(percentSeeded) ? 1 : 0);
			}
		}
		
//        colorOverDungeon(&darkGray);
//        hiliteGrid(grid, &white, 100);
//        temporaryMessage("Random starting noise:", true);
		
		// Some iterations of cellular automata
		for (k=0; k<roundCount; k++) {
			cellularAutomataRound(grid, birthParameters, survivalParameters);
            
//            colorOverDungeon(&darkGray);
//            hiliteGrid(grid, &white, 100);
//            temporaryMessage("Cellular automata progress:", true);
		}
        
//        colorOverDungeon(&darkGray);
//        hiliteGrid(grid, &white, 100);
//        temporaryMessage("Cellular automata result:", true);
        
		// Now to measure the result. These are best-of variables; start them out at worst-case values.
		topBlobSize =   0;
		topBlobNumber = 0;
		topBlobMinX =   maxBlobWidth;
		topBlobMaxX =   0;
		topBlobMinY =   maxBlobHeight;
		topBlobMaxY =   0;
        
		// Fill each blob with its own number, starting with 2 (since 1 means floor), and keeping track of the biggest:
		blobNumber = 2;
		
		for(i=0; i<DCOLS; i++) {
			for(j=0; j<DROWS; j++) {
				if (grid[i][j] == 1) { // an unmarked blob
					// Mark all the cells and returns the total size:
					blobSize = fillContiguousRegion(grid, i, j, blobNumber);
					if (blobSize > topBlobSize) { // if this blob is a new record
						topBlobSize = blobSize;
						topBlobNumber = blobNumber;
					}
					blobNumber++;
				}
			}
		}
		
		// Figure out the top blob's height and width:
		// First find the max & min x:
		for(i=0; i<DCOLS; i++) {
			foundACellThisLine = false;
			for(j=0; j<DROWS; j++) {
				if (grid[i][j] == topBlobNumber) {
					foundACellThisLine = true;
					break;
				}
			}
			if (foundACellThisLine) {
				if (i < topBlobMinX) {
					topBlobMinX = i;
				}
				if (i > topBlobMaxX) {
					topBlobMaxX = i;
				}
			}
		}
		
		// Then the max & min y:
		for(j=0; j<DROWS; j++) {
			foundACellThisLine = false;
			for(i=0; i<DCOLS; i++) {
				if (grid[i][j] == topBlobNumber) {
					foundACellThisLine = true;
					break;
				}
			}
			if (foundACellThisLine) {
				if (j < topBlobMinY) {
					topBlobMinY = j;
				}
				if (j > topBlobMaxY) {
					topBlobMaxY = j;
				}
			}
		}
        
		blobWidth =		(topBlobMaxX - topBlobMinX) + 1;
		blobHeight =	(topBlobMaxY - topBlobMinY) + 1;
        
	} while (blobWidth < minBlobWidth
             || blobHeight < minBlobHeight
             || topBlobNumber == 0);
	
	// Replace the winning blob with 1's, and everything else with 0's:
    for(i=0; i<DCOLS; i++) {
        for(j=0; j<DROWS; j++) {
			if (grid[i][j] == topBlobNumber) {
				grid[i][j] = 1;
			} else {
				grid[i][j] = 0;
			}
		}
	}
    
    // Populate the returned variables.
    *retMinX = topBlobMinX;
    *retMinY = topBlobMinY;
    *retWidth = blobWidth;
    *retHeight = blobHeight;
}