Ejemplo n.º 1
0
Archivo: land.c Proyecto: Dinth/naev
/**
 * @brief Attempts to sell a commodity.
 *    @param wid Window selling commodity from.
 *    @param str Unused.
 */
static void commodity_sell( unsigned int wid, char* str )
{
   (void)str;
   char *comname;
   Commodity *com;
   unsigned int q;
   credits_t price;
   HookParam hparam[3];

   /* Get parameters. */
   q     = commodity_getMod();
   comname = toolkit_getList( wid, "lstGoods" );
   com   = commodity_get( comname );
   price = planet_commodityPrice( land_planet, com );

   /* Remove commodity. */
   q = pilot_cargoRm( player.p, com, q );
   price = price * (credits_t)q;
   player_modCredits( price );
   land_checkAddRefuel();
   commodity_update(wid, NULL);

   /* Run hooks. */
   hparam[0].type    = HOOK_PARAM_STRING;
   hparam[0].u.str   = comname;
   hparam[1].type    = HOOK_PARAM_NUMBER;
   hparam[1].u.num   = q;
   hparam[2].type    = HOOK_PARAM_SENTINEL;
   hooks_runParam( "comm_sell", hparam );
   if (land_takeoff)
      takeoff(1);
}
Ejemplo n.º 2
0
Archivo: land.c Proyecto: Dinth/naev
/**
 * @brief Approaches guy in mission computer.
 */
static void bar_approach( unsigned int wid, char *str )
{
   (void) str;
   int pos, n;

   /* Get position. */
   pos = toolkit_getImageArrayPos( wid, "iarMissions" );

   /* Should never happen, but in case news is selected */
   if (pos == 0)
      return;

   /* Ignore news. */
   pos--;

   n = npc_getArraySize();
   npc_approach( pos );
   bar_genList( wid ); /* Always just in case. */
   if (n == npc_getArraySize())
      toolkit_setImageArrayPos( wid, "iarMissions", pos+1 );

   /* Reset markers. */
   mission_sysMark();

   /* Mission forced take off. */
   if (land_takeoff)
      takeoff(0);
}
Ejemplo n.º 3
0
Archivo: land.c Proyecto: Dinth/naev
/**
 * @brief Wrapper for takeoff mission button.
 *
 *    @param wid Window causing takeoff.
 *    @param unused Unused.
 */
void land_buttonTakeoff( unsigned int wid, char *unused )
{
   (void) wid;
   (void) unused;
   /* We'll want the time delay. */
   takeoff(1);
}
Ejemplo n.º 4
0
Archivo: land.c Proyecto: Dinth/naev
/**
 * @brief Opens up all the land dialogue stuff.
 *    @param p Planet to open stuff for.
 *    @param load Whether or not loading the game.
 */
void land( Planet* p, int load )
{
   /* Do not land twice. */
   if (landed)
      return;

   /* Stop player sounds. */
   player_soundStop();

   /* Load stuff */
   land_planet = p;
   gfx_exterior = gl_newImage( p->gfx_exterior, 0 );

   /* Generate the news. */
   if (planet_hasService(land_planet, PLANET_SERVICE_BAR))
      news_load();

   /* Clear the NPC. */
   npc_clear();

   /* Create all the windows. */
   land_genWindows( load, 0 );

   /* Mission forced take off. */
   if (land_takeoff)
      takeoff(0);
}
Ejemplo n.º 5
0
static void
mavlink_connect_cb(void *data, struct sol_mavlink *mavlink)
{
    int err;
    enum sol_mavlink_mode mode;

    SOL_INF("mavlink connection stablished");

    mode = sol_mavlink_get_mode(mavlink);
    if (mode != SOL_MAVLINK_MODE_GUIDED) {
        err = sol_mavlink_set_mode(mavlink, SOL_MAVLINK_MODE_GUIDED);
        if (err < 0) {
            SOL_ERR("Could not set mode: %s", sol_util_strerrora(-err));
        }
        return;
    }

    if (!sol_mavlink_check_armed(mavlink)) {
        err = sol_mavlink_set_armed(mavlink, true);
        if (err < 0) {
            SOL_ERR("Could not arm vechicle: %s", sol_util_strerrora(-err));
        }
        return;
    }

    takeoff(mavlink);
}
Ejemplo n.º 6
0
Archivo: land.c Proyecto: mchelen/naev
/**
 * @brief Opens up all the land dialogue stuff.
 *    @param p Planet to open stuff for.
 *    @param load Whether or not loading the game.
 */
