Esempio n. 1
0
bool NSParser::readActionOrVar(Symbol *symbol, NSParser::VariableList &variables, int &actionId, int &param, int &time)
{
	bool result = false;
	if (symbol->type == NON_TERMINAL)
	{
		result = true;
		if (symbol->symbolIndex == SYM_ACTION2)
			readAction(symbol, actionId, param, time);
		else if (symbol->symbolIndex == SYM_VAR)
			result = readActionVar(symbol, variables, actionId, param, time);
		else //SYM_ACTION_OR_VAR
		{
			NonTerminal* nt = static_cast<NonTerminal*>(symbol);
			switch(nt->ruleIndex)
			{
				case PROD_ACTION_OR_VAR:
					readAction(symbol, actionId, param, time);
					break;
				case PROD_ACTION_OR_VAR2:
					result = readActionVar(symbol, variables, actionId, param, time);
					break;
				default:
					result = false;
					break;
			}
		}
	}

	return result;
}
Esempio n. 2
0
//read a state
void readState(int index){
	int i, aux;
	char a;
	
	states[index].id = index;
	//read the state parameters
	scanf("%f %d %d", &states[index].reward, &aux, &states[index].n_actions);
	
	if(aux == 1)
		states[index].n_actions = 0;
		
	i = 0;
	while(i < states[index].n_actions){
		a = getchar();
		
		if(a == '#')
			ignoreComments();
			
		else if(a == 45 || (a > 47 && a < 58)){
			ungetc(a, stdin);
			readAction(index, i);
			i++;
		}
	}
}
Esempio n. 3
0
Golem::Golem(Vec2f _pos, Vec2f _size) :
	Enemy(_pos, _size)
{
	std::string pattern("res/Texture/Enemy/golem_pattern.txt");
	std::string action("res/Texture/Enemy/golem_animation.txt");
	readPatterns(pattern);
	readAction(action);

	std::string register_key("golem");
	std::string resourse("res/Texture/Enemy/golemMotion.png");
	Textures::set(register_key, resourse);
}
Esempio n. 4
0
Slime::Slime(Vec2f _pos, Vec2f _size) :
	Enemy(_pos, _size)
{
	std::string pattern("res/Texture/Enemy/slime_pattern.txt");
	std::string action("res/Texture/Enemy/slime_animation.txt");
	readPatterns(pattern);
	readAction(action);

	std::string register_key("slime");
	std::string resourse("res/Texture/Enemy/slimeMotion.png");
	Textures::set(register_key, resourse);
	vec_.x() = 0.5f;
}
Esempio n. 5
0
void Resource::readRule(Common::File *file, RuleList &rules) {
	rules.clear();
	while (file->readByte() == 1) {
		rules.push_back(Rule());
		Rule &rule = rules.back();

		rule._ruleType = (RuleType)file->readSint16LE();
		rule._param1 = file->readSint16LE();
		rule._param2 = file->readSint16LE();
		rule._condition = readConditions(file);
		readAction(file, rule._actionList);
	}
}
Esempio n. 6
0
void NetworkClient::readTable() {
    // Command get table
    // 4 octets Devices number
    // 4 octets Name size
    // x octets Name
    // 4 octets Type size
    // x octets Type name
    // 4 octets Action number
    
    int magic = read4FromByteStream(readStream);
    int globalSize = read4FromByteStream(readStream);
    char command = read1FromByteStream(readStream);
    
    (void)magic;
    (void)globalSize;
    (void)command;
    
    //System.out.println("Magic 0x" + Integer.toHexString(magic));
    //System.out.println("Global size " + globalSize);
    //System.out.println("Command " + command);
    
    int numDevices = read4FromByteStream(readStream);
    
    for(int i=0; i<numDevices; i++) {
        
        int nameSize = read4FromByteStream(readStream);
        char *name = (char*)malloc(nameSize);
        readBufferFromByteStream(readStream, (unsigned char*)name, nameSize);
        
        int typeSize = read4FromByteStream(readStream);
        char *type = (char*)malloc(typeSize);
        readBufferFromByteStream(readStream, (unsigned char*)type, typeSize);
        
        printf("Name %d : %s\n", nameSize, name);
        printf("Type %d : %s\n", typeSize, type);

        Device* device = (Device*)GlobalFactory::addComponent(name, type);
        
        int numActions = read4FromByteStream(readStream);
        for(int j=0; j<numActions; j++) {
            readAction(device);
        }
    }
}
Esempio n. 7
0
bool NSParser::readCallArg(Symbol *symbol, VariableList &variables, NSParser::DeclaredVariable& callArgVariable)
{
	bool result = true;
	switch(symbol->symbolIndex)
	{
		case SYM_VAR:
		{
			QString name = readVar(symbol);
			if (variables.contains(name))
				callArgVariable = variables[name];
			else
			{
				addError(NSParsingError::undeclaredVariableError(name, symbol));
				result = false;
			}
			break;
		}
		case SYM_POINT:
		case SYM_FIXED_POINT:
		{
			Tools::RPoint p = readPoint(symbol);
			callArgVariable = DeclaredVariable::fromPoint(p);
			break;
		}
		case SYM_RECT2:
		case SYM_FIXED_RECT:
		{
			QRectF r = readRect(symbol, variables);
			callArgVariable = DeclaredVariable::fromRect(r);
			break;
		}
		case SYM_SENSOR_IDENTIFIER:
		{
			int type = -1, id = 0;
			readSensorIdentifier(symbol, type, id);
			callArgVariable = DeclaredVariable::fromSensor(id, type);
			break;
		}
		case SYM_PARAMETER_IDENTIFIER:
		{
			int paramId = readSubId(symbol);
			callArgVariable = DeclaredVariable::fromParameter(paramId);
			break;
		}
		case SYM_AX12_IDENTIFIER:
		{
			int ax12Id = readSubId(symbol);
			callArgVariable = DeclaredVariable::fromAx12(ax12Id);
			break;
		}
		case SYM_ACTION2:
		{
			int actionId, param, time;
			readAction(symbol, actionId, param, time);
			callArgVariable = DeclaredVariable::fromAction(actionId, param, time);
			break;
		}
		case SYM_STRING:
		{
			QString str = readString(symbol);
			callArgVariable = DeclaredVariable::fromString(str);
			break;
		}
		case SYM_CALLARG:
		{
			if (symbol->type == NON_TERMINAL)
			{
				result = false;
				NonTerminal* nt = static_cast<NonTerminal*>(symbol);
				for(Symbol* child: nt->children)
				{
					readCallArg(child, variables, callArgVariable);
					if (callArgVariable.isValid())
					{
						result = true;
						break;
					}

				}
			}
		}
	}

	return result;
}
Esempio n. 8
0
/* returns >= 0 if match should continue, -1 for failure */
static int processTransactionFile( const Game *game, const int fixedSeats,
				   uint32_t *handId, uint8_t *player0Seat,
				   rng_state_t *rng, ErrorInfo *errorInfo,
				   double totalValue[ MAX_PLAYERS ],
				   MatchState *state, FILE *file )
{
  int c, r;
  uint32_t h;
  uint8_t s;
  Action action;
  struct timeval sendTime, recvTime;
  char line[ MAX_LINE_LEN ];

  while( fgets( line, MAX_LINE_LEN, file ) ) {

    /* get the log entry */

    /* ACTION */
    c = readAction( line, game, &action );
    if( c < 0 ) {

      fprintf( stderr, "ERROR: could not parse transaction action %s", line );
      return -1;
    }

    /* ACTION HANDID SEND RECV */
    if( sscanf( &line[ c ], " %"SCNu32" %zu.%06zu %zu.%06zu%n", &h,
		&sendTime.tv_sec, &sendTime.tv_usec,
		&recvTime.tv_sec, &recvTime.tv_usec, &r ) < 4 ) {

      fprintf( stderr, "ERROR: could not parse transaction stamp %s", line );
      return -1;
    }
    c += r;

    /* check that we're processing the expected handId */
    if( h != *handId ) {

      fprintf( stderr, "ERROR: handId mismatch in transaction log: %s", line );
      return -1;
    }

    /* make sure the action is valid */
    if( !isValidAction( game, &state->state, 0, &action ) ) {

      fprintf( stderr, "ERROR: invalid action in transaction log: %s", line );
      return -1;
    }

    /* check for any timeout issues */
    s = playerToSeat( game, *player0Seat,
		      currentPlayer( game, &state->state ) );
    if( checkErrorTimes( s, &sendTime, &recvTime, errorInfo ) < 0 ) {

      fprintf( stderr,
	       "ERROR: seat %"PRIu8" ran out of time in transaction file\n",
	       s + 1 );
      return -1;
    }

    doAction( game, &action, &state->state );

    if( stateFinished( &state->state ) ) {
      /* hand is finished */

      /* update the total value for each player */
      for( s = 0; s < game->numPlayers; ++s ) {

	totalValue[ s ]
	  += valueOfState( game, &state->state,
			   seatToPlayer( game, *player0Seat, s ) );
      }

      /* move on to next hand */
      if( setUpNewHand( game, fixedSeats, handId, player0Seat,
			rng, errorInfo, &state->state ) < 0 ) {

	return -1;
      }
    }
  }

  return 0;
}
Esempio n. 9
0
/* returns >= 0 if action/size has been set to a valid action
   returns -1 for failure (disconnect, timeout, too many bad actions, etc) */
