示例#1
0
int main(int argc, const char * argv[])
{
    char* input = (char*)malloc(sizeof(char) * 10);
    char** gameboard = newboard();
    int gameplayer = 1;
    
    if (argc == 2) {
        if (load(gameboard, argv[1], &gameplayer))
            printf("Hra byla uspesne nactena.\n");
    }
    
    if (colors == 0) {
        printf("Chcete zapnout barvy? (jen pro Unix)\n> ");
        scanf("%s", input);
        if (strcmp(input, "ano") == 0)
            colors = 1;
    }
    
    while (1) {
        printboard(gameboard);
        
        printf("Na rade je hrac %i (%s)\n", gameplayer, (gameplayer - 1) ? "kolecka" : "krizky");
        printf("> ");
        scanf("%s", input);
        
        if (strcmp(input, "konec") == 0) {
            printf("Konec hry.\n");
            break;
        }
        else if (strcmp(input, "uloz") == 0) {
            if (save(gameboard, "piskvorky.txt", gameplayer)) {
                printf("Hra byla uspesne ulozena. Konec hry.\n");
                break;
            }
        }
        else if (strcmp(input, "novy") == 0) {
            gameboard = newboard();
            gameplayer = 1;
            printf("\nVitej v nove hre.\n");
        }
        else if (strcmp(input, "?") == 0)
            printf("Napoveda:\n \"a1\" az \"c3\" pro zadavani souradnic\n \"novy\" pro novou hru\n \"konec\" pro ukonceni hry\n \"uloz\" pro ulozeni hry\n");
        else
            if (turn(gameboard, input, gameplayer)) {
                if (win(gameboard, gameplayer)) {
                    printboard(gameboard);
                    printf("Vyhral hrac %i (%s). Konec hry.\n", gameplayer, (gameplayer - 1) ? "kolecka" : "krizky");
                    break;
                }
                else if (full(gameboard)) {
                    printf("Remiza, vsechny policka jsou zaplneny. Konec hry.\n");
                    break;
                }
                gameplayer = (gameplayer == 1) ? 2 : 1;
            }
    }
    return 0;
}
示例#2
0
void printall(int turn)
{
	clear();
	printboard(turn);
	printlog();
	
}
示例#3
0
int main() {

    char board[3][3];
    int i,j, result;
    int turn = 0; // Set the current turn to player X

    init(board);
  
    // Play until the game is over.
    while (status(board) == UNFINISHED) {

        // Execute a turn and change who's move it is.
        domove(board, getplayer(turn));
        turn = (turn+1)%2;
    }

    result = status(board);
  
    printf("\nHere is the final board:\n");
    printboard(board);

    // Output the appropriate message for each possible outcome.
    if (result == WINX)
        printf("Congrats team X, you won!\n");
    else if (result == WINO)
        printf("Congrats team O, you won!\n");
    else
        printf("Good job to both teams, the outcome is a tie!\n");

  system("PAUSE");
  return 0;
}
示例#4
0
int main(int argc, char** argv)
{
    char inbuf[256];
    char playerstring[1];
    int X,Y;

    turn = 0;
    fgets(inbuf, 256, stdin);
    if (sscanf(inbuf, "game %1s %d %d %d", playerstring, &depthlimit,
                &timelimit1, &timelimit2) != 4) error("Bad initial input");
    if (timelimit2 != 0) timelimit1 = timelimit2 / 64;
    if (timelimit1 == 0 && depthlimit == 0) depthlimit = 4;

    if (playerstring[0] == 'B') me = 1; else me = -1;
    NewGame();
    if (me == 1) MakeMove();
    while (fgets(inbuf, 256, stdin)!=NULL){
        if (strncmp(inbuf,"pass",4)!=0) {
            if (sscanf(inbuf, "%d %d", &X, &Y) != 2) return 0;
            Update(gamestate, -me, X, Y);
            if (debug) printboard(gamestate, -me, ++turn, X, Y);
        }
        MakeMove();
    }
    return 0;
}
示例#5
0
void cmd_load(char *s)
{
    FILE *in;
    move m;
    char *filename;

    filename = (s[1] == 0) ? "bce.saved" : ++s;

    in = fopen(filename, "r");

    if (!in)
    {
	printf("error opening saved game: %s\n", filename);
	return;
    }

    initialize();

    computer[0] = 0;
    computer[1] = 0;
    
    while(!feof(in))
    {
	fscanf(in, "%u", &m);
	if (feof(in)) break;
	domove(m);
/*  	printf("Move: %s\n", movestring(m)); */
    }
    
    printf("- Board Loaded -\n");
    printboard();
    countmaterial();
    
    fclose(in);
}
示例#6
0
boool gameinit()
{
	int c;
	int i;
	char hashi[17];
	randinsertboard();
	randinsertboard();
	printboard();
	while((c=getch())!=27)
	{
		strcpy(hashi,hashgen());
		switch(c)
		{
			case UP_KEY:
				for(i=0;i<4;++i)
					bunchcall(&board[0][i],&board[1][i],&board[2][i],&board[3][i]);
				break;
			case DOWN_KEY:
				for(i=0;i<4;++i)
					bunchcall(&board[3][i],&board[2][i],&board[1][i],&board[0][i]);
				break;
			case LEFT_KEY:
				for(i=0;i<4;++i)
					bunchcall(&board[i][0],&board[i][1],&board[i][2],&board[i][3]);
				break;
			case RIGHT_KEY:
				for(i=0;i<4;++i)
					bunchcall(&board[i][3],&board[i][2],&board[i][1],&board[i][0]);
				break;		
		}
		if (strcmp(hashi,hashgen())!=0)
			randinsertboard();
		printboard();
		switch(boardcheck())
		{
			case 1:
				return 1;
				break;/*not required*/
			case -1:
				return 0;
				break;/*not required*/
			case 0:
				continue;
				break;/*not required*/
		}
	}
}
int main() {
  
    int gameover = 0; // used to check if the game is over or not
  
    char uncovered_board[SIDE][SIDE]; // board that stores the location of all
                                      // the bombs and numbers of adjacent bombs.

    char current_board[SIDE][SIDE]; // stores the current board as it should be
                                    // printed out.

    int totalmoves; // stores the total moves left for the user before they win.

    int i,j;
    int x,y;

    int listbombs[NUMBOMBS][2]; // stores (x,y) coordinates of all bombs.
  
    srand(time(0)); // Seed the random number generator.

    // Initialize the current board.
    for (i=0;i<SIDE;i++) {
        for (j=0;j<SIDE;j++) {
            current_board[i][j] = '_';
            uncovered_board[i][j] = '_';
        }
    }

    // Randomly choose where the bombs will go.
    getbombs(listbombs);
  
    // Place the bombs onto the board.
    for (i=0;i<NUMBOMBS;i++) 
        uncovered_board[listbombs[i][0]][listbombs[i][1]]='*';
  
    totalmoves = SIDE*SIDE - NUMBOMBS;

    // Continue playing until the game ends.
    while (!gameover) {
        
        // Get a move from the user.
        printf("Here is the board : \n");
        printboard(current_board);
        getmove(&x,&y);
        printf("at 7 1 when get move is %c\n", current_board[7][1]);
    
        // Execute that move.
        gameover = domove(current_board,uncovered_board,listbombs,x,y,&totalmoves);

        // Check if they have won.
        if ((!gameover) && (totalmoves==0)) {
            printf("Great! You win!!!\n");
            gameover = 1;
        }
    }
  
    system("PAUSE");
    return 0;
  
}
示例#8
0
void cmd_debug(char *s)
{
    freopen("debug.bce", "w+", stdout);
    printboard();
    cmd_inspect(NULL);
    cmd_set(NULL);
    exit(EXIT_FAILURE);
}
void printpuzzle(board *b)
{
  int i;
  for(i=0;i<4;i++)
  {
   switch((i+1))
   {
    case 1:
      if(b->c1!=NULL && b->c1->to_goal==1)
      {
    printboard(b->c1);
    getch();
    printpuzzle(b->c1);
      }
      break;
    case 2:
      if(b->c2!=NULL && b->c2->to_goal==1)
      {
    printboard(b->c2);
    getch();
    printpuzzle(b->c2);
      }
      break;
    case 3:
      if(b->c3!=NULL && b->c3->to_goal==1)
      {
    printboard(b->c3);
    getch();
    printpuzzle(b->c3);
      }
      break;
    case 4:
      if(b->c4!=NULL && b->c4->to_goal==1)
      {
    printboard(b->c4);
    getch();
    printpuzzle(b->c4);
      }
      break;
     default:
       return;
   }
  }
}
示例#10
0
// Pre-conditions: Both character arrays are squre 2D arrays with each
//                 dimension of size SIZE, the first dimension of the 
//                 list of bombs array should be of size NUMBOMBS,
//                 row and column must represent the row and column of
//                 the player's move, and totalmoves must equal how many
//                 more squares the user must uncover before winning.
// Post-conditions: The procedure will execute a single move in the game
//                  and make the necessary changes to the auxiliary
//                  data structures to ensure the game runs properly following
//                  the move.
int domove(char board[][SIDE], char realboard[][SIDE],
            int listbombs[][2], int row, int column, int *totalmoves) {


    int i, j, num;
  
    // Take care of the case that the user loses.
    if (realboard[row][column]=='*') {
    
        board[row][column]='*';
        for (i=0;i<NUMBOMBS;i++) 
            board[listbombs[i][0]][listbombs[i][1]]='*';
    
        printboard(board);
        printf("Sorry, you lose!\n");
        return 1;
    }
    
    // Take care of the case that the user chooses a square already chosen.
    else if (board[row][column]!='_') {
    
        printf("That square as already been cleared, try again!\n");
        return 0;
    }
  
    // Execute a normal non-losing move.
    else {
 
        // Calculate the number of adjacent bombs, and place this number on
        // the regular board.
        num = numberbombs(row, column, listbombs);
        (*totalmoves)--;
        
        // Cast is to make sure we store a character in the array.
        board[row][column]=(char)(num+'0');

        // If there are no adjacent bombs, we can recursively clear.
        if (num == 0) {
                
            // Loop through all adjacent indexes to the current square.    
            for (i=-1;i<2;i++) {
	            for (j=-1;j<2;j++) {
	  
	                // We only want to clear this new square IF it hasn't
	                // previously been cleared, so check that first.
	                if (valid(row+i,column+j) && (board[row+i][column+j]=='_'))
	                    domove(board, realboard, listbombs, row+i, column+j, totalmoves);
	            }
            }
	      
        } // end-if num==0

        return 0;
        
    } // end else
}
示例#11
0
void knighttour(int x,int y,int movecount) {
    if(movecount>pow(n,2)) {
        printboard(board);
    }
    else {
        getnextmove(&x,&y);
        board[x][y]=movecount;
        movecount++;
        knighttour(x,y,movecount);
    }
}
示例#12
0
文件: tic-tac-toe.c 项目: NathiyaM/C
//main function
int main()
{
	/* variable declaration */
	char done=' ';
	printf("WELCOME TO TIC-TAC-TOE GAME\n");
	printf("PLAYER1 plays against another PLAYER2\n");
	/*calling function for intializing the board with empty cells*/
	initboard();
	do
	{
		//print the board
		printboard();
		player1_move();//call player1 move function to place the cell for player1
		done=check();//check whether the player1 wins or not,if it wins,exit from the loop
		if(done!=' ')
			break;
		printboard();
		/* check whether the board is full or not continue to the move for player2 and check whether the 
		player 2 wins after their move and check whether the board is full or not*/
		done=isBoardFull();
		if(done!=' ')
			break;
		player2_move();
		done=check();
		if(done!=' ')
			break;
		done=isBoardFull();
		if(done!=' ')
			break;
	}while(done==' ');
	/*check for return statement from the loop,to declare the win*/
	if(done=='X')
		{printf("Congrats, Player1 Wins\n");
		printboard();}
	else if(done=='0')
		{printf("Congrats, Player2  Wins\n");
		printboard();}
	else
		printf("Match Draw\n");
return 0;
}
void getpath(board *init,board *b)
{
  int i=0;
  int c=b->path[i++];
  board *p=init;

  while(c!=-1)
  {

     switch(c)
     {
      case 1:
         printboard(p->c1);
         getch();
         p=p->c1;
         break;
      case 2:
         printboard(p->c2);
         getch();
         p=p->c2;
         break;
      case 3:
         printboard(p->c3);
         getch();
         p=p->c3;
         break;
      case 4:
         printboard(p->c4);
         getch();
         p=p->c4;
         break;
      default:
         printf("\nERROR DE CAMINO.");
     }

    c=b->path[i++];
      }
}
示例#14
0
/* without ai for now */
int main (int argc , char **argv)
{
    char board[3][3] , c ;
    int x , i ; 
    fillboard(board);
    printf("Simple Tic Tac Toe game WITHOUT AI\n");
    for(i = 1 ; i <= 9 ; i++)
    {
        printboard(board);
        printf("enter the number :");
        scanf("%d" , &x);    
    } 

}
示例#15
0
void MakeMove(void)
{
    int X,Y, bestX, bestY, d, nosol;

    if (timelimit1 == 0){
        if (debug) fprintf(stderr, "alphabeta depthlimit = %d\n", depthlimit);
        (void) AlphaBeta(gamestate, depthlimit, -10000000, 10000000, me, &X,
                &Y);
        if (debug) fprintf(stderr, "returned X = %d  Y = %d\n", X, Y);
    }
    else {
        currenttime = clock();						//get current time
        deadline = currenttime + timelimit1 * (CLOCKS_PER_SEC / 1000);
        //calculate by when we need to make a move
        d = 1;

        if (debug)
            fprintf(stderr, "timelimit1 = %d  currenttime = %lu deadline = %lu\n", timelimit1, currenttime, deadline);

        nosol = TRUE;
        while (currenttime < deadline){
            d = d + 1;
            if (debug) fprintf(stderr, "interation depth = %d\n", d);
            (void) AlphaBeta(gamestate, d, -10000000, 10000000, me, &bestX,
                    &bestY);
            if (currenttime < deadline)
            {
                //storing the best possible move in the time given
                X = bestX;
                Y = bestY;
                nosol = FALSE;
                if (debug) fprintf(stderr, "saving move (%d , %d)\n", X, Y);
            }
        }
        if (nosol) error("timelimit too small to find a move\n");
        if (debug) fprintf(stderr, "end of iteration at currentime = %lu\n",
                currenttime);
    }

    if (X>=0) {
        Update(gamestate, me, X, Y);
        printf("%d %d\n", X, Y);
        fflush(stdout);
    } else {
        printf("pass\n");
        fflush(stdout);
    }
    if (debug) printboard(gamestate, me, ++turn, X, Y);
}
示例#16
0
void showmoves(c)
{
    move_and_score *restore_sp = move_sp;
    
    genmoves(c);
    
    while (move_sp>restore_sp)
    {
	move m;
	m = popmove();
	domove(m);
	printboard();
	undomove();
    }
}
示例#17
0
void Update(board state, int player, int X, int Y)
{
    int i,j;

    if (X<0) return; /* pass move */
    if (state[X][Y] != 0) {
        printboard(state, player, turn, X, Y);
        error("Illegal move");
    }
    state[X][Y] = player;
    for (i=-1; i<=1; i++)
        for (j=-1; j<=1; j++)
            if ((i!=0 || j!=0) && CanFlip(state, player, X, Y, i, j))
                DoFlip(state, player, X, Y, i, j);
}
示例#18
0
void addlog(char *str, int who, int turn)	// who -> 1 : you, 2: opp, 3: system
{
	rear=_add(rear);
	if(who==1)
		strcpy(logq[rear], "<YOU>    : ");
	else if(who == 2)
		strcpy(logq[rear], "<OPP>    : ");
	else
		strcpy(logq[rear], "<System> : ");
	strcat(logq[rear],str);
	if(rear==front)
		front=_add(front);
	printboard(turn);
	printlog();
}
示例#19
0
//计算可行组合数
void cq(int i)
{
	for(int j=1; j <= N; j++)
		if(bSafe(i, j))
		{
			flag[i]=j;
			if (i < N)
				cq(1+i);
			else
			{	
				count++;
				printboard();
				break;
			}
		}
}
示例#20
0
// Executes a move for the player specified by the second parameter and
// reflects those changes on the board.
void domove(char board[][3], char player) {

    int done = 0;
    int r, c, temp;

    // Continue until a move has been executed.
    while (!done) {

        // Human player is X.
        if (player == 'X') {
                   
            // Prompt for and read in the player's move.
            printf("\nHere is the current board:\n");
            printboard(board);   
            printf("\nEnter your move, player %c.\n", player);
            printf("Enter the row(0-2) followed by a space and the col(0-2).\n");
            scanf("%d%d", &r, &c);
        }
    
        // Computer Player is O
        else {
        
            // Get the computer's move, split into row&col and print it.     
            temp = compmove(board, player);
            r = temp/3;
            c = temp%3;   
            printf("\nThe computer has chosen to take square %d, %d.\n", r, c);
        }
    
        // Check for invalid indexes.
        if (r<0 || r>2 || c<0 || c>2)
            printf("Sorry, that is not a valid square.\n");

        // Check for a taken square.
        else if (board[r][c] != '_')
            printf("Sorry, that square has been taken already.\n");

        // Execute the move.
        else {
      
            board[r][c] = player;
            done=1;
        }
        
    } // end while loop
}
示例#21
0
文件: archess.c 项目: arpruss/ozdev
int main(void)
{
static unsigned x;

initprg();
initgame();

clrscr();
printf("Alpha test AR-Chess V 1.0\n"
"Copyright November 30, 1992\n"
"\nMr. Carey Bloodworth\n"
"\nThis program may be freely\n"
"copied and modified as long\n"
"as my name is present as the\n"
"original author.\n"
"Sharp 7xx port: A.R. Pruss");
ozdelay64hz(200);
/* ozsendscreen(); */

while (! quit)
  {
   if ( /* (breakpress) || */ (draw) || (mate) ||
        ((tomove==human) && (!bothsides)) ) inputcommand();
   printboard();
/*   if (pvsflag)
   {
    currow=7;
    atright();
    printf(pvsmsg);
   } */
   if (status[0])
   {
    currow=8;
    atright();
    printf(status);
   }
   currow=6;
   atright();
   printf(msg);
   if (! (quit || mate || draw)) selectmove(tomove);
   /* if (! breakpress) */ tomove=chngcolor(tomove);
   };

endprg();
return 0;
}
示例#22
0
int main(int argc, char **argv){
	int c;
	int index;

	for(index = 0; ((c = getchar()) != EOF) && index < 81; index++){
		if(isdigit(c)){
			c -= '0';
			if(c){
				if(!place(index,c)){
#if CGI
					printf("%d\n",index);
#else
					printf("Invalid input board: cell %d\n",index);
#endif
					return 2;
				}
			}
		} else if(c == '\n' || c == '\r'){
#if CGI
			puts("-1 Inadequate input!");
			return 4;
#endif
			index--;
			// never mind!
		} else if(isspace(c) || c == '?' || c == '.' || c == '_') {
			; // blank-space handling
		} else {
#if CGI
			printf("%d",index);
#else
			printf("Problem with input character '%c' in cell %d\n",c,index);
#endif
			return 3;
		}
	}
	if(try()){
		printboard(board);
	} else {
		puts("No success.");
		return 1;
	}
	return 0;
}
示例#23
0
int main(){
#ifdef LOCAL
	freopen("input.in", "r", stdin);
	freopen("output.out", "w", stdout);
#endif

	int gamenum;
	scanf("%d", &gamenum);
	while(gamenum--){
		int position;
		memset(board, 0, sizeof(board));
		for(int i = 1; i < 9; i++){
			for(int j = 1; j < 9; j++){
				board[i][j] = gotchar();
			}
		}
		// printboard();
		player = gotchar();

		enemy = (player == 'B')? 'W':'B';
		while(1){
			inst = gotchar();
			if(inst == 'L'){
				list();
			} else if (inst == 'M'){
				scanf("%d", &position);
				move_x = position/10;
				move_y = position%10;
				move();
			} else {
				printboard();
				break;
			}
		}
		if(gamenum){
			printf("\n");
		}
	}
	return 0;
}
示例#24
0
void printboard_and_time()
{
    int full, part;
    
    printboard();
    
    printf("W %s\t", formattime(chessclock[WHITE]));
    printf("B %s\n", formattime(chessclock[BLACK]));

    full = fullincheckp(tomove());
    part = ply ? incheckp(tomove()) : 0;
    
    if (full)
	printf("In Check : %d\n", full);

    if ((part &&  !full)||(full && !part))
    {
	printf("partial checktest (%d) and full checktest (%d) do no agree\n",
	       part, full);
    }
    
    printf("%c To Move\n", (tomove()==WHITE) ? 'W' : 'B');
}
示例#25
0
文件: ttt.c 项目: cyphar/tic-tac-toe
int main(int argc, char *argv[]) {
	/* Seed randomness. */
	srand(time(NULL) ^ getpid());

	bake_args(argc, argv);
	initgame();

	do {
		if(thegame.players == 1)
			whatside();
		else
			player = X;

		thegame.restart = false;
		cleargame();

		while(thegame.running) {
			if(thegame.players == 0) {
				printboard(false);
				compmove(player);

				if(checkwinner())
					break;

				compmove(-player);
			}

			else if(thegame.players == 1) {
				if(player == X){
					printboard(true);
					makemove(player);

					if(checkwinner())
						break;

					compmove(-player);
				}

				else {
					compmove(-player);

					if(checkwinner())
						break;

					printboard(true);
					makemove(player);
				}
			}

			else {
				printboard(true);

				makemove(player);
				player = -player;

			}

			checkwinner();
		}
		printwinner();
		restart();
	} while(thegame.restart);

	/* we so funny */
	if(thegame.players == 0)
		wargames();

	return 0;
}
int main()
{
  initscr();
  board *init,*goal;
  int i,j,t[valor],k;
  init=getboard();
  puts("\t\t\t*****JUEGO DEL 8-PUZZLE (PROFUNDIDAD)*****\n");
  printf("\n*INGRESA TU ESTADO INICIAL: \n\n");

  for(i=0;i<valor;i++)
   scanf("%d",&init->s[i]);

  int cnt=0;
  for(i=0;i<valor;i++)
  {
    int lcnt=0;
    for(j=i+1;j<valor;j++)
    {
     if(init->s[j]<init->s[i] && init->s[j]!=0)
       lcnt++;
    }
    cnt=cnt+lcnt;
  }
  goal=getboard();
  printf("\nMOVIMIENTOS:%d\n",cnt);
  if((cnt%2)==0)
  {
  	for(k=0;k<valor;k++)
  	{
  		goal->s[k]=k;
  	}
  }
  else
  {
  	for(k=0;k<valor;k++)
  	{
  		goal->s[k]=k;
  	}
  }
  printf("\n-TU ESTADO FINAL ES:\n\n");
  printboard(goal);
  printf("\n-TU ESTADO INICIAL ES:\n\n");
  printboard(init);
  printf("\nPRESIONA UNA TECLA HACIA EL ESTADO FINAL\n");
  getch();
  is_on_path(goal,init);
  init->to_goal=1;
  enq(init);
  spantree(init);
  flag=solve_by_bfs(init,init,goal);
  if(flag==1)
  {
  getpath(init,found);
  getch();
  printf("\nTU ESTADO FINAL ES INOPERABLE");
  getch();
  }
  else
  {
   printf("\nPROBLEMA COMPLEJO, PODRIA HBAER DESBORDAMIENTO DE MEMORIA");
   getch();
  }
  endwin();
  return 0;
}
示例#27
0
int main(int argc, char **argv, char **envp)
{
	struct pollfd fdset[7];
	int nfds = 7;
	int gpio_fd1, gpio_fd2, gpio_fd3, gpio_fd4,gpio_fd5,gpio_fd6, timeout, rc;
	char buf[MAX_BUF];
	unsigned int gpio;
	int len;
	char board[HEIGHT][WIDTH];
	int xpos=WIDTH/2;
	int ypos=HEIGHT/2;
        int row;
	int col;
	int colorint=0;
	char color[]={'x','y','z'};	
	for(row=0;row<HEIGHT;row++){
		printf("\n");
		for(col=0;col<WIDTH;col++){
			board[row][col]=' ';
		}
	}

	int res, i2cbus, address, file;
	char filename[20];
	int force = 0;

	i2cbus = lookup_i2c_bus("1");
	printf("i2cbus = %d\n", i2cbus);
	if (i2cbus < 0)
		help();

	address = parse_i2c_address("0x70");
	printf("address = 0x%2x\n", address);
	if (address < 0)
		help();

	file = open_i2c_dev(i2cbus, filename, sizeof(filename), 0);
//	printf("file = %d\n", file);
	if (file < 0
	 || check_funcs(file)
	 || set_slave_addr(file, address, force))
		exit(1);

	// Check the return value on these if there is trouble
	i2c_smbus_write_byte(file, 0x21); // Start oscillator (p10)
	i2c_smbus_write_byte(file, 0x81); // Disp on, blink off (p11)
	i2c_smbus_write_byte(file, 0xe7); // Full brightness (page 15)

//	Display a series of pictures
	

	system("/home/root/homework3/i2csetup.sh");
	board[xpos][ypos]='x';
	printboard(board,file,colorint);
	//printf("wgat");
	/*if (argc < 2) {
		printf("Usage: gpio-int <gpio-pin>\n\n");
		printf("Waits for a change in the GPIO pin voltage level or input on stdin\n");


		FILE* f = fopen("/sys/class/leds/beaglebone\:green\:usr0/brightness", "w");
                FILE* trig = fopen("/sys/class/leds/beaglebone\:green\:usr0/trigger", "w");
 
    		if (trig == NULL){
			printf("oops\n");        			
			exit(EXIT_FAILURE);
		}
    		fprintf(trig, "none");
    		fclose(trig);
		if (fled== NULL){
			printf("oops\n");        			
			exit(EXIT_FAILURE);
		}
		printf("should light up\n");
    		fprintf(fled, "1");
    		fclose(fled);
		usleep(10000000);
		exit(-1);
	}
		*/
	// Set the signal callback for Ctrl-C
	signal(SIGINT, signal_handler);


	gpio_export(GPIOIN1);
	gpio_set_dir(GPIOIN1, "in");
	gpio_set_edge(GPIOIN1, "both");  // Can be rising, falling or both
	gpio_fd1 = gpio_fd_open(GPIOIN1, O_RDONLY);

	gpio_export(GPIOIN2);
	gpio_set_dir(GPIOIN2, "in");
	gpio_set_edge(GPIOIN2, "both");  // Can be rising, falling or both
	gpio_fd2 = gpio_fd_open(GPIOIN2, O_RDONLY);
	gpio_export(GPIOIN3);
	gpio_set_dir(GPIOIN3, "in");
	gpio_set_edge(GPIOIN3, "both");  // Can be rising, falling or both
	gpio_fd3 = gpio_fd_open(GPIOIN3, O_RDONLY);

	gpio_export(GPIOIN4);
	gpio_set_dir(GPIOIN4, "in");
	gpio_set_edge(GPIOIN4, "both");  // Can be rising, falling or both
	gpio_fd4 = gpio_fd_open(GPIOIN4, O_RDONLY);

	gpio_export(GPIOIN5);
	gpio_set_dir(GPIOIN5, "in");
	gpio_set_edge(GPIOIN5, "both");  // Can be rising, falling or both
	gpio_fd5 = gpio_fd_open(GPIOIN5, O_RDONLY);

	gpio_export(GPIOIN6);
	gpio_set_dir(GPIOIN6, "in");
	gpio_set_edge(GPIOIN6, "both");  // Can be rising, falling or both
	gpio_fd6 = gpio_fd_open(GPIOIN6, O_RDONLY);

	timeout = POLL_TIMEOUT;
 	FILE* f0 = fopen("/sys/class/leds/beaglebone:green:usr0/trigger", "w");
	FILE* f1 = fopen("/sys/class/leds/beaglebone:green:usr1/trigger", "w");
	FILE* f2 = fopen("/sys/class/leds/beaglebone:green:usr2/trigger", "w");
	FILE* f3 = fopen("/sys/class/leds/beaglebone:green:usr3/trigger", "w");

    	if (f0 == NULL){
		exit(EXIT_FAILURE);
	}
	fprintf(f0, "none");
	fclose(f0);

	if (f1 == NULL){
		exit(EXIT_FAILURE);
	}
	fprintf(f1, "none");
	fclose(f1);

	if (f2 == NULL){
		exit(EXIT_FAILURE);
	}
	fprintf(f2, "none");
	fclose(f2);
	
	if (f3 == NULL){
		exit(EXIT_FAILURE);
	}
	fprintf(f3, "none");
	fclose(f3);
	
			
	while (keepgoing) {
		memset((void*)fdset, 0, sizeof(fdset));
		
		fdset[0].fd = STDIN_FILENO;
		fdset[0].events = POLLIN;
      
		fdset[1].fd = gpio_fd1;
		fdset[1].events = POLLPRI;

		fdset[2].fd = gpio_fd2;
		fdset[2].events = POLLPRI;

		fdset[3].fd = gpio_fd3;
		fdset[3].events = POLLPRI;

		fdset[4].fd = gpio_fd4;
		fdset[4].events = POLLPRI;

		fdset[5].fd = gpio_fd5;
		fdset[5].events = POLLPRI;

		fdset[6].fd = gpio_fd6;
		fdset[6].events = POLLPRI;


		rc = poll(fdset, nfds, timeout);      

		if (rc < 0) {
			printf("\npoll() failed!\n");
			return -1;
		}
      
		
            
		if (fdset[1].revents & POLLPRI) {
			lseek(fdset[1].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[1].fd, buf, MAX_BUF);
			FILE* f = fopen("/sys/class/leds/beaglebone:green:usr3/brightness", "w");
 
    			if (f == NULL){        			
				exit(EXIT_FAILURE);
			}
			if (buf[0]=='1'){
				fprintf(f, "0");
			}
			if (buf[0]=='0'){
				fprintf(f, "1");
				if((xpos+1)<WIDTH){
					board[xpos+1][ypos]='x';
					xpos++;
				}
				printboard(board,file,colorint);
			}
			fclose(f);
				
		}
		if (fdset[2].revents & POLLPRI) {
			lseek(fdset[2].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[2].fd, buf, MAX_BUF);
			FILE* f = fopen("/sys/class/leds/beaglebone:green:usr2/brightness", "w");
 
    			if (f == NULL){        			
				exit(EXIT_FAILURE);
			}
			if (buf[0]=='1'){
				fprintf(f, "0");
			}
			if (buf[0]=='0'){
				fprintf(f, "1");
				if((xpos-1)>=0){
					board[xpos-1][ypos]='x';
					xpos--;
				}
				
				printboard(board,file,colorint);

			}
			fclose(f);
				
		}
		if (fdset[3].revents & POLLPRI) {
			lseek(fdset[3].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[3].fd, buf, MAX_BUF);
			FILE* f = fopen("/sys/class/leds/beaglebone:green:usr1/brightness", "w");
 
    			if (f == NULL){        			
				exit(EXIT_FAILURE);
			}
			if (buf[0]=='1'){
				fprintf(f, "0");
			}
			if (buf[0]=='0'){
				if((ypos+1)<HEIGHT){
					board[xpos][ypos+1]='x';
					ypos++;
				}
				printboard(board,file,colorint);
				fprintf(f, "1");
			}
			fclose(f);
				
		}
		if (fdset[4].revents & POLLPRI) {
			lseek(fdset[4].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[4].fd, buf, MAX_BUF);
			FILE* f = fopen("/sys/class/leds/beaglebone:green:usr0/brightness", "w");
 
    			if (f == NULL){        			
				exit(EXIT_FAILURE);
			}
			if (buf[0]=='1'){
				fprintf(f, "0");
			}
			if (buf[0]=='0'){
				if((ypos-1)>=0){
					board[xpos][ypos-1]='x';
					ypos--;
				}
				printboard(board,file,colorint);
				fprintf(f, "1");

			}
			fclose(f);
				
		}
		if (fdset[5].revents & POLLPRI) {
			lseek(fdset[5].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[5].fd, buf, MAX_BUF);
			
			if (buf[0]=='0'){
				for(row=0;row<HEIGHT;row++){
				printf("\n");
					for(col=0;col<WIDTH;col++){
						board[row][col]=' ';
					}
					printf("\n");
					system("i2cget -y 1 0x48 0");
					printboard(board,file,colorint);
				}
				
				

			}
			
				
		}
		if (fdset[6].revents & POLLPRI) {
			lseek(fdset[6].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[6].fd, buf, MAX_BUF);
			
			if (buf[0]=='0'){
				if(colorint<=0){
					colorint++;
				}else{
					colorint=0;
				}
				printf("\n");
				system("i2cget -y 1 0x4a 0");
				printboard(board,file,colorint);

			}
			
			
			
				
		}
		/*if (fdset[0].revents & POLLIN) {
			(void)read(fdset[0].fd, buf, 1);
			printf("\npoll() stdin read 0x%2.2X\n", (unsigned int) buf[0]);
		}*/
		
		
		
		fflush(stdout);
	}
	
	
	gpio_fd_close(gpio_fd1);
	gpio_fd_close(gpio_fd2);
	gpio_fd_close(gpio_fd3);
	gpio_fd_close(gpio_fd4);
	return 0;
}
示例#28
0
文件: main.c 项目: Mirzok/CIS-340
int main() {
    int gen = 1;
    int x = 0;
    int y;
    int width = 0;
    int height = 0;
    int born = 0;
    int died = 0;


    printf("Enter the number of generations: ");
    scanf("%d", &gen);
    while (gen < 1) {
        printf("Please enter a valid generation number: ");
        scanf("%d", &gen);
    }
    printf("Enter the dimensions of the game board: ");
    scanf("%d %d", &width, &height);
    if (width > 80 || height > 100) {
        printf("Please enter new dimensions: ");
        scanf("%d %d", &width, &height);
    }

    //first create array
    char board[width][height];  //array created with given dimensions
    //populate gameboard with '-' using loop
    makeboard((char *)board, width, height);
    //Loop to grab coordinates
    while (x != -1) {
        printf("\nEnter coordinates: "); //can't be bigger than height and width of the board
        scanf("%d %d", &x, &y);
        //easier to implement and read when adding * in the main method
        if (x <= width && y <= height)
            board[x-1][y-1] = '*';
        else
            printf("Out of bounds");
    }
    printf("Initial State\n");
    printboard((char *)board, width, height);

    //PART TWO - Life and Death
    //first find cells and use occ if they are occupied.
    //died counter goes up if parameters are matched
    //born goes up when every cell is analyzed and occ is 3 for any one of them
    int genIterator;

    for (genIterator = 1; genIterator <= gen; genIterator++) {
        printf("\nGeneration #%d", genIterator);


        for (x = 0; x < width; x++) {
            for (y = 0; y < height; y++ ) {
                if ((board[x][y] == '*') && (2 <= (occ((char*)board, width, height, x, y))) && ((occ((char*)board, width, height, x, y)) <= 3)) {
                    //it gets to live
                }
                if ((board[x][y] == '-') && ((occ((char*)board, width, height, x, y)) == 3)) {
                    board[x][y] = '^'; //an organism is marked as born
                    born++;
                }

                if ((board[x][y] == '*') && ((2 > (occ((char*)board, width, height, x, y))) || ((occ((char*)board, width, height, x, y)) >= 4))) {  //if occ is less than 2
                    board[x][y] = 'x'; //x,y is now marked for death
                    died++;
                }
            }
        }
        //go back through and replace the dead and the born with their appropriate symbols
        for (y = 0; y < height; y++ ) {
            for (x = 0; x < width; x++) {
                if (board[x][y] == 'x') {
                    board[x][y] = '-';
                } else if(board[x][y] == '^') {
                    board[x][y] = '*';
                }
            }

        }
        printf("\nNumber born = %d", born);
        printf("    Number died = %d \n", died);
        printboard((char *)board, width, height);
        died = 0;
        born = 0;

    }

    return 0;
}
示例#29
0
文件: book.c 项目: ageneau/scid
/*
 *	This function returns index of a random move found in book
 *	or -1, if no move was found.  Moves must be generated.
 */
