How to create a function that listens for a button press before continuing?

Started by Salsa, 09 June 2015, 05:39:45

Salsa

Hi, firstly I just wanted to say thank you to the creator of TGUI for making something like this, it's been very easy to use and learn for coding newbies like me.

I am making a turn based battle system for a small game I'm working on.  The player takes a turn, then the enemy takes a turn etc. My issue as of late is getting the turns to be "orderly" - and this may be more of a programming question than a specific tgui question. The problem is that the player never gets to take a turn and instead the monster keeps taking turns until the player is dead and the player never gets a chance.



(Sorry for the crap art, I am just playing around with the core game mechanics  :P)

What I want to accomplish is to have an event that waits for a list box or button press from the user before continuing, and I am at a loss as how to do that with tgui. What is happening is that the event for the player's turn listens for a keypress but proceeds anyway even if it got no input from the user. Is there a function for something of this nature?

Thank you!


bool Battle::TakeTurn(Player player){ //player's turn
int choice = 0;
StatusScreen("It's your turn.", sf::Color::Blue);
tgui::Callback callback;

choice = options->getSelectedItemId();

sf::Event event;

while (!gui.pollCallback(callback)){

switch (choice){
/* 1.Attack //player options
Change CA
3.Item
4.Flee*/
case 1:
StatusScreen("You chose to attack.", sf::Color::Blue);
StatusScreen(PlayerAttack(), sf::Color(222, 222, 222, 255));
playersTurn = false;
return true;
break;
}
}

}


If more code is needed for context let me know, I have a full Battle class that this is working with but I didn't want to dump a large mess of code on here, I just am wondering if there is a specific way to achieve this "listener event".


texus

What is missing in that code is indeed something that blocks. Right now that function will do nothing since there will never be callbacks since you don't give the user time to make a move. The most straightforward way to fix it is putting a while loop around the pollCallback and once there is a callback you return from the function. But then you would also have to handle events and draw to the screen in that while loop so this method leads to a lot of duplicated code.

Instead you should always have one main loop and no part of the program should be blocking so that that loop is always executed many times per second. All you need to solve your problem is a simple boolean (or an integer if there are more enemies/players). Your simplified main loop will look like this:
Code (cpp) Select
while (window.isOpen()) {
    handleEvents();

    if (playerTurn)
        takeTurn(player);
    else
        opponentTurn();

    drawEverything();
}