static int readPlayerResponse( const Game *game,
			       const MatchState *state,
			       const int quiet,
			       const uint8_t seat,
			       const struct timeval *sendTime,
			       ErrorInfo *errorInfo,
			       ReadBuf *readBuf,
			       Action *action,
			       struct timeval *recvTime )
{
  int c, r;
  MatchState tempState;
  char line[ MAX_LINE_LEN ];

  while( 1 ) {

    /* read a line of input from player */
    struct timeval start;
    gettimeofday( &start, NULL );
    if( getLine( readBuf, MAX_LINE_LEN, line,
		 errorInfo->maxResponseMicros ) <= 0 ) {
      /* couldn't get any input from player */

      struct timeval after;
      gettimeofday( &after, NULL );
      uint64_t micros_spent =
	(uint64_t)( after.tv_sec - start.tv_sec ) * 1000000
	+ ( after.tv_usec - start.tv_usec );
      fprintf( stderr, "ERROR: could not get action from seat %"PRIu8"\n",
	       seat + 1 );
      // Print out how much time has passed so we can see if this was a
      // timeout as opposed to some other sort of failure (e.g., socket
      // closing).
      fprintf( stderr, "%.1f seconds spent waiting; timeout %.1f\n",
	       micros_spent / 1000000.0,
	       errorInfo->maxResponseMicros / 1000000.0);
      return -1;
    }

    /* note when the message arrived */
    gettimeofday( recvTime, NULL );

    /* log the response */
    if( !quiet ) {
      fprintf( stderr, "FROM %d at %zu.%06zu %s", seat + 1,
	       recvTime->tv_sec, recvTime->tv_usec, line );
    }

    /* ignore comments */
    if( line[ 0 ] == '#' || line[ 0 ] == ';' ) {
      continue;
    }

    /* check for any timeout issues */
    if( checkErrorTimes( seat, sendTime, recvTime, errorInfo ) < 0 ) {

      fprintf( stderr, "ERROR: seat %"PRIu8" ran out of time\n", seat + 1 );
      return -1;
    }

    /* parse out the state */
    c = readMatchState( line, game, &tempState );
    if( c < 0 ) {
      /* couldn't get an intelligible state */

      fprintf( stderr, "WARNING: bad state format in response\n" );
      continue;
    }

    /* ignore responses that don't match the current state */
    if( !matchStatesEqual( game, state, &tempState ) ) {

      fprintf( stderr, "WARNING: ignoring un-requested response\n" );
      continue;
    }

    /* get the action */
    if( line[ c++ ] != ':'
	|| ( r = readAction( &line[ c ], game, action ) ) < 0 ) {

      if( checkErrorInvalidAction( seat, errorInfo ) < 0 ) {

	fprintf( stderr, "ERROR: bad action format in response\n" );
      }

      fprintf( stderr,
	       "WARNING: bad action format in response, changed to call\n" );
      action->type = a_call;
      action->size = 0;
      goto doneRead;
    }
    c += r;

    /* make sure the action is valid */
    if( !isValidAction( game, &state->state, 1, action ) ) {

      if( checkErrorInvalidAction( seat, errorInfo ) < 0 ) {

	fprintf( stderr, "ERROR: invalid action\n" );
	return -1;
      }

      fprintf( stderr, "WARNING: invalid action, changed to call\n" );
      action->type = a_call;
      action->size = 0;
    }

    goto doneRead;
  }

