Esempio n. 1
0
struct Rocket* CreateRocket(struct Game *game, struct RocketsResources* data, struct Rocket* rockets, bool right) {
	  struct Rocket *n = malloc(sizeof(struct Rocket));
		n->next = NULL;
		n->prev = NULL;
		n->dx = (right ? -1.5 : 1.5) + (rand() / (float)RAND_MAX) * 0.6 - 0.3;
		n->dy = -2.1 + (rand() / (float)RAND_MAX) * 0.5 - 0.25;
		n->modifier = 0.025;
		n->blown = false;
		n->character = CreateCharacter(game, "rocket");
		n->character->spritesheets = data->rocket_template->spritesheets;
		n->character->shared = true;
		SelectSpritesheet(game, n->character, rand() % 2 ? "rock" : rand() % 2 ? "bottle" : "bottle2");
		SetCharacterPosition(game, n->character, (right ? 250 : 50) + rand() % 90 - 40, 100, right ? -0.33 : 0.33);
		al_play_sample_instance(data->jump_sound);
		data->currentspawn = data->spawnspeed + (data->spawnspeed * 0.1) * (float)(rand() / (float)RAND_MAX * 2) - (data->spawnspeed * 0.05);

		if (rockets) {
			  struct Rocket *tmp = rockets;
				while (tmp->next) {
					  tmp=tmp->next;
				}
				tmp->next = n;
				n->prev = tmp;
				return rockets;
		} else {
			  return n;
		}
}
void CCharacterPhysicsSupport::SpawnInitPhysics(CSE_Abstract* e)
{
	//if(!m_physics_skeleton)CreateSkeleton(m_physics_skeleton);

	if(m_EntityAlife.g_Alive())
	{
#ifdef DEBUG
		if(ph_dbg_draw_mask1.test(ph_m1_DbgTrackObject)&&stricmp(PH_DBG_ObjectTrack(),*m_EntityAlife.cName())==0)
		{
			Msg("CCharacterPhysicsSupport::SpawnInitPhysics obj %s before collision correction %f,%f,%f",PH_DBG_ObjectTrack(),m_EntityAlife.Position().x,m_EntityAlife.Position().y,m_EntityAlife.Position().z);
		}
#endif
		CreateIKController();
		CreateCharacter();
#ifdef DEBUG
		if(ph_dbg_draw_mask1.test(ph_m1_DbgTrackObject)&&stricmp(PH_DBG_ObjectTrack(),*m_EntityAlife.cName())==0)
		{
			Msg("CCharacterPhysicsSupport::SpawnInitPhysics obj %s after collision correction %f,%f,%f",PH_DBG_ObjectTrack(),m_EntityAlife.Position().x,m_EntityAlife.Position().y,m_EntityAlife.Position().z);
		}
#endif
		//m_PhysicMovementControl.SetMaterial( )
	}
	else
	{
		ActivateShell(NULL);
	}
}
Esempio n. 3
0
void LoadPlayerCharacter( game g, chr c ) {
    if( g == NULL || c == NULL ) return;
    if( g->pc ) { // Start from scratch ...
        PurgeCharacter( g->pc );
        DESTROY(g->pc);
    }
    g->pc = CreateCharacter(g);
    CopyCharacter( g->pc, c );
    wrefresh(g->arena);
}
Esempio n. 4
0
float
vsBuiltInFont::GetCharacterWidth( char c, float size, float capSize )
{
	float width = 0.f;

	vsDisplayList * list = CreateCharacter(c, size, capSize);

	if ( list )
	{
		vsVector2D topLeft, bottomRight;

		list->GetBoundingBox(topLeft, bottomRight);
		delete(list);
		width = bottomRight.x - topLeft.x;
	}

	return width;
}
Esempio n. 5
0
game NewGame() {
    game g = CreateGame();
    if( g == NULL ) return NULL;
    RandomMap(g->gameMap);
    g->pc = CreateCharacter(g);
    wrefresh(g->win);
    init_pc(g->pc);    
    box(g->arena, 0, 0);
    wrefresh(g->arena);
    int nzombies = NumZombies(g->arena);
    g->ZombieListHead = CreateCreature(g);
    init_npc(g->ZombieListHead->Character);
    wrefresh(g->arena);
    int n = 1;
    while( n < nzombies ) {
        wrefresh(g->arena);
        creature Z = CreateCreature(g);
        init_npc(Z->Character);
        InsertCreatureNode( g->ZombieListHead, Z );
        ++n;
    }
    return g;
}
Esempio n. 6
0
void cScenarioArmRL::BuildCoach()
{
	CreateCharacter(eCharNone, mCoach);

	cSimCharacter::tParams char_params;
	char_params.mPos = GetDefaultCharPos();
	char_params.mCharFile = mCharacterFile;
	char_params.mStateFile = mCharStateFile;
	char_params.mPlaneCons = GetCharPlaneCons();

	bool succ = mCoach->Init(mWorld, char_params);
	if (succ)
	{
		mCoach->RegisterContacts(cWorld::eContactFlagCharacter, cWorld::eContactFlagEnvironment);
		InitCharacterPos(mCoach);

		std::shared_ptr<cCharController> ctrl;
		succ = BuildCoachController(ctrl);
		if (succ)
		{
			mCoach->SetController(ctrl);
		}
	}
}
Esempio n. 7
0
void JGCharacterCreateRequest(LPSDHP_CREATECHAR lpMsg,int aIndex)
{
	char szAccountID[MAX_IDSTRING+1];
	char szName[MAX_IDSTRING+1];

	memcpy(szAccountID, lpMsg->AccountId, MAX_IDSTRING);
	memcpy(szName, lpMsg->Name, MAX_IDSTRING);

	szAccountID[MAX_IDSTRING] = 0;
	szName[MAX_IDSTRING] = 0;

	SDHP_CREATECHARRESULT pResult;

	pResult.ClassSkin = lpMsg->ClassSkin;
	pResult.Number = lpMsg->Number;

	memcpy(pResult.AccountId,szAccountID,MAX_IDSTRING);
	memcpy(pResult.Name,szName,MAX_IDSTRING);

	memset(pResult.Equipment,0x00,sizeof(pResult.Equipment));

	if ( SQLSyntexCheck(szName) == FALSE )
	{
		pResult.Result = 0;
	}
	else
	{
		pResult.Result = CreateCharacter(szAccountID,szName,&pResult);
	}

	pResult.h.c = PMHC_BYTE;
	pResult.h.size = sizeof( pResult );
	pResult.h.headcode = 0x04;

	DataSend(aIndex,(LPBYTE)&pResult,pResult.h.size);
}
Esempio n. 8
0
//-----------------------------------------------------------------------------
// Purpose: 
//
//-----------------------------------------------------------------------------
void CUICreateChar::PressOKBtn()
{
	CUIManager* pUIManager = CUIManager::getSingleton();

	// Get input string
	if( m_ebCharName.GetString() )
	{
		m_strCharName = m_ebCharName.GetString();	
		
		// 공백 체크.		
		for(const char *chr = m_strCharName.str_String; *chr != 0; chr++)
		{
			if( (*chr) == ' ' || (*chr) == '\t' || (*chr) == '\n' || (*chr) == '\r' || 
				(*chr) == '%' || (*chr) == '#' || (*chr) == '&' || (*chr) == '?' || (*chr) == '+' || (*chr) == '=' ||
				(g_iCountry == HONGKONG && !CheckCharacterHK(chr))) // 홍콩 특수문자는 입력 불가처리
			{
				pUIManager->CloseMessageBox(MSGCMD_CREATE_ERROR);
				CUIMsgBox_Info	MsgBoxInfo;
				MsgBoxInfo.SetMsgBoxInfo( _S( 145, "캐릭터 생성 오류" ), UMBS_OK,
					UI_CREATE_CHAR, MSGCMD_CREATE_ERROR );
				CTString	strMessage = _S( 146, "캐릭터명에 공백이 들어갈 수 없습니다." );
				MsgBoxInfo.AddString( strMessage );
				pUIManager->CreateMessageBox( MsgBoxInfo );
				
				m_ebCharName.ResetString();
				return;
			}
#if defined(G_RUSSIA)
				// [100510: selo] LC-RU-P20100504-006
				// http://en.wikipedia.org/wiki/Windows-1251 참고하여 변경
				if( !((*chr) >= 48 && (*chr) <= 57 )
					&& !((*chr) >= -64 && (*chr) <= -1)
					&& !((*chr) == -88)
					&& !((*chr) == -72)	)
				{
					pUIManager->CloseMessageBox(MSGCMD_CREATE_ERROR);
					CUIMsgBox_Info	MsgBoxInfo;
					MsgBoxInfo.SetMsgBoxInfo( _S( 145, "캐릭터 생성 오류" ), UMBS_OK,
						UI_CREATE_CHAR, MSGCMD_CREATE_ERROR );
					CTString	strMessage = _S(2980, "아이디는 영문과 숫자만 허용됩니다." );
					MsgBoxInfo.AddString( strMessage );
					pUIManager->CreateMessageBox( MsgBoxInfo );
					
					m_ebCharName.ResetString();
					return;
				}

#elif !defined(G_HONGKONG) && !defined(G_EUROPE2) && !defined(G_KOR) && !defined(G_JAPAN) && !defined(G_THAI)
			if( !((*chr) >= 48 && (*chr) <=57)  //! 0 ~ 9
				&& !((*chr) >= 65 && (*chr) <=90) // ! A ~ Z 
				&& !((*chr) >= 97 && (*chr) <=122) // ! a ~ z 
				)
			{
				pUIManager->CloseMessageBox(MSGCMD_CREATE_ERROR);
				CUIMsgBox_Info	MsgBoxInfo;
				MsgBoxInfo.SetMsgBoxInfo( _S( 145, "캐릭터 생성 오류" ), UMBS_OK,
					UI_CREATE_CHAR, MSGCMD_CREATE_ERROR );
				CTString	strMessage = _S(2980, "아이디는 영문과 숫자만 허용됩니다." );
				MsgBoxInfo.AddString( strMessage );
				pUIManager->CreateMessageBox( MsgBoxInfo );
				
				m_ebCharName.ResetString();
				return;
			}
#endif

		}
	}
//#define RESTRICT_SOUND 	

	_pSound->Mute();
	CreateCharacter();

#ifdef RESTRICT_SOUND
	extern BOOL _bNTKernel;
	//if( _bNTKernel )
		_pSound->UpdateSounds();
	#endif
}
Esempio n. 9
0
void* Gamestate_Load(struct Game *game, void (*progress)(struct Game*)) {
	  struct RocketsResources *data = malloc(sizeof(struct RocketsResources));

		data->timeline = TM_Init(game, "riots");

		data->bg = al_load_bitmap( GetDataFilePath(game, "riots/bg.png"));

		data->earth = al_load_bitmap( GetDataFilePath(game, "riots/separator.png"));

		data->clouds = al_load_bitmap( GetDataFilePath(game, "riots/fog.png"));
		(*progress)(game);

		data->rocket_sample = al_load_sample( GetDataFilePath(game, "bump.flac") );
		(*progress)(game);
		data->boom_sample = al_load_sample( GetDataFilePath(game, "boom.flac") );
		(*progress)(game);
		data->jump_sample = al_load_sample( GetDataFilePath(game, "launch.flac") );
		(*progress)(game);
		data->rainbow_sample = al_load_sample( GetDataFilePath(game, "win.flac") );
		(*progress)(game);
		data->wuwu_sample = al_load_sample( GetDataFilePath(game, "riots/vuvu.flac") );
		(*progress)(game);
		data->riot_sample = al_load_sample( GetDataFilePath(game, "riots/riot.flac") );
		(*progress)(game);

		data->rocket_sound = al_create_sample_instance(data->rocket_sample);
		al_attach_sample_instance_to_mixer(data->rocket_sound, game->audio.fx);
		al_set_sample_instance_playmode(data->rocket_sound, ALLEGRO_PLAYMODE_ONCE);

		data->boom_sound = al_create_sample_instance(data->boom_sample);
		al_attach_sample_instance_to_mixer(data->boom_sound, game->audio.fx);
		al_set_sample_instance_playmode(data->boom_sound, ALLEGRO_PLAYMODE_ONCE);

		data->rainbow_sound = al_create_sample_instance(data->rainbow_sample);
		al_attach_sample_instance_to_mixer(data->rainbow_sound, game->audio.fx);
		al_set_sample_instance_playmode(data->rainbow_sound, ALLEGRO_PLAYMODE_ONCE);

		data->jump_sound = al_create_sample_instance(data->jump_sample);
		al_attach_sample_instance_to_mixer(data->jump_sound, game->audio.fx);
		al_set_sample_instance_playmode(data->jump_sound, ALLEGRO_PLAYMODE_ONCE);

		data->riot_sound = al_create_sample_instance(data->riot_sample);
		al_attach_sample_instance_to_mixer(data->riot_sound, game->audio.fx);
		al_set_sample_instance_playmode(data->riot_sound, ALLEGRO_PLAYMODE_ONCE);

		data->wuwu_sound = al_create_sample_instance(data->wuwu_sample);
		al_attach_sample_instance_to_mixer(data->wuwu_sound, game->audio.fx);
		al_set_sample_instance_playmode(data->wuwu_sound, ALLEGRO_PLAYMODE_ONCE);


		data->cursor = CreateCharacter(game, "cursor");
		RegisterSpritesheet(game, data->cursor, "hand");
		LoadSpritesheets(game, data->cursor);
		(*progress)(game);

		data->pixelator = al_create_bitmap(320, 180);
		al_set_target_bitmap(data->pixelator);
		al_clear_to_color(al_map_rgb(0, 0, 0));

		al_set_target_backbuffer(game->display);

		data->rocket_template = CreateCharacter(game, "rocket");
		RegisterSpritesheet(game, data->rocket_template, "rock");
		RegisterSpritesheet(game, data->rocket_template, "bottle");
		RegisterSpritesheet(game, data->rocket_template, "bottle2");
		RegisterSpritesheet(game, data->rocket_template, "atom");
		RegisterSpritesheet(game, data->rocket_template, "boom");
		RegisterSpritesheet(game, data->rocket_template, "blank");
		LoadSpritesheets(game, data->rocket_template);
		(*progress)(game);

		data->usa_flag = CreateCharacter(game, "kibols");
		RegisterSpritesheet(game, data->usa_flag, "legia");
		RegisterSpritesheet(game, data->usa_flag, "poland");
		LoadSpritesheets(game, data->usa_flag);

		data->ru_flag = CreateCharacter(game, "kibols");
		RegisterSpritesheet(game, data->ru_flag, "lech");
		RegisterSpritesheet(game, data->ru_flag, "poland");
		LoadSpritesheets(game, data->ru_flag);
		(*progress)(game);

		data->rainbow = CreateCharacter(game, "rainbow");
		RegisterSpritesheet(game, data->rainbow, "shine");
		RegisterSpritesheet(game, data->rainbow, "be");
		LoadSpritesheets(game, data->rainbow);

		data->riot = CreateCharacter(game, "riot");
		RegisterSpritesheet(game, data->riot, "riot");
		LoadSpritesheets(game, data->riot);
		(*progress)(game);

		data->euro = CreateCharacter(game, "euro");
		RegisterSpritesheet(game, data->euro, "euro");
		LoadSpritesheets(game, data->euro);

		return data;
}
void CUICharacterCreateNew::PressOk()
{
	CUIManager* pUIManager = CUIManager::getSingleton();
	GameDataManager* pGame = GameDataManager::getSingleton();

	if (pGame == NULL)
		return;

	CharacterCreateNew* pCharCreate = pGame->GetCharCreate();

	if (pCharCreate == NULL)
		return;

	if (m_pebCharName == NULL)
		return;
	
	// Get input string
	if( m_pebCharName->GetString() )
	{
		CTString strNewName = m_pebCharName->GetString();
		pCharCreate->SetNewName(strNewName);

		// 공백 체크.
		const char *chr = pCharCreate->GetName();
		for( ; *chr != 0; chr++)
		{
			if( (*chr) == ' ' || (*chr) == '\t' || (*chr) == '\n' || (*chr) == '\r' || 
				(*chr) == '%' || (*chr) == '#' || (*chr) == '&' || (*chr) == '?' || (*chr) == '+' || (*chr) == '=')
			{
				pUIManager->CloseMessageBox(MSGCMD_CREATE_ERROR);
				CUIMsgBox_Info	MsgBoxInfo;
				MsgBoxInfo.SetMsgBoxInfo( _S( 145, "캐릭터 생성 오류" ), UMBS_OK,
					UI_CREATE_CHAR, MSGCMD_CREATE_ERROR );
				CTString	strMessage = _S( 146, "캐릭터명에 공백이 들어갈 수 없습니다." );
				MsgBoxInfo.AddString( strMessage );
				pUIManager->CreateMessageBox( MsgBoxInfo );

				ResetName();
				return;
			}
#if defined(G_RUSSIA)
			if( !((*chr) >= 48 && (*chr) <= 57 )
				&& !((*chr) >= -64 && (*chr) <= -1)
				&& !((*chr) == -88)
				&& !((*chr) == -72)	)
			{
				pUIManager->CloseMessageBox(MSGCMD_CREATE_ERROR);
				CUIMsgBox_Info	MsgBoxInfo;
				MsgBoxInfo.SetMsgBoxInfo( _S( 145, "캐릭터 생성 오류" ), UMBS_OK,
					UI_CREATE_CHAR, MSGCMD_CREATE_ERROR );
				CTString	strMessage = _S(2980, "아이디는 영문과 숫자만 허용됩니다." );
				MsgBoxInfo.AddString( strMessage );
				pUIManager->CreateMessageBox( MsgBoxInfo );

				ResetName();
				return;
			}

#elif !defined(G_KOR) && !defined(G_THAI)
			if( !((*chr) >= 48 && (*chr) <=57)  //! 0 ~ 9
				&& !((*chr) >= 65 && (*chr) <=90) // ! A ~ Z 
				&& !((*chr) >= 97 && (*chr) <=122) // ! a ~ z 
				)
			{
				pUIManager->CloseMessageBox(MSGCMD_CREATE_ERROR);
				CUIMsgBox_Info	MsgBoxInfo;
				MsgBoxInfo.SetMsgBoxInfo( _S( 145, "캐릭터 생성 오류" ), UMBS_OK,
					UI_CREATE_CHAR, MSGCMD_CREATE_ERROR );
				CTString	strMessage = _S(2980, "아이디는 영문과 숫자만 허용됩니다." );
				MsgBoxInfo.AddString( strMessage );
				pUIManager->CreateMessageBox( MsgBoxInfo );

				ResetName();
				return;
			}
#endif

		}
	}
	//#define RESTRICT_SOUND 	

	_pSound->Mute();
	CreateCharacter();

#ifdef RESTRICT_SOUND
	extern BOOL _bNTKernel;
	//if( _bNTKernel )
	_pSound->UpdateSounds();
#endif
}
Esempio n. 11
0
// The Game Loop http://www.youtube.com/watch?v=c4b9lCfSDQM
void CGame::GameLoop()
{
	m_hPlayer = CreateCharacter();

	// Initialize the box's position etc
	m_hPlayer->SetGlobalOrigin(Point(0, 0, 0));
	m_hPlayer->m_vecMovement = Vector(0, 0, 0);
	m_hPlayer->m_vecMovementGoal = Vector(0, 0, 0);
	m_hPlayer->m_vecVelocity = Vector(0, 0, 0);
	m_hPlayer->m_vecGravity = Vector(0, -10, 0);
	m_hPlayer->m_flSpeed = 15;
	m_hPlayer->m_clrRender = Color(0.8f, 0.4f, 0.2f, 1.0f);
	m_hPlayer->m_bHitByTraces = false;
	m_hPlayer->m_aabbSize = AABB(-Vector(0.5f, 0, 0.5f), Vector(0.5f, 2, 0.5f));
	m_hPlayer->m_bTakesDamage = true;

	Vector vecMonsterMin = Vector(-1, 0, -1);
	Vector vecMonsterMax = Vector(1, 2, 1);

	/*CCharacter* pTarget1 = CreateCharacter();
	pTarget1->SetTransform(Vector(2, 2, 2), 0, Vector(0, 1, 0), Vector(6, 0, 6));
	pTarget1->m_aabbSize.vecMin = vecMonsterMin;
	pTarget1->m_aabbSize.vecMax = vecMonsterMax;
	pTarget1->m_iBillboardTexture = m_iMonsterTexture;
	pTarget1->m_bEnemyAI = true;
	pTarget1->m_bTakesDamage = true;

	CCharacter* pTarget2 = CreateCharacter();
	pTarget2->SetTransform(Vector(2, 2, 2), 0, Vector(0, 1, 0), Vector(6, 0, -6));
	pTarget2->m_aabbSize.vecMin = vecMonsterMin;
	pTarget2->m_aabbSize.vecMax = vecMonsterMax;
	pTarget2->m_iBillboardTexture = m_iMonsterTexture;
	pTarget2->m_bEnemyAI = true;
	pTarget2->m_bTakesDamage = true;

	CCharacter* pTarget3 = CreateCharacter();
	pTarget3->SetTransform(Vector(3, 3, 3), 0, Vector(0, 1, 0), Vector(-6, 0, 8));
	pTarget3->m_aabbSize.vecMin = vecMonsterMin;
	pTarget3->m_aabbSize.vecMax = vecMonsterMax;
	pTarget3->m_iBillboardTexture = m_iMonsterTexture;
	pTarget3->m_bEnemyAI = true;
	pTarget3->m_bTakesDamage = true;*/

	Vector vecPropMin = Vector(-.1f, 0, -.1f);
	Vector vecPropMax = Vector(.1f, .2f, .1f);

	mtsrand(0);

	for (int i = 0; i < 800; i++)
	{
		float rand1 = (float)(mtrand()%1000)/1000; // [0, 1]
		float rand2 = (float)(mtrand()%1000)/1000; // [0, 1]

		float theta = rand1 * 2.0f * (float)M_PI;
		float radius = sqrt(rand2);

		Vector position = Vector(radius * cos(theta), 0, radius * sin(theta));
		position = position * 50;

		CCharacter* pProp = CreateCharacter();
		pProp->SetTransform(Vector(1, 1, 1), 0, Vector(0, 1, 0), position);
		pProp->m_aabbSize.vecMin = vecPropMin;
		pProp->m_aabbSize.vecMax = vecPropMax;
		pProp->m_clrRender = Color(0.4f, 0.8f, 0.2f, 1.0f);
		pProp->m_iTexture = m_iCrateTexture;
	}

	CRenderingContext c(GetRenderer());
	c.RenderBox(Vector(-1, 0, -1), Vector(1, 2, 1));
	c.CreateVBO(m_iMeshVB, m_iMeshSize);

	float flPreviousTime = 0;
	float flCurrentTime = Application()->GetTime();

	while (true)
	{
		// flCurrentTime will be lying around from last frame. It's now the previous time.
		flPreviousTime = flCurrentTime;
		flCurrentTime = Application()->GetTime();

		float dt = flCurrentTime - flPreviousTime;

		// Keep dt from growing too large.
		if (dt > 0.15f)
			dt = 0.15f;

		Update(dt);

		Draw();
	}
}
Esempio n. 12
0
// Handle mouse event
void _Menu::MouseEvent(const _MouseEvent &MouseEvent) {
	if(State == STATE_NONE)
		return;

	if(!CurrentLayout)
		return;

	if(MouseEvent.Button == SDL_BUTTON_LEFT)
		CurrentLayout->HandleInput(MouseEvent.Pressed);

	// Get clicked element
	_Element *Clicked = CurrentLayout->GetClickedElement();
	if(Clicked) {
		bool DoubleClick = false;
		if(PreviousClick == Clicked && PreviousClickTimer < MENU_DOUBLECLICK_TIME) {
			PreviousClick = nullptr;
			DoubleClick = true;
		}
		else
			PreviousClick = Clicked;
		PreviousClickTimer = 0.0;

		switch(State) {
			case STATE_TITLE: {
				if(Clicked->Identifier == "button_title_play") {
					PlayState.Connect(true);
				}
				else if(Clicked->Identifier == "button_title_joinserver") {
					InitConnect(true);
				}
				else if(Clicked->Identifier == "button_title_mapeditor") {
					InitEditor();
				}
				else if(Clicked->Identifier == "button_title_exit") {
					Framework.Done = true;
				}
			} break;
			case STATE_CHARACTERS: {
				if(CharactersState == CHARACTERS_NONE) {

					if(Clicked->Identifier == "button_characters_delete") {
						size_t SelectedSlot = GetSelectedCharacter();
						if(SelectedSlot < CharacterSlots.size() && CharacterSlots[SelectedSlot].Used) {
							_Buffer Packet;
							Packet.Write<PacketType>(PacketType::CHARACTERS_DELETE);
							Packet.Write<uint8_t>((uint8_t)SelectedSlot);
							PlayState.Network->SendPacket(Packet);
						}
					}
					else if(Clicked->Identifier == "button_characters_play") {
						size_t SelectedSlot = GetSelectedCharacter();
						if(SelectedSlot < CharacterSlots.size() && CharacterSlots[SelectedSlot].Used) {
							PlayCharacter(SelectedSlot);
						}
					}
					else if(Clicked->Identifier == "button_characters_back") {
						PlayState.Network->Disconnect();
					}
					else if(Clicked->Identifier.substr(0, CharacterButtonPrefix.size()) == CharacterButtonPrefix) {

						// Deselect slots
						_Element *CharactersElement = Assets.Elements["element_menu_characters"];
						for(auto &Element : CharactersElement->Children) {
							if(Element->Identifier.substr(0, CharacterButtonPrefix.size()) == CharacterButtonPrefix) {
								_Button *Button = (_Button *)Element;
								Button->Checked = false;
							}
						}

						// Set selection
						size_t SelectedSlot = (size_t)(intptr_t)Clicked->UserData;
						CharacterSlots[SelectedSlot].Button->Checked = true;

						// Open new character screen
						if(!CharacterSlots[SelectedSlot].Used)
							InitNewCharacter();

						UpdateCharacterButtons();

						if(DoubleClick && SelectedSlot < CharacterSlots.size()) {
							PlayCharacter(SelectedSlot);
						}
					}
				}
				else if(CharactersState == CHARACTERS_CREATE) {
					if(Clicked->Identifier == NewCharacterPortraitPrefix || Clicked->Identifier == NewCharacterBuildPrefix) {
						size_t SelectedID = (size_t)(intptr_t)Clicked->UserData;

						// Unselect all portraits and select the clicked element
						for(auto &Element : Clicked->Parent->Children) {
							_Button *Button = (_Button *)Element;
							Button->Checked = false;
							if((size_t)(intptr_t)Button->UserData == SelectedID) {
								_TextBox *Name = Assets.TextBoxes["textbox_newcharacter_name"];
								FocusedElement = Name;
								Name->ResetCursor();
								Button->Checked = true;
							}
						}

						ValidateCreateCharacter();
					}
					else if(Clicked->Identifier == "button_newcharacter_create") {
						CreateCharacter();
					}
					else if(Clicked->Identifier == "button_newcharacter_cancel") {
						RequestCharacterList();
					}
				}
			} break;
			case STATE_CONNECT: {
				if(Clicked->Identifier == "button_connect_connect") {
					if(!PlayState.Network->IsDisconnected()) {
						PlayState.Network->Disconnect(true);
						InitConnect(false);
					}
					else
						ConnectToHost();
				}
				else if(Clicked->Identifier == "button_connect_back") {
					InitTitle(true);
				}
			} break;
			case STATE_ACCOUNT: {
				if(Clicked->Identifier == "button_account_login") {
					SendAccountInfo();
				}
				else if(Clicked->Identifier == "button_account_create") {
					SendAccountInfo(true);
				}
				else if(Clicked->Identifier == "button_account_back") {
					InitConnect(true);
				}
			} break;
			case STATE_INGAME: {
				if(Clicked->Identifier == "button_ingame_resume") {
					InitPlay();
				}
				else if(Clicked->Identifier == "button_ingame_disconnect") {
					PlayState.Network->Disconnect();
				}
			} break;
			default:
			break;
		}
	}
}
Esempio n. 13
0
void StageState::Input() {
	if ((InputManager::GetInstance().KeyPress(SDLK_ESCAPE)) || (InputManager::GetInstance().ShouldQuit())){
		PauseState *state = new PauseState();
		Game::GetInstance().Push(state);
	}

	if (InputManager::GetInstance().KeyPress(SDLK_c)){
		Point tile(InputManager::GetInstance().GetMouseX() - Camera::pos.x, InputManager::GetInstance().GetMouseY() - Camera::pos.y);
		tile = tileMap.GetTile(tile.x, tile.y);
		CreateCharacter(tile.x, tile.y);
	}

	if (InputManager::GetInstance().KeyPress(SDLK_d)){
		DestroyCharacter(objectArray.size()-1);
	}

	if (InputManager::GetInstance().KeyPress(SDLK_RETURN)){
		CheatState *state = new CheatState(this, data);
		Game::GetInstance().Push(state);
	}
	if(InputManager::GetInstance().MouseRelease(SDL_BUTTON_LEFT)){

		switch (action){
		case NONE:
			ptile = tileMap.GetTile(InputManager::GetInstance().GetMouseX() - Camera::pos.x, InputManager::GetInstance().GetMouseY() - Camera::pos.y);
			p = tileMap.GetTileCenter(ptile);
			//objectArray[0]->AddObjective(p.x, p.y, ptile);
			SelectCharacter();
			for (int i = 0; i < roomArray.size(); i++){
				roomArray[i]->EditRoom(false);
				for (int j = 0; j < objectArray.size(); j++){
					if (objectArray[j]->Is("Wall")){
						objectArray[j]->Editing(false);
					}
				}
			}
			break;
		case GUI_A:
			if(gui.BuildIconPressed()){
				click.Play(1);
				action = GUI_ROOM;
				gui.SetState(ROOMS);
            }
			else{
				if (gui.DestroyIconPressed()){
					click.Play(1);
					action = DESTROY_ROOM;
				}
				else{
					if (gui.BuyIconPressed()){
						click.Play(1);
						action = BUY;
					}
					else{
						if (gui.EditIconPressed()){
							click.Play(1);
							subGuiEdit.SetPositionSubGUI(InputManager::GetInstance().GetMouseX(), InputManager::GetInstance().GetMouseY());
							action = SUB_GUI_EDIT;
							subGuiEdit.SetState(EDIT);
						}
						else {
							action = NONE;
						}
					}
				}
			}
			break;
		case SUB_GUI_EDIT:
			if (subGuiEdit.DoorIconPressed()){
				click.Play(1);
				cout << "editando porta..." << endl;
				action = EDIT_DOOR;
			}
			else{
				if (subGuiEdit.WallIconPressed()){
					click.Play(1);
					cout << "editando parede..." << endl;
					action = EDIT_WALL;
				}
				else {
					action = NONE;
				}
			}
			break;
		case TILE_SELECT:
			break;
		case GUI_ROOM:
			if (!roomSheet.IsInside(InputManager::GetInstance().GetMouseX(), InputManager::GetInstance().GetMouseY())){
				action = NONE;
			}
			if (roomSheet.IsBuy(InputManager::GetInstance().GetMouseX(), InputManager::GetInstance().GetMouseY())){
				action = TILE_SELECT;
				roomAttributes = roomSheet.GetAttributes();
				selectionBox.SetSprite(roomAttributes.tileSprite);
			}
			gui.SetState(BASIC);

			break;
		case CONSTRUCT_ROOM:
			{
			action = NONE;
			Point aux;

			if (selectionBox.begin.y > selectionBox.end.y) {
				aux = selectionBox.begin;
				selectionBox.begin = selectionBox.end;
				selectionBox.end = aux;
			}

			if ((selectionBox.begin.x > selectionBox.end.x) && (selectionBox.begin.y < selectionBox.end.y)) {
				aux = selectionBox.begin;
				selectionBox.begin.x = selectionBox.end.x;
				selectionBox.end.x = aux.x;
			}
			RoomAttributes asd;
			asd.cost = 50;
			asd.tileSprite = "img/tileset/tile_madeira.png";
			asd.type = "Pirate";
			Room *newRoom = new Room(selectionBox.begin, selectionBox.end, &tileMap, &objectArray, roomArray.size(), roomAttributes);
			data->money -= newRoom->cost;
            roomArray.emplace_back(newRoom);
			vector<int> heuristc = occupancyMap.CreateHeuristic(&tileMap, roomArray[roomArray.size() - 1]->GetDoor());
			heuristicsArray.emplace(newRoom->GetID(),heuristc);
			obstacleMap = occupancyMap.Update(&tileMap, &objectArray);
			//Point tileC = tileMap.GetTile(objectArray[0]->box.x + objectArray[0]->box.w / 2, objectArray[0]->box.y + objectArray[0]->box.h);
			//vector<int> path = PathAStar(tileC.x, tileC.y, newRoom->GetID());
			//objectArray[0]->AddObjective(path);
			}
			break;
		case DESTROY_ROOM:
			for (int i = 0; i < roomArray.size(); i++){
				p = tileMap.GetTile(InputManager::GetInstance().GetMouseX() - Camera::pos.x, InputManager::GetInstance().GetMouseY() - Camera::pos.y);
				if (roomArray[i]->IsInside(p)){
					heuristicsArray.erase(roomArray[i]->GetID());
					cout << "Destroying..." << endl;
					DestroyRoom(roomArray[i]->GetID());
					roomArray.erase(roomArray.begin() + i);
					i = roomArray.size();
				}
				
			}
			action = NONE;
			break;
		case BUY:
			if (!buySheet.IsInside(InputManager::GetInstance().GetMouseX(), InputManager::GetInstance().GetMouseY())){
				action = NONE;
			}
			if (buySheet.IsBuy(InputManager::GetInstance().GetMouseX(), InputManager::GetInstance().GetMouseY())){
				Point Tiles = Point(InputManager::GetInstance().GetMouseX() - Camera::pos.x, InputManager::GetInstance().GetMouseY() - Camera::pos.y);
				Tiles = tileMap.GetTileCenterFromScreen(Tiles);
				Object* object = new Object(Tiles.x, Tiles.y, buySheet.GetAttributes(), tileMap);
				selectedObject = objectArray.size();
				objectArray.emplace_back(object);
				action = EDIT_OBJECT;
			}
			//data->money -= 100;
			break;
		case AREA_SELECT:
			break;
		case EDIT_DOOR:
			for (int i = 0; i < roomArray.size(); i++){
				p = tileMap.GetTile(InputManager::GetInstance().GetMouseX() - Camera::pos.x, InputManager::GetInstance().GetMouseY() - Camera::pos.y);
				if (roomArray[i]->IsInside(p)){
					roomArray[i]->EditRoom(true);
					for (int j = 0; j < objectArray.size(); j++){
						if (objectArray[j]->Is("Wall")){
							if ((p.x == objectArray[j]->tile.x) && (p.y == objectArray[j]->tile.y))
								roomArray[i]->SetDoor(p.x, p.y, roomArray[i]->GetID(), &objectArray);
						}
					}
					
					for (int j = 0; j < objectArray.size(); j++){
						if (objectArray[j]->Is("Wall")){
							if (objectArray[j]->roomID == roomArray[i]->GetID()) {
								objectArray[j]->Editing(true);
								if (objectArray[j]->tile.DisPoints(objectArray[j]->tile, roomArray[i]->GetDoor()) == 0) {
									objectArray.erase(objectArray.begin() + j); 
								}
							}
						}
					}
					vector<int> heuristc = occupancyMap.CreateHeuristic(&tileMap, roomArray[i]->GetDoor());
					heuristicsArray[roomArray[i]->GetID()] = heuristc;
					obstacleMap = occupancyMap.Update(&tileMap, &objectArray);
					obstacleMap = occupancyMap.CleanTile(&tileMap, roomArray[i]->GetDoor());
				}
			}
			action = NONE;
			break;
		case EDIT_WALL:
			for (int i = 0; i < roomArray.size(); i++){
				p = tileMap.GetTile(InputManager::GetInstance().GetMouseX() - Camera::pos.x, InputManager::GetInstance().GetMouseY() - Camera::pos.y);
				if (roomArray[i]->IsInside(p)){
					roomArray[i]->EditRoom(true);
					for (int j = 0; j < objectArray.size(); j++){
						if (objectArray[j]->Is("Wall")){
							if (objectArray[j]->roomID == roomArray[i]->GetID()) {
								objectArray[j]->Editing(true);
							}
						}
					}
				}
			}
			action = NONE;
			break;
		case EDIT_OBJECT:
			if (objectArray[selectedObject]->SettlePos(obstacleMap)){
				obstacleMap = occupancyMap.Update(&tileMap, &objectArray);
				action = NONE;
			}
		default:
			break;
		}

	}

	if(InputManager::GetInstance().MousePress(SDL_BUTTON_RIGHT)){
		if (sheet.GetRender() || objSheet.GetRender()){
			if (!sheet.GetBox().IsInside(InputManager::GetInstance().GetMouseX(), InputManager::GetInstance().GetMouseY())){
				sheet.SetRender(false);
				Camera::Unfollow();
			}

			if (!objSheet.GetBox().IsInside(InputManager::GetInstance().GetMouseX(), InputManager::GetInstance().GetMouseY()))
				objSheet.SetRender(false);
		}
		else{
			switch (action)
			{
			case NONE:
				gui.SetPosition(InputManager::GetInstance().GetMouseX(), InputManager::GetInstance().GetMouseY());
				action = GUI_A;
				break;
			case TILE_SELECT:
				break;
			case CONSTRUCT_ROOM:
				break;
			case DESTROY_ROOM:
				break;
			case AREA_SELECT:
				break;
			case GUI_A:
				gui.SetPosition(InputManager::GetInstance().GetMouseX(), InputManager::GetInstance().GetMouseY());
				break;
			case SUB_GUI_EDIT:
				action = NONE;
				break;
			default:
				break;
			}
		}
	}

	if(InputManager::GetInstance().IsMouseDown(SDL_BUTTON_LEFT)){

		switch (action){
		case NONE:
			break;
		case TILE_SELECT:
			action = CONSTRUCT_ROOM;
			break;
		case CONSTRUCT_ROOM:
			break;
		case DESTROY_ROOM:
			break;
		case AREA_SELECT:
			break;
		default:
			break;
		}

	}

	if(InputManager::GetInstance().MouseRelease(SDL_BUTTON_RIGHT)){

		switch (action){
		case NONE:
			//action = TILE_SELECT;
			break;
		case TILE_SELECT:
			break;
		case CONSTRUCT_ROOM:
			break;
		case DESTROY_ROOM:
			break;
		case AREA_SELECT:
			break;
		default:
			break;
		}

	}
	
}
Esempio n. 14
0
// Handle key event
void _Menu::KeyEvent(const _KeyEvent &KeyEvent) {
	if(State == STATE_NONE)
		return;

	switch(State) {
		case STATE_TITLE: {
			if(KeyEvent.Pressed && !KeyEvent.Repeat) {
				if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
					Framework.Done = true;
				else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN) {
					PlayState.Connect(true);
				}
			}
		} break;
		case STATE_CHARACTERS: {
			if(CharactersState == CHARACTERS_NONE) {
				if(KeyEvent.Pressed && !KeyEvent.Repeat) {
					if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
						PlayState.Network->Disconnect();
					else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN) {
						size_t SelectedSlot = GetSelectedCharacter();
						if(SelectedSlot >= CharacterSlots.size())
							SelectedSlot = 0;

						if(CharacterSlots[SelectedSlot].Used) {
							PlayCharacter(SelectedSlot);
						}
					}
				}
			}
			else if(CharactersState == CHARACTERS_CREATE){
				ValidateCreateCharacter();

				if(KeyEvent.Pressed) {
					if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
						RequestCharacterList();
					else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN)
						CreateCharacter();
				}
			}
		} break;
		case STATE_CONNECT: {
			if(KeyEvent.Pressed && !KeyEvent.Repeat) {
				if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
					InitTitle(true);
				else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN)
					ConnectToHost();
				else if(KeyEvent.Scancode == SDL_SCANCODE_TAB)
					FocusNextElement();
			}
		} break;
		case STATE_ACCOUNT: {
			if(KeyEvent.Pressed && !KeyEvent.Repeat) {
				if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
					InitConnect(true);
				else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN)
					SendAccountInfo();
				else if(KeyEvent.Scancode == SDL_SCANCODE_TAB)
					FocusNextElement();
			}
		} break;
		case STATE_INGAME: {
		} break;
		default:
		break;
	}
}
bool CPHMovementControl:: ActivateBoxDynamic(DWORD id,int num_it/*=8*/,int num_steps/*5*/,float resolve_depth/*=0.01f*/)
{
	bool  character_exist=CharacterExist();
	if(character_exist&&trying_times[id]!=u32(-1))
	{
		Fvector dif;dif.sub(trying_poses[id],cast_fv(dBodyGetPosition(m_character->get_body())));
		if(Device.dwTimeGlobal-trying_times[id]<500&&dif.magnitude()<0.05f)
																	return false;
	}
	if(!m_character||m_character->PhysicsRefObject()->PPhysicsShell())return false;
	DWORD old_id=BoxID();

	bool  character_disabled=character_exist && !m_character->IsEnabled();
	if(character_exist&&id==old_id)return true;

	if(!character_exist)
	{
		CreateCharacter();
	}

	//m_PhysicMovementControl->ActivateBox(id);
	m_character->CPHObject::activate();
	ph_world->Freeze();
	UnFreeze();

	saved_callback=ObjectContactCallback();
	SetOjectContactCallback(TestDepthCallback);
	SetFootCallBack(TestFootDepthCallback);
	max_depth=0.f;



	//////////////////////////////////pars///////////////////////////////////////////
//	int		num_it=8;
//	int		num_steps=5;
//	float	resolve_depth=0.01f;

	
	if(!character_exist)
	{
		num_it=20;
		num_steps=1;		
		resolve_depth=0.1f;
	}
	///////////////////////////////////////////////////////////////////////
	float	fnum_it=float(num_it);
	float	fnum_steps=float(num_steps);
	float	fnum_steps_r=1.f/fnum_steps;

	Fvector vel;
	Fvector pos;
	GetCharacterVelocity(vel);
	GetCharacterPosition(pos);
	//const Fbox& box =Box();
	float pass=	character_exist ? _abs(Box().getradius()-boxes[id].getradius()) : boxes[id].getradius();
	float max_vel=pass/2.f/fnum_it/fnum_steps/fixed_step;
	float max_a_vel=M_PI/8.f/fnum_it/fnum_steps/fixed_step;
	dBodySetForce(GetBody(),0.f,0.f,0.f);
	dBodySetLinearVel(GetBody(),0.f,0.f,0.f);
	Calculate(Fvector().set(0,0,0),Fvector().set(1,0,0),0,0,0,0);
	CVelocityLimiter vl(GetBody(),max_vel,max_vel);
	max_vel=1.f/fnum_it/fnum_steps/fixed_step;

	bool	ret=false;
	m_character->SwitchOFFInitContact();
	vl.Activate();
	vl.l_limit*=(fnum_it*fnum_steps/5.f);
	vl.y_limit=vl.l_limit;
////////////////////////////////////
	for(int m=0;30>m;++m)
	{
		Calculate(Fvector().set(0,0,0),Fvector().set(1,0,0),0,0,0,0);
		EnableCharacter();
		m_character->ApplyForce(0,ph_world->Gravity()*m_character->Mass(),0);
		max_depth=0.f;
		ph_world->Step();
		if(max_depth	<	resolve_depth) 
		{
			break;
		}	
		ph_world->CutVelocity(max_vel,max_a_vel);
	}
	vl.l_limit/=(fnum_it*fnum_steps/5.f);
	vl.y_limit=vl.l_limit;
/////////////////////////////////////

	for(int m=0;num_steps>m;++m)
	{
		float param =fnum_steps_r*(1+m);
		InterpolateBox(id,param);
		ret=false;
		for(int i=0;num_it>i;++i){
			max_depth=0.f;
			Calculate(Fvector().set(0,0,0),Fvector().set(1,0,0),0,0,0,0);
			EnableCharacter();
			m_character->ApplyForce(0,ph_world->Gravity()*m_character->Mass(),0);
			ph_world->Step();
			ph_world->CutVelocity(max_vel,max_a_vel);
			if(max_depth	<	resolve_depth) 
			{
				ret=true;
				break;
			}	
		}
		if(!ret) break;
	}
	m_character->SwitchInInitContact();
	vl.Deactivate();

	ph_world->UnFreeze();
	if(!ret)
	{	
		if(!character_exist)DestroyCharacter();
		else if(character_disabled)m_character->Disable();
		ActivateBox(old_id);
		SetVelocity(vel);
		dBodyID b=GetBody();
		if(b)
		{
			dMatrix3 R;
			dRSetIdentity (R);
			dBodySetAngularVel(b,0.f,0.f,0.f);
			dBodySetRotation(b,R);
		}
		SetPosition(pos);
		
		//Msg("can not activate!");
	}
	else
	{
		ActivateBox(id);
		//Msg("activate!");
	}

	SetOjectContactCallback(saved_callback);
	SetVelocity(vel);
	saved_callback=0;
	if(!ret&&character_exist)
	{
		trying_times[id]=Device.dwTimeGlobal;
		trying_poses[id].set(cast_fv(dBodyGetPosition(m_character->get_body())));
	}
	else
	{
		trying_times[id]=u32(-1);
	}
	return ret;
}
Esempio n. 16
0
void StageState::Update(float dt) {
	if (music.isOverInd){
		cMusic++;
		if (cMusic == musicNames.size()){
			cMusic = 0;
		}
		music.Open(musicNames[cMusic]);
		music.Play(1);
	}
	
	int size = 0;
	int cost = 0;
	Input();
	creationTimer.Update(dt);
	switch (action)	{
	case NONE:
		break;
	case TILE_SELECT:
		p = tileMap.GetTile(InputManager::GetInstance().GetMouseX()-Camera::pos.x,InputManager::GetInstance().GetMouseY()-Camera::pos.y);
        selectionBox.SetBegin(p);
		selectionBox.Update(&tileMap);
        p = tileMap.GetTileCenter(p);
		break;
	case GUI_ROOM:
		roomSheet.UpdateObjectSheet();
		break;
	case CONSTRUCT_ROOM:
		selectionBox.Update(&tileMap);
		size = (abs(selectionBox.end.x - selectionBox.begin.x) + 1)*(abs(selectionBox.end.y - selectionBox.begin.y) + 1);
		cost = size * 5;
		break;
	case DESTROY_ROOM:
		break;
	case AREA_SELECT:
		break;
	case BUY:
		buySheet.UpdateObjectSheet();
		break;
	case EDIT_OBJECT:{
		Point tiles = Point(InputManager::GetInstance().GetMouseX() - Camera::pos.x, InputManager::GetInstance().GetMouseY() - Camera::pos.y);
		tiles = tileMap.GetTileCenterFromScreen(tiles);
		objectArray[selectedObject]->MoveTo(tiles.x, tiles.y);
	}
		break;
	default:
		break;
	}
	

	for (unsigned int i = 0; i < objectArray.size(); i++) {
		if (objectArray[i]->IsDead()) {
			DestroyCharacter(i);
			for (unsigned int j = 0; j < objectArray.size(); j++) {
				if (objectArray[j]->IsCharacter()) {
					objectArray[j]->ChangeSelection(i);
				}
			}
			i--;
		}
	}

	UpdateArray(dt, &tileMap);
	
	for (int i = 0; i < objectArray.size(); i++){

		if (objectArray[i]->IsCharacter()){
			if (objectArray[i]->GetAction() == DECIDING_ROOM){
				charChoice = objectArray[i]->GetChoice();
				charRoom = charChoice;

				if (!roomArray.empty()){
					for (int j = 0; j < roomArray.size(); j++){
						if ((roomArray[j]->GetState() == charRoom) && (roomArray[j]->roomState != Room::EDITING)){
							int x, y;
							Point t;
							x = objectArray[i]->box.x + objectArray[i]->box.w / 2;
							y = objectArray[i]->box.y + objectArray[i]->box.h;
							t = tileMap.GetTile(x, y);
							vector<int> path = PathAStar(t.x, t.y, roomArray[j]->GetDoor(), heuristicsArray[roomArray[j]->GetID()]);
							if (!path.empty())
								objectArray[i]->AddObjective(path);
							else
								cout << "No path!!!!" << endl;
						}
					}
				}
			}
			else{
				if (objectArray[i]->GetAction() == DECIDING_OBJECT){
					int objectIndex = objectArray[i]->GetObjectIndex();
					if (objectIndex != -1){
						Point objective = Point(objectArray[objectIndex]->GetTile().x, objectArray[objectIndex]->GetTile().y - 1);
						Point t = objectArray[i]->GetTile();
						cout << endl << "Debug action DO" << endl << endl;
						cout << "X,Y : " << t.x << "," << t.y << endl;
						cout << "Object index : " << objectIndex << endl;
						cout << objectArray[objectIndex]->GetHeuristic(0).size() << endl;
						vector<int> path = PathAStar(t.x, t.y, objective, objectArray[objectIndex]->GetHeuristic(0));
						if (!path.empty())
							objectArray[i]->AddObjective(path);
						else
							cout << "No path!!!!" << endl;
					}
				}
				else{
					if (objectArray[i]->GetAction() == EXITING){
						cout << "Entrou exitting!!!!!!!!!!" << endl;
						int objectIndex = objectArray[i]->GetObjectIndex();
						if (objectIndex != -1){
							Point objective = Point(objectArray[objectIndex]->GetTile().x, objectArray[objectIndex]->GetTile().y - 1);
							Point t = objectArray[i]->GetTile();
							vector<int> path = PathAStar(t.x, t.y, objective, objectArray[objectIndex]->GetHeuristic(0));
							if (!path.empty())
								objectArray[i]->AddObjective(path);
							else
								cout << "No path!!!!" << endl;
						}
					}

				}
			}
		}
	}
	if (creationTimer.Get() > 10){
		CreateCharacter(5, 5);
		creationTimer.Restart();
	}
	if (cost > 0)
		costText.SetText(to_string(-cost));
	else
		costText.SetText(" ");
	costText.SetPos(InputManager::GetInstance().GetMouseX() + 10, InputManager::GetInstance().GetMouseY() + 5, false, false);
	
}
Esempio n. 17
0
File: main.c Progetto: dos1/bttbw
int main(int argc, char **argv){
	signal(SIGSEGV, derp);

	srand(time(NULL));

	al_set_org_name("Super Derpy");
    al_set_app_name("Back to the Browser Wars");

       #ifdef ALLEGRO_MACOSX
       char exe_path[MAXPATHLEN];
       char link_path[MAXPATHLEN];

       uint32_t size = sizeof(exe_path);
       _NSGetExecutablePath(exe_path, &size);
       realpath(exe_path, link_path);
       chdir(link_path);
       #endif

	if(!al_init()) {
		fprintf(stderr, "failed to initialize allegro!\n");
		return -1;
	}

	struct Game game;

	InitConfig(&game);

	game._priv.fps_count.frames_done = 0;
	game._priv.fps_count.fps = 0;
	game._priv.fps_count.old_time = 0;

	game._priv.font_bsod = NULL;
	game._priv.console = NULL;

	game.config.fullscreen = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "fullscreen", "0"));
	game.config.music = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "music", "10"));
	game.config.voice = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "voice", "10"));
	game.config.fx = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "fx", "10"));
	game.config.debug = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "debug", "0"));
	game.config.width = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "width", "1280"));
	if (game.config.width<320) game.config.width=320;
	game.config.height = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "height", "720"));
	if (game.config.height<180) game.config.height=180;

	if(!al_init_image_addon()) {
		fprintf(stderr, "failed to initialize image addon!\n");
		/*al_show_native_message_box(display, "Error", "Error", "Failed to initialize al_init_image_addon!",
															 NULL, ALLEGRO_MESSAGEBOX_ERROR);*/
		return -1;
	}

	if(!al_init_acodec_addon()){
		fprintf(stderr, "failed to initialize audio codecs!\n");
		return -1;
	}

	if(!al_install_audio()){
		fprintf(stderr, "failed to initialize audio!\n");
		return -1;
	}

	if(!al_install_keyboard()){
		fprintf(stderr, "failed to initialize keyboard!\n");
		return -1;
	}

	if(!al_init_primitives_addon()){
		fprintf(stderr, "failed to initialize primitives!\n");
		return -1;
	}

    if(!al_install_mouse()) {
        fprintf(stderr, "failed to initialize the mouse!\n");
        return -1;
    }
	
	al_init_font_addon();

	if(!al_init_ttf_addon()){
		fprintf(stderr, "failed to initialize fonts!\n");
		return -1;
	}

	if (game.config.fullscreen) al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
	else al_set_new_display_flags(ALLEGRO_WINDOWED);
	al_set_new_display_option(ALLEGRO_VSYNC, 2-atoi(GetConfigOptionDefault(&game, "SuperDerpy", "vsync", "1")), ALLEGRO_SUGGEST);
	al_set_new_display_option(ALLEGRO_OPENGL, atoi(GetConfigOptionDefault(&game, "SuperDerpy", "opengl", "1")), ALLEGRO_SUGGEST);
