Пример #1
0
int main(int argc, char *argv[])
{

    for (int i = 0; i < argc; ++i) {
        //std::cout << argv[i] << std::endl;
        
    }

	// create an object of game of life
	GameOfLife game;

	// initialize the game with some random lives
	game.init();

	// play the game for ever
	while(true){
		// display the current state of the game
		game.Display();

		// update the grid with some rule
		game.LiveOrDie();

    sleep(2);
	}

    return 0;

}
Пример #2
0
/**************************************************************************************************
 ** Function:       void runGame(GameOfLife game, int scol, int waitMS, int cycles)
 ** Description:    Runs the seed to cycles iterations, with waitMS wait time.
 *************************************************************************************************/
void runGame(GameOfLife game, int scol, int col, int waitMS, int cycles){
	int currentCycle = 1;
	
	std::string msg = "hit any key to return to main";
	mvprintw(2,(col - strlen(msg.c_str()))/2,"%s",msg.c_str());	//print header menu
	
	for (int loop=0;loop<cycles;loop++){	//run the # of cycles
		char ch;
		mvprintw(0,2,"%d of %d",currentCycle,cycles);
		currentCycle++;
		nodelay(stdscr,TRUE);
		if((ch=getch())==ERR){}
		else {
			nodelay(stdscr,FALSE);
			return;
		}
	
		std::vector<std::vector<char> > v = game.run();
		
		move(3,scol);		//top line of *
		for(int i = 0 ; i < game.getRows() + 2 ; i++){
			addch('*');
		}
		
		for (int i = 0 ; i < v.size() ; i++){	//print vector
			move(4+i,scol);
			addch('*');
			for (int j = 0 ; j < v[i].size() ; j++){
				addch(v[i][j]);
			}
			addstr("*\n");
		}
		
		move(4 + game.getColumns(),scol);		//bottom line of *
		for(int i = 0 ; i < game.getRows() + 2 ; i++){
			addch('*');
		}
		
		refresh();
		usleep(waitMS);
	}
	nodelay(stdscr,FALSE);
}
/* bir objedeki canli hucreleri digerine ekler */
void GameOfLife::addLiveCell(const GameOfLife & other)
{
	bool serachCheck = true;
	int temp;
	temp = livingCells.size(); 

	/* eklenen objedeki canli hucre sayisi kadar donen dongu */
	for (int i = 0; i < other.livingCells.size(); ++i)
	{
		/* eklenilen objedeki canli hucre sayisi kadar donen dongu */
		for (int k = 0; k < temp; ++k)
		{
			/* iki objeninde ayni koordinattaki hucrelerinin canli olup olmadigini kontrol eder. */
			if((livingCells[k].getX() == other.livingCells[i].getX()) && (livingCells[k].getY() == other.livingCells[i].getY()))
			{
				/* ayni koordinattaki hucrelerin ikiside canli ise false doner */
				serachCheck = false;
				break;
			}
		}

		if (serachCheck)
		{
			livingCells.push_back(other.livingCells[i]);
			numOfLiveCell++;
		}

		serachCheck = true;
	}

	if (row < other.getRow())
		row = other.getRow();

	if (column < other.getColumn())
		column = other.getColumn();
}
Пример #4
0
/**************************************************************************************************
 ** Function:       void printPresetsMenu(int mrow, int col)
 ** Description:    Builds the menu
 *************************************************************************************************/