 doneRead:
  return 0;
}
Esempio n. 10
0
void* client_connect(void* info){
    thread_info* new_info = (thread_info* )info;
    int sockfd = new_info -> sockfd;
    std::string addr = new_info -> address;
    int port = new_info -> port;

    std::cout << sockfd << " " << addr << " " << port << '\n';
    /*int read_size;
    char client_message[2000];
    char welcome_message[200];
    strcpy(welcome_message, "Welcome to simple P2P server !\n");

    write(sockfd, welcome_message, strlen(welcome_message));
	//test block

	login::Login login;
	login.set_id("testID");
	login.set_passwd("testPasswd");
	int pkg_size = login.ByteSize() + 4;
	char* pkt = new char[pkg_size];
	google::protobuf::io::ArrayOutputStream aos(pkt, pkg_size);
	google::protobuf::io::CodedOutputStream* coded_output = new google::protobuf::io::CodedOutputStream(&aos);
	coded_output -> WriteVarint32(login.ByteSize());
	login.SerializeToCodedStream(coded_output);

	write(sockfd, pkt, pkg_size);*/
	//test block
    update();
    login::Login login;
    while( true ){
        int count;
        char buffer[4];
        count = recv(sockfd, buffer, 4, MSG_PEEK);
        if(count == -1)
            perror("Recv with error");
        else{
            ACTION request;
            request = readAction(sockfd, readHdr(buffer));
            if ( request == LOGIN ) {
                login = login_check(sockfd, addr, port);
            } else if ( request == REGIST ) {
                regist_check(sockfd);
            } else if ( request == DELETEACCOUNT ) {
                delete_account(sockfd);
            } else if ( request == SEARCHINFO ) {
                search_info(sockfd);
            } else if ( request == DOWNLOAD ) {
                download_p2p(sockfd);
            } else if ( request == CHAT ) {
                chat(sockfd);
            } else if (request == LOGOUT ) {
                logout(sockfd, file_sets);
                break;
            } else if (request == RECVFILEINFO ) {
                recv_file_info(sockfd, file_sets, login);
            } else if (request == ONLINEINFO){
                send_online_info(sockfd);
            } else if (request == PORTREQUEST) {
                //send_port(sockfd);
            } else {
                printf("%sBugssssssssssss%s\n", ANSI_COLOR_RED, ANSI_COLOR_RESET);
            }
        }
    }


    /*while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 ){
		client_message[read_size] = '\0';
        write(sock , client_message , strlen(client_message));
		memset(client_message, 0, 2000);
    }

    if(read_size == 0) {
        puts("Client disconnected");
        fflush(stdout);
    }else if(read_size == -1){
        perror("recv failed");
    }*/
    //printf("Connection left\n");
    return 0;
}
Esempio n. 11
0
bool Server::read(MsgData& message, ServerPlayer &player) {
    MsgType msgType;
    MsgData messageCopy(message);

    bool isRead(false);

    message >> msgType;
    std::cout << "[Serv][Read][Start] \t Read message(" << static_cast<int> (msgType) << ") from " << player.getName() << std::endl;
    switch (msgType) {
        case MsgType::Action:
            if (m_stateInWait)
                return readAction(message, player);
            break;
        case MsgType::ClientPlayerInfo:
        {
            // Receive info from Client
            std::cout << "[Serv][Read] \t Read ClientPlayerInfo" << std::endl;
            //            auto msgCPI = static_cast<MsgClientPlayerInfo> (*message);
            sf::Uint16 sfPort;
            std::string name;
            message >> sfPort >> name;
            //            std::cout << "[Serv][Read] \t cast done : " << msgCPI << std::endl;
            player.setUdpPort(sfPort);
            player.setName(name);
            std::cout << "[Serv][Read] \t Read info client(" << player.getName() << "@" << player.getAddress().toString() << ":" << player.getUdpPort() << ")" << std::endl;
            // Send info to Client

            unsigned short port = m_network.getUDPManager().getPort();
            MsgData msgServer;
            msgServer << MsgType::ServerPlayerInfo << sf::Uint16(port) << sf::Int16(player.getId());
            std::cout << "[Serv][Read] \t Send info serv. ServUdpPort(" << port << "), playerId(" << sf::Int16(player.getId()) << ")" << std::endl;
            m_network.getTCPManager().send(msgServer, player.getTCPSocket());
            m_players.setPlayerReady(player);
            isRead = true;
        }
            break;
        case MsgType::Acknowledgment:
        {
            std::cout << "Ack" << std::endl;
            m_acknowledgment.release();
            isRead = true;
        }
            break;
        case MsgType::Disconnect:
        {
            isRead |= readDisconnect(message, player);
        }
            break;
        case MsgType::Undef:
        {
            std::cout << "Undefined" << std::endl;
        }
            break;
        default:
        {
        }
    }

    if (m_game)
        isRead = m_game->read(messageCopy, player);

    return isRead;
}
Esempio n. 12
0
/* returns >= 0 if action/size has been set to a valid action
   returns -1 for failure (disconnect, timeout, too many bad actions, etc) */
