Exemple #1
0
int main(int argc, char* argv[]) {
	LoginVista* loginVista = new LoginVista();
	string gameType = loginVista->askGameType();
	int clientsQty = loginVista->askClientsNumber();
	int port = loginVista->askPort();
	cout << "Partida: "<< gameType << " cantidad: " <<clientsQty<< " Puerto: "<< port<<endl;
	loginVista->~LoginVista();

	GameController* gController = new GameController(gameType);
	Server* server = new Server(port,gController, clientsQty);
	if( server->initSocketServer() == ERROR)
		return ERROR;
	server->start((void *) &server);
	cout << "SERVER is RUNNING"<< endl;
	while(gController->isGameRunning()){
		server->verifyWaitingClients();
		//Proceso las novedades de la cola del server y seteo la posicion de los protagonistas modificados
		server->processReceivedMessages();
		//Los protagonistas se trasladan a su posicion destino
		gController->updateGame();
		server->setSeenTiles();
		//Se le manda a los clientes las novedades
		server->notifyClients();
		gController->delay();
		server->verifyClientsConections();
	}
	gController->~GameController();
	gController=NULL;
	server->~Server();
	return 0;
}
/*
 * Position the notification relative to the block it is
 * talking about.
 */
void GameController::HandleNotificationUpdateCallback(void *handler, void *notification)
{
    hdVec2 screenPos;
    hdVec2 aa,bb;

    /* Volatile - both the notification and handler may go away at any time */
    if (handler == NULL || notification == NULL) return;

    GameController *self = (GameController *)handler;
    Polygon* note = (Polygon *)notification;
    Block* block = (Block *)note->GetRelative();

    if (NULL == note->GetWorld()) return;

    if (block != NULL)
    {
        self->ConvertInterfaceToScreen(screenPos, block->GetWorldCenter().x, block->GetWorldCenter().y);
        aa.Set(screenPos.x - 35.0f, screenPos.y + 30.0f);
        bb.Set(aa.x + 70, aa.y + 35);

        note->RemoveAllPoints();
        note->AddPoint(aa.x, aa.y);
        note->AddPoint(aa.x, bb.y);
        note->AddPoint(bb.x, bb.y);
        note->AddPoint(bb.x, aa.y);
    }
}
Exemple #3
0
bool DeviceManager::open(int sdlIndex) {
	if(sdlIndexExists(sdlIndex)) {
		return false; // ignore duplicates
	}
	DeviceIndices indices;
	indices.index = firstAvailableIndex();
	indices.sdlIndex = sdlIndex;
	if(SDL_IsGameController(sdlIndex) == SDL_TRUE) { // false when controller api not inited
		GameController *gc = new GameController();
		if(gc->open(&indices)) {
			m_devices[gc->getInstanceID()] = gc;
			if(sendDeviceEvents) {
				Config &config = Config::instance();
				config.getOscSender() << osc::BeginMessage(config.notificationAddress + "/open")
									  << "controller" << indices.index << osc::EndMessage();
				config.getOscSender().send();
			}
			return true;
		}
	}
	else {
		Joystick *js = new Joystick();
		if(js->open(&indices)) {
			m_devices[js->getInstanceID()] = js;
			if(sendDeviceEvents) {
				Config &config = Config::instance();
				config.getOscSender() << osc::BeginMessage(config.notificationAddress + "/open")
									  << "joystick" << indices.index << osc::EndMessage();
				config.getOscSender().send();
			}
			return true;
		}
	}
	return false;
}
Exemple #4
0
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    int retCode = 0;

    try {
        GameController *game = new GameController(&app);

        qmlRegisterType<Tile>();
        qmlRegisterType<AnimatedBoardObject>();
        qmlRegisterType<BoardObject>();

        GameBoard* gameBoard = game->getGameBoard();
        engine.rootContext()->setContextProperty("gameBoard", gameBoard);

        engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));

        retCode = app.exec();
    }
    catch(const std::bad_alloc&) {
        // There is no references to external resources yet, so show message and exit
        qDebug("Not enough memory!");
    }

    return retCode;
}
Exemple #5
0
void Player::startGo(std::vector<int> rowVector, std::vector<int> colVector) //开始走
{
	GameMapBaseScene::drawPathMark(rowVector, colVector);//路标

	GameController* gameController = GameController::getInstance();
	gameController->startGo(rowVector, colVector, this); //开始走
}
Exemple #6
0
/** Helper to load gameplay controllers in preload */
void MainMenuController::loadGameController(const char * levelkey, const char * levelpath) {
	GameController* gc = GameController::create(levelkey, levelpath);
	gc->preload();
	MainMenuButton* b = MainMenuButton::create(gc);
	mainMenuButtons.push_back(b);
	b->retain();
	int i = 0;
}
Exemple #7
0
int main()
{
	GameController* gameController = new GameController();
	gameController->runGame();

	delete gameController;

    return 0;
}
Exemple #8
0
void LoadingScene::Update(float dt)
{
	mSceneManager->update(dt);

	if (mFinishLoading)
	{
		GameController* game = GameController::getInstance();
		game->SwitchScene(mRaceScene);
	}
}
int main(int argc, char** argv) {
    // string configFileName;
    // if (argc > 2 && string(argv[1]) == "-t") {
    //     configFileName = argv[2];
    // }
    // else {
    //     configFileName = "test-configs/test.cfg";
    // }

    // cout << "Running: " << configFileName << endl;
    // TestingSuite::start(configFileName);
    // cout << "...done." << endl;

    /*
    Arguments to the executable:
    (0. The executable itself)
    1. Number of generations
    2. Number of nets per generation
    3. Number of games per net per generation
    4. Size of the hidden layer
    5. Depth of parsing for minimax tree
    6. Mean for gaussian random number
    7. Standard deviation for gaussian random number
    8. Mode for evaluating the "quality" of a net
    9. Number of parents to inherit traits from, when creating new generation
    */
    if (argc != NUM_ARGS) // Number of arguments plus the executable
        throw runtime_error("Invalid number of arguments");

    istringstream convertedArgv[NUM_ARGS];
    for (int i = 0; i < NUM_ARGS; ++i) {
        convertedArgv[i].str(argv[i]);
    }

    int gens, nets, games, hSize, treeDepth, numParents;
    float randomMean, randomStdDev;
    char evalMode;

    convertedArgv[1] >> gens;
    convertedArgv[2] >> nets;
    convertedArgv[3] >> games;
    convertedArgv[4] >> hSize;
    convertedArgv[5] >> treeDepth;
    convertedArgv[6] >> randomMean;
    convertedArgv[7] >> randomStdDev;
    convertedArgv[8] >> evalMode;
    convertedArgv[9] >> numParents;

    GameController gc;

    RandomGen::initialize(randomMean, randomStdDev);
    NeuralNet bestNet = gc.runTraining(gens, nets, games, hSize, evalMode, treeDepth, numParents);
    
    saveNet(bestNet);
}
Exemple #10
0
int main(int ac, char** av)
{
	argc = ac;
  	argv = av;
	GameController* controller = GameController::makeInstance();
	while (true)
	{
		controller->display();
		controller->update();
			
	}
	

}
Exemple #11
0
    INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
    {
        try 
		{
            GameController toy;
			toy.start();
        } 
		catch( Ogre::Exception& e ) 
		{

            MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
        }

        return 0;
    }