void land( Planet* p, int load )
{
   /* Do not land twice. */
   if (landed)
      return;

   /* Resets the player's heat. */
   pilot_heatReset( player.p );

   /* Stop player sounds. */
   player_soundStop();

   /* Load stuff */
   land_planet = p;
   gfx_exterior = gl_newImage( p->gfx_exterior, 0 );

   /* Generate the news. */
   if (planet_hasService(land_planet, PLANET_SERVICE_BAR))
      news_load();

   /* Clear the NPC. */
   npc_clear();

   /* Create all the windows. */
   land_genWindows( load, 0 );

   /* Hack so that load can run player.takeoff(). */
   if (load)
      hooks_run( "load" );

   /* Mission forced take off. */
   if (land_takeoff)
      takeoff(0);
}
Ejemplo n.º 7
0
::Ice::DispatchStatus
jderobot::Quadrotor::___takeoff(::IceInternal::Incoming& __inS, const ::Ice::Current& __current)
{
    __checkMode(::Ice::Normal, __current.mode);
    __inS.is()->skipEmptyEncaps();
    takeoff(__current);
    return ::Ice::DispatchOK;
}
Ejemplo n.º 8
0
static void
armed_cb(void *data, struct sol_mavlink *mavlink)
{
    enum sol_mavlink_mode mode;

    SOL_DBG("vehicle just armed");

    mode = sol_mavlink_get_mode(mavlink);
    if (mode == SOL_MAVLINK_MODE_GUIDED) {
        takeoff(mavlink);
    }
}
Ejemplo n.º 9
0
int
main ()
{
  int j;
  pthread_t t[30], te[3];

  printf
    ("\n This is Airport Terminal !! \n 20 Flights are going to send their request. \n In addition to that, 2 emergency landing will be shown. \n");
  sleep (2);
  printf
    (" \n After sucessful execution of Landing, the flights will be asked to take off, one by one at the interval of 2 sec.! \n");
  sleep (2);

  for (i = 0; i < 30; i++)	//WE GENERATE 30 THREADS , WHICH ARE SENDING A REQUEST TO LAND .
    {

      pthread_create (&t[i], NULL, send_request, NULL);
    }
  for (j = 0; j < 3; j++)	//THESE 3 THREADS ARE SENDING A REQUEST FOR EMERGENCY LANDING.
    {

      pthread_create (&te[j], NULL, send_emergencyrequest, NULL);

    }


  sleep (15);
  printf ("\n The landing is finished sucessfully !\n\n\n");
  sleep (2);
  takeoff ();			//ALL THE FLIGHTS WHICH HAD LANDED WILL NOW TAKEOFF.

  for (i = 0; i < 30; i++)
    {
      pthread_join (t[i], NULL);	// MAIN WAITS UNTIL ALL 30 THREADS ARE TERMINATED !
    }

  for (j = 0; j < 3; j++)
    {
      pthread_join (te[j], NULL);
    }
  printf
    ("\n All the flights have taken off.\n The Airport Terminal is free now!!\n");
  return 0;
}
Ejemplo n.º 10
0
Archivo: land.c Proyecto: Dinth/naev
/**
 * @brief Buys the selected commodity.
 *    @param wid Window buying from.
 *    @param str Unused.
 */
