Esempio n. 1
0
int main(){

	int Board[NQueen][NQueen], i, j;

	ResetBoard(Board);

	//Board[0][0] = 8;
	//Board[hold_x][hold_y] = 8;
	printBoard(Board);
	//printf("%d\n", CheckRow(Board, hold_x, hold_y) );
	//printf("%d\n", CheckCol(Board, hold_x, hold_y) );
	//printf("%d\n", CheckDiag(Board, hold_x, hold_y) );

	for(i = 0; i < NQueen/2; i++){
		for(j = 0; j < NQueen/2; j++){
			Board[i][j] = 8; //put queen
			//printf("i = %d\n", i);
			//printf("j = %d\n", j);
			//printBoard(Board);
			//getchar();
				if(MakeAMove(Board, 1) == TRUE ) printBoard(Board);
				ResetBoard(Board);
		}
	}

}
Esempio n. 2
0
void StartGame(Game* game)
{   if(game == NULL) return;
    game->random = game->random_seed;
    if(game->status != GAME_STATUS_NEW)
    {   game->status = GAME_STATUS_NEW;
        game->score = 0;
        ResetBoard(game->board);
    }
}
Esempio n. 3
0
void MirrorBoard(S_BOARD *pos) {

    int tempPiecesArray[64];
    int tempSide = pos->side^1;
	int SwapPiece[13] = { EMPTY, bP, bN, bB, bR, bQ, bK, wP, wN, wB, wR, wQ, wK };
    int tempCastlePerm = 0;
    int tempEnPas = NO_SQ;

	int sq;
	int tp;

    if (pos->castlePerm & WKCA) tempCastlePerm |= BKCA;
    if (pos->castlePerm & WQCA) tempCastlePerm |= BQCA;

    if (pos->castlePerm & BKCA) tempCastlePerm |= WKCA;
    if (pos->castlePerm & BQCA) tempCastlePerm |= WQCA;

	if (pos->enPas != NO_SQ)  {
        tempEnPas = SQ120(Mirror64[SQ64(pos->enPas)]);
    }

    for (sq = 0; sq < 64; sq++) {
        tempPiecesArray[sq] = pos->pieces[SQ120(Mirror64[sq])];
    }

    ResetBoard(pos);

	for (sq = 0; sq < 64; sq++) {
        tp = SwapPiece[tempPiecesArray[sq]];
        pos->pieces[SQ120(sq)] = tp;
    }

	pos->side = tempSide;
    pos->castlePerm = tempCastlePerm;
    pos->enPas = tempEnPas;

    pos->posKey = GeneratePosKey(pos);

	UpdateListsMaterial(pos);

    ASSERT(CheckBoard(pos));
}
Esempio n. 4
0
int main(int argc, char **argv) {

	std::string board = std::string(BOARD_WIDTH*BOARD_HEIGHT, '=');

	int p1Move = 1;
	int p2Move = -1;
	int p1Score = 0;
	int p2Score = 0;
	int fruitPos = 0;

	std::vector<int> player1;
	std::vector<int> player2;

	ResetBoard(board, player1, player2, fruitPos, p1Move, p2Move);


	bool quit = false;

	while (!quit) {
		//REMOVE FOR FINAL CODE
		system("cls");

		//REMOVE FOR FINAL CODE
		//Change to receive client comamnds
		if (_kbhit())
		{
			switch (_getch())
			{
			//Player 1 Movement
			case 'a': 
				if(p1Move != 1)
					p1Move = -1;
				break;
			case 'd':
				if(p1Move != -1)
					p1Move = 1;
				break;
			case 'w': 
				if(p1Move != BOARD_WIDTH)
					p1Move = BOARD_WIDTH*-1;
				break;
			case 's': 
				if(p1Move != BOARD_WIDTH*-1)
					p1Move = BOARD_WIDTH*1;
				break;

			//Player 2 Movement
			case 75:
				if(p2Move != 1)
					p2Move = -1;
				break;
			case 77:
				if(p2Move != -1)
					p2Move = 1;
				break;
			case 72:
				if(p2Move != BOARD_WIDTH)
					p2Move = BOARD_WIDTH*-1;
				break;
			case 80: 
				if(p2Move != BOARD_WIDTH*-1)
				p2Move = BOARD_WIDTH * 1;
				break;

			}
		}

		bool gameover = false;

		int p1Next = player1.front() + p1Move;
		player1.insert(player1.begin(),p1Next);

		int p2Next = player2.front() + p2Move;
		player2.insert(player2.begin(), p2Next);

		if (HitBoundary(player1.front(), p1Move)) {
			p2Score++;
			gameover = true;
		}
		if (HitBoundary(player2.front(), p2Move)) {
			p1Score++;
			gameover = true;
		}

		if (!gameover) {
			if (fruitPos != player1.front())
				player1.pop_back();
			else {
				RandomSpawn(fruitPos, board);
				p1Score++;
			}

			if (fruitPos != player2.front())
				player2.pop_back();
			else {
				RandomSpawn(fruitPos, board);
				p2Score++;
			}
		}

		ClearBoard(board);
		if(gameover || !UpdateBoard(board, player1,player2,fruitPos,p1Score,p2Score,p1Move,p2Move))
			ResetBoard(board, player1, player2, fruitPos, p1Move, p2Move);


		//REMOVE FOR FINAL CODE
		DisplayState(board,p1Score,p2Score);
		Sleep(100);
	}


	
	return 0;
}
Esempio n. 5
0
int ParseFen(char *fen, S_BOARD *pos){

	int rank = RANK_8;
	int file = FILE_A;
	int piece = 0;
	int count = 0;
	int i = 0;
	int sq64 = 0;
	int sq120 = 0;
	
	ASSERT(fen!=NULL);
	ASSERT(pos!=NULL);
	
	ResetBoard(pos);
	
	while(( rank >= RANK_1) && *fen){
		count = 1;
		
		switch(*fen){
			case 'p': piece = bP; break;
            case 'r': piece = bR; break;
            case 'n': piece = bN; break;
            case 'b': piece = bB; break;
            case 'k': piece = bK; break;
            case 'q': piece = bQ; break;
            case 'P': piece = wP; break;
            case 'R': piece = wR; break;
            case 'N': piece = wN; break;
            case 'B': piece = wB; break;
            case 'K': piece = wK; break;
            case 'Q': piece = wQ; break;

            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
                piece = EMPTY;
                count = *fen - '0';
                break;

            case '/':
            case ' ':
                rank--;
                file = FILE_A;
                fen++;
                continue;              

            default:
                printf("FEN error \n");
                return -1;
		}
		
		for(i = 0; i < count; i++){
			sq64 = rank * 8 + file;
			sq120 = SQ120(sq64);
			if(piece != EMPTY){
				pos->pieces[sq120] = piece;
			}
			file++;
		}
		fen++;
	}
	
	ASSERT(*fen == 'w' || *fen == 'b');
	
	pos->side = (*fen == 'w') ? WHITE : BLACK;
	
	fen += 2;
	
	for(i = 0; i < 4; i++){
		if(*fen == ' '){
			break;
		}
		switch(*fen){
			case 'K': pos->castlePerm |= WKCA; break;
			case 'Q': pos->castlePerm |= WQCA; break;
			case 'k': pos->castlePerm |= BKCA; break;
			case 'q': pos->castlePerm |= BQCA; break;
			default:						   break;
		}
		fen++;
	}
	fen++;
	
	ASSERT(pos->castlePerm>=0 && pos->castlePerm <= 15);
	
	if(*fen != '-'){
		file = fen[0] - 'a';
		rank = fen[1] - '1';
		
		ASSERT(file>=FILE_A && file <= FILE_H);
		ASSERT(rank>=RANK_1 && rank <= RANK_8);
		
		pos->enPas = FR2SQ(file,rank);
	}
	pos->posKey = GeneratePosKey(pos);
	
	return 0;
}
Esempio n. 6
0
int ibmlana_probe(struct net_device *dev)
{
	int force_detect = 0;
	int slot, z;
	int base = 0, irq = 0, iobase = 0, memlen = 0;
	ibmlana_priv *priv;
	ibmlana_medium medium;

	SET_MODULE_OWNER(dev);

	/* can't work without an MCA bus ;-) */
	if (MCA_bus == 0)
		return -ENODEV;

	/* start address of 1 --> forced detection */
	if (dev->mem_start == 1)
		force_detect = 1;

	/* search through slots */
	if (dev != NULL) {
		base = dev->mem_start;
		irq = dev->irq;
	}
	slot = mca_find_adapter(IBM_LANA_ID, startslot);

	while (slot != -1) {
		/* deduce card addresses */
		getaddrs(slot, &base, &memlen, &iobase, &irq, &medium);

		/* slot already in use ? */
		if (mca_is_adapter_used(slot)) {
			slot = mca_find_adapter(IBM_LANA_ID, slot + 1);
			continue;
		}
		/* were we looking for something different ? */
		if (dev->irq != 0 || dev->mem_start != 0) {
			if (dev->irq != 0 && dev->irq != irq) {
				slot = mca_find_adapter(IBM_LANA_ID, slot + 1);
				continue;
			}
			if (dev->mem_start != 0 && dev->mem_start != base) 
			{
				slot = mca_find_adapter(IBM_LANA_ID, slot + 1);
				continue;
			}
		}
		/* found something that matches */
		break;
	}

	/* nothing found ? */
	if (slot == -1)
		return (base != 0 || irq != 0) ? -ENXIO : -ENODEV;

	/* announce success */
	printk(KERN_INFO "%s: IBM LAN Adapter/A found in slot %d\n", dev->name, slot + 1);

	/* try to obtain I/O range */
	if (!request_region(iobase, IBM_LANA_IORANGE, dev->name)) {
		printk(KERN_ERR "%s: cannot allocate I/O range at %#x!\n", dev->name, iobase);
		startslot = slot + 1;
		return -EBUSY;
	}

	/* make procfs entries */
	mca_set_adapter_name(slot, "IBM LAN Adapter/A");
	mca_set_adapter_procfn(slot, (MCA_ProcFn) ibmlana_getinfo, dev);

	mca_mark_as_used(slot);

	/* allocate structure */
	priv = dev->priv = (ibmlana_priv *) kmalloc(sizeof(ibmlana_priv), GFP_KERNEL);
	if (!priv) {
		release_region(iobase, IBM_LANA_IORANGE);
		return -ENOMEM;
	}
	priv->slot = slot;
	priv->realirq = irq;
	priv->medium = medium;
	spin_lock_init(&priv->lock);
	memset(&priv->stat, 0, sizeof(struct net_device_stats));

	/* set base + irq for this device (irq not allocated so far) */

	dev->irq = 0;
	dev->mem_start = base;
	dev->mem_end = base + memlen;
	dev->base_addr = iobase;

	/* set methods */

	dev->open = ibmlana_open;
	dev->stop = ibmlana_close;
	dev->set_config = ibmlana_config;
	dev->hard_start_xmit = ibmlana_tx;
	dev->do_ioctl = NULL;
	dev->get_stats = ibmlana_stats;
	dev->set_multicast_list = ibmlana_set_multicast_list;
	dev->flags |= IFF_MULTICAST;

	/* generic setup */

	ether_setup(dev);

	/* copy out MAC address */

	for (z = 0; z < sizeof(dev->dev_addr); z++)
		dev->dev_addr[z] = inb(dev->base_addr + MACADDRPROM + z);

	/* print config */

	printk(KERN_INFO "%s: IRQ %d, I/O %#lx, memory %#lx-%#lx, "
	       "MAC address %02x:%02x:%02x:%02x:%02x:%02x.\n",
	       dev->name, priv->realirq, dev->base_addr,
	       dev->mem_start, dev->mem_end - 1,
	       dev->dev_addr[0], dev->dev_addr[1], dev->dev_addr[2],
	       dev->dev_addr[3], dev->dev_addr[4], dev->dev_addr[5]);
	printk(KERN_INFO "%s: %s medium\n", dev->name, MediaNames[priv->medium]);

	/* reset board */

	ResetBoard(dev);

	/* next probe will start at next slot */

	startslot = slot + 1;

	return 0;
}
Esempio n. 7
0
int main(int argc, char *argv[])
{
    char buf[1028],move[12];
    int len,mlen;

    /* Convert command line parameters */
    SecPerMove = (float) atof(argv[1]); /* Time allotted for each move */
    MaxDepth = (argc == 4) ? atoi(argv[3]) : -1;

fprintf(stderr, "%s SecPerMove == %lg\n", argv[0], SecPerMove);

    /* Determine if I am player 1 (red) or player 2 (white) */
    //fgets(buf, sizeof(buf), stdin);
    len=read(STDIN_FILENO,buf,1028);
    buf[len]='\0';
    if(!strncmp(buf,"Player1", strlen("Player1"))) 
    {
        fprintf(stderr, "I'm Player 1\n");
        player1 = 1; 
    }
    else 
    {
        fprintf(stderr, "I'm Player 2\n");
        player1 = 0;
    }
    if(player1) me = 1; else me = 2;

    /* Set up the board */ 
    ResetBoard();
    srand((unsigned int)time(0));

    if (player1) {
        start = times(&bff);
        goto determine_next_move;
    }

    for(;;) {
        /* Read the other player's move from the pipe */
        //fgets(buf, sizeof(buf), stdin);
        len=read(STDIN_FILENO,buf,1028);
        buf[len]='\0';
        start = times(&bff);
        memset(move,0,12*sizeof(char));

        /* Update the board to reflect opponents move */
        mlen = TextToMove(buf,move);
        PerformMove(board,move,mlen);
        
determine_next_move:
        /* Find my move, update board, and write move to pipe */
        if(player1) FindBestMove(1); else FindBestMove(2);
        if(bestmove[0] != 0) { /* There is a legal move */
            mlen = MoveLength(bestmove);
            PerformMove(board,bestmove,mlen);
            MoveToText(bestmove,buf);
        }
        else exit(1); /* No legal moves available, so I have lost */

        /* Write the move to the pipe */
        //printf("%s", buf);
        write(STDOUT_FILENO,buf,strlen(buf));
        fflush(stdout);
    }

    return 0;
}
Esempio n. 8
0
int main(int argc, char *argv[])
{
    char text[1028],temptext[1028], str[1028];
    int tlen,mlen,move[12],numlegal,done;
    if(argc>=3)
    {
       if(!strncasecmp("-MaxDepth",argv[argc-2], strlen("-MaxDepth")))
       {
          MaxDepth = atoi(argv[argc-1]);
          argc-=2;
       }
       else MaxDepth = -1;
    }
    else MaxDepth = -1;

#ifndef GRAPHICS
    printf("No graphics\n");
    if(argc != 4) Usage(argv[0]);
    strcpy(player1,argv[1]);
    strcpy(player2,argv[2]);
    SecPerMove = atof(argv[3]);
#endif

#ifdef GRAPHICS
    printf("Graphics\n");
    InitGraphics(argc,argv);
#else
      NewGame();
      {
     int x,y;
     /* I'll wait a bit to make sure both oponents are ready to go */
     printf("waiting\n");
     sleep(1);
     for(x=0;x<1000;x++)
     for(y=0;y<10000;y++);
      }
#endif
    ResetBoard();
    for(;;) {
        pthread_t thread;
        int rc, dummy;
        HandleEvents();
        if(playing) {
            sprintf(str,"Waiting for player %d",turn+1);
            Message(str);
            HumanMoved = done = 0;
            //start = times(&bff);
            rc = pthread_create(&thread, NULL, timer, (void*)&done);
            pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &dummy);
            do {
                HandleEvents();
                /* Give humans all the time they want to move */
                if(player[turn] == HUMAN) done = HumanMoved;
                else if(player[turn] == COMPUTER) 
                {
                    char *ptr;
                    memset(temptext,0,sizeof(temptext));
                    tlen = read(readfd[turn],temptext,1028);
                    if(tlen > 0) 
                    {
                        ptr = temptext;
                        while(*ptr == 10 && *ptr !=0) ptr++;
                        strcpy(text,ptr);
                        if(strlen(text)) done=1;
                    }
                }
            } while(playing && !done);
            pthread_cancel(thread);
            if(!playing) continue;
            if(player[turn] == COMPUTER && tlen <= 0) {
                sprintf(str,"Player %d has lost the game (time limit reached).",turn+1);
                Message(str);
                StopGame();
            }    
            else {
                if(player[turn] == COMPUTER) {
                    text[tlen] = '\0';
                    memset(move,0,12*sizeof(int));
                    mlen = TextToMove(text,move);
                }
                else if(player[turn] == HUMAN) {
                    mlen = hlen;
                    memcpy(move,hmove,12*sizeof(int));
                    hlen = 0;
                    memset(hmove,0,12*sizeof(int));
                    MoveToText(move,text);
                }

                if(!mlen) { /* Illegal move check 1 */
                    /*char temp[1000];
                    char *ptr1, *ptr2;
                    ptr1=text;
                    temp[0] = 0;
                    ptr2=temp;
                    while(*ptr1) 
                    {
                        sprintf(ptr2,"%i, ", *ptr1);
                        ptr1++;
                        ptr2 = &(ptr2[strlen(ptr2)]);
                    }*/
                    //sprintf(str,"Player %d has lost the game (illegal move %s %s submitted).",turn+1,text, temp);
                    sprintf(str,"Player %d has lost the game (illegal move %s submitted).",turn+1,text);
                    Message(str);
                    StopGame();
                }
                else {
                    if(!IsLegal(move,mlen)) { /* Illegal move check 2 */
                       /*char temp[1000];
                       char *ptr1, *ptr2;
                       ptr1=text;
                       temp[0] = 0;
                       ptr2=temp;
                       while(*ptr1) 
                       {
                           sprintf(ptr2,"%i, ", *ptr1);
                           ptr1++;
                           ptr2 = &(ptr2[strlen(ptr2)]);
                       }
                        sprintf(str,"Player %d has lost the game (illegal move %s %s submitted).",turn+1,text, temp);*/
                        sprintf(str,"Player %d has lost the game (illegal move %s submitted).",turn+1,text);
                        Message(str);
                        StopGame();
                    }
                    else {  /* Legal Move */
                        PerformMove(move,mlen);
#ifdef GRAPHICS
                        UpdateBoard();
#else
                        printf("Move: %s\n",text);
                        PrintBoard();
#endif
                        if(turn) turn=0; else turn=1;
    
                        /* Check to see if other player has now lost */
                        numlegal = FindLegalMoves(turn+1);
                        if(!numlegal) {
                            sprintf(str,"Player %d has lost the game.",turn+1);
                            Message(str);
                            StopGame();
                        }
                        else if(player[turn] == COMPUTER) {
                            write(writefd[turn],text,strlen(text));
                        }
                    }
                }
            }
        }            
    }
}
Esempio n. 9
0
/* Called when the 'New Game' menu item is selected */
void NewGame(void)
{
    char arg1[16],arg2[16], arg01[16], arg02[16];
    int i;
#ifdef GRAPHICS
    if(!NewDialog(player1,player2,&SecPerMove)) return;
    if(!strcmp(player1,"human")) player[0] = HUMAN; else player[0] = COMPUTER;
    if(!strcmp(player2,"human")) player[1] = HUMAN; else player[1] = COMPUTER;
#else
   player[0]=COMPUTER;
   player[1]=COMPUTER;
#endif


    arg01[0]=0;
    arg02[0]=0;
    player1Java=0;
    player2Java=0;
    if(!strncmp(player1,"java",4)) 
    {
        player1Java=1;
        fprintf(stderr,"Player1 is java player\n");
        strcpy(arg01,&(player1[5]));
        player1[4]=0;
        strcpy(player1,"/usr/bin/java");
        fprintf(stderr,"%s %s\n", player1, arg01);
    }
    if(!strncmp(player2,"java",4)) 
    {
        player2Java=1;
        fprintf(stderr,"Player2 is java player\n");
        strcpy(arg02,&(player2[5]));
        //player2[4]=0;
        strcpy(player2,"/usr/bin/java");
        fprintf(stderr,"%s %s\n", player2, arg02);
    }

    /* If 'New Game' is chosen while a game is in progress, stop the game */
    if (playing) StopGame();

    // Set up the pipes necessary for communication with computer players.
    for (i = 0; i < 2; i++) {
        int to_proc[2];
        int from_proc[2];

        if (player[i] == HUMAN) {
            // Pipes aren't needed for human players.
            continue;
        }

        pipe(to_proc);
        pipe(from_proc);

        writefd[i] = to_proc[1];
        readfd[i] = from_proc[0];

        if (fcntl(readfd[i],F_SETFL,(int)O_NDELAY) < 0) {
            printf("fcntl failed\n");
            return;
        }

        /* Fork a child process. We will then overlay the computer program */
        if((pid[i] = fork()) == (pid_t)0) {
            int temp;
            dup2(to_proc[0], STDIN_FILENO);
            close(to_proc[0]);

            dup2(from_proc[1], STDOUT_FILENO);
            close(from_proc[1]);

            sprintf(arg1,"%.2f",SecPerMove);
            if(MaxDepth >= 0)
            {
               sprintf(arg2,"%d", MaxDepth);
               if((i==0 && player1Java ) || (i==1 && player2Java))
                   temp = execl(i?player2:player1,i?player2:player1, i?arg02:arg01,arg1,arg2, NULL);
               else
                   temp = execl(i?player2:player1,i?player2:player1, arg1,arg2,(char *)0);
               if(temp)
               {
                   fprintf(stderr, "exec for %s failed\n",i?player2:player1);
                   exit(0);
               }
            }
            else
            {
               if((i==0 && player1Java ) || (i==1 && player2Java))
                   temp = execl(i?player2:player1,i?player2:player1, i?arg02:arg01,arg1, NULL);
               else 
                   temp = execl(i?player2:player1,i?player2:player1, arg1,(char *)0);
               if(temp)
               {
                   fprintf(stderr, "exec for %s failed\n",i?player2:player1);
                   exit(0);
               }
            }
        }
    }
    ResetBoard();
    playing = 1;
    turn = 0;
    hlen = 0;
    memset(hmove,0,12*sizeof(int));
    FindLegalMoves(turn+1);

    /* Tell the computer programs which player they are */
    if(player[0] == COMPUTER) 
    {
       write(writefd[0],"Player1",7);
       fsync(writefd[0]);
    }
    if(player[1] == COMPUTER) 
    {
       write(writefd[1],"Player2",7);
       fsync(writefd[1]);
    }
}
void setup()
{
	LoadShips();
	ResetBoard();

	//"PLACE SHIPS" phase of game
	//Loop through each player...

	//Loop through each ship type to place
	for (int thisShip = 0; thisShip < numberOfShipTypes; ++thisShip)
	{
		//Display game board for player
		system("cls");
		DrawBoard(1, true);
		//Give instructions
		cout << "\n";
		cout << "INSTRUCTIONS:";
		cout << "\n";
		cout << "You are about to place your ships.";
		cout << "\n";
		cout << "Format should be:";
		cout << "\n";
		cout << "Facing (0:Horizontal, 1:Vertical), X (top-row), Y (left-side)";
		cout << "\n";
		cout << "Example: 0 7 2    Places a ship beginning at X:7 Y:2 going horizontal.";
		cout << "\n";
		cout << "\n";
		cout << "Ship to place: " << ship[thisShip].name << " which has a length of " << ship[thisShip].length;
		cout << "\n";
		cout << "Where do you want it placed?";

		//Get input from user and loop until good data is returned
		PlaceShips aShip;
		aShip.shipType.onGrid[0].X = -1;
		while (aShip.shipType.onGrid[0].X == -1)
		{
			aShip = UserInputShipPlacement();
		}

		//Combine user data with "this ship" data
		aShip.shipType.length = ship[thisShip].length;
		aShip.shipType.name = ship[thisShip].name;

		//Add the FIRST grid point to the current player's game board
		player[1].grid[aShip.shipType.onGrid[0].X][aShip.shipType.onGrid[0].Y] = isShip;

		//Determine ALL grid points based on length and direction
		for (int i = 1; i < aShip.shipType.length; ++i)
		{
			if (aShip.direction == horizontal)
			{
				aShip.shipType.onGrid[i].X = aShip.shipType.onGrid[i - 1].X + 1;
				aShip.shipType.onGrid[i].Y = aShip.shipType.onGrid[i - 1].Y;
			}
			if (aShip.direction == vertical)
			{
				aShip.shipType.onGrid[i].Y = aShip.shipType.onGrid[i - 1].Y + 1;
				aShip.shipType.onGrid[i].X = aShip.shipType.onGrid[i - 1].X;
			}

			//Add the REMAINING grid points to our current players game board
			player[1].grid[aShip.shipType.onGrid[i].X][aShip.shipType.onGrid[i].Y] = isShip;
		}
			//Loop back through each ship type

	}

	//********* FINISHED WITH "PLACE SHIPS" PHASE *********************************
	//*****************************************************************************
}
Esempio n. 11
0
File: ibmlana.c Progetto: E-LLP/n900
static int __devinit ibmlana_init_one(struct device *kdev)
{
	struct mca_device *mdev = to_mca_device(kdev);
	struct net_device *dev;
	int slot = mdev->slot, z, rc;
	int base = 0, irq = 0, iobase = 0, memlen = 0;
	ibmlana_priv *priv;
	ibmlana_medium medium;
	DECLARE_MAC_BUF(mac);

	dev = alloc_etherdev(sizeof(ibmlana_priv));
	if (!dev)
		return -ENOMEM;

	dev->irq = ibmlana_irq;
	dev->base_addr = ibmlana_io;

	base = dev->mem_start;
	irq = dev->irq;

	/* deduce card addresses */
	getaddrs(mdev, &base, &memlen, &iobase, &irq, &medium);

	/* were we looking for something different ? */
	if (dev->irq && dev->irq != irq) {
		rc = -ENODEV;
		goto err_out;
	}
	if (dev->mem_start && dev->mem_start != base) {
		rc = -ENODEV;
		goto err_out;
	}

	/* announce success */
	printk(KERN_INFO "%s: IBM LAN Adapter/A found in slot %d\n", dev->name, slot + 1);

	/* try to obtain I/O range */
	if (!request_region(iobase, IBM_LANA_IORANGE, DRV_NAME)) {
		printk(KERN_ERR "%s: cannot allocate I/O range at %#x!\n", DRV_NAME, iobase);
		startslot = slot + 1;
		rc = -EBUSY;
		goto err_out;
	}

	priv = netdev_priv(dev);
	priv->slot = slot;
	priv->realirq = mca_device_transform_irq(mdev, irq);
	priv->medium = medium;
	spin_lock_init(&priv->lock);

	/* set base + irq for this device (irq not allocated so far) */

	dev->irq = 0;
	dev->mem_start = base;
	dev->mem_end = base + memlen;
	dev->base_addr = iobase;

	priv->base = ioremap(base, memlen);
	if (!priv->base) {
		printk(KERN_ERR "%s: cannot remap memory!\n", DRV_NAME);
		startslot = slot + 1;
		rc = -EBUSY;
		goto err_out_reg;
	}

	mca_device_set_name(mdev, ibmlana_adapter_names[mdev->index]);
	mca_device_set_claim(mdev, 1);

	/* set methods */

	dev->open = ibmlana_open;
	dev->stop = ibmlana_close;
	dev->hard_start_xmit = ibmlana_tx;
	dev->set_multicast_list = ibmlana_set_multicast_list;
	dev->flags |= IFF_MULTICAST;

	/* copy out MAC address */

	for (z = 0; z < sizeof(dev->dev_addr); z++)
		dev->dev_addr[z] = inb(dev->base_addr + MACADDRPROM + z);

	/* print config */

	printk(KERN_INFO "%s: IRQ %d, I/O %#lx, memory %#lx-%#lx, "
	       "MAC address %s.\n",
	       dev->name, priv->realirq, dev->base_addr,
	       dev->mem_start, dev->mem_end - 1,
	       print_mac(mac, dev->dev_addr));
	printk(KERN_INFO "%s: %s medium\n", dev->name, MediaNames[priv->medium]);

	/* reset board */

	ResetBoard(dev);

	/* next probe will start at next slot */

	startslot = slot + 1;

	rc = register_netdev(dev);
	if (rc)
		goto err_out_claimed;

	dev_set_drvdata(kdev, dev);
	return 0;

err_out_claimed:
	mca_device_set_claim(mdev, 0);
	iounmap(priv->base);
err_out_reg:
	release_region(iobase, IBM_LANA_IORANGE);
err_out:
	free_netdev(dev);
	return rc;
}
Esempio n. 12
0
bool CMine_Sweeper::On_Execute_Position(CSG_Point ptWorld, TSG_Module_Interactive_Mode Mode)
{
	int ok = true;
	
	int time;
	int redraw = false;
	int xpos; 	int ypos;

	if( !Get_Grid_Pos(xpos, ypos) )
		return( false );

	xpos/=SPRITE_SIZE; 	ypos/=SPRITE_SIZE;

	ypos=Mine_NY-1-ypos;
	
	switch( Mode )
	{
	default:
		return( false );

	case MODULE_INTERACTIVE_LDOWN:
		if(First_Click)
		{
			ResetBoard(xpos, ypos);
			First_Click=false;
		}

		ok = Play(xpos, ypos, false);
		redraw = true;
		break;

	case MODULE_INTERACTIVE_RDOWN:
		Mark(xpos, ypos);
		redraw = true;
		break;
	}

	if (redraw)
	{
		if(ok)
		{
			Show_GameBoard(false);
			
			time= Time->Time();
			
			Message_Add(CSG_String::Format(SG_T(":-) Time:%ds Mines:%d\n"),time,N_Mines-MarkedMines));
			
			if (OpenFields == Mine_NX*Mine_NY-N_Mines  )
			{
				Message_Add(CSG_String::Format(_TL(":-) :-) you are a winner :-) :-) Time:%ds\n"),time));
				Message_Dlg(CSG_String::Format(_TL(":-) :-) you are a winner :-) :-) Time:%ds\n"),time));
			
				Show_GameBoard(true);

				First_Click=true;
			}
		}
		else 
		{
			Show_GameBoard(true);

			Message_Dlg(CSG_String::Format(_TL(":-( :-( you are a loser :-( :-(")));
			Message_Add(CSG_String::Format(_TL(":-( :-( you are a loser :-( :-(")));

			First_Click=true;
		}
	}
	return true;
}
Esempio n. 13
0
void CCommandProcessor::ParseCommand ( const char * const cmdBegin,
                                       const uint64_t currentTime )
{
  const char * const cmdEnd = SkipCharsNotInSet( cmdBegin, SPACE_AND_TAB );
  assert( cmdBegin != cmdEnd );

  const char * const paramBegin = SkipCharsInSet( cmdEnd, SPACE_AND_TAB );

  bool extraParamsFound = false;

  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_QUESTION_MARK, true, false, &extraParamsFound ) ||
       IsCmd( cmdBegin, cmdEnd, CMDNAME_HELP, false, false, &extraParamsFound ) )
  {
    PrintStr( "This console is similar to the Bus Pirate console." EOL );
    PrintStr( "Commands longer than 1 character are case insensitive." EOL );
    PrintStr( "WARNING: If a command takes too long to run, the watchdog may reset the board." EOL );
    PrintStr( "Commands are:" EOL );

    Printf( "  %s, %s: Show this help text." EOL, CMDNAME_QUESTION_MARK, CMDNAME_HELP );
    Printf( "  %s: Show version information." EOL, CMDNAME_I );
    Printf( "  %s: Test USB transfer speed." EOL, CMDNAME_USBSPEEDTEST );
    Printf( "  %s: Show JTAG pin status (read as inputs)." EOL, CMDNAME_JTAGPINS );
    Printf( "  %s: Test JTAG shift speed. WARNING: Do NOT connect any JTAG device." EOL, CMDNAME_JTAGSHIFTSPEEDTEST );
    Printf( "  %s: Exercises malloc()." EOL, CMDNAME_MALLOCTEST );
    Printf( "  %s: Exercises C++ exceptions." EOL, CMDNAME_CPP_EXCEPTION_TEST );
    Printf( "  %s: Shows memory usage." EOL, CMDNAME_MEMORY_USAGE );
    Printf( "  %s" EOL, CMDNAME_CPU_LOAD );
    Printf( "  %s" EOL, CMDNAME_UPTIME );
    Printf( "  %s" EOL, CMDNAME_RESET );
    Printf( "  %s" EOL, CMDNAME_RESET_CAUSE );
    Printf( "  %s <addr> <byte count>" EOL, CMDNAME_PRINT_MEMORY );
    Printf( "  %s <milliseconds>" EOL, CMDNAME_BUSY_WAIT );
    Printf( "  %s <command|protocol>" EOL, CMDNAME_SIMULATE_ERROR );

    return;
  }

  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_I, true, false, &extraParamsFound ) )
  {
    #ifndef NDEBUG
      const char buildType[] = "Debug build";
    #else
      const char buildType[] = "Release build";
    #endif

    Printf( "JtagDue %s" EOL, PACKAGE_VERSION );
    Printf( "%s, compiler version %s" EOL, buildType, __VERSION__ );
    Printf( "Watchdog %s" EOL, ENABLE_WDT ? "enabled" : "disabled" );

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_RESET, false, false, &extraParamsFound ) )
  {
    // This message does not reach the other side, we would need to add some delay.
    //   UsbPrint( txBuffer, "Resetting the board..." EOL );
    __disable_irq();
    // Note that this message always goes to the serial port console,
    // even if the user is connected over USB. It might be possible to send
    // it over USB and then wait for the outgoing buffer to be empty.
    SerialSyncWriteStr( "Resetting the board..." EOL );
    SerialWaitForDataSent();
    ResetBoard( ENABLE_WDT );
    assert( false );  // We should never reach this point.
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_CPU_LOAD, false, false, &extraParamsFound ) )
  {
    if ( ENABLE_CPU_SLEEP )
      PrintStr( "CPU load statistics not available." EOL );
    else
      DisplayCpuLoad();

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_UPTIME, false, false, &extraParamsFound ) )
  {
    char buffer[ CONVERT_TO_DEC_BUF_SIZE ];
    Printf( "Uptime: %s seconds." EOL, convert_unsigned_to_dec_th( GetUptime() / 1000, buffer, ',' ) );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_RESET_CAUSE, false, false, &extraParamsFound ) )
  {
    DisplayResetCause();
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_PRINT_MEMORY, false, true, &extraParamsFound ) )
  {
    PrintMemory( paramBegin );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_BUSY_WAIT, false, true, &extraParamsFound ) )
  {
    BusyWait( paramBegin );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_USBSPEEDTEST, false, true, &extraParamsFound ) )
  {
    ProcessUsbSpeedTestCmd( paramBegin, currentTime );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_JTAGPINS, false, false, &extraParamsFound ) )
  {
    PrintJtagPinStatus();
    return;
  }

  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_JTAGSHIFTSPEEDTEST, false, false, &extraParamsFound ) )
  {
    if ( !IsNativeUsbPort() )
      throw std::runtime_error( "This command is only available on the 'Native' USB port." );


    // Fill the Rx buffer with some test data.
    assert( m_rxBuffer != NULL );

    m_rxBuffer->Reset();
    for ( uint32_t i = 0; !m_rxBuffer->IsFull(); ++i )
    {
      m_rxBuffer->WriteElem( CUsbRxBuffer::ElemType( i ) );
    }


    // If the mode is set to MODE_HIZ, you cannot see the generated signal with the oscilloscope.
    // Note also that the built-in pull-ups on the Atmel ATSAM3X8 are too weak (between 50 and 100 KOhm,
    // yields too slow a rising time) to be of any use.

    const bool oldPullUps = GetJtagPullups();
    SetJtagPullups( false );

    const JtagPinModeEnum oldMode = GetJtagPinMode();
    SetJtagPinMode ( MODE_JTAG );


    // Each JTAG transfer needs 2 bits in the Rx buffer, TMS and TDI,
    // but produces only 1 bit, TDO.
    const uint32_t jtagByteCount = m_rxBuffer->GetElemCount() / 2;

    const uint16_t bitCount = jtagByteCount * 8;

    // Shift all JTAG data through several times.

    const uint64_t startTime = GetUptime();
    const uint32_t iterCount = 50;

    for ( uint32_t i = 0; i < iterCount; ++i )
    {
      // We hope that this will not clear the buffer contents.
      assert( m_rxBuffer != NULL );
      assert( m_txBuffer != NULL );

      m_rxBuffer->Reset();
      m_rxBuffer->CommitWrittenElements( jtagByteCount * 2 );

      m_txBuffer->Reset();

      ShiftJtagData( m_rxBuffer,
                     m_txBuffer,
                     bitCount );

      assert( m_txBuffer->GetElemCount() == jtagByteCount );
    }

    const uint64_t finishTime = GetUptime();
    const uint32_t elapsedTime = uint32_t( finishTime - startTime );

    m_rxBuffer->Reset();
    m_txBuffer->Reset();
    const unsigned kBitsPerSec = unsigned( uint64_t(bitCount) * iterCount * 1000 / elapsedTime / 1024 );

    SetJtagPinMode( oldMode );
    SetJtagPullups( oldPullUps );

    // I am getting 221 KiB/s with GCC 4.7.3 and optimisation level "-O3".
    Printf( EOL "Finished JTAG shift speed test, throughput %u Kbits/s (%u KiB/s)." EOL,
               kBitsPerSec, kBitsPerSec / 8 );

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_MALLOCTEST, false, false, &extraParamsFound ) )
  {
    PrintStr( "Allocalling memory..." EOL );

    volatile uint32_t * const volatile mallocTest = (volatile uint32_t *) malloc(123);
    *mallocTest = 123;

    PrintStr( "Releasing memory..." EOL );

    free( const_cast< uint32_t * >( mallocTest ) );

    PrintStr( "Test finished." EOL );

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_CPP_EXCEPTION_TEST, false, false, &extraParamsFound ) )
  {
    try
    {
      PrintStr( "Throwing integer exception..." EOL );
      throw 123;
      PrintStr( "Throw did not work." EOL );
      assert( false );
    }
    catch ( ... )
    {
      PrintStr( "Caught integer exception." EOL );
    }
    PrintStr( "Test finished." EOL );

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_SIMULATE_ERROR, false, true, &extraParamsFound ) )
  {
    SimulateError( paramBegin );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_MEMORY_USAGE, false, false, &extraParamsFound ) )
  {
    const unsigned heapSize = unsigned( GetHeapEndAddr() - uintptr_t( &_end ) );

    Printf( "Partitions: malloc heap: %u bytes, free: %u bytes, stack: %u bytes." EOL,
               heapSize,
               GetStackStartAddr() - GetHeapEndAddr(),
               STACK_SIZE );

    Printf( "Used stack (estimated): %u from %u bytes." EOL,
               unsigned( GetStackSizeUsageEstimate() ),
               STACK_SIZE );

    const struct mallinfo mi = mallinfo();
    const unsigned heapSizeAccordingToNewlib = unsigned( mi.arena );

    Printf( "Heap: %u allocated from %u bytes." EOL,
               unsigned( mi.uordblks ),
               unsigned( mi.arena ) );

    assert( heapSize == heapSizeAccordingToNewlib );
    UNUSED_IN_RELEASE( heapSizeAccordingToNewlib );

    return;
  }

  if ( extraParamsFound )
    Printf( "Command \"%.*s\" does not take any parameters." EOL, cmdEnd - cmdBegin, cmdBegin );
  else
    Printf( "Unknown command \"%.*s\"." EOL, cmdEnd - cmdBegin, cmdBegin );
}