GameController* GameController::create(Layer* layer, float positionY)
{
	GameController* pRet = new GameController();
	if (pRet && pRet->init(layer, positionY))
	{
		pRet->autorelease();
		return pRet;
	}
	else
	{
		delete pRet;
		pRet = NULL;
		return NULL;
	}
}
Exemple #13
0
/*
 * Runs the game loop
 *
 * TODO: This should be a member of game controller
 */
void StartGameLoop(GameController game_controller, GLContext& gl_context) {

	int next_game_tick;
	double time_elapsed;
	next_game_tick = SDL_GetTicks();
	
	SDL_ShowCursor(SDL_DISABLE);
 
    // Loop control variable
    int done = 0;
 	while ( !done ) {
		
	
        // Check events
        SDLCheckEvents(game_controller);


		int sleep_time = 0;
		next_game_tick += SKIP_TICKS;
		sleep_time = next_game_tick - SDL_GetTicks();

		if( sleep_time >= 0 ) {
			//cout << "Sleep time: " << sleep_time << "\n";
			usleep( sleep_time * 1000 );
		} else {
			// Shit, we are running behind!
		}
		
		time_elapsed = sleep_time / 1000.0f;
		//cout << "Time elapsed: " << time_elapsed << "\n";
		
		game_controller.UpdateObjects(time_elapsed);

        // Call draw scene.
        // Pass in the list of objects to draw
	    Player player = game_controller.GetPlayer();
		gl_context.DrawScene(player, game_controller.GetCrates());
	}

	/* clean ourselves up and exit */
	Quit( 0 );
	
	/* Should never get here */
	return;

}
	virtual void ControllerExit()
	{
		if(cc->localBrowser->GetSave())
		{
			cc->gameModel->SetStamp(cc->localBrowser->GetSave()->GetGameSave());
			cc->LoadStamp();
		}
	}