static void commodity_buy( unsigned int wid, char* str )
{
   (void)str;
   char *comname;
   Commodity *com;
   unsigned int q;
   credits_t price;
   HookParam hparam[3];

   /* Get selected. */
   q     = commodity_getMod();
   comname = toolkit_getList( wid, "lstGoods" );
   com   = commodity_get( comname );
   price = planet_commodityPrice( land_planet, com );
   price *= q;

   /* Check stuff. */
   if (!player_hasCredits( price )) {
      dialogue_alert( "Insufficient credits!" );
      return;
   }
   else if (pilot_cargoFree(player.p) <= 0) {
      dialogue_alert( "Insufficient free space!" );
      return;
   }

   /* Make the buy. */
   q = pilot_cargoAdd( player.p, com, q );
   player_modCredits( -price );
   land_checkAddRefuel();
   commodity_update(wid, NULL);

   /* Run hooks. */
   hparam[0].type    = HOOK_PARAM_STRING;
   hparam[0].u.str   = comname;
   hparam[1].type    = HOOK_PARAM_NUMBER;
   hparam[1].u.num   = q;
   hparam[2].type    = HOOK_PARAM_SENTINEL;
   hooks_runParam( "comm_buy", hparam );
   if (land_takeoff)
      takeoff(1);
}
Ejemplo n.º 11
0
/* ----- [ step ] ----------------------------------------------------------- */
Uint32 step(Uint32 interv,void *param)
{
    struct Var_conf *config = param;
    SDL_Rect pos;

    if(config->state == J_PLAY)
    {
	// No current piece
	if(config->pc_cur_id == PCMPTY)
	{
	    add(config);
	    if(config->state != J_LOST) disp_gamepanel(config);
	    return interv;
	}
	// A current piece
	else
	{
	    pos.x = config->piece_pos.x;
	    pos.y = config->piece_pos.y + 1;
			
	    // Check new position
	    if(check_pc(config,
			config->model,
			config->pieces[config->pc_cur_id],
			pos))
	    {
		config->piece_pos.y++;
		disp_gamepanel(config);
	    }
	    else
	    {
		// Take off current piece
		takeoff(config,config->model,&(config->pc_cur_id),
			config->piece_pos,1);
		disp_gamepanel(config);
		check(config);
	    }

	    return interv;
	}
    }
}
Ejemplo n.º 12
0
Archivo: land.c Proyecto: Dinth/naev
/**
 * @brief Saves the last place the player was.
 *
 *    @param wid Unused.
 *    @param wgt Unused.
 *    @param tab Tab changed to.
 */