#ifdef ALLEGRO_WINDOWS
	al_set_new_window_position(20, 40); // workaround nasty Windows bug with window being created off-screen
#endif

	game.display = al_create_display(game.config.width, game.config.height);
	if(!game.display) {
		fprintf(stderr, "failed to create display!\n");
		return -1;
	}

	SetupViewport(&game);

	PrintConsole(&game, "Viewport %dx%d", game.viewport.width, game.viewport.height);

    ALLEGRO_BITMAP *icon = al_load_bitmap(GetDataFilePath(&game, "icons/bttbw.png"));
	al_set_window_title(game.display, "Back to the Browser Wars");
	al_set_display_icon(game.display, icon);
	al_destroy_bitmap(icon);

    if (game.config.fullscreen) al_hide_mouse_cursor(game.display);
    al_inhibit_screensaver(true);

	al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR);

	game._priv.gamestates = NULL;

	game._priv.event_queue = al_create_event_queue();
	if(!game._priv.event_queue) {
		FatalError(&game, true, "Failed to create event queue.");
		al_destroy_display(game.display);
		return -1;
	}

	game.audio.v = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
	game.audio.mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	game.audio.fx = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	game.audio.music = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	game.audio.voice = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	al_attach_mixer_to_voice(game.audio.mixer, game.audio.v);
	al_attach_mixer_to_mixer(game.audio.fx, game.audio.mixer);
	al_attach_mixer_to_mixer(game.audio.music, game.audio.mixer);
	al_attach_mixer_to_mixer(game.audio.voice, game.audio.mixer);
	al_set_mixer_gain(game.audio.fx, game.config.fx/10.0);
	al_set_mixer_gain(game.audio.music, game.config.music/10.0);
	al_set_mixer_gain(game.audio.voice, game.config.voice/10.0);

	al_register_event_source(game._priv.event_queue, al_get_display_event_source(game.display));
    al_register_event_source(game._priv.event_queue, al_get_mouse_event_source());
    al_register_event_source(game._priv.event_queue, al_get_keyboard_event_source());

	game._priv.showconsole = game.config.debug;

	al_clear_to_color(al_map_rgb(0,0,0));
	game._priv.timer = al_create_timer(ALLEGRO_BPS_TO_SECS(60)); // logic timer
	if(!game._priv.timer) {
		FatalError(&game, true, "Failed to create logic timer.");
		return -1;
	}
	al_register_event_source(game._priv.event_queue, al_get_timer_event_source(game._priv.timer));

	al_flip_display();
	al_start_timer(game._priv.timer);

	setlocale(LC_NUMERIC, "C");

	game.shuttingdown = false;
	game.restart = false;

    game.mediator.lives = 3;
    game.mediator.score = 0;
    game.mediator.modificator = 1;

    game.mediator.heart = CreateCharacter(&game, "heart");
    RegisterSpritesheet(&game, game.mediator.heart, "heart");
    RegisterSpritesheet(&game, game.mediator.heart, "blank");
    LoadSpritesheets(&game, game.mediator.heart);
    SelectSpritesheet(&game, game.mediator.heart, "heart");

	char* gamestate = strdup("dosowisko"); // FIXME: don't hardcore gamestate

	int c;
	while ((c = getopt (argc, argv, "l:s:")) != -1)
		switch (c) {
			case 'l':
				free(gamestate);
				gamestate = strdup("levelX");
				gamestate[5] = optarg[0];
				break;
			case 's':
				free(gamestate);
				gamestate = strdup(optarg);
				break;
		}

	LoadGamestate(&game, gamestate);
    game._priv.gamestates->showLoading = false; // we have only one gamestate right now
    StartGamestate(&game, gamestate);
	free(gamestate);

	char libname[1024] = {};
    snprintf(libname, 1024, "libsuperderpy-%s-loading" LIBRARY_EXTENTION, "bttbw");
	void *handle = dlopen(libname, RTLD_NOW);
	if (!handle) {
		FatalError(&game, true, "Error while initializing loading screen %s", dlerror());
		exit(1);
	} else {

		#define GS_LOADINGERROR FatalError(&game, true, "Error on resolving loading symbol: %s", dlerror()); exit(1);

		if (!(game._priv.loading.Draw = dlsym(handle, "Draw"))) { GS_LOADINGERROR; }
		if (!(game._priv.loading.Load = dlsym(handle, "Load"))) { GS_LOADINGERROR; }
		if (!(game._priv.loading.Start = dlsym(handle, "Start"))) { GS_LOADINGERROR; }
		if (!(game._priv.loading.Stop = dlsym(handle, "Stop"))) { GS_LOADINGERROR; }
		if (!(game._priv.loading.Unload = dlsym(handle, "Unload"))) { GS_LOADINGERROR; }
	}

	game._priv.loading.data = (*game._priv.loading.Load)(&game);

	bool redraw = false;

	while(1) {
		ALLEGRO_EVENT ev;
		if (redraw && al_is_event_queue_empty(game._priv.event_queue)) {

			struct Gamestate *tmp = game._priv.gamestates;
			int toLoad = 0, loaded = 0;

			// FIXME: move to function
			// TODO: support dependences
			while (tmp) {
				if ((tmp->pending_start) && (tmp->started)) {
					PrintConsole(&game, "Stopping gamestate \"%s\"...", tmp->name);
					(*tmp->api.Gamestate_Stop)(&game, tmp->data);
					tmp->started = false;
					tmp->pending_start = false;
				}

				if ((tmp->pending_load) && (!tmp->loaded)) toLoad++;
				tmp=tmp->next;
			}

			tmp = game._priv.gamestates;
			// FIXME: move to function
			// TODO: support dependences

			double t = -1;

			while (tmp) {
				if ((tmp->pending_load) && (tmp->loaded)) {
					PrintConsole(&game, "Unloading gamestate \"%s\"...", tmp->name);
					al_stop_timer(game._priv.timer);
					tmp->loaded = false;
					tmp->pending_load = false;
					(*tmp->api.Gamestate_Unload)(&game, tmp->data);
					dlclose(tmp->handle);
					tmp->handle = NULL;
					al_start_timer(game._priv.timer);
				} else if ((tmp->pending_load) && (!tmp->loaded)) {
					PrintConsole(&game, "Loading gamestate \"%s\"...", tmp->name);
					al_stop_timer(game._priv.timer);
					// TODO: take proper game name
					char libname[1024];
                    snprintf(libname, 1024, "libsuperderpy-%s-%s" LIBRARY_EXTENTION, "bttbw", tmp->name);
					tmp->handle = dlopen(libname,RTLD_NOW);
					if (!tmp->handle) {
						//PrintConsole(&game, "Error while loading gamestate \"%s\": %s", tmp->name, dlerror());
						FatalError(&game, false, "Error while loading gamestate \"%s\": %s", tmp->name, dlerror());

						tmp->pending_load = false;
						tmp->pending_start = false;
					} else {

#define GS_ERROR FatalError(&game, false, "Error on resolving gamestate symbol: %s", dlerror()); tmp->pending_load = false; tmp->pending_start = false; tmp=tmp->next; continue;

						if (!(tmp->api.Gamestate_Draw = dlsym(tmp->handle, "Gamestate_Draw"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Logic = dlsym(tmp->handle, "Gamestate_Logic"))) { GS_ERROR; }

						if (!(tmp->api.Gamestate_Load = dlsym(tmp->handle, "Gamestate_Load"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Start = dlsym(tmp->handle, "Gamestate_Start"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Pause = dlsym(tmp->handle, "Gamestate_Pause"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Resume = dlsym(tmp->handle, "Gamestate_Resume"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Stop = dlsym(tmp->handle, "Gamestate_Stop"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Unload = dlsym(tmp->handle, "Gamestate_Unload"))) { GS_ERROR; }

						if (!(tmp->api.Gamestate_ProcessEvent = dlsym(tmp->handle, "Gamestate_ProcessEvent"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Reload = dlsym(tmp->handle, "Gamestate_Reload"))) { GS_ERROR; }

						if (!(tmp->api.Gamestate_ProgressCount = dlsym(tmp->handle, "Gamestate_ProgressCount"))) { GS_ERROR; }

						int p = 0;

						void progress(struct Game *game) {
							p++;
							DrawGamestates(game);
							float progress = ((p / (*(tmp->api.Gamestate_ProgressCount) ? (float)*(tmp->api.Gamestate_ProgressCount) : 1))/(float)toLoad)+(loaded/(float)toLoad);
							if (game->config.debug) PrintConsole(game, "[%s] Progress: %d% (%d/%d)", tmp->name, (int)(progress*100), p, *(tmp->api.Gamestate_ProgressCount));
							if (tmp->showLoading) (*game->_priv.loading.Draw)(game, game->_priv.loading.data, progress);
							DrawConsole(game);
							if (al_get_time() - t >= 1/60.0) {
								al_flip_display();
							}
							t = al_get_time();
						}

						t = al_get_time();

						// initially draw loading screen with empty bar
						DrawGamestates(&game);
						if (tmp->showLoading) {
                            (*game._priv.loading.Draw)(&game, game._priv.loading.data, loaded/(float)toLoad);
						}
						DrawConsole(&game);
						if (al_get_time() - t >= 1/60.0) {
							al_flip_display();
						}
						t = al_get_time();
						tmp->data = (*tmp->api.Gamestate_Load)(&game, &progress); // feel free to replace "progress" with empty function if you want to compile with clang
						loaded++;

						tmp->loaded = true;
						tmp->pending_load = false;
					}
					al_start_timer(game._priv.timer);
				}

				tmp=tmp->next;
			}

			bool gameActive = false;
			tmp=game._priv.gamestates;

			while (tmp) {

				if ((tmp->pending_start) && (!tmp->started) && (tmp->loaded)) {
					PrintConsole(&game, "Starting gamestate \"%s\"...", tmp->name);
					al_stop_timer(game._priv.timer);
					(*tmp->api.Gamestate_Start)(&game, tmp->data);
					al_start_timer(game._priv.timer);
					tmp->started = true;
					tmp->pending_start = false;
				}

				if ((tmp->started) || (tmp->pending_start) || (tmp->pending_load)) gameActive = true;
				tmp=tmp->next;
			}

			if (!gameActive) {
				PrintConsole(&game, "No gamestates left, exiting...");
				break;
			}

			DrawGamestates(&game);
			DrawConsole(&game);
			al_flip_display();
			redraw = false;

		} else {
Esempio n. 18
0
void CCharacterPhysicsSupport::CreateCharacterSafe( )
{
	if( m_PhysicMovementControl->CharacterExist( ) )return;
	CollisionCorrectObjPos( m_EntityAlife.Position( ), true );
	CreateCharacter	( );
}