Chat TelegramCache::readChat(const Peer &peer) const
{
    const QString folderPath = p->path + "/chats";
    const QString filePath = folderPath + "/" + QCryptographicHash::hash(TelegramTools::identifier(peer),
                                                                         QCryptographicHash::Md5).toHex();
    const QMap<QString, QVariant> &map = readMap(filePath);
    return Chat::fromMap(map);
}
Beispiel #2
0
Map *MapReader::readMap(const std::string &filename)
{
    logger->log("Attempting to read map %s", filename.c_str());
    // Load the file through resource manager
    ResourceManager *resman = ResourceManager::getInstance();
    int fileSize;
    void *buffer = resman->loadFile(filename, fileSize);
    Map *map = NULL;

    if (buffer == NULL)
    {
        logger->log("Map file not found (%s)", filename.c_str());
        return NULL;
    }

    unsigned char *inflated;
    unsigned int inflatedSize;

    if (filename.find(".gz", filename.length() - 3) != std::string::npos)
    {
        // Inflate the gzipped map data
        inflatedSize =
            inflateMemory((unsigned char*) buffer, fileSize, inflated);
        free(buffer);

        if (inflated == NULL)
        {
            logger->log("Could not decompress map file (%s)",
                    filename.c_str());
            return NULL;
        }
    }
    else
    {
        inflated = (unsigned char*) buffer;
        inflatedSize = fileSize;
    }

    XML::Document doc((char*) inflated, inflatedSize);
    free(inflated);

    xmlNodePtr node = doc.rootNode();

    // Parse the inflated map data
    if (node)
    {
        if (!xmlStrEqual(node->name, BAD_CAST "map"))
            logger->log("Error: Not a map file (%s)!", filename.c_str());
        else
            map = readMap(node, filename);
    }
    else
        logger->log("Error while parsing map file (%s)!", filename.c_str());

    if (map) map->setProperty("_filename", filename);

    return map;
}
Beispiel #3
0
static int getMapNames(char *nameBuffer)
{
	// Look in the keymap directory for keymap files.

	int status = 0;
	file theFile;
	char *fileName = NULL;
	keyMap *map = NULL;
	int bufferChar = 0;
	int count;

	fileName = malloc(MAX_PATH_NAME_LENGTH);
	map = malloc(sizeof(keyMap));
	if (!fileName || !map)
		return (status = ERR_MEMORY);

	nameBuffer[0] = '\0';
	numMapNames = 0;

	// Loop through the files in the keymap directory
	for (count = 0; ; count ++)
	{
		if (count)
			status = fileNext(cwd, &theFile);
		else
			status = fileFirst(cwd, &theFile);

		if (status < 0)
			break;

		if (theFile.type != fileT)
			continue;

		if (strcmp(cwd, "/"))
		{
			snprintf(fileName, MAX_PATH_NAME_LENGTH, "%s/%s", cwd,
				theFile.name);
		}
		else
		{
			snprintf(fileName, MAX_PATH_NAME_LENGTH, "/%s", theFile.name);
		}

		status = readMap(fileName, map);
		if (status < 0)
			// Not a keymap file we can read.
			continue;

		strncpy((nameBuffer + bufferChar), map->name, sizeof(map->name));
		bufferChar += (strlen(map->name) + 1);
		numMapNames += 1;
	}

	free(fileName);
	free(map);
	return (status = 0);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
bool DataContainerArrayProxy::readJson(QJsonObject& json)
{
  if (json["Data Containers"].isArray())
  {
    dataContainers = readMap(json["Data Containers"].toArray());
    return true;
  }
  return false;
}
Beispiel #5
0
/**
 * Allocate and initialize the GDB structure, read the "map.txt" file
 * but don't look for kit folders themselves.
 */
void GDB::load()
{
	GDB_DEBUG_OPEN(wlog,this->dir);
	GDB_DEBUG(wlog,(slog,L"Loading GDB...\n"));

    // process kit map file
    hash_map<WORD,wstring> mapFile;
    if (!readMap((this->dir + L"GDB\\uni\\map.txt").c_str(), mapFile))
    {
        GDB_DEBUG(wlog,(slog,L"Unable to find uni-map: %s\n",mapFile));
        LOG1S(L"Couldn't open uni-map for reading: {%s}",(this->dir + L"GDB\\uni\\map.txt").c_str());
    }

    for (hash_map<WORD,wstring>::iterator it = mapFile.begin(); it != mapFile.end(); it++)
    {
        KitCollection kitCol(it->second);

        // strip off leading and trailing spaces
        string_strip(kitCol.foldername);

        // strip off quotes, if present
        if (kitCol.foldername[0]=='"' || kitCol.foldername[0]=='\'')
            kitCol.foldername.erase(0,1);
        int last = kitCol.foldername.length()-1;
        if (kitCol.foldername[last]=='"' || kitCol.foldername[last]=='\'')
            kitCol.foldername.erase(last);

        GDB_DEBUG(wlog,(slog,L"teamId = {%d}, foldername = {%s}\n", 
                    it->first, kitCol.foldername.c_str()));

        // store in the "uni" map
        this->uni.insert(pair<WORD,KitCollection>(it->first,kitCol));

        // find kits for this team
        this->findKitsForTeam(it->first);
    }

    // create two dummy kit collections: for use with AFS kits
    Kit dummyKit;
    dummyKit.configLoaded = true;

    this->dummyHome.players.insert(pair<wstring,Kit>(L"pa",dummyKit));
    this->dummyHome.players.insert(pair<wstring,Kit>(L"pb",dummyKit));
    this->dummyHome.goalkeepers.insert(pair<wstring,Kit>(L"ga",dummyKit));
    this->dummyHome.goalkeepers.insert(pair<wstring,Kit>(L"gb",dummyKit));
    this->dummyHome.loaded = true;

    this->dummyAway.players.insert(pair<wstring,Kit>(L"pa",dummyKit));
    this->dummyAway.players.insert(pair<wstring,Kit>(L"pb",dummyKit));
    this->dummyAway.goalkeepers.insert(pair<wstring,Kit>(L"ga",dummyKit));
    this->dummyAway.goalkeepers.insert(pair<wstring,Kit>(L"gb",dummyKit));
    this->dummyAway.loaded = true;

	GDB_DEBUG(wlog,(slog,L"Loading GDB complete.\n"));
    GDB_DEBUG_CLOSE(wlog);
}
Beispiel #6
0
static int findMapFile(const char *mapName, char *fileName)
{
	// Look in the current directory for the keymap file with the supplied map
	// name

	int status = 0;
	file theFile;
	keyMap *map = NULL;
	int count;

	map = malloc(sizeof(keyMap));
	if (!map)
		return (status = ERR_MEMORY);

	memset(&theFile, 0, sizeof(file));

	// Loop through the files in the keymap directory
	for (count = 0; ; count ++)
	{
		if (count)
			status = fileNext(cwd, &theFile);
		else
			status = fileFirst(cwd, &theFile);

		if (status < 0)
			// No more files.
			break;

		if (theFile.type != fileT)
			continue;

		if (strcmp(cwd, "/"))
			snprintf(fileName, MAX_PATH_NAME_LENGTH, "%s/%s", cwd, theFile.name);
		else
			snprintf(fileName, MAX_PATH_NAME_LENGTH, "/%s", theFile.name);

		status = readMap(fileName, map);
		if (status < 0)
			continue;

		if (!strncmp(map->name, mapName, sizeof(map->name)))
		{
			status = 0;
			goto out;
		}
	}

	// If we fall through to here, it wasn't found.
	fileName[0] = '\0';
	status = ERR_NOSUCHENTRY;

out:
	free(map);
	return (status);
}
Beispiel #7
0
uint16_t generateLevel(uint8_t* m, uint8_t w, uint8_t h, uint16_t length)
{
	uint16_t d = w*h;

	uint8_t ver[] = {1,1,0,2};
	uint8_t hor[] = {0,2,1,1};

	uint8_t tries = 0;
	uint8_t best[d];
	uint16_t l=0, maxl=0;
	do {
		for (uint16_t i=0; i<d; i++) m[i]=0;

		tries++;
		uint8_t x=0, y=0;
		l=0;

		while (l<length) {
			if (readMap(m,w,h,x+1,y)==3 && readMap(m,w,h,x+w-1,y)==3 && readMap(m,w,h,x,y+1)==3 && readMap(m,w,h,x,y+h-1)==3) break;
			l++;

			uint8_t newX=0, newY=0;
			do {
				uint8_t k = rand()%4;
				newX = (x+w+hor[k]-1)%w;
				newY = (y+h+ver[k]-1)%h;
			} while (readMap(m,w,h,newX,newY)==3);

			x = newX;
			y = newY;
			m[y*w+x]++;
		}

		if (l>maxl) {
			maxl = l;
			memcpy(best, m, d);
		}
	} while (tries<15);

	memcpy(best, m, d);
	return maxl;
}
Beispiel #8
0
static int loadLevels() {
	Uint8 i, j, k;
	FILE *levList = fopen(br_find_data("levlist.dat"), "r");
	char buf[32];

	if(levList) {
		i = 0;
		while(!feof(levList)) {
			(void)fgets(buf, 32, levList);
			if(strlen(buf)) {
				buf[strlen(buf)-1] = 0;
				strcpy((&levels[i])->name, buf);
				if(readMap(&levels[i])) i++;
			}
		}
		(void)fclose(levList);
	}
	else {
		printf("Couldn't find '%s': generating levels\n", br_find_data("levlist.dat"));
		state->level = 0;
		for(k=0; k<16; k++) {
			levels[k].inited = 1;
			if(k <= 5) {
				levels[k].fieldWidth = 5;
				levels[k].fieldHeight = 8;
			}
			else if(k <= 10) {
				levels[k].fieldWidth = 6;
				levels[k].fieldHeight = 10;
			}
			else {
				levels[k].fieldWidth = 7;
				levels[k].fieldHeight = 12;
			}
			levels[k].target = 5;
			levels[k].px = levels[k].fieldWidth / 2;
			levels[k].py = levels[k].fieldHeight - 2;
			for(i=0; i<levels[k].fieldHeight/4; i++) {
				for(j=0; j<levels[k].fieldWidth; j++) {
					levels[k].blocks[j][i] = rand()/(RAND_MAX/3);
				}
			}
			for(i=levels[k].fieldHeight/4; i<levels[k].fieldHeight; i++) {
				for(j=0; j<levels[k].fieldWidth; j++) {
					levels[k].blocks[j][i] = BT_NULL;
				}
			}
		}
	}

	return 1;
}
Beispiel #9
0
// -----------------------------------------------------------------
// Name : readAny
// -----------------------------------------------------------------
JoS_Element * JoSon::readAny(std::stringstream * stream)
{
	char nextc = getNextChar(stream);
	switch (nextc) {
	case '{':
		return readMap(stream);
	case '[':
		return readList(stream);
	default:
		streamUnget(stream);
		return readLeaf(stream);
	}
}
Beispiel #10
0
	void handle_file(const boost::system::error_code& e, connection_ptr conn,string nameFile)	{
		if (!e)	{	// lecture des informations
			db::DataBaseType<MySQL> dbMySQL("root", "", "mycloud") ;
			string idMySQL;
			for(model::info i : infos)	{
				idMySQL = dbMySQL.getUser(i.getAddressMail(), i.getPwd());
			}
			File file("/home/steven/server/",idMySQL);
			std::string path="/home/steven/client/" + idMySQL + nameFile;
			std::stringstream data_in;
			data_in << readMap(path.c_str());
			conn->socket().send(boost::asio::buffer(data_in.str()));
		}
	}
Beispiel #11
0
int initSugoroku(Sugoroku *s, int player_num) {
  int i;
  s->player_num = player_num;
  s->player = (Player *)malloc(sizeof(Player)*player_num);
  for(i = 0; i < player_num; i++) {
    initPlayer(&(s->player[i]), i);
  }
  if(!readMap(&s->map, "./map.dat")) return 0;
  if(!importItemFile(s, "./ITEM.csv")) return 0;
  if(!importShop(&s->shop, "./shop.csv")) return 0;
  if(!setPlayerStart(s)) return 0;

  return 1;
}
MessagesDialogs TelegramCache::readDialogs() const
{
    MessagesDialogs result(MessagesDialogs::typeMessagesDialogs);

    const QString filePath = p->path + "/dialogs";
    const QList<QVariant> &list = readList(filePath);
    QList<Dialog> dialogs;

    QHash<QByteArray, Chat> chats;
    QHash<QByteArray, User> users;
    QHash<QByteArray, Message> messages;

    Q_FOREACH(const QVariant &var, list)
    {
        const Dialog &dialog = Dialog::fromMap( var.toMap() );

        const Peer &peer = dialog.peer();
        const QByteArray &key = TelegramTools::identifier(peer);
        switch(static_cast<int>(peer.classType()))
        {
        case Peer::typePeerChannel:
        case Peer::typePeerChat:
            if(!chats.contains(key))
                chats[key] = readChat(peer);
            break;
        case Peer::typePeerUser:
            if(!users.contains(key))
                users[key] = readUser(peer);
            break;
        }

        if(dialog.topMessage())
        {
            QByteArray topMsgKey = TelegramTools::identifier(dialog.peer(), dialog.topMessage());
            const QString &messageFolder = getMessageFolder(peer);
            const QString messageFile = messageFolder + "/" + QString::number(dialog.topMessage());
            messages[topMsgKey] = Message::fromMap( readMap(messageFile) );
        }

        dialogs << dialog;
    }

    result.setDialogs(dialogs);
    result.setChats(chats.values());
    result.setUsers(users.values());
    result.setMessages(messages.values());
    result.setCount(dialogs.count());

    return result;
}
Beispiel #13
0
/*
 * level_disasm()
 */
static void level_disasm(uint8_t dunno, uint8_t levno)
{
    uint32_t	i;
    b3level_t	*level;
    FILE		*fp;
    uint16_t	offset;

    rangeSkipList = gl_list_create_empty(GL_ARRAY_LIST,
                                         NULL, NULL, range_free, 1);

    level = readMap(duns[dunno].levels[levno]);

    currentLevel.dataStartOffset	= level->dataBaseOffset;
    currentLevel.monsterIndex	= level->monIndex;

    if ((dunno == 11) && (levno == 0))
        currentLevel.codeStartOffset = 4;
    else
        currentLevel.codeStartOffset = 0;

    fp = xfopen(mkCodePath("%s-%d.code", duns[dunno].name, levno), "wb");

#undef DUMP_CODE
#ifdef DUMP_CODE
    dump_btstring(bts_sprintf("%s-%d.dump", duns[dunno].name, levno),
                  level->codeBuf, 0);
#endif

    for (i = 0; i < level->dataCount; i++) {
        offset = level->dataList[i].offset;
        fprintf(fp, "(%3d, %3d) offset: %04x\n",
                level->dataList[i].sqE,
                level->dataList[i].sqN,
                offset
               );
    }
    fprintf(fp, "=====================================\n");

    disasmCode(fp, level->codeBuf, level->dataBaseOffset);

    gl_list_free(rangeSkipList);
    rangeSkipList = NULL;

    fclose(fp);

    freeLevel(level);
}
Beispiel #14
0
void XMLimport::readUnknownMapElement()
{
    while( ! atEnd() )
    {

        readNext();

        if( isEndElement() )
        {
            break;
        }

        if( isStartElement() )
        {
            readMap();
        }
    }
}
Beispiel #15
0
Map::Map()
{
	lvlList = { "lvl1" };
	lvlMap.clear();
	currentMap = 0;
	blockToDestroy = 0;
	dashLength = 0;
	dashX = -1;
	ballX = -1;
	ballY = -1;
	ballAng = 0;
	dx = 0;
	dy = -1;
	ball = NULL;
	block = NULL;
	dash = NULL;
	wall = NULL;
	readMap();
}
Beispiel #16
0
Map::Map(SDL_Texture* bball, SDL_Texture* ddash, SDL_Texture* bblock, SDL_Texture* wwall)
{
	lvlList = { "lvl1" };
	lvlMap.clear();
	currentMap = 0;
	blockToDestroy = 0;
	dashLength = 0;
	dashX = -1;
	ballX = -1;
	ballY = -1;
	ballAng = 0;
	dx = 0;
	dy = -1;
	readMap();
	ball = bball;
	dash = ddash;
	block = bblock;
	wall = wwall;
}
Beispiel #17
0
void XMLimport::readUnknownMapElement()
{
    while( ! atEnd() )
    {

        readNext();
        qDebug()<<"[ERROR]: UNKNOWN map element:name="<<name().toString();

        if( isEndElement() )
        {
            break;
        }

        if( isStartElement() )
        {
            readMap();
        }
    }
}
Beispiel #18
0
int main(int argc, char** argv)
{
    //load map
    readMap();
    num_expands = 0;
    num_discovered = 1;

    //run planner
    test_duration = 0;
    Clock::time_point t0 = Clock::now();
    timeout = t0 + chrono::seconds(5);
    prepare();
    search();
    Clock::time_point t1 = Clock::now();
    
    //report joint plan
    testSolution(joint_solution, true);

    //report stats
    double dt =  chrono::duration<double, chrono::seconds::period>(t1-t0).count();
    cout << "results: Path Length=" << joint_cost/10000.0;
    cout << " Visited Nodes=" << num_discovered;
    cout << " Explored Nodes=" << num_expands;
    cout << " Planning Time=" << dt << endl;
    cout << " Joint Testing Time=" << test_duration << endl;
    
    FILE* fout = fopen("stats.csv","w");
    fprintf(fout,"%d %f %d %f %f\n",W,joint_cost/10000.0,num_expands,dt,test_duration);
    fclose(fout);
    
    for (int a = 0; a < agents.size(); ++a)
    {
        fout = fopen("visualf.txt","w");
        vector<string> visual = visualizePath();
        for (int i = 0; i < visual.size(); ++i)
            fprintf(fout,"%s\n",visual[i].c_str());
        fclose(fout);
    }
}
Beispiel #19
0
static int loadMap(const char *mapName)
{
	int status = 0;
	char *fileName = NULL;

	fileName = malloc(MAX_PATH_NAME_LENGTH);
	if (!fileName)
		return (status = ERR_MEMORY);

	// Find the map by name
	status = findMapFile(mapName, fileName);
	if (status < 0)
	{
		error(_("Couldn't find keyboard map %s"), mapName);
		goto out;
	}

	// Read it in
	status = readMap(fileName, selectedMap);

out:
	free(fileName);
	return (status);
}
Beispiel #20
0
///Modo de jogo em que só há uma vida, e termina apenas quando o jogador morre
void survivalMode()
{
    system("mode con:cols=90 lines=30"); //tamanho da tela de jogo

    LEVEL_SCENE hell   = {RED, {176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,177,
                                176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,177,
                                176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,177,177,
                                176,176,176,176,176,176,176,176,178,178,176,176,176,176,176,176,178,177,177,177,
                                176,176,178,177,177,176,176,178,178,178,178,176,176,176,176,178,178,177,177,177,
                                176,176,178,177,177,177,176,178,178,178,178,176,176,176,176,178,178,178,177,177,
                                178,178,178,177,177,177,176,178,178,178,178,176,176,176,178,178,178,178,178,178,
                                178,178,177,177,177,177,176,178,178,178,178,178,176,178,178,178,178,177,178,178,
                                177,178,177,177,177,177,177,177,178,178,177,177,177,177,177,177,177,177,177,178,
                                177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177
                               }
                         };  //cenário do modo de jogo

    FILE *arq;
    int score;  //pontuação
    int level;  //como só há um level nesse jogo, esta variavél serve apenas para o peso da pontuação
    int speed;  //velocidade do jogo
    int rows, columns;  //Linhas e colunas do mapa
    int rocksNum;   // Número de pedras
    int ratNum;  //Indica qual o rato a ser gerado, há no máximo 4 ratos na tela
    int ratsEaten;
    int ratsColor; //Cor do rato a ser gerado
    int i;  // Usado nos loops for
    int cont; //Usado para contabilizar o número de movimentos da snake
    char auxDirection; //
    BOOL isDead; //Flag de morte da snake

    char map[ROWSMAX][COLUMNSMAX];
    int hasPassed[ROWSMAX*COLUMNSMAX];

    SNAKE snake;

    POSN initialCoord; //Coordenada onde a snake começa o nível

    POSN rocks[ROWSMAX*COLUMNSMAX];
    POSN rats[4];

    ratNum = 0;
    ratsColor = 2;
    ratsEaten = 0;
    cont = 0;
    isDead = 0;
    level = 1;
    score = 0;
    speed = 200; //speed inicial

    for(i=0; i<rocksNum; i++)
        hasPassed[i]=0;

    readMap(42, &rows, &columns, map, &rocksNum, rocks, &initialCoord);
    restartLevel(&snake, columns, rows, rats, speed, &speed, initialCoord, &isDead);
    print_lvlART(hell, columns + 5, 0);
    fadeIN(rows, columns, GREY, 1);
    printMap(rows, columns, map, hell.color);
    printRocks(rows, columns, rocksNum, rocks, map);
    printSnake(&snake);
    getch(); //pausa o jogo

    while(!isDead)
    {

        for(i=0; i<rocksNum; i++)
        {
            if(hasPassed[i]!=0) hasPassed[i]+=1;
        }

        print_lvlART(hell, columns + 5, 0);
        printScore(score);
        eraseTrail(snake);
        updateSnakeCoord(&snake);
        printSnake(&snake);
        checkColision(&snake, &isDead, rows, columns, map, rocks, rocksNum, hasPassed, &score);

        if(score < 0)
        {
            score = 0;  //Não há score negativo!
        }

        cont++; //contador de movimentos
        if(cont % 10 == 0)
        {
            makeRats(rows, columns, rats, ratNum, &snake, map, &ratsColor); //gera e printa um rato
            ratNum++;
            if(ratNum == 4)  //Há 4 ratos, de 0 a 3, logo rato 4 == rato 0
            {
                ratNum = 0;
            }
        }

        eatRat(&snake, rats, &ratsEaten, &score, level); //checa se um rato foi comido

        Sleep(speed); //controla a velocidade do jogo
        if(speed > 100) //máxima velocidade do jogo
            speed -= 1;

        auxDirection = changeDirection(snake.direction); //lê nova direção to teclado
        if(auxDirection == 'P')
        {
            getch(); //Pausa o jogo
        }
        else if(auxDirection == 'C')
        {
            cheatCode(&isDead, &isDead, &speed); //Lê cheat code
        }
        else if(auxDirection == 'Q' || auxDirection == ESC) //Se o jogador aperta para sair, perde suas vidas para encerrar
        {
            isDead = 1;
        }
        else snake.direction = auxDirection; //só troca a direção se a nova direção não for uma tecla de pause ou saída

    }

    fadeOUT(rows, columns, GREY, 1); //Efeito de fade out na tela
    printGameOver();

    arq = fopen("highscore_survival.bin", "rb+"); //Abre arquivo de highscore, informando caso de erro
    if(arq == NULL)
        printf("error");

    uptadeHighScore(score, arq); //coloca o score no rank

    system("cls");

}
Beispiel #21
0
///Executa uma fase do jogo no modo story
void playOneLevel(int level, int objetivo, int speed, LEVEL_SCENE scenario, int *lifes, int *score)
{
    int rows, columns;  //Linhas e colunas do mapa
    int rocksNum;   // Número de pedras
    int ratsEaten;  //Número de ratos
    int ratNum;  //Indica qual o rato a ser gerado, há no máximo 4 ratos na tela
    int ratsColor; //Cor do rato a ser gerado
    int i;  // Usado nos loops for
    int cont; //Usado para contabilizar o número de movimentos da snake
    int actualSpeed; //velocidade que vai sendo aumentada
    char auxDirection;  //recebe direção antes de trocar a direção da snake
    BOOL isDead; //Flag de morte da snake
    BOOL levelEnded; //Flag que indica se o nível chegou ao fim
    BOOL eatenAllRats; //Flag que indica se todos os ratos necessário para gerar a maçã foram comidos

    char map[ROWSMAX][COLUMNSMAX];
    int hasPassed[ROWSMAX*COLUMNSMAX]; //array para indicar as pedras pelas quais a snake passou

    SNAKE snake;

    POSN initialCoord; //Coordenada onde a snake começa o nível

    POSN rocks[ROWSMAX*COLUMNSMAX];
    POSN rats[4];
    POSN apple = {500, 500}; //coordenada fora do mapa

    eatenAllRats = 0;
    ratsEaten = 0;
    ratNum = 0;
    ratsColor = GREEN; //primeiro rato é verde
    cont = 0;
    isDead = 0;
    levelEnded = 0;

    for(i=0; i<rocksNum; i++)
        hasPassed[i]=0;

    readMap(level, &rows, &columns, map, &rocksNum, rocks, &initialCoord);
    print_lvlART(scenario, columns + 5, 0);
    restartLevel(&snake, columns, rows, rats, speed, &actualSpeed, initialCoord, &eatenAllRats);
    fadeIN(rows, columns, GREY, 1);
    printMap(rows, columns, map, scenario.color);
    printRocks(rows, columns, rocksNum, rocks, map);
    printSnake(&snake);
    printInfo(level, *lifes, *score, ratsEaten, objetivo);
    getch(); //pausa o jogo

    while(*lifes > 0 && levelEnded == 0)
    {

        for(i=0; i<rocksNum; i++)
        {
            if(hasPassed[i] != 0)
               hasPassed[i] += 1;
        }

        print_lvlART(scenario, columns + 5, 0);
        printInfo(level, *lifes, *score, ratsEaten, objetivo);
        eraseTrail(snake);
        updateSnakeCoord(&snake);
        printSnake(&snake);
        checkColision(&snake, &isDead, rows, columns, map, rocks, rocksNum, hasPassed, score);
        teleport(&snake, rows, columns);

        if(*score < 0)
        {
            *score = 0;  //Não há score negativo!
        }

        cont++; //conta o número de movimentos
        if(cont % 10 == 0 && ratsEaten < objetivo) //a cada 10 movimentos gera um rato, se não for atingido o objetivo
        {
            makeRats(rows, columns, rats, ratNum, &snake, map, &ratsColor);
            ratNum++;
            if(ratNum == 4)
            {
                ratNum = 0;
            }
        }

        eatRat(&snake, rats, &ratsEaten, score, level);
        eatApple(&snake, &apple, score, &levelEnded);

        if(ratsEaten >= objetivo && eatenAllRats == 0) //gera maçã se forem comidos todos os ratos necessários
        {
            eatenAllRats = 1;
            makeApple(rows, columns, &apple, rats, ratNum, &snake, map);
        }

        if(isDead || snake.size == 1)  //Se a cobra teve uma colisão fatal ou perdeu todo o corpo exceto a cabeça
        {
            Beep(700, 100);
            isDead = 0;
            (*lifes)--;
            ratsEaten = 0; //Se morrer, deve comer todos os ratos de novo
            if(*lifes > 0) //Se ainda há vidas, continua o jogo
            {
                system("cls");
                print_lvlART(scenario, columns + 5, 0);
                restartLevel(&snake, columns, rows, rats, speed, &actualSpeed, initialCoord, &eatenAllRats);
                printMap(rows, columns, map, scenario.color);
                printRocks(rows, columns, rocksNum, rocks, map);
                printSnake(&snake);
                printInfo(level, *lifes, *score, ratsEaten, objetivo);
                getch(); //pausa o jogo
            }
        }

        Sleep(speed); //controla a velocidade do jogo
        if(speed > 100) //máxima velocidade do jogo
            speed -= 1;

        auxDirection = changeDirection(snake.direction); //lê nova direção to teclado
        if(auxDirection == 'P')
        {
            getch(); //Pausa o jogo
        }
        else if(auxDirection == 'C')
        {
            cheatCode(&(*lifes), &levelEnded, &speed); //Lê cheat code
        }
        else snake.direction = auxDirection;

        if(snake.direction == 'Q' || snake.direction == ESC) //Se o jogador aperta para sair, perde suas vidas para encerrar
        {
            *lifes = 0;
        }
    }

    fadeOUT(rows, columns, GREY, 1); //Efeito de fade out na tela
    system("cls");

}
Beispiel #22
0
MapWidget::MapWidget()
{
    readMap();                                	//读取地图信息

    zoom=50;

    int width = map.width();
    int height = map.height();
    QGraphicsScene *scene = new QGraphicsScene(this);
    scene->setSceneRect(-width/2,-height/2,width,height);
    setScene(scene);
    setCacheMode(CacheBackground);

    //用于地图缩放的滑动条
    QSlider *slider = new QSlider;
    slider->setOrientation(Qt::Vertical);
    slider->setRange(1,100);
    slider->setTickInterval(10);
    slider->setValue(50);
    connect(slider,SIGNAL(valueChanged(int)),this,SLOT(slotZoom(int)));

    QLabel *zoominLabel = new QLabel;
    zoominLabel->setScaledContents(true);
    zoominLabel->setPixmap(QPixmap("zoomin.png"));

    QLabel *zoomoutLabel = new QLabel;
    zoomoutLabel->setScaledContents(true);
    zoomoutLabel->setPixmap(QPixmap("zoomout.png"));

    //坐标值显示区
    QLabel *label1 = new QLabel(tr("GraphicsView:"));
    viewCoord = new QLabel;
    QLabel *label2 = new QLabel(tr("GraphicsScene:"));
    sceneCoord = new QLabel;
    QLabel *label3 = new QLabel(tr("map:"));
    mapCoord = new QLabel;

    //坐标显示区布局
    QGridLayout *gridLayout = new QGridLayout;
    gridLayout->addWidget(label1,0,0);
    gridLayout->addWidget(viewCoord,0,1);
    gridLayout->addWidget(label2,1,0);
    gridLayout->addWidget(sceneCoord,1,1);
    gridLayout->addWidget(label3,2,0);
    gridLayout->addWidget(mapCoord,2,1);
    gridLayout->setSizeConstraint(QLayout::SetFixedSize);

    QFrame *coordFrame = new QFrame;
    coordFrame->setLayout(gridLayout);

    //缩放控制子布局
    QVBoxLayout *zoomLayout = new QVBoxLayout;
    zoomLayout->addWidget(zoominLabel);
    zoomLayout->addWidget(slider);
    zoomLayout->addWidget(zoomoutLabel);

    //坐标显示区域布局
    QVBoxLayout *coordLayout = new QVBoxLayout;
    coordLayout->addWidget(coordFrame);
    coordLayout->addStretch();

    //主布局
    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addLayout(zoomLayout);
    mainLayout->addLayout(coordLayout);
    mainLayout->addStretch();
    mainLayout->setMargin(30);
    mainLayout->setSpacing(10);
    setLayout(mainLayout);

    setWindowTitle("Map Widget");
    setMinimumSize(600,400);
}
UserFull TelegramCache::readMe() const
{
    const QMap<QString, QVariant> &map = readMap(p->path + "/me");
    return UserFull::fromMap(map);
}
Beispiel #24
0
void DataReader::readOne(pn_data_t* data)
{
    qpid::amqp::Descriptor descriptor(0);
    bool described = pn_data_is_described(data);
    if (described) {
        pn_data_enter(data);
        pn_data_next(data);
        if (pn_data_type(data) == PN_ULONG) {
            descriptor = qpid::amqp::Descriptor(pn_data_get_ulong(data));
        } else if (pn_data_type(data) == PN_SYMBOL) {
            descriptor = qpid::amqp::Descriptor(convert(pn_data_get_symbol(data)));
        } else {
            QPID_LOG(notice, "Ignoring descriptor of type " << pn_data_type(data));
        }
        pn_data_next(data);
    }
    switch (pn_data_type(data)) {
      case PN_NULL:
        reader.onNull(described ? &descriptor : 0);
        break;
      case PN_BOOL:
        reader.onBoolean(pn_data_get_bool(data), described ? &descriptor : 0);
        break;
      case PN_UBYTE:
        reader.onUByte(pn_data_get_ubyte(data), described ? &descriptor : 0);
        break;
      case PN_BYTE:
        reader.onByte(pn_data_get_byte(data), described ? &descriptor : 0);
        break;
      case PN_USHORT:
        reader.onUShort(pn_data_get_ushort(data), described ? &descriptor : 0);
        break;
      case PN_SHORT:
        reader.onShort(pn_data_get_short(data), described ? &descriptor : 0);
        break;
      case PN_UINT:
        reader.onUInt(pn_data_get_uint(data), described ? &descriptor : 0);
        break;
      case PN_INT:
        reader.onInt(pn_data_get_int(data), described ? &descriptor : 0);
        break;
      case PN_CHAR:
        pn_data_get_char(data);
        break;
      case PN_ULONG:
        reader.onULong(pn_data_get_ulong(data), described ? &descriptor : 0);
        break;
      case PN_LONG:
        reader.onLong(pn_data_get_long(data), described ? &descriptor : 0);
        break;
      case PN_TIMESTAMP:
        reader.onTimestamp(pn_data_get_timestamp(data), described ? &descriptor : 0);
        break;
      case PN_FLOAT:
        reader.onFloat(pn_data_get_float(data), described ? &descriptor : 0);
        break;
      case PN_DOUBLE:
        reader.onDouble(pn_data_get_double(data), described ? &descriptor : 0);
        break;
      case PN_DECIMAL32:
        pn_data_get_decimal32(data);
        break;
      case PN_DECIMAL64:
        pn_data_get_decimal64(data);
        break;
      case PN_DECIMAL128:
        pn_data_get_decimal128(data);
        break;
      case PN_UUID:
        reader.onUuid(convert(pn_data_get_uuid(data)), described ? &descriptor : 0);
        break;
      case PN_BINARY:
        reader.onBinary(convert(pn_data_get_binary(data)), described ? &descriptor : 0);
        break;
      case PN_STRING:
        reader.onString(convert(pn_data_get_string(data)), described ? &descriptor : 0);
        break;
      case PN_SYMBOL:
        reader.onSymbol(convert(pn_data_get_symbol(data)), described ? &descriptor : 0);
        break;
      case PN_DESCRIBED:
        break;
      case PN_ARRAY:
        readArray(data, described ? &descriptor : 0);
        break;
      case PN_LIST:
        readList(data, described ? &descriptor : 0);
        break;
      case PN_MAP:
        readMap(data, described ? &descriptor : 0);
        break;
    }
    if (described) pn_data_exit(data);
}
MessagesMessages TelegramCache::readMessages(const Peer &peer, int offset, int limit) const
{
    MessagesMessages result(MessagesMessages::typeMessagesMessages);

    const QString folderPath = getMessageFolder(peer);
    QStringList files = QDir(folderPath).entryList(QDir::Files);
    qStableSort(files.begin(), files.end(), fileListDeSort);

    files = files.mid(offset, limit);

    QHash<QByteArray, Chat> chats;
    QHash<QByteArray, User> users;

    QList<Message> messages;
    Q_FOREACH(const QString &f, files)
    {
        const QString path = folderPath + "/" + f;
        const QMap<QString, QVariant> &map = readMap(path);
        if(map.isEmpty())
            continue;

        const Message &msg = Message::fromMap(map);
        const Peer &toPeer = msg.toId();
        const QByteArray &toKey = TelegramTools::identifier(toPeer);
        switch(static_cast<int>(toPeer.classType()))
        {
        case Peer::typePeerChannel:
        case Peer::typePeerChat:
            if(!chats.contains(toKey))
                chats[toKey] = readChat(toPeer);
            break;
        case Peer::typePeerUser:
            if(!users.contains(toKey))
                users[toKey] = readUser(toPeer);
            break;
        }

        if(msg.fromId())
        {
            Peer fromPeer(Peer::typePeerUser);
            fromPeer.setUserId(msg.fromId());
            const QByteArray &fromKey = TelegramTools::identifier(fromPeer);
            switch(static_cast<int>(fromPeer.classType()))
            {
            case Peer::typePeerChannel:
            case Peer::typePeerChat:
                if(!chats.contains(fromKey))
                    chats[fromKey] = readChat(fromPeer);
                break;
            case Peer::typePeerUser:
                if(!users.contains(fromKey))
                    users[fromKey] = readUser(fromPeer);
                break;
            }
        }

        messages << msg;
    }

    result.setMessages(messages);
    result.setChats(chats.values());
    result.setUsers(users.values());
    result.setCount(messages.count());

    return result;
}
Beispiel #26
0
void setUpBoard(Unit *u[NUM]) {
    Unit t;
    readMap();
    bool gotNames = false;
    int i;
    int pnum;
    int minr, maxr, minc, maxc;

    for (i = 0; i < NUM; ++i)u[i] = 0;

    if (!AUTOTOURNEY) {
        for (i = 0; i < numplayers; ++i) {
            tryagain:
            cout << "tla" << i << ": ";
            cin >> tla[i];
            if (tla[i] == "?") {
                printTlaList();
                goto tryagain;
            }
            if (!checksOut(tla[i])) {
                cout << "That tla is not in the list.\n";
                cout << "type '?' to see a full list.\n";
                goto tryagain;
            }
        }
    }

    // make all the crowns
    for (i = 0; i < numplayers; ++i) {
        pnum = i % numplayers;
        minr = startBox[pnum].minr;
        maxr = startBox[pnum].maxr;
        minc = startBox[pnum].minc;
        maxc = startBox[pnum].maxc;
        u[i] = newUnit(tla[pnum], crown);
        t = *u[i];
        u[i]->Place(minr, maxr, minc, maxc, makeSitRep(u, i));
        checkPlacement(u[i], t, minr, maxr, minc, maxc);
        updateB(u[i]);
    }
    // make all the knights
    for (; i < (numplayers + NUMKNIGHTS); ++i) {
        pnum = i % numplayers;
        pnum = i % numplayers;
        minr = startBox[pnum].minr;
        maxr = startBox[pnum].maxr;
        minc = startBox[pnum].minc;
        maxc = startBox[pnum].maxc;
        u[i] = newUnit(tla[pnum], knight);
        t = *u[i];
        u[i]->Place(minr, maxr, minc, maxc, makeSitRep(u, i));
        checkPlacement(u[i], t, minr, maxr, minc, maxc);
        updateB(u[i]);
    }
    // make all the archers
    for (; i < (numplayers + NUMKNIGHTS + NUMARCHERS); ++i) {
        pnum = i % numplayers;
        minr = startBox[pnum].minr;
        maxr = startBox[pnum].maxr;
        minc = startBox[pnum].minc;
        maxc = startBox[pnum].maxc;
        u[i] = newUnit(tla[pnum], archer);
        t = *u[i];
        u[i]->Place(minr, maxr, minc, maxc, makeSitRep(u, i));
        checkPlacement(u[i], t, minr, maxr, minc, maxc);
        updateB(u[i]);
    }
    // make all the infantry
    for (; i < NUM; ++i) {
        pnum = i % numplayers;
        minr = startBox[pnum].minr;
        maxr = startBox[pnum].maxr;
        minc = startBox[pnum].minc;
        maxc = startBox[pnum].maxc;
        u[i] = newUnit(tla[pnum], infantry);
        t = *u[i];
        u[i]->Place(minr, maxr, minc, maxc, makeSitRep(u, i));
        checkPlacement(u[i], t, minr, maxr, minc, maxc);
        updateB(u[i]);
    }

    return;
}
Beispiel #27
0
bool XMLimport::importPackage( QIODevice * device, QString packName, int moduleFlag)
{
    mPackageName = packName;
    setDevice( device );

    gotTrigger = false;
    gotTimer = false;
    gotAlias = false;
    gotKey = false;
    gotAction = false;
    gotScript = false;
    module = moduleFlag;
    /*if (moduleFlag)
        module=1;*/
    qDebug()<<"module flag:"<<module<<" importing: "<<mPackageName;


    if( ! packName.isEmpty() )
    {
        mpKey = new TKey( 0, mpHost );
        if (module){
            mpKey->mModuleMasterFolder=true;
            mpKey->mModuleMember=true;
        }
        mpKey->setPackageName( mPackageName );
        mpKey->setIsActive( true );
        mpKey->setName( mPackageName );
        mpKey->setIsFolder( true );

        mpTrigger = new TTrigger( 0, mpHost );
        if (module){
            mpTrigger->mModuleMasterFolder=true;
            mpTrigger->mModuleMember=true;
        }
        mpTrigger->setPackageName( mPackageName );
        mpTrigger->setIsActive( true );
        mpTrigger->setName( mPackageName );
        mpTrigger->setIsFolder( true );

        mpTimer = new TTimer( 0, mpHost );
        if (module){
            mpTimer->mModuleMasterFolder=true;
            mpTimer->mModuleMember=true;
        }
        mpTimer->setPackageName( mPackageName );
        mpTimer->setIsActive( true );
        mpTimer->setName( mPackageName );
        mpTimer->setIsFolder( true );

        mpAlias = new TAlias( 0, mpHost );
        if (module){
            mpAlias->mModuleMasterFolder=true;
            mpAlias->mModuleMember=true;
        }
        mpAlias->setPackageName( mPackageName );
        mpAlias->setIsActive( true );
        mpAlias->setName( mPackageName );
        mpAlias->setIsFolder( true );
        mpAction = new TAction( 0, mpHost );
        if (module){
            mpAction->mModuleMasterFolder=true;
            mpAction->mModuleMember=true;
        }
        mpAction->setPackageName( mPackageName );
        mpAction->setIsActive( true );
        mpAction->setName( mPackageName );
        mpAction->setIsFolder( true );
        mpScript = new TScript( 0, mpHost );
        if (module){
            mpScript->mModuleMasterFolder=true;
            mpScript->mModuleMember=true;
        }
        mpScript->setPackageName( mPackageName );
        mpScript->setIsActive( true );
        mpScript->setName( mPackageName );
        mpScript->setIsFolder( true );
        mpHost->getTriggerUnit()->registerTrigger( mpTrigger );
        mpHost->getTimerUnit()->registerTimer( mpTimer );
        mpHost->getAliasUnit()->registerAlias( mpAlias );
        mpHost->getActionUnit()->registerAction( mpAction );
        mpHost->getKeyUnit()->registerKey( mpKey );
        mpHost->getScriptUnit()->registerScript( mpScript );
    }
    while( ! atEnd() )
    {
        readNext();

        if( isStartElement() )
        {
            if( name() == "MudletPackage" )// && attributes().value("version") == "1.0")
            {
                readPackage();
            }
            else if( name() == "map" )
            {
                maxAreas = 0;
                maxRooms = 0;
                areaMap.clear();
                readMap();
                mpHost->mpMap->init(mpHost);
            }
            else
            {
                qDebug()<<"ERROR:name="<<name().toString()<<"text:"<<text().toString();
            }
        }
    }
    if( ! packName.isEmpty())
    {
       if( ! gotTrigger )
            mpHost->getTriggerUnit()->unregisterTrigger( mpTrigger );
       if( ! gotTimer )
            mpHost->getTimerUnit()->unregisterTimer( mpTimer );
       if( ! gotAlias )
            mpHost->getAliasUnit()->unregisterAlias( mpAlias );
       if( ! gotAction )
            mpHost->getActionUnit()->unregisterAction( mpAction );
       if( ! gotKey )
            mpHost->getKeyUnit()->unregisterKey( mpKey );
       if( ! gotScript )
            mpHost->getScriptUnit()->unregisterScript( mpScript );
    }
    return ! error();
}
Beispiel #28
0
void readLevel(int map_array[][bricksPerRow], int profile_number)
{
	readMap(map_array, profile_number, 1);
	printf("Read Level from SD CARD \n");
	// printIntArray(map_array);
}
Beispiel #29
0
void bservInitMaps()
{
	WIN32_FIND_DATA fData;
    wstring pattern(getPesInfo()->gdbDir);
    pattern += L"GDB\\balls\\*";

	HANDLE hff = FindFirstFile(pattern.c_str(), &fData);
    if (hff != INVALID_HANDLE_VALUE)
    {
        while(true)
        {
            // check if this is a file
            if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0
                    && wcsicmp(fData.cFileName,L"map.txt")!=0)
            {
                ball_t ball;
                ball._file = fData.cFileName;

                if (ball._file.size() > 0x2f)
                {
                    LOG1S1N(L"ERROR: Ball filename too long for {%s}: %d characters. Must be 0-47. Skipping.", ball._file.c_str(), ball._file.size());
                }
                else
                {
                    _balls.insert(pair<wstring,ball_t>(
                                fData.cFileName, ball
                    ));
                }
            }

            // proceed to next file
            if (!FindNextFile(hff, &fData)) break;
        }
        FindClose(hff);
    }

    // read home-ball map
    hash_map<WORD,wstring> entries;
    wstring mapFile(getPesInfo()->gdbDir);
    mapFile += L"GDB\\balls\\map.txt";
    if (readMap(mapFile.c_str(), entries))
    {
        for (hash_map<WORD,wstring>::iterator it = entries.begin();
                it != entries.end();
                it++)
        {
            wstring dir(it->second);
            string_strip(dir);
            string_strip_quotes(dir);

            // find this ball in the normal map
            ball_iter_t sit = _balls.find(dir);
            if (sit != _balls.end())
                _home_balls.insert(pair<WORD,ball_iter_t>(
                            it->first, sit));
            else
                LOG1S(L"ERROR in home-balls map: ball {%s} not found. Skipping.", dir.c_str());
        }
    }

    LOG1N(L"total balls: %d", _balls.size());
    LOG1N(L"home balls assigned: %d", _home_balls.size());

    // reset the iterator
    _ball_iter = _balls.end();
}
Beispiel #30
0
void InitMaps()
{
    hash_map<wstring,WORD> slots;

    // process boots map file
    hash_map<DWORD,wstring> mapFile;
    wstring mpath(getPesInfo()->gdbDir);
    mpath += L"GDB\\boots\\map.txt";
    if (!readMap(mpath.c_str(), mapFile))
    {
        LOG1S(L"Couldn't open boots map for reading: {%s}",mpath.c_str());
    }
    else
    {
        int slot = 0;
        for (hash_map<DWORD,wstring>::iterator it = mapFile.begin(); it != mapFile.end(); it++)
        {
            wstring boot(it->second);
            string_strip(boot);
            if (!boot.empty())
                string_strip_quotes(boot);

            if (!boot.empty())
            {
                // check that the file exists, so that we don't crash
                // later, when it's attempted to replace a boot.
                wstring filename(getPesInfo()->gdbDir);
                filename += L"GDB\\boots\\" + boot;
                HANDLE handle;
                DWORD size;
                if (OpenFileIfExists(filename.c_str(), handle, size))
                {
                    CloseHandle(handle);
                    if (slot >= MAX_BOOTS)
                    {
                        LOG2N(L"ERROR in bootserver map: Too many boots: %d (MAX supported = %d). Aborting map processing", slot, MAX_BOOTS);
                        break;
                    }

                    hash_map<wstring,WORD>::iterator wit = slots.find(boot);
                    if (wit != slots.end())
                    {
                        // boot already has an assigned slot
                        _boot_slots.insert(pair<DWORD,WORD>(
                                    it->first, wit->second));
                    }
                    else
                    {
                        _boot_slots.insert(pair<DWORD,WORD>(
                                    it->first, FIRST_EXTRA_BOOT_SLOT + slot));
                        slots.insert(pair<wstring,WORD>(
                                    boot, FIRST_EXTRA_BOOT_SLOT + slot));
                        slot++;
                    }
                }
                else
                    LOG1N1S(L"ERROR in bootserver map for ID = %d: FAILED to open boot BIN \"%s\". Skipping", it->first, boot.c_str());
            }
        }
    }

    if (_bootserv_config._random_boots)
    {
        // enumerate all boots and add them to the slots list
        wstring dir(getPesInfo()->gdbDir);
        dir += L"GDB\\boots\\";

        // normalize the path
        wchar_t fullpath[MAX_PATH];
        GetFullPathName(dir.c_str(), MAX_PATH, fullpath, 0);
        dir = fullpath;

        int count;
        LOG(L"Enumerating all boots in GDB...");
        EnumerateBoots(dir, count);
        _num_random_boots = count;
        LOG1N(L"_num_random_boots = %d", _num_random_boots);
    }

    // initialize fast bin lookup table
    for (hash_map<wstring,WORD>::iterator sit = slots.begin();
            sit != slots.end();
            sit++)
    {
        _fast_bin_table[sit->second - FIRST_EXTRA_BOOT_SLOT] = 
            new wstring(sit->first);
        if (k_bootserv.debug)
            LOG1N1S(L"slot %d <-- boot {%s}", sit->second, sit->first.c_str());
    }

    LOG1N(L"Total assigned GDB boots: %d", slots.size());
    LOG1N(L"Total random GDB boots: %d", _num_random_boots);

    if (slots.size() > 0)
        _num_slots = FIRST_EXTRA_BOOT_SLOT + slots.size();
    if (_num_random_boots > 0)
        _num_slots = FIRST_RANDOM_BOOT_SLOT + _num_random_boots;
    LOG1N(L"_num_slots = %d", _num_slots);
}