static void land_changeTab( unsigned int wid, char *wgt, int tab )
{
   int i;
   (void) wid;
   (void) wgt;
   unsigned int w;
   const char *torun_hook;
   unsigned int to_visit;

   /* Sane defaults. */
   torun_hook = NULL;
   to_visit   = 0;

   /* Find what switched. */
   for (i=0; i<LAND_NUMWINDOWS; i++) {
      if (land_windowsMap[i] == tab) {
         last_window = i;
         w = land_getWid( i );

         /* Must regenerate outfits. */
         switch (i) {
            case LAND_WINDOW_MAIN:
               land_checkAddRefuel();
               break;
            case LAND_WINDOW_OUTFITS:
               outfits_update( w, NULL );
               outfits_updateQuantities( w );
               to_visit   = VISITED_OUTFITS;
               torun_hook = "outfits";
               break;
            case LAND_WINDOW_SHIPYARD:
               shipyard_update( w, NULL );
               to_visit   = VISITED_SHIPYARD;
               torun_hook = "shipyard";
               break;
            case LAND_WINDOW_BAR:
               bar_update( w, NULL );
               to_visit   = VISITED_BAR;
               torun_hook = "bar";
               break;
            case LAND_WINDOW_MISSION:
               misn_update( w, NULL );
               to_visit   = VISITED_MISSION;
               torun_hook = "mission";
               break;
            case LAND_WINDOW_COMMODITY:
               commodity_update( w, NULL );
               to_visit   = VISITED_COMMODITY;
               torun_hook = "commodity";
               break;
            case LAND_WINDOW_EQUIPMENT:
               equipment_updateShips( w, NULL );
               equipment_updateOutfits( w, NULL );
               to_visit   = VISITED_EQUIPMENT;
               torun_hook = "equipment";
               break;

            default:
               break;
         }

         /* Clear markers if closing Mission Computer. */
         if (i != LAND_WINDOW_MISSION) {
            space_clearComputerMarkers();
         }

         break;
      }
   }

   /* Check land missions - always run hooks. */
   /*if ((to_visit != 0) && !has_visited(to_visit)) {*/
   {
      /* Run hooks, run after music in case hook wants to change music. */
      if (torun_hook != NULL)
         if (hooks_run( torun_hook ) > 0)
            bar_genList( land_getWid(LAND_WINDOW_BAR) );

      visited(to_visit);

      if (land_takeoff)
         takeoff(1);
   }
}
Ejemplo n.º 13
0
/** \fn void main(void)
	\ingroup Rabbit
	\brief Fonction principal : gestion du pilotage du drone en fonctions des entrées/sorties
	\author Baudouin Feildel
	\author Thibaut Marty
**/
void main(void)
{
	etat_commandes ec;
	ardrone droneV;
	ardrone* drone = &droneV;
	char cptPassErr = 0;
	wifi_status status;
	int initOk;
	
	/// Initialise les ports de la carte et les entrées/sorties
	brdInit(); // fonction de base de Rabbit
	BRDInit(); // fonction pour les bits utilisés
	init_etat_commandes(&ec);
	lireCommandes(&ec);

	/// Crée la structure du drone
	newARDrone(drone);
	
	/// Initialise la connexion (tant que toutes les étapes ne sont pas réussies) :
	do
	{
		printf("tentative d'initialisation\n");
		initOk = 0;
		
		/// .... Initialise le driver TCP
		if(sock_init())
			printf("erreur de sock_init()\n");
		else
			initOk++;
	
		/// .... Initialise la socket de connexion avec le drone
		if(!connectToDrone(drone))
			printf("erreur connectToDrone()\n");
		else
			initOk++;
		
		/// .... Se connecte au réseau WiFi
		connexion(&ec);
		
		/// .... Initialise le drone
		if(!initDrone(drone, &ec))
			printf("erreur initDrone()\n");
		else
			initOk++;
	} while(initOk < 3);
	printf("tentative d'initialisation reussie\n");
	
	/// Vérifie que l'on n'est pas déjà en position 'vol', sinon indique à l'utilisateur de changer le switch en faisant clignoter la LED erreur
	do
	{
		costate
		{
			lireCommandes(&ec);
			yield;
		}
		costate // Fait clignoter la LED d'erreur
		{
			ec.led_erreur = ec.led_erreur ? 0 : 1;
			ecrireCommandes(&ec);
			waitfor(DelayMs(300));
		}
	} while(ec.switch_land == 0);
	
	ec.led_erreur = 0;
	ecrireCommandes(&ec);

	
	/// Boucle principale (déroulement) :
	for(;;)
	{
		/// .... Tâche de gestion des entrées/sorties et de l'envoi de commandes au drone
		costate
		{
			tcp_tick(NULL);
			
			
			// Lit les entrées
			lireCommandes(&ec);

			/// ........ Si le bouton d'arrêt d'urgence est actif :
			if(!ec.bp_arret_urgence)
			{
				/// ............ Envoie la commande d'arrêt d'urgence
				aru(drone);
				drone->fly = false;
				/// ............ Attend le relâchement du bouton en faisant clignoter la LED debug
				do
				{
					costate
					{
						lireCommandes(&ec);
						yield;
					}
					costate // Fait clignoter la LED de debug
					{
						ec.led_debug = ec.led_debug ? 0 : 1;
						ecrireCommandes(&ec);
						waitfor(DelayMs(100));
					}
					yield; // Pour la tâche de vérification de la connexion WiFi
				} while(!ec.bp_arret_urgence);
				ec.led_debug = 0;
				ecrireCommandes(&ec);
				
				/// ............ Renvoie la commande (pour sortir du mode d'arrêt d'urgence)
				aru(drone);
			}
			/// ........ Sinon (traitement de tous les cas position du switch / vol en cours) :
			else
			{
				// pour plus tard :
				// if(ec.bp_video)	{ }
				
				/// ............ Si le bouton trim est actif et que l'on n'est pas en cours de vol, réinitialise le drone
				if(!ec.bp_trim && !drone->fly)
					initDrone(drone, &ec);
				
				/// ............ Si le switch est en position haute et que l'on ne vole pas
				if(ec.switch_land == 0 && !drone->fly)
				{
					/// ................ Fait décoler le drone. S'il y a une erreur : attend que l'utilisateur repasse le switch en position basse en faisant clignoter la LED erreur
					if(!(initDrone(drone, &ec) && takeoff(drone)))
					{
						do
						{
							costate
							{
								lireCommandes(&ec);
								yield;
							}
							costate // Fait clignoter la LED d'erreur
							{
								ec.led_erreur = ec.led_erreur ? 0 : 1;
								ecrireCommandes(&ec);
								waitfor(DelayMs(100));
							}
						} while(ec.switch_land == 0);
					}
				}
				/// ............ Si le switch est en position basse et que l'on vole
				else if(ec.switch_land == 1 && drone->fly)
				{
					/// ................ Fait atterrir le drone. S'il y a une erreur : attend que l'utilisateur passe le switch en position haute
					if(!land(drone))
					{
						do
						{
							costate
							{
								lireCommandes(&ec);
								yield;
							}
							costate // Fait clignoter la LED d'erreur
							{
								ec.led_erreur = ec.led_erreur ? 0 : 1;
								ecrireCommandes(&ec);
								waitfor(DelayMs(300));
							}
						} while(ec.switch_land == 1);
					}
				}
				/// ............ Les autres cas sont normaux et ne nécessitent pas de traitement particulier


				/// ............ Si on est en vol :
				if(drone->fly)
				{
					/// ................ Traite la valeur des joysticks et la stock dans la structure ardrone
					
					     setGoUpDown(drone, (float)(ec.joystick_2x - 2048) / 2048);
					setTurnLeftRight(drone, (float)(ec.joystick_2y - 2048) / 2048);
					setTiltFrontBack(drone, (float)(ec.joystick_1x - 2048) / 2048);
					setTiltLeftRight(drone, (float)(ec.joystick_1y - 2048) / 2048);

					/// ................ Envoie la commande avec les valeurs : s'il y a une erreur on incrémente un compteur d'erreurs. Au delà de dix erreurs de suite on tente de faire atterir le drone. S'il n'y a pas d'erreurs, on attend 30ms avant le prochain envoi
					if(!(volCommand(drone, drone->tiltLeftRight, drone->tiltFrontBack, drone->goUpDown, drone->turnLeftRight)))
					{
						if(cptPassErr > 10)
							land(drone);
						else
							cptPassErr++;
					}
					else
					{
						cptPassErr = 0; // Remise à zéro du compteur d'erreur en cas de réussite
						waitfor(DelayMs(30)); // prochain envoi de commande dans 30 ms
					}
				}
				else
					yield;
			}
Ejemplo n.º 14
0
void FlyLine::localCallBack(const geometry_msgs::PoseStampedConstPtr &msg)
{
    double roll, pitch, yaw;
    tf::Quaternion q;
    tf::quaternionMsgToTF(msg->pose.orientation, q);
    tf::Matrix3x3(q).getRPY(roll, pitch, yaw);
    if(fabs(msg->pose.position.x)                       < AllowError_d
       && fabs(msg->pose.position.y)                    < AllowError_d
       && fabs(msg->pose.position.z - beginpoint_(2))   < AllowError_d
       && fabs(yaw)                                     < AllowError_rad
       && !in_line
       && !in_land)
    {
        in_line = true;
        ROS_INFO("Begin to fly line!!!");
    }
    if(in_line == false && in_land == false)
    {
        ROS_INFO("Taking off to beginpoint,  waiting line!!!! ");
        takeoff(beginpoint_);
    }
    if(in_line == true)
    {

        t_now = ros::Time::now();
        double dt = (t_now.toNSec() - t_prev.toNSec())/1e+9;
        dt = dt < 0.1 ? dt : 0;
        line_t += dt;
        if(line_t < loiter_t)
        {
            ROS_INFO("Waiting 5 second in begin point!!!");
            loiter(beginpoint_);
        }
        else if(line_t >= loiter_t && line_t <= allline_t + loiter_t)
        {
            ROS_INFO("Fly line!!!");
            line(beginpoint_, line_t, endpoint_);
        }
        else if(line_t  > allline_t + loiter_t && line_t  <= allline_t + 2 * loiter_t)
        {

                ROS_INFO("line end!!!Waiting endpoint 5 second!!!");
                loiter(endpoint_);
        }
        else
        {
            in_land = true;
            in_line = false;
        }
    }
    if(in_land == true)
    {
        ROS_INFO("it is landing!!!");
        t_now = ros::Time::now();
        double dt = (t_now.toNSec() - t_prev.toNSec())/1e+9;
        dt = dt < 0.1 ? dt : 0;
        land_t += dt;
        land(endpoint_, land_t);
    }
    t_prev = t_now;
    publish();
}
Ejemplo n.º 15
0
 void execute() override {
     takeoff();
 }
Ejemplo n.º 16
0
int
cypher(void)
{
	int n;
	int junk;
	int lflag;
	char buffer[10];

	lflag = -1;
	while (wordtype[wordnumber] == ADJS)
		wordnumber++;
	while (wordnumber <= wordcount) {
		switch (wordvalue[wordnumber]) {
		case UP:
			if (location[position].access || wiz || tempwiz) {
				if (!location[position].access)
					puts("Zap!  A gust of wind lifts you up.");
				if (!battlestar_move(location[position].up, AHEAD))
					return (-1);
			} else {
				puts("There is no way up");
				return (-1);
			}
			lflag = 0;
			break;

		case DOWN:
			if (!battlestar_move(location[position].down, AHEAD))
				return (-1);
			lflag = 0;
			break;

		case LEFT:
			if (!battlestar_move(left, LEFT))
				return (-1);
			lflag = 0;
			break;

		case RIGHT:
			if (!battlestar_move(right, RIGHT))
				return (-1);
			lflag = 0;
			break;

		case AHEAD:
			if (!battlestar_move(ahead, AHEAD))
				return (-1);
			lflag = 0;
			break;

		case BACK:
			if (!battlestar_move(back, BACK))
				return (-1);
			lflag = 0;
			break;

		case SHOOT:
			if (wordnumber < wordcount &&
			    wordvalue[wordnumber + 1] == EVERYTHING) {
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(location[position].objects,
					    n) && objsht[n]) {
						wordvalue[wordnumber + 1] = n;
						wordnumber = shoot();
					}
				wordnumber++;
				wordnumber++;
			} else
				shoot();
			break;

		case TAKE:
			if (wordnumber < wordcount &&
			    wordvalue[wordnumber + 1] == EVERYTHING) {
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(location[position].objects,
					    n) && objsht[n]) {
						wordvalue[wordnumber + 1] = n;
						wordnumber =
							take(location[position].objects);
					}
				wordnumber++;
				wordnumber++;
			} else
				take(location[position].objects);
			break;

		case DROP:
			if (wordnumber < wordcount &&
			    wordvalue[wordnumber + 1] == EVERYTHING) {
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(inven, n)) {
						wordvalue[wordnumber + 1] = n;
						wordnumber = drop("Dropped");
					}
				wordnumber++;
				wordnumber++;
			} else
				drop("Dropped");
			break;

		case KICK:
		case THROW:
			if (wordnumber < wordcount &&
			    wordvalue[wordnumber + 1] == EVERYTHING) {
				for (n = 0; n < NUMOFOBJECTS; n++) {
					if ((testbit(inven, n) ||
					     testbit(location[position].objects, n)) && objsht[n]) {
						wordvalue[wordnumber + 1] = n;
						wordnumber = throw(wordvalue[wordnumber] ==
							KICK ? "Kicked" : "Thrown");
					}
				}
				wordnumber += 2;
			} else
				throw(wordvalue[wordnumber] == KICK ? "Kicked" : "Thrown");
			break;

		case TAKEOFF:
			if (wordnumber < wordcount &&
			    wordvalue[wordnumber + 1] == EVERYTHING) {
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(wear, n)) {
						wordvalue[wordnumber + 1] = n;
						wordnumber = takeoff();
					}
				wordnumber += 2;
			} else
				takeoff();
			break;

		case DRAW:
			if (wordnumber < wordcount &&
			    wordvalue[wordnumber + 1] == EVERYTHING) {
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(wear, n)) {
						wordvalue[wordnumber + 1] = n;
						wordnumber = draw();
					}
				wordnumber += 2;
			} else
				draw();
			break;

		case PUTON:
			if (wordnumber < wordcount &&
			    wordvalue[wordnumber + 1] == EVERYTHING) {
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(location[position].objects,
					    n) && objsht[n]) {
						wordvalue[wordnumber + 1] = n;
						wordnumber = puton();
					}
				wordnumber += 2;
			} else
				puton();
			break;

		case WEARIT:
			if (wordnumber < wordcount &&
			    wordvalue[wordnumber + 1] == EVERYTHING) {
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(inven, n)) {
						wordvalue[wordnumber + 1] = n;
						wordnumber = wearit();
					}
				wordnumber += 2;
			} else
				wearit();
			break;

		case EAT:
			if (wordnumber < wordcount &&
			    wordvalue[wordnumber + 1] == EVERYTHING) {
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(inven, n)) {
						wordvalue[wordnumber + 1] = n;
						wordnumber = eat();
					}
				wordnumber += 2;
			} else
				eat();
			break;

		case PUT:
			put();
			break;

		case INVEN:
			if (ucard(inven)) {
				puts("You are holding:\n");
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(inven, n))
						printf("\t%s\n", objsht[n]);
				printf("\n= %d kilogram%s (%d%%)\n", carrying,
				       (carrying == 1 ? "." : "s."),
				       (WEIGHT ? carrying * 100 / WEIGHT : -1));
				printf("Your arms are %d%% full.\n",
				       encumber * 100 / CUMBER);
			} else
				puts("You aren't carrying anything.");

			if (ucard(wear)) {
				puts("\nYou are wearing:\n");
				for (n = 0; n < NUMOFOBJECTS; n++)
					if (testbit(wear, n))
						printf("\t%s\n", objsht[n]);
			} else
				puts("\nYou are stark naked.");
			if (card(injuries, NUMOFINJURIES)) {
				puts("\nYou have suffered:\n");
				for (n = 0; n < NUMOFINJURIES; n++)
					if (injuries[n])
						printf("\t%s\n", ouch[n]);
				printf("\nYou can still carry up to %d kilogram%s\n",
				    WEIGHT, (WEIGHT == 1 ? "." : "s."));
			} else
				puts("\nYou are in perfect health.");
			break;

		case USE:
			lflag = use();
			break;

		case LOOK:
			if (!notes[CANTSEE] || testbit(inven, LAMPON) ||
			    testbit(location[position].objects, LAMPON) ||
			    matchlight) {
				beenthere[position] = 2;
				writedes();
				printobjs();
				if (matchlight) {
					puts("\nYour match splutters out.");
					matchlight = 0;
				}
			} else
				puts("I can't see anything.");
			return (-1);
			break;

		case SU:
			if (wiz || tempwiz) {
				printf("\nRoom (was %d) = ", position);
				fgets(buffer, 10, stdin);
				if (*buffer != '\n')
					sscanf(buffer, "%d", &position);
				printf("Time (was %d) = ", gtime);
				fgets(buffer, 10, stdin);
				if (*buffer != '\n')
					sscanf(buffer, "%d", &gtime);
				printf("Fuel (was %d) = ", fuel);
				fgets(buffer, 10, stdin);
				if (*buffer != '\n')
					sscanf(buffer, "%d", &fuel);
				printf("Torps (was %d) = ", torps);
				fgets(buffer, 10, stdin);
				if (*buffer != '\n')
					sscanf(buffer, "%d", &torps);
				printf("CUMBER (was %d) = ", CUMBER);
				fgets(buffer, 10, stdin);
				if (*buffer != '\n')
					sscanf(buffer, "%d", &CUMBER);
				printf("WEIGHT (was %d) = ", WEIGHT);
				fgets(buffer, 10, stdin);
				if (*buffer != '\n')
					sscanf(buffer, "%d", &WEIGHT);
				printf("Clock (was %d) = ", gclock);
				fgets(buffer, 10, stdin);
				if (*buffer != '\n')
					sscanf(buffer, "%d", &gclock);
				printf("Wizard (was %d, %d) = ", wiz, tempwiz);
				fgets(buffer, 10, stdin);
				if (*buffer != '\n') {
					sscanf(buffer, "%d", &junk);
					if (!junk)
						tempwiz = wiz = 0;
				}
				printf("\nDONE.\n");
				return (0);
			} else
				puts("You aren't a wizard.");
			break;

		case SCORE:
			printf("\tPLEASURE\tPOWER\t\tEGO\n");
			printf("\t%3d\t\t%3d\t\t%3d\n\n", pleasure, power, ego);
			printf("This gives you the rating of %s in %d turns.\n",
			    rate(), gtime);
			printf("You have visited %d out of %d rooms this run (%d%%).\n",
			    card(beenthere, NUMOFROOMS), NUMOFROOMS,
			    card(beenthere, NUMOFROOMS) * 100 / NUMOFROOMS);
			break;

		case KNIFE:
		case KILL:
			murder();
			break;

		case UNDRESS:
		case RAVAGE:
			ravage();
			break;

		case SAVE:
			save();
			break;

		case FOLLOW:
			lflag = follow();
			break;

		case GIVE:
			give();
			break;

		case KISS:
			kiss();
			break;

		case LOVE:
			love();
			break;

		case RIDE:
			lflag = ride();
			break;

		case DRIVE:
			lflag = drive();
			break;

		case LIGHT:
			light();
			break;

		case LAUNCH:
			if (!launch())
				return (-1);
			else
				lflag = 0;
			break;

		case LANDIT:
			if (!land())
				return (-1);
			else
				lflag = 0;
			break;

		case TIME:
			chime();
			break;

		case SLEEP:
			zzz();
			break;

		case DIG:
			dig();
			break;

		case JUMP:
			lflag = jump();
			break;

		case BURY:
			bury();
			break;

		case SWIM:
			puts("Surf's up!");
			break;

		case DRINK:
			drink();
			break;

		case QUIT:
			die(0);

		default:
			puts("How's that?");
			return (-1);
			break;
		}
		if (wordnumber < wordcount && *words[wordnumber++] == ',')
			continue;
		else
			return (lflag);
	}
	return (lflag);
}
Ejemplo n.º 17
0
Archivo: ai.c Proyecto: sbusard/testris
/* ----- [ ai_best_pos ] ---------------------------------------------------- */
void ai_best_pos(struct Var_conf *config,struct model *model_tmp,
				 SDL_Rect *position, int *turning)
{
    enum Piece_bloc piece_id = config->pc_cur_id;
    enum Piece_bloc piece_next_id = config->pc_next_id;
    SDL_Rect pos;
    SDL_Rect next_pos;
    int score_tmp;
    int i = 0, j = 0, k = 0, l = 0;
    int sum = 0;
    int max_score = 0;
    // Init table of scores
    int scores[4*4][((int)PNL_LB+4)*((int)PNL_LB+4)];
    for(i = 0;i < 4*4;i++)
		for(j = 0;j < (PNL_LB+4)*(PNL_LB+4);j++)
	    	scores[i][j] = 0;
    // Init position
    pos.x = 0;
    pos.y = config->piece_pos.y;

    // Checking each configuration
    //	    checking each position
    //		checking holes
    //		checking lines
    //	    checking each rotation
    //		checking holes
    //		checking lines
    for(i = 0;i < 4;i++)
    {
	for(j = 0;j < PNL_LB+4;j++)
	{
	    // Update position
	    pos.x = j-4;
	    pos.y = config->piece_pos.y;

	    score_tmp = ai_score_pos(config,model_tmp,piece_id,pos);

	    for(k = 0;k < 4;k++)
		for(l = 0;l < PNL_LB+4;l++)
		    scores[i*4+k][(int)(j*(PNL_LB+4)+l)] = score_tmp;

	    // Get dropped position
	    if(check_pc(config,model_tmp,config->pieces[piece_id],pos))
	    {
		while(check_pc(config,model_tmp,config->pieces[piece_id],pos)
		      && pos.y != PNL_HB)
		    pos.y++;
		    pos.y--;

		// Take off piece in temporary model
		takeoff(config,model_tmp,&piece_id,pos,0);

		// Remove lines
		remove_lines(config,model_tmp,0);

		// Get next piece
		piece_next_id = config->pc_next_id;

		// For all turns
		for(k = 0;k < 4;k++)
		{
		    // For all positions
		    for(l = 0;l < (PNL_LB+4);l++)
		    {
			// Get new position
			next_pos.x = l-4;
			next_pos.y = 1;

			// Calculate score for new piece position
			score_tmp = ai_score_pos(config,model_tmp,
						 piece_next_id,next_pos);
			scores[i*4+k][(int)(j*(PNL_LB+4)+l)] += score_tmp;
		    }
		    // Turn new piece
		    next_pos.x = config->piece_pos.x;
		    turn(config,model_tmp,&piece_next_id,&next_pos,HORLO,0,0);
		}

		// Copy model
		for(k = 0;k < PNL_HB;k++)
		    for(l = 0;l < PNL_LB;l++)
		    model_set(model_tmp,k,l,model_get(config->model,k,l));
	    }
	}

	// Turn
	turn(config,model_tmp,&piece_id,&(config->piece_pos),
	     HORLO,0,0);    
    }

    // Get best position
    pos.x = 0;
    *turning = 0;
    max_score = scores[0][0];
    for(i = 0;i < 4;i++)
    {
	for(j = 0;j < PNL_LB+4;j++)
	{
	    for(k = 0;k < 4;k++)
		for(l = 0;l < (PNL_LB+4);l++)
		//printf("%d ",scores[i][j]);
		if(scores[i*4+k][(int)(j*(PNL_LB+4)+l)] > max_score)
		{
		    max_score = scores[i*4+k][(int)(j*(PNL_LB+4)+l)];
		    pos.x = j-4;
		    *turning = i;
		}
	}
	//printf("\n");
    }

    // Print scores table
    /*for(i = 0;i < 4;i++)
    {
	for(j = 0;j < PNL_LB+4;j++)
	{
	    for(k = 0;k < 4;k++)
	    {
		for(l = 0;l < PNL_LB+4;l++)
		{
		    if( 3 < j & j < 10) printf("%d ",scores[i*4+k][(int)(j*(PNL_LB+4)+l)]);
		}
		if( 3 < j & j < 10) printf("\n");
	    }
	    if( 3 < j & j < 10) printf("\n\n");
	}
	if( 3 < j & j < 10) printf("\n\n");
    }*/
    position->x = pos.x;
    //printf("i = %d j = %d \n",pos->x,*turning);
}