示例#1
0
int processEvent(GameEvent* e) {
  int value = 0;
  Data *data;

  if(game2->mode == GAME_SINGLE_RECORD) {
    writeEvent(e);
  }
  switch(e->type) {
  case EVENT_TURN_LEFT:
    data = game->player[e->player].data;
    if(data->speed > 0) {
      data->iposx = e->x;
      data->iposy = e->y;
      data->turn = TURN_LEFT;
      doTurn(data, e->timestamp);
    }
    break;
  case EVENT_TURN_RIGHT:
    data = game->player[e->player].data;
    if(data->speed > 0) {
      data->iposx = e->x;
      data->iposy = e->y;
      data->turn = TURN_RIGHT;
      doTurn(data, e->timestamp);
    }
    break;
  case EVENT_CRASH: 
    data = game->player[e->player].data;
    data->posx = data->iposx = e->x;
    data->posy = data->iposy = e->y;
    sprintf(messages, "player %d crashed", e->player + 1);
    fprintf(stderr, "%s\n", messages);
    consoleAddLine(messages);
    crashPlayer(e->player);
    break;
  case EVENT_STOP:
    fprintf(stderr, "game stopped\n");
    if(game2->mode == GAME_SINGLE_RECORD) {
      stopRecording();
      game2->mode = GAME_SINGLE;
    } else if(game2->mode == GAME_PLAY) {
      stopPlaying();
      game2->mode = GAME_SINGLE;
    }
    game->winner = e->player;
    sprintf(messages, "winner: %d", game->winner + 1);
    printf("%s\n", messages);
    consoleAddLine(messages);
    switchCallbacks(&pauseCallbacks);
    /* screenSaverCheck(0); */
    stoptime = SystemGetElapsedTime();
    game->pauseflag = PAUSE_GAME_FINISHED;
    value = 1;
    break;
  }
  free(e);
  return value;
}
示例#2
0
task main ()
{
	nxtDisplayCenteredTextLine(3, "Roaming");
	nxtDisplayCenteredTextLine(5, "This is a test");
	while(nextEmptyCell<numLocalCells)
	{
		alive();
		char lastCellNum = nextEmptyCell;
	  nSyncedMotors = synchBC;
	  nSyncedTurnRatio = 101;
    nMotorEncoderTarget[motorB] = 200;
	  motor[motorB] =60;
    while(nMotorRunState[motorB] != runStateIdle) {}
    setTemp();
    checkLocalCell();
    doTurn();
    if(lastCellNum != nextEmptyCell)
    {
      AddToDatalog(1);
    }
    else
    {
    	AddToDatalog(0);
    }
 // wait1Msec(200);

  }
  SaveNxtDatalog();
  StarWars();
}
示例#3
0
文件: event.c 项目: Zoxc/gltron
int processEvent(GameEvent* e) {
  int value = 0;

#ifdef RECORD
  if(game2->mode == GAME_SINGLE_RECORD) {
    writeEvent(e);
  }
#endif
  switch(e->type) {
  case EVENT_TURN_LEFT:
    doTurn(e, TURN_LEFT);
    break;
  case EVENT_TURN_RIGHT:
    doTurn(e, TURN_RIGHT);
    break;
  case EVENT_CRASH: 
    displayMessage(TO_CONSOLE, "player %d crashed", e->player + 1);
    doCrashPlayer(e);
    break;
  case EVENT_STOP:
    // displayMessage(TO_STDOUT, "game stopped");
#ifdef RECORD
    if(game2->mode == GAME_SINGLE_RECORD) {
      stopRecording();
      game2->mode = GAME_SINGLE;
    } else if(game2->mode == GAME_PLAY) {
      stopPlaying();
      game2->mode = GAME_SINGLE;
    }
#endif
    if(e->player<PLAYERS && game->player[e->player].ai->active != AI_NONE) {
      game->winner = e->player;
      displayMessage(TO_CONSOLE, "winner: %d", game->winner + 1);
    } else {
      game->winner = -2;
      displayMessage(TO_CONSOLE, "everyone died! no one wins!");
    }
		SystemExitLoop(RETURN_GAME_END);
    game->pauseflag = PAUSE_GAME_FINISHED;
    value = 1;
    break;
  }
  free(e);
  return value;
}
示例#4
0
void TankDrive::turnRight(int turnAngle)
{
	// Set motor directions to turn Right
	  digitalWrite(_forwardPinLeft, HIGH);
	  digitalWrite(_reversePinLeft, LOW);
	  digitalWrite(_forwardPinRight, LOW);
	  digitalWrite(_reversePinRight, LOW);

         doTurn(turnAngle);
}
示例#5
0
void playToLose(int word, char **answer) {
   char alpha[] = "aeioursthclmndpbjfgkqvwxyz";
   reset();
   getWord(word);
   while (1) {
      int i = cgc_strlen(alpha) - 1;
      char guess = alpha[i];
      alpha[i] = 0;
      if (doTurn(guess, answer)) return;
   }
}
示例#6
0
//run an automatic game.  tla1 and tla2 should be set up prior to calling
int autoGame(Unit *u[]) {
    bool done = false;

    // set up the board
    setUpBoard(u);

    while (!done) {
        // do a turn
        ++numTurns;
        doTurn(u);
        if (oneLeft(u))done = true;
    }
    if (AUTOTOURNEY) {
        if (winner == tla[0])return 2;
        else if (winner == "tie")return 1;
    }
    return 0;
}
示例#7
0
//----main----//
task main ()
{
	nxtDisplayCenteredTextLine(3, "Roaming");
	nxtDisplayCenteredTextLine(5, "This is a test");
	initialisePose(); //set up
	iterate(stepSize); //run excitation etc
	currentDirection = 0; //set initial
  currentTheta = 0;
  setTemp();  //get local view
  checkLocalCell(); //create first association
  displayMax();
  nxtDisplayTextLine(2, "Num Act.: %3d",numActive);
  nxtDisplayTextLine(3, "Direction: %3d", currentDirection);
  nxtDisplayTextLine(4, "changeTheta:%3d", changeTheta);
	while(nextEmptyCell<numLocalCells)
	{
		alive(); //stop NXT from sleeping
		//eraseDisplay();

		//nxtDisplayCenteredTextLine(2, "Num Active: - %4d",numActive);
		char lastCellNum = nextEmptyCell;
	  drive(100,180,50);

    pose3D(changeTheta,0.5);

    setTemp();
    checkLocalCell();
    doTurn();

    displayMax();
    nxtDisplayTextLine(2, "Num Act.: %3d",numActive);
    nxtDisplayTextLine(3, "Direction: %3d", currentDirection);
    nxtDisplayTextLine(4, "changeTheta:%3d", changeTheta);
    //store data

    clearEncoders(); //clear encoder count
    changeTheta=0;
 // wait1Msec(200);

  }


}
示例#8
0
文件: b4 rat.c 项目: mjs513/rsnxt08
//----main----//
task main ()
{
	Delete(sFileName1, nIoResult);
	Delete(sFileName2, nIoResult);
	nxtDisplayCenteredTextLine(3, "Roaming");
	nxtDisplayCenteredTextLine(5, "This is a test");
	initialisePose(); //set up
	iterate(stepSize); //run excitation etc
	currentDirection = 0; //set initial
  currentTheta = 0;
  setTemp();  //get local view
  checkLocalCell(); //create first association

  datalogging();
  sumPoseStruct();
	while(1)
	{
		alive(); //stop NXT from sleeping

    float centreSonarValue = SensorValue(centreSonar);
    if(centreSonarValue<19)
	  {
	  	doTurn();
	  	pose3D(changeTheta,0);
	  }
	  else {
	  drive(100,180,50);
    pose3D(changeTheta,0.5);
    }
    sumPoseStruct();
    setTemp();
    checkLocalCell();

    //store data
    datalogging();
    clearEncoders(); //clear encoder count
    changeTheta=0;
  }
  SaveNxtDatalog();
  PlaySound(soundException);
  while(bSoundActive){}
}
示例#9
0
int main() {


    Unit *u[NUM];
    char line[1024];
    bool done = false;
    numTurns = 0;

    srand(time(NULL));

    // if running an auto tourney, just do that and quit
    if (AUTOTOURNEY) {
        autoTourney(u);
        return 0;
    }

    // set up the board
    setUpBoard(u);
    display(u);
    cin.getline(line, 1023);
    cout << sout.str();
    sout.str("");

    while (!done) {
        // do a turn
        ++numTurns;
        doTurn(u);
        display(u);
        cin.getline(line, 1023);
        cout << sout.str();
        sout.str("");
        if (line[0] == 'q')done = true;
        if (oneLeft(u))done = true;
    }
    return 0;


}
示例#10
0
void playToWin(int word, char *answer) {
   int i = 0;
   char *dummy;
   reset();
   getWord(word);
   while (1) {
      int j;
      
      char guess = answer[i];
      if (guess == 0) {
         break;
      }
      for (j = 0; j < i; j++) {
         if (answer[j] == guess) {
            break;
         }
      }
      if (j == i) {
         if (doTurn(guess, &dummy)) break;
      }
      i++;
   }
}
示例#11
0
void handleSpecialEvents(short* enc){
	static uint8_t oldTagValue = None;
	static short elapsedEnc[2] = {0,0};
	uint8_t resetAdjustSpeed = 0;
	//Check for Error
	if( tagValue & Error ){
		//Report Error, Clear Flag, and Do Nothing
		printw_err("Invalid RFID Tag!\n");
		disableTag(Error);
		lineFound = FALSE;
		return;
	}

	//Depending on tag values adjust motor speed
	if( tagValue != oldTagValue ){
		lineFound = FALSE;
		//Do first occurence actions
		uint8_t diff = tagValue & ~oldTagValue;
		//printw("diff = %X\n",diff);
		if( diff & SpeedUp){
			//Disable SPD DOWN
			disableTag(SlowDown);
			resetAdjustSpeed = 1;
		}

		if( diff & SlowDown ){
			//Disable SPD UP
			disableTag(SpeedUp);
			resetAdjustSpeed = 1;
		}

		if( diff & GoLeft ){
			//Disable RIGHT
			disableTag(GoRight);
			elapsedEnc[0] = 0;
			elapsedEnc[1] = 0;
		}
		
		if( diff & GoRight ){
			//Disable LEFT
			disableTag(GoLeft);
			elapsedEnc[0] = 0;
			elapsedEnc[1] = 0;
		}
		
		if( diff & EndZone){
			disableTag(SpeedUp);
			disableTag(SlowDown);
			disableTag(EndZone);
		}
	}

	if( tagValue & SpeedUp ){ //SPD UP
		setState("Go Fast");
		//adjust to target
		adjustSpeed(oldEnc[0], oldEnc[1], MAX_SPEED, resetAdjustSpeed);	 
	}
	if( tagValue & SlowDown ){ //SPD DOWN
		setState("Go Slow");
		//adjust to target
		adjustSpeed(oldEnc[0], oldEnc[1], MIN_SPEED, resetAdjustSpeed);		
	}
	if( tagValue & GoLeft ){ //LEFT
		setState("Go Left");
		//Update Encoder counts
		elapsedEnc[0] += enc[0];
		elapsedEnc[1] += enc[1];
		//Check angle
		float angle = enc2Ang(elapsedEnc[0], elapsedEnc[1]);
		switch( doTurn(angle,MIN_TURN_ANGLE,MAX_TURN_ANGLE) ){
			case 0: //Continue
				setMotorData(&motorData,32,96); //Half Speed 0-Radius Left Turn
				break;
			case 1: //Done, Proceed
				disableTag(GoLeft);
				break;
			case 2:	//Done, Blocked
				disableTag(GoLeft);
				enableTag(GoRight);
				//TODO: Handle stuck at corner situation
				break;
		} 
			
	}
	if( tagValue & GoRight ){ //RIGHT
		setState("Go Right");
		//Update Encoder counts
		elapsedEnc[0] += enc[0];
		elapsedEnc[1] += enc[1];
		//Check angle
		float angle = -enc2Ang(elapsedEnc[0], elapsedEnc[1]);
		switch( doTurn(angle,MIN_TURN_ANGLE,MAX_TURN_ANGLE) ){
			case 0: //Continue
				setMotorData(&motorData,96,32); //Half Speed 0-Radius Right Turn
				break;
			case 1: //Done, Proceed
				disableTag(GoRight);
				break;
			case 2:	//Done, Blocked
				disableTag(GoRight);
				enableTag(GoLeft);
				//TODO: Handle stuck at corner situation
				break;
		} 
		
	}

	if( tagValue & Finish ){ //FIN -- AT END TO ENSURE STOPPING IN EVENT OF OTHER TAGS
		//Stop if found line
		setMotorData(&motorData,64,64);
		//else slow down?
	}

	oldTagValue = tagValue;

	return;
}
/*!

 */