static int readPlayerResponse( const Game *game, const MatchState *state,
			       const int quiet, const uint8_t seat,
			       const struct timeval *sendTime,
			       ErrorInfo *errorInfo,
			       int seatFD, ReadBuf *readBuf,
			       Action *action, struct timeval *recvTime )
{
  int c, r;
  MatchState tempState;
  char line[ MAX_LINE_LEN ];

  while( 1 ) {

    /* read a line of input from player */
    if( getLine( seatFD, readBuf, MAX_LINE_LEN, line,
		 errorInfo->maxResponseMicros ) <= 0 ) {
      /* couldn't get any input from player */

      fprintf( stderr, "ERROR: could not get action from seat %"PRIu8"\n",
	       seat + 1 );
      return -1;
    }

    /* note when the message arrived */
    gettimeofday( recvTime, NULL );

    /* log the response */
    if( !quiet ) {
      fprintf( stderr, "FROM %d at %zu.%06zu %s", seat + 1,
	       recvTime->tv_sec, recvTime->tv_usec, line );
    }

    /* ignore comments */
    if( line[ 0 ] == '#' || line[ 0 ] == ';' ) {
      continue;
    }

    /* check for any timeout issues */
    if( checkErrorTimes( seat, sendTime, recvTime, errorInfo ) < 0 ) {

      fprintf( stderr, "ERROR: seat %"PRIu8" ran out of time\n", seat + 1 );
      return -1;
    }

    /* parse out the state */
    c = readMatchState( line, game, &tempState );
    if( c < 0 ) {
      /* couldn't get an intelligible state */

      fprintf( stderr, "WARNING: bad state format in response\n" );
      continue;
    }

    /* ignore responses that don't match the current state */
    if( !matchStatesEqual( game, state, &tempState ) ) {

      fprintf( stderr, "WARNING: ignoring un-requested response\n" );
      continue;
    }

    /* get the action */
    if( line[ c++ ] != ':'
	|| ( r = readAction( &line[ c ], game, action ) ) < 0 ) {

      if( checkErrorInvalidAction( seat, errorInfo ) < 0 ) {

	fprintf( stderr, "ERROR: bad action format in response\n" );
      }

      fprintf( stderr,
	       "WARNING: bad action format in response, changed to call\n" );
      action->type = call;
      action->size = 0;
      goto doneRead;
    }
    c += r;

    /* make sure the action is valid */
    if( !isValidAction( game, &state->state, 1, action ) ) {

      if( checkErrorInvalidAction( seat, errorInfo ) < 0 ) {

	fprintf( stderr, "ERROR: invalid action\n" );
	return -1;
      }

      fprintf( stderr, "WARNING: invalid action, changed to call\n" );
      action->type = call;
      action->size = 0;
    }

    goto doneRead;
  }

 doneRead:
  return 0;
}