Exemple #15
0
int main(int argc, char* argv[]) {
	GameController* gController = new GameController();
	Client* jorge = new Client(gController);
	//jorge->connectToServer("192.168.1.1");
	jorge->connectToServer("127.0.0.1");
	
	//delay to wait all messages from server
	SDL_Delay(9000);

	while( jorge->isConected() ){
		//leemos las novedades del server
		jorge->processReceivedMessages();
		gController->updateGame();
		//Si el juego no esta corriendo no actualizo la vista
		if(gController->gameIsRunning()){
			gController->getJuegoVista()->render(gController->getRunCycles(),jorge->getResourceCounter(), jorge->getUserName());
		}
		//escuchamos eventos y los mandamos al server
		jorge->sendEvents();
		jorge->verifyServerAlive();
		gController->delay();
	}
	gController->showFinalMessage();
	jorge->~Client();
	//delete(jorge);
	delete(gController);
	return 0;
}
Exemple #16
0
int main(const int argc, const char* argv[])
{
	/*if(true) // RunTests (WIP)
	{
		char const* arguments[] = {"JuEngine_Game", "--reporter=spec"};
		return bandit::run(2, (char**)arguments);
	}*/

	GameController* app = new GameController();

	char const* arguments[] = {"JuEngine_Game", "--noconsole"};
	app->Init(2, arguments);
	app->Run();

	delete app;

	return 0;
}
	virtual void ControllerExit()
	{
		if(cc->localBrowser->GetSave())
		{
			cc->gameModel->SetStamp(cc->localBrowser->GetSave()->GetGameSave());
			if (cc->localBrowser->GetMoveToFront())
				Client::Ref().MoveStampToFront(cc->localBrowser->GetSave()->GetName());
			cc->LoadStamp();
		}
	}
 virtual void ControllerExit()
 {
     SaveFile *file = cc->localBrowser->GetSave();
     if (file)
     {
         if (file->GetError().length())
             new ErrorMessage("Error loading stamp", file->GetError());
         else if (cc->localBrowser->GetMoveToFront())
             Client::Ref().MoveStampToFront(file->GetName());
         cc->LoadStamp(file->GetGameSave());
     }
 }