bool
Body_GoToPoint2009::execute( PlayerAgent * agent )
{
#ifdef DEBUG_PRINT
    dlog.addText( Logger::ACTION,
                  __FILE__": Body_GoToPoint2009 target=(%.2f %.2f) max_power=%.3f speed=%.3f",
                  M_target_point.x, M_target_point.y,
                  M_max_dash_power, M_dash_speed );
#endif

    if ( std::fabs( M_max_dash_power ) < 0.1
         || std::fabs( M_dash_speed ) < 0.001 )
    {
#ifdef DEBUG_PRINT
        dlog.addText( Logger::ACTION,
                      __FILE__": max_dash_power=%f dash_speed=%f, turn only",
                      M_max_dash_power, M_dash_speed );
#endif
        agent->doTurn( 0.0 );
        return false;
    }

    const WorldModel & wm = agent->world();

    const Vector2D inertia_point = wm.self().inertiaPoint( M_cycle );
    Vector2D target_rel = M_target_point - inertia_point;

    // ------------------------------------------------------------
    // already there
    double target_dist = target_rel.r();
    if ( target_dist < M_dist_thr )
    {
#ifdef DEBUG_PRINT
        dlog.addText( Logger::ACTION,
                      __FILE__": already there. inertia_point_dist=%.3f < dist_thr=%.3f",
                      target_dist, M_dist_thr );
#endif
        agent->doTurn( 0.0 ); // dumy action
        return false;
    }

    // ------------------------------------------------------------
    // omni dash
#ifdef USE_OMNI_DASH
    if ( doOmniDash( agent ) )
    {
        return true;
    }
#endif

    // ------------------------------------------------------------
    // turn
    if ( doTurn( agent ) )
    {
        return true;
    }

    // ------------------------------------------------------------
    // dash
    if ( doDash( agent ) )
    {
        return true;
    }

    agent->doTurn( 0.0 ); // dummy action
    return false;
}
示例#13
0
void Controller::handleTurnMessage(Message &msg) {
	game->handleTurnMessage(msg);
	doTurn();
}
int main(int argc,char *argv[]) {
	struct sockaddr_in server;
	int
		sock,
		port,
		err;
	char
		buff[2000];

	if (argc != 3) {
		printf("Numero de argumentos invalido\n");
		printf("Modo de uso:\n\n");
		printf("\t robot [IP] [PORT]\n\n");
		printf("\t IP: dirección ip del servidor. e.j. 127.0.0.1\n");
		printf("\t PORT: número del puerto del servidor. e.j. 5600\n\n");
		exit(-1);
	}

	sock = socket(PF_INET, SOCK_STREAM, 0);
	port = atoi(argv[2]);
	server.sin_family = AF_INET;
	server.sin_port = htons(port);
	server.sin_addr.s_addr = inet_addr(argv[1]);

	err = connect(sock, (struct sockaddr *)&server, sizeof(server));

	if (err == -1) {
		printf("No se pudo establecer la conexión con el servidor\n");
		exit(-1);
	}

	FD = fdopen(sock, "w+");

    signal(SIGCONT, s_cont);

    if (pipe(pipeFD) == -1) {
        printf("Error al inicial el pipe. pipe() returned -1\n");
        exit(-1);
    }
    
	setbuf(FD, NULL);
	initRobot();

	buff[0] = '\0';

	if (login() == FALSE) {
		printf("Error al iniciar la sesion\n");
		fclose(FD);
		exit(-1);
	}

	CONTROLLER_ID = getpid();
	ROBOT_ID = fork();

    if (ROBOT_ID == -1) {
        printf("Error al iniciar, fork() returned -1\n");
        exit(-1);
    }

	if (ROBOT_ID > 0) {
	    signal(NTFY_ROBOT_PAUSE, pausedRobot);

		// CONTROLLER
		while (_fgets(buff, 2000, FD) != NULL) {
		    debug printf("[Controller %d] msg from server: %s\n", getpid(), buff);

			if (strpos(buff, "S ACCEPTED") != -1) {
				kill(ROBOT_ID, S_ACCEPTED);
			} else if (strpos(buff, "S WIN") != -1) {
				kill(ROBOT_ID, S_WIN);
				break;
			} else if (strpos(buff, "S LOSE") != -1) {
				kill(ROBOT_ID, S_LOSE);
				break;
			} else if (strpos(buff, "S DRAW") != -1) {
				kill(ROBOT_ID, S_DRAW);
				break;
			} else if (strpos(buff, "S URTURN") != -1) {
			    if (resumeRobot() == 0) {
                    write(pipeFD[1], buff, strlen(buff) + 1);
			    }

                debug printf("[Controller %d]: Durmiendo\n", getpid());
                pause();
                debug printf("[Controller %d]: Despertado\n", getpid());
			}
		}

        kill(ROBOT_ID, SIGTERM);
		wait(ROBOT_ID);
		shutdown(sock, 2);
		fclose(FD);
		close(pipeFD[0]);
		close(pipeFD[1]);
		debug printf("## Fin del programa ##\n");
		exit(0);
	} else if (ROBOT_ID == 0) {
		// ROBOT
		ROBOT_ID = getpid();

		signal(S_ACCEPTED, s_accepted);
		signal(S_WIN, s_win);
		signal(S_LOSE, s_lose);
		signal(S_DRAW, s_draw);

    	while(1) {
			// se bloquea a la espera del tubo
    	    doTurn();
    	}
	}
}