bool runPresetMenu(GameOfLife game, std::string &fileName, int mrow, int col){
		int menuWidth = 4;
		
		std::vector<std::string> files = game.getSeedFileNames();
		int height = files.size() + 4;		//set height of menu
		
		for(int i= 0 ; i < files.size() ; i++){	//set width of menu
			std::string str = files[i];
			if(str.length() > menuWidth){ menuWidth = str.length(); }
		}
		
		menuWidth += 4;
		int menuStartColumn = (col - menuWidth)/2;
		
		std::string edge = "";
		for(int i = 0 ; i < menuWidth+5 ; i++){ edge += "*"; }
		
		mvprintw(mrow-1,menuStartColumn,"%s",edge.c_str());	//print top edge
		int i = 0;		
		for(i=0;i < files.size();i++) {			//print each item
			std::string str = files[i];
			mvprintw(mrow+i,menuStartColumn,"* [%c] %s",char(i+97),str.c_str());
			for (int j = 0 ; j < (menuWidth - 2 - str.length()) ; j++){
				addch(' ');
			}
			addch('*');
		}
		mvprintw(mrow+i,menuStartColumn,"* [z] back");
		for (int j = 0 ; j < (menuWidth - 6) ; j++){
			addch(' ');
		}		
		addch('*');
		mvprintw(mrow+i+1,menuStartColumn,"%s",edge.c_str());	//print top edge
		
		char mch;
		do{
			mch = getch();
			int imch = int(mch) - 97;
			if(mch == 'z'){ return false; }
			else if (imch < i && imch > -1){
 				fileName += files[imch];
				return true;
		 	}
		}while(mch != 'z');
}
Пример #5
0
int main(int argc, char ** argv) {
    if (argc < 4) {
        printf("Please input M, N and K\n");
        return 1;
    }
    int row = atoi(argv[1]);
    int col = atoi(argv[2]);
    int num_iterate = atoi(argv[3]);

    GameOfLife* game;
    if (row <= 0 || col <= 0) {
        game = new GameOfLife(6, 4);
        game->specificInit();
    }
    else {
        game = new GameOfLife(row, col);
        game->randomInit();
    }
    if (game->notTooLarge()) {
        game->print();
    }

    // start to record time consumption
    reset_and_start_timer();
    
    game->iterateAll(num_iterate);

   // stop timer and print out total cycles
    double one_round = get_elapsed_mcycles();
    if (game->notTooLarge()) {
        game->print();
    }
    printf("\n-------- Statistic Infomation --------\n\n");
    printf("time consumption:\t\t\t[%.3f] million cycles\n", one_round);

    delete(game);
    return 0;
}
Пример #6
0
int main(void) {
    
	FILE* programHandle;
	size_t programSize, kernelSourceSize;
	char *programBuffer, *kernelSource;
    
	// get size of kernel source
	programHandle = fopen("kernel.cl", "r");
	if (programHandle == NULL)
	{
		printf("Can't open kernel file!\n");
		return 1;
	}
	fseek(programHandle, 0, SEEK_END);
	programSize = ftell(programHandle);
	rewind(programHandle);
    
	// read kernel source into buffer
	programBuffer = (char*) malloc(programSize + 1);
	programBuffer[programSize] = '\0';
	fread(programBuffer, sizeof(char), programSize, programHandle);
	fclose(programHandle);
    
    // Create game of life board and initialize it
	GameOfLife *test = new GameOfLife(COLUMNS, ROWS);
    
	test->setItem(1, 1, 1);
	test->setItem(2, 1, 1);
	test->setItem(3, 1, 1);
    
	test->setItem(14, 0, 1);
	test->setItem(15, 1, 1);
	test->setItem(13, 2, 1);
	test->setItem(14, 2, 1);
	test->setItem(15, 2, 1);
    
	//test->print();
    
	printDevices();
    
	// Get platform and device information
	cl_platform_id * platforms = NULL;
	cl_uint num_platforms;
    
	//Set up the Platform
	cl_int clStatus = clGetPlatformIDs(0, NULL, &num_platforms);
    assert(clStatus == 0);
	platforms = (cl_platform_id *) malloc(sizeof(cl_platform_id)*num_platforms);
	clStatus = clGetPlatformIDs(num_platforms, platforms, NULL);
    assert(clStatus == 0);
    
	//Get the devices list and choose the device you want to run on
	cl_device_id *device_list = NULL;
	cl_uint num_devices;
	clStatus = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_GPU, 0, NULL, &num_devices);
	device_list = (cl_device_id *) malloc(sizeof(cl_device_id)*num_devices);
	clStatus = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_GPU, num_devices, device_list, NULL);
    assert(clStatus == 0);
    
	// Create one OpenCL context for each device in the platform
	cl_context context;
	context = clCreateContext(NULL, num_devices, device_list, NULL, NULL, &clStatus);
	assert(clStatus == 0);
    
	// Create a command queue
	cl_command_queue command_queue = clCreateCommandQueue(context, device_list[0], 0, &clStatus);
	assert(clStatus == 0);
    
	// Create memory buffers on the device for matrix and result
	cl_mem matrix = clCreateBuffer(context, CL_MEM_READ_ONLY, VECTOR_SIZE * sizeof(int), NULL, &clStatus);
	assert(clStatus == 0);
    
	cl_mem result = clCreateBuffer(context, CL_MEM_WRITE_ONLY, VECTOR_SIZE * sizeof(int), NULL, &clStatus);
	assert(clStatus == 0);
    
	// Copy the Buffer matrix to the device
	clStatus = clEnqueueWriteBuffer(command_queue, matrix, CL_TRUE, 0, VECTOR_SIZE * sizeof(int), test->getRow(0), 0, NULL, NULL);
	assert(clStatus == 0);
    
	// Create a program from the kernel source
	cl_program program = clCreateProgramWithSource(context, 1, (const char **) &programBuffer, &programSize, &clStatus);
	assert(clStatus == 0);
    
	// read kernel source back in from program to check
	clGetProgramInfo(program, CL_PROGRAM_SOURCE, 0, NULL, &kernelSourceSize);
	kernelSource = (char*) malloc(kernelSourceSize);
	clGetProgramInfo(program, CL_PROGRAM_SOURCE, kernelSourceSize, kernelSource, NULL);
    // Print the kernel source
	//printf("\nKernel source:\n\n%s\n", kernelSource);
	free(kernelSource);
    
	// Build the program
	clStatus = clBuildProgram(program, 1, device_list, NULL, NULL, NULL);
    
	//assert(clStatus==0);
	if (clStatus != CL_SUCCESS) {
		size_t logSize;
		cl_build_status status;
		char *programLog;
        
		// check build error and build status first
		clGetProgramBuildInfo(program, device_list[0], CL_PROGRAM_BUILD_STATUS, sizeof(cl_build_status), &status, NULL);
        
		// check build log
		clGetProgramBuildInfo(program, device_list[0],
                              CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);
		programLog = (char*) calloc(logSize + 1, sizeof(char));
		clGetProgramBuildInfo(program, device_list[0], CL_PROGRAM_BUILD_LOG, logSize + 1, programLog, NULL);
		printf("Build failed; error=%d, status=%d, programLog:\n\n%s\n", clStatus, status, programLog);
		free(programLog);
		return 1;
	}
    
	// Create the OpenCL kernel
	cl_kernel kernel = clCreateKernel(program, "gameOfLifeKernel", &clStatus);
    assert(clStatus == 0);
    
    int rows = ROWS;
    int columns = COLUMNS;

	// Set the arguments of the kernel
    clStatus = clSetKernelArg(kernel, 0, sizeof(int *), (void *) &rows);
	assert(clStatus == 0);
    clStatus = clSetKernelArg(kernel, 1, sizeof(int *), (void *) &columns);
	assert(clStatus == 0);
	clStatus = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *) &matrix);
	assert(clStatus == 0);
	clStatus = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void *) &result);
	assert(clStatus == 0);
    
	// Execute the OpenCL kernel on the list
	size_t global_size = VECTOR_SIZE; // Process the entire lists
	size_t local_size = 1; // Process one item at a time
    
    // ----- NORMAL STEP -----
    
    Timer::bit64 start, end;
    
	start = Timer::getTime();
	test->step();
	end = Timer::getTime();
    
	//test->print();
	std::cout << "Time elapsed normal step: " << end - start << std::endl;
    
	// -----------------------
    
    
	start = Timer::getTime();  // START -----
	clStatus = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL);
	assert(clStatus == 0);
    
	// Read the cl memory result on device to the host variable result
	clStatus = clEnqueueReadBuffer(command_queue, result, CL_TRUE, 0, VECTOR_SIZE * sizeof(int), test->getRow(0), 0, NULL, NULL);
	assert(clStatus == 0);
    
	// Clean up and wait for all the comands to complete.
	clStatus = clFlush(command_queue);
	assert(clStatus == 0);
	clStatus = clFinish(command_queue); // to make sure the kernel completed
	assert(clStatus == 0);
    
	end = Timer::getTime();  // END -----
    
	//test->print();
	std::cout << "Time elapsed with OpenCL: " << end - start << std::endl;
    
	// Finally release all OpenCL allocated objects and host buffers
	clStatus = clReleaseKernel(kernel);
	assert(clStatus == 0);
	clStatus = clReleaseProgram(program);
	assert(clStatus == 0);
	clStatus = clReleaseMemObject(matrix);
	assert(clStatus == 0);
	clStatus = clReleaseMemObject(result);
	assert(clStatus == 0);
	clStatus = clReleaseCommandQueue(command_queue);
	assert(clStatus == 0);
	clStatus = clReleaseContext(context);
	assert(clStatus == 0);
	free(platforms);
	free(device_list);
	delete test;
    

	std::cout << "Press Enter to continue...";
    std::cin.get();
	return 0;
    
}
Пример #7
0
/*******************************
 * Function: main
 * --------------
 * reads in arguments and runs generations of those boards according to said
 * arguments.
 */