Exemple #19
0
void TestCaseGameController::tick(unsigned int ticks)
{
	for (unsigned int i=0; i < ticks; i++)
	{
		if (stop_ticks)
		{
			log_msg("STOP", "do not tick anymore");
			return;
		}
		
		game->tick();
	}
}
Exemple #20
0
SceneManager::SceneManager()
{
    //ctor
    GameController* controller = GameController::getInstance();
    m_target = controller->GetRenderTarget();
    m_windowWidth = controller->GetWindowWidth();
    m_windowHeight = controller->GetWindowHeight();


    m_posx = m_windowWidth / 2;
    m_posy = m_windowHeight / 2;


    m_animationNode = new Node();
    m_gui = new Node();
    m_mainMenu = new MenuNode(m_windowWidth);
    m_mainMenu->setVisibility(false);
    m_gui->addChild(m_mainMenu);

    m_memberStats = new Node();
    m_gui->addChild(m_memberStats);
    m_mainNode = nullptr;
}
int main(int argc, char** argv)
{
	ros::init(argc, argv, "game_controller");

	GameController ctrl;
	if (! ctrl.initNetwork())
		return EXIT_FAILURE;


	ctrl.createResponse();

	while(true)
	{

		if(ctrl.update())
			ctrl.publish();

		ros::spinOnce();
		if (! ros::ok())
			break;
	}
	return 0;
}
	virtual void ControllerExit()
	{
		if(cc->activePreview->GetDoOpen() && cc->activePreview->GetSave())
		{
			try
			{
				cc->LoadSave(cc->activePreview->GetSave());
			}
			catch(GameModelException & ex)
			{
				new ErrorMessage("Cannot open save", ex.what());
			}
		}
	}
Exemple #23
0
int main()
{
    srand(time(NULL));
    GameController* controller = GameController::getInstance();
    int width = controller->GetWindowWidth();
    int height = controller->GetWindowHeight();

    Localization* local = Localization::GetInstance();
    sf::RenderWindow window(sf::VideoMode(width, height), local->GetLocalization("main.window.title"));
    sf::View view(sf::FloatRect(0,0,width,height));
    window.setView(view);
    window.setVerticalSyncEnabled(true);
    controller->SetRenderTarget(&window);

    SceneManager* sm = new SceneManagerMainMenu();
    controller->LoadSceneManager(sm);

    try
    {
        while (window.isOpen())
        {
            sf::Event event;
            while (window.pollEvent(event))
            {
                if (event.type == sf::Event::Closed)
                    window.close();
                else if (event.type == sf::Event::GainedFocus)
                    controller->SetWindowFocus(true);
                else if (event.type == sf::Event::LostFocus)
                    controller->SetWindowFocus(false);
                else if (event.type == sf::Event::KeyPressed)
                    Configuration::GetInstance()->SetLastKeyPressed(event.key.code);
            }

            controller->Tick();
            window.display();
        }
    }
    catch(std::exception& ex)
    {
        std::ofstream o("crash.log");
        o << ex.what() << std::endl;
        std::cout << ex.what() << std::endl;
    }

    return 0;
}
/**
 * This sample shows how to make an application scriptable with the QScript
 * framework.
 * It provides a game where a yellow circle can be move through a maze by turning
 * it 90 degree to the left or to the right and moving one step in the current direction.
 * The code that does the actual manipulation of the circle's position is implemented in
 * C++, however the single commands (turn left / turn right / go forward) come from
 * a JS script that the user can modify in the UI.
 */