int bookmove( tmove *m, int n )
{
	int moves[80], values[80], index;
	int foundtxt=0;

	index = bookmoves(moves,values,m,n);
	if( index <= 0 ) index = sbookmoves(moves,values,m,n);
	else
	{
#ifdef SHOWDUPS
		int moves2[80]; int values2[80], index2;
		index2 = sbookmoves(moves2,values,m,n);
		if( index2>=1 && index>=1 && Counter>8 )
		{
			char p[256]; int i;
			postr(p);
			puts("found in both sbook and pbook");
			printboard(NULL);
			puts(p);
			printf("   0      0       0      0  book2 ");
			for( i=0; i!=index2; i++ )
			if( i==0 || moves2[i-1]!=moves2[i] )
			{ printm( m[moves2[i]], NULL ); }
			puts("");
		}
#endif
		foundtxt=1;
	}

	if( index > 0 )
	{
		int ii, sumvalues=0, rn;
		for( ii=0; ii!=index; ii++ )
		{ sumvalues += values[ii]; }

		rn = rand()%sumvalues;

		sumvalues = 0;
		for( ii=0; ii!=index; ii++ )
		{ sumvalues += values[ii]; if( sumvalues >= rn ) break; }

		if( Flag.post )
		{	int i;
			char s[128];
			if( Flag.xboard )
			sprintf(s,"   0      0       0      0  book");
			else
			sprintf(s,"Book moves ");
			if( foundtxt ) sprintf(s+strlen(s),"1 ");
			else sprintf(s+strlen(s),"2 ");
			for( i=0; i!=index; i++ )
			{ printm( m[moves[i]], s+strlen(s) ); }
			sprintf(s+strlen(s),"\n");
			printf(s);
			if( Flag.log!=NULL && Flag.ponder<2 )
			{
				char sm[64];
				if(Flag.xboard) fprintf(Flag.log,s+26);
				else            fprintf(Flag.log,s);
				fprintf(Flag.log,"  selected move ");
				printm( m[moves[ii]], sm );
				fprintf(Flag.log,sm);
				fprintf(Flag.log,"\n");
			}
		}
		return ( moves[ii] );
	}

	return( -1 );
}
示例#30
0
void cmd_redraw(char *s){printboard();}