int main(int argc, char* argv[]){
  GameOfLife *g;
  bool usingGameboard = false;
  bool printGameboard = false;
  string gameboard = "";
  int iterations = 100000;
  int threads = 2;
  int boardsize = 64;

  // Declare the supported options.
  po::options_description desc("Allowed options");
  desc.add_options()
      ("help,h", "produce help message")
      ("iterations,i", po::value<int>(), "set number of iterations (default: 100,002) ")
      ("threads,t", po::value<int>(), "set number of threads (default: 2)")
      ("boardsize,b", po::value<int>(), "set board dimensions to N, results in a NxN array (default: 64x64)")
      ("gameboard,g", po::value<string>(), "set the gameboard file (default: random board)")
      ("printboard,p", "print the game board? (default: false)")
  ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help")) {
      cout << desc << "\n";
      return 1;
  }

  if (vm.count("iterations")) {
    iterations = vm["iterations"].as<int>();
  }
  if (vm.count("threads")) {
    threads = vm["threads"].as<int>();
  }
  if (vm.count("boardsize")) {
    boardsize = vm["boardsize"].as<int>();
  }
  if (vm.count("gameboard")) {
    usingGameboard = true;
    gameboard = vm["gameboard"].as<string>();
  }
  if (vm.count("printboard")) {
    printGameboard = true;
  }

  if (usingGameboard) {
    g = new GameOfLife(gameboard);
  } else {
    g = new GameOfLife(boardsize);
  }

  if (printGameboard)
      g->printBoard();

  //while (true){
  struct timeval start_t, stop_t;
  double total_time;

  gettimeofday(&start_t, 0);  // start timer for measured portion of code

  cout << "Board Size is " << g->getRows() << " x " << g->getCols() << endl;
  cout << "Running " << iterations << " iterations with " << threads <<
    " thread" << (threads != 1 ? "s" : "") << "..." << endl;

  for (int i=0; i<iterations; i++){
    g->runGeneration();
  }

  gettimeofday(&stop_t, 0);  // stop timer for measured portion of code

  total_time = (stop_t.tv_sec + stop_t.tv_usec*0.000001)
    - (start_t.tv_sec + start_t.tv_usec*0.000001);

  // don't want to include printf in timed code
  if (printGameboard)
      g->printBoard();

  printf("total time is: %g\n", total_time);

  delete g;
  return 0;
}
Пример #8
0
void Screen::drawScreen(GameOfLife& game,int s,bool p){
    Surface *swt = surfaces;
    SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 237,191, 130 ) );
    SDL_Rect clip;
    clip.x = 0;
    clip.y = 0;
    clip.w = height;
    clip.h = width;
    SDL_FillRect( screen, &clip, SDL_MapRGB( screen->format, 255,255, 255 ) );


    int i = 0;
    SDL_Rect *vert =  getLine(1,0,0);
    SDL_Rect *hor =  getLine(0,0,0);
        int ax,ay;
    for (ax=0;ax<=(height/BG->w);ax++){
       for (ay=0;ay<=(width/BG->h);ay++)
        apply_surface(ax*BG->w,ay*BG->h,BG);
    }



    apply_surface(0,width,MBG);
    apply_surface(175,width+11,txtp);
    apply_surface(310,width+11,txts);
    apply_surface(410,width+11,txte);
    apply_surface(520,width+11,txtg);
    apply_surface(495,width+8,und);
    apply_surface(10,width+4,ln1);
    apply_surface(10,width+18,ln2);
    apply_surface(460,width+8,refresh);

    apply_surface(580,width+8,gen);
    if (!p)
        apply_surface(250,width+8,play);
    else
        apply_surface(250,width+8,pause);
    switch(s){
    case 1:
        apply_surface(350,width+8,f);
        break;
    case 2:
        apply_surface(350,width+8,ff);
        break;
    case 3:
        apply_surface(350,width+8,fff);
        break;

    }

    for(int i = 0; i < row; i++) {
        for(int j = 0; j < col; j++) {
            if (game.isCellAlive(j,i)){
                int cola[3] = {255,255,255};
                struct rule *r = game.rules;
                while (r){
                    if (game.getCell(j,i)->getType() == r->id){
                        cola[0] = r->color[0];
                        cola[1] = r->color[1];
                        cola[2] = r->color[2];
                        break;
                    }

                    r = r->next;
                }
                SDL_Rect square;
                square.x = ((double)j)*((double)height/(double)col) -.5 ;
                square.y = ((double)i)*((double)width/(double)row) -.5;
                square.h = ((double)width/(double)col) + 1;
                square.w = ((double)height/(double)row) + 1 ;
                SDL_FillRect( screen, &square,  SDL_MapRGB( screen->format, cola[0],cola[1], cola[2] ) );
                //apply_surface(,,game.getCell(j,i)->s);
            }
            //tela->setCell(i,j,);
        }
    }

    int x=0;
    for (x=0;x<=(col);x++){
        vert->x = ((double)height/(double)col)*(double)x;
        if (game.grid)
        SDL_FillRect( screen, vert, SDL_MapRGB( screen->format, 237,191, 130 ) );
        //apply_surface(,0,gv);
    }
    int y=0;
    for (y=0;y<=(row);y++){
        hor->y = ((double)width/(double)row)*(double)y;

        //
        if (game.grid)
        SDL_FillRect( screen, hor, SDL_MapRGB( screen->format, 237,191, 130 ) );
        //apply_surface(0,,gh);
    }
    vert->x = ((double)height/(double)col)*(double)col;
    vert->w = height;
    hor->y = ((double)width/(double)row)*((double)row);
    hor->h = width;
    //SDL_FillRect( screen, vert, SDL_MapRGB( screen->format,237,191, 130 ) );
    //SDL_FillRect( screen, hor, SDL_MapRGB( screen->format, 237,191, 130 ) );
    free(hor);
    free(vert);
    SDL_Flip( screen );

    SDL_Delay(10);
}