int main(int argc, char **argv)
{
    Application app(argc, argv);

    // Create the game controller object
    GameController gameController;

    // Load the UI description from main.qml
    QmlDocument *qml = QmlDocument::create("asset:///main.qml");

    // We make the GameController and Application object available to the UI as context properties
    qml->setContextProperty("_gameController", &gameController);
    qml->setContextProperty("_app", &app);

    // Create the application scene
    AbstractPane *appPage = qml->createRootObject<AbstractPane>();

    // Tell the gameController which Container should be used as board
    gameController.setBoard(appPage->findChild<Container*>("board"));

    Application::instance()->setScene(appPage);

    return Application::exec();
}
void LinearMovement::move(){
	//If the movement is not over yet, then do it
    if (!isReady()){
		std::pair<double, double> destinyInGL = gameController.translateMapToGL(destiny);

		//Error accepted regarded to the discretization of the movement
		double e = speed;

		//Always supose one of the coordinate are equal. Because the movement is linear (one row or one column)
		assert(fabs(object->position.first - destinyInGL.first) <= e
				|| fabs(object->position.second - destinyInGL.second) <= e);

		//Calculate how much yet to the end of movement
		double yetToMove;
		if (fabs(object->position.first - destinyInGL.first) < e){
			//firsts are "equal"(near enough), we are changing the second (or the movement is done)
			yetToMove = object->position.second - destinyInGL.second;
		}else{
			//Firsts are not equal, then get the remaining movement to perform
			yetToMove = object->position.first - destinyInGL.first;
		}
		
		//If there is no more movement to perform, then movement is ready
		if (fabs(yetToMove) < e){
			ready = true;
			object->position = destiny;

			// notify Observers, once the movement is finished
			this->notifyObservers();
		}else{
			//Define diretion and velocity of movement
			double deltaMove;
			if (forward)
				deltaMove = speed;
			else
				deltaMove = -speed;

			//Let the object define where to go and behavior in case of colision
			object->makeMovementInMap(this, deltaMove);
		}
	}
}
Exemple #26
0
void InputDaemon::secondInputPass(QQueue<SDL_Event> *sdlEventQueue)
{
    QHash<SDL_JoystickID, InputDevice*> activeDevices;

    while (!sdlEventQueue->isEmpty())
    {
        SDL_Event event = sdlEventQueue->dequeue();

        switch (event.type)
        {
            //qDebug() << QTime::currentTime() << " :";
            case SDL_JOYBUTTONDOWN:
            case SDL_JOYBUTTONUP:
            {
#ifdef USE_SDL_2
                InputDevice *joy = trackjoysticks.value(event.jbutton.which);
#else
                InputDevice *joy = joysticks->value(event.jbutton.which);
#endif
                if (joy)
                {
                    SetJoystick* set = joy->getActiveSetJoystick();
                    JoyButton *button = set->getJoyButton(event.jbutton.button);

                    if (button)
                    {
                        //button->joyEvent(event.type == SDL_JOYBUTTONDOWN ? true : false);
                        button->queuePendingEvent(event.type == SDL_JOYBUTTONDOWN ? true : false);

                        if (!activeDevices.contains(event.jbutton.which))
                        {
                            activeDevices.insert(event.jbutton.which, joy);
                        }
                    }
                }
#ifdef USE_SDL_2
                else if (trackcontrollers.contains(event.jbutton.which))
                {
                    GameController *gamepad = trackcontrollers.value(event.jbutton.which);
                    gamepad->rawButtonEvent(event.jbutton.button, event.type == SDL_JOYBUTTONDOWN ? true : false);
                }
#endif

                break;
            }

            case SDL_JOYAXISMOTION:
            {
#ifdef USE_SDL_2
                InputDevice *joy = trackjoysticks.value(event.jaxis.which);
#else
                InputDevice *joy = joysticks->value(event.jaxis.which);
#endif
                if (joy)
                {
                    SetJoystick* set = joy->getActiveSetJoystick();
                    JoyAxis *axis = set->getJoyAxis(event.jaxis.axis);
                    if (axis)
                    {
                        //axis->joyEvent(event.jaxis.value);
                        axis->queuePendingEvent(event.jaxis.value);

                        if (!activeDevices.contains(event.jaxis.which))
                        {
                            activeDevices.insert(event.jaxis.which, joy);
                        }
                    }

                    joy->rawAxisEvent(event.jaxis.which, event.jaxis.value);
                }
#ifdef USE_SDL_2
                else if (trackcontrollers.contains(event.jaxis.which))
                {
                    GameController *gamepad = trackcontrollers.value(event.jaxis.which);
                    gamepad->rawAxisEvent(event.jaxis.axis, event.jaxis.value);
                }
#endif

                break;
            }

            case SDL_JOYHATMOTION:
            {
#ifdef USE_SDL_2
                InputDevice *joy = trackjoysticks.value(event.jhat.which);
#else
                InputDevice *joy = joysticks->value(event.jhat.which);
#endif
                if (joy)
                {
                    SetJoystick* set = joy->getActiveSetJoystick();
                    JoyDPad *dpad = set->getJoyDPad(event.jhat.hat);
                    if (dpad)
                    {
                        //dpad->joyEvent(event.jhat.value);
                        dpad->joyEvent(event.jhat.value);

                        if (!activeDevices.contains(event.jhat.which))
                        {
                            activeDevices.insert(event.jhat.which, joy);
                        }
                    }
                }
#ifdef USE_SDL_2
                else if (trackcontrollers.contains(event.jhat.which))
                {
                    GameController *gamepad = trackcontrollers.value(event.jaxis.which);
                    gamepad->rawDPadEvent(event.jhat.hat, event.jhat.value);
                }
#endif

                break;
            }

#ifdef USE_SDL_2
            case SDL_CONTROLLERAXISMOTION:
            {
                InputDevice *joy = trackcontrollers.value(event.caxis.which);
                if (joy)
                {
                    SetJoystick* set = joy->getActiveSetJoystick();
                    JoyAxis *axis = set->getJoyAxis(event.caxis.axis);
                    if (axis)
                    {
                        //qDebug() << QTime::currentTime() << ": " << "Axis " << event.caxis.axis+1
                        //         << ": " << event.caxis.value;
                        //axis->joyEvent(event.caxis.value);
                        axis->queuePendingEvent(event.caxis.value);

                        if (!activeDevices.contains(event.caxis.which))
                        {
                            activeDevices.insert(event.caxis.which, joy);
                        }
                    }
                }
                break;
            }

            case SDL_CONTROLLERBUTTONDOWN:
            case SDL_CONTROLLERBUTTONUP:
            {
                InputDevice *joy = trackcontrollers.value(event.cbutton.which);
                if (joy)
                {
                    SetJoystick* set = joy->getActiveSetJoystick();
                    JoyButton *button = set->getJoyButton(event.cbutton.button);

                    if (button)
                    {
                        //button->joyEvent(event.type == SDL_CONTROLLERBUTTONDOWN ? true : false);
                        button->queuePendingEvent(event.type == SDL_CONTROLLERBUTTONDOWN ? true : false);

                        if (!activeDevices.contains(event.cbutton.which))
                        {
                            activeDevices.insert(event.cbutton.which, joy);
                        }
                    }
                }

                break;
            }

            case SDL_JOYDEVICEREMOVED:
            {
                InputDevice *device = joysticks->value(event.jdevice.which);
                if (device)
                {
                    Logger::LogInfo(QString("Removing joystick #%1 [%2]")
                                    .arg(device->getRealJoyNumber())
                                    .arg(QTime::currentTime().toString("hh:mm:ss.zzz")));

                    //activeDevices.remove(event.jdevice.which);
                    removeDevice(device);
                }

                break;
            }

            case SDL_JOYDEVICEADDED:
            {
                Logger::LogInfo(QString("New joystick found - #%1 [%2]")
                                .arg(event.jdevice.which+1)
                                .arg(QTime::currentTime().toString("hh:mm:ss.zzz")));
                addInputDevice(event.jdevice.which);
                break;
            }
#endif

            case SDL_QUIT:
            {
                stopped = true;
                break;
            }

            default:
                break;
        }

        // Active possible queued events.
        QHashIterator<SDL_JoystickID, InputDevice*> activeDevIter(activeDevices);
        while (activeDevIter.hasNext())
        {
            InputDevice *tempDevice = activeDevIter.next().value();
            tempDevice->activatePossibleControlStickEvents();
            tempDevice->activatePossibleAxisEvents();
            tempDevice->activatePossibleDPadEvents();
            tempDevice->activatePossibleVDPadEvents();
            tempDevice->activatePossibleButtonEvents();
        }

        if (JoyButton::shouldInvokeMouseEvents())
        {
            // Do not wait for next event loop run. Execute immediately.
            JoyButton::invokeMouseEvents();
        }
    }
}
Exemple #27
0
LRESULT CALLBACK WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) {
	switch (uMsg) {
	case WM_CREATE:
		gc.Initial(hWnd);
		gc.StartGame();
		break;

	case WM_DESTROY:
		gc.Destroy();
		::PostQuitMessage(0);
		break;

	case WM_TIMER:
		gc.NextFrame();
		break;

	case WM_KEYDOWN:
		switch (wParam) {
		case VK_LEFT:
			gc.Swipe(GameController::SWIPE_LEFT);
			break;
		case VK_UP:
			gc.Swipe(GameController::SWIPE_UP);
			break;
		case VK_RIGHT:
			gc.Swipe(GameController::SWIPE_RIGHT);
			break;
		case VK_DOWN:
			gc.Swipe(GameController::SWIPE_DOWN);
			break;
		case VK_ESCAPE:
			if (IDYES == ::MessageBox(hWnd,_T("Are you sure to restart?"),_T("WTF2048"),MB_ICONQUESTION | MB_YESNO)) {
				gc.StartGame();
			}
			break;
		}
		if (gc.IsGameOver()) {
			if (IDYES == ::MessageBox(hWnd,_T("Game over, try again?"),_T("WTF2048"),MB_ICONWARNING | MB_YESNO)) {
				gc.StartGame();
			}
		}
		break;

	case WM_PAINT:
		{
			PAINTSTRUCT ps;
			::BeginPaint(hWnd,&ps);
			gc.OutputUI(ps.hdc);
			::EndPaint(hWnd,&ps);
		}
		break;

	default:
		return ::DefWindowProc(hWnd,uMsg,wParam,lParam);
	}
	return 0;
}
Exemple #28
0
    GameOverState::GameOverState(const std::string &name, const Json::Value &params, GameController & controller, ServiceLocator &services)
        : name(name)
        , controller(controller)
        , audioService(services.locateService<AudioService>(Services::AUDIO))
        , keyboardInput(services.locateService<InputService>(Services::INPUT))
        , mainPanel(new gui::Panel())
        , guiWrapper(new gcn::Container())
        , guiMenu(new gui::Menu())
        , guiCursorIcon(new gui::Icon("assets/images/sp-gui-atlas.png"))
        , gameOverLabel(new gcn::Label())
        , guiService(services.locateService<GuiService>(Services::GUISERVICE))
        , goToNextState(false)
    {
        guiCursorIcon->setSubrectangle(gcn::Rectangle(0, 0, 4, 8));
        guiCursorIcon->setWidth(4);
        guiCursorIcon->setHeight(8);

        guiWrapper->setWidth(256);
        guiWrapper->setHeight(240);
        guiWrapper->setOpaque(true);
        guiWrapper->setBaseColor(gcn::Color(0, 112, 236));

        gameOverLabel->setCaption("GAME OVER");
        gameOverLabel->adjustSize();

        std::shared_ptr<gui::MenuItem> continueMenuItem(new gui::MenuItem(ITEM_CONTINUE));
        continueMenuItem->setForegroundColor(gcn::Color(0, 0, 0, 0));
        continueMenuItem->setSelectionColor(gcn::Color(0, 0, 0, 0));
        guiMenu->addItem(continueMenuItem);

        std::shared_ptr<gui::MenuItem> passWordMenuItem(new gui::MenuItem(ITEM_PASS_WORD));
        passWordMenuItem->setY(16);
        passWordMenuItem->setForegroundColor(gcn::Color(0, 0, 0, 0));
        passWordMenuItem->setSelectionColor(gcn::Color(0, 0, 0, 0));
        guiMenu->addItem(passWordMenuItem);

        std::shared_ptr<gui::MenuItem> stageSelectMenuItem(new gui::MenuItem(ITEM_STAGE_SELECT));
        stageSelectMenuItem->setY(32);
        stageSelectMenuItem->setForegroundColor(gcn::Color(0, 0, 0, 0));
        stageSelectMenuItem->setSelectionColor(gcn::Color(0, 0, 0, 0));
        guiMenu->addItem(stageSelectMenuItem);

        std::shared_ptr<gui::MenuItem> titleScreenMenuItem(new gui::MenuItem(ITEM_TITLE_SCREEN));
        titleScreenMenuItem->setY(48);
        titleScreenMenuItem->setForegroundColor(gcn::Color(0, 0, 0, 0));
        titleScreenMenuItem->setSelectionColor(gcn::Color(0, 0, 0, 0));
        guiMenu->addItem(titleScreenMenuItem);

        guiMenu->setSelectedIndex(0);

        mainPanel->setWidth(guiWrapper->getWidth() - 32);
        mainPanel->setHeight(guiWrapper->getHeight() - 32);
        mainPanel->setBaseColor(gcn::Color(0, 0, 0));

        guiMenu->setWidth(mainPanel->getWidth() - 24);
        guiMenu->setHeight(mainPanel->getHeight() - 16);
        guiMenu->setBackgroundColor(gcn::Color(0, 0, 0, 0));
        guiMenu->enableWrapping();

        guiActionListener.reset(new gcn::FunctorActionListener([&](const gcn::ActionEvent& event) {
            auto item = guiMenu->getMenuItemAt(guiMenu->getSelectedIndex());

            if(item) {
                std::cout << "Actioned on #" << guiMenu->getSelectedIndex() << ", " << item->getName() << std::endl;

                const std::string & menuItemName = item->getName();

                if(menuItemName == ITEM_CONTINUE) {
                    controller.requestStateChange("gameplay");
                    goToNextState = true;
                } else if(menuItemName == ITEM_PASS_WORD) {
                    controller.requestStateChange("password");
                    goToNextState = true;
                } else if(menuItemName == ITEM_STAGE_SELECT) {
                    controller.requestStateChange("stageselect");
                    goToNextState = true;
                } else if(menuItemName == ITEM_TITLE_SCREEN) {
                    controller.requestStateChange("title");
                    goToNextState = true;
                }
            }
        }));

        guiSelectionListener.reset(new gcn::FunctorSelectionListener([&](const gcn::SelectionEvent & event) {
            std::cout << "Selection changed! " << guiMenu->getSelectedIndex() << std::endl;

            positionCursorOnItem();

            if(auto audio = audioService.lock()) {
                audio->playSample("Menu Item Select");
            }
        }));

        guiMenu->addActionListener(guiActionListener.get());
        guiMenu->addSelectionListener(guiSelectionListener.get());

        guiWrapper->add(gameOverLabel.get(), 100, 4);
        guiWrapper->add(mainPanel.get(), 16, 16);
        mainPanel->add(guiMenu.get(), 24, 16);
        guiWrapper->add(guiCursorIcon.get(), 16, 16);
    }
		virtual void FileSelected(SaveFile* file)
		{
			c->LoadSaveFile(file);
			delete file;
		}
		virtual void ConfirmCallback(ConfirmPrompt::DialogueResult result) {
			if (result == ConfirmPrompt::ResultOkay)
			{
				c->RunUpdater();
			}
		}