The basic logic of my game is:
the player goes from random room to random
there is a set of rooms that randomly repeat
each room he passes the counter goes up
he has a button where he can signal, if he goes through a room that he already passed
if a room repeats and he presses the button, he goes to the next random room and the counter goes up
if a room repeats and he didnt notice, he is set back to the unnoticed room and the counter goes back to the repeating room
The result of the following code is, that the room doesnt change at all, when he reaches the trigger at the end of the room. But there are no compiler errors.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class RoomHandler : MonoBehaviour
{
public List<Vector2> PassedRoomsAndCounter;
Vector2 roomAndCounter;
int roomCounting = 1; //position in ascending order
int roomNumber = 1; //unique number of current room
bool RepetitionWasSignaled;
float CountOfRepeatedRoom;
void Update()
{
//Has Repetition button been pressed?
bool InputRepetition = Input.GetButtonDown("Submit");
if(InputRepetition == true){
RepetitionWasSignaled = true;
}
}
void OnTriggerEnter2D(Collider2D col){
print("Trigger "+col.gameObject.name);
//collided with Scene Trigger?
if(col.gameObject.tag == "SceneTrigger"){
roomCounting++;
roomNumber = Random.Range(1,6);
roomAndCounter = new Vector2(roomNumber,roomCounting);
print(roomAndCounter);
PassedRoomsAndCounter.Add(roomAndCounter);
for(int i = 1; i < PassedRoomsAndCounter.Count; i++) { //Go throught all entries
if(PassedRoomsAndCounter[i].x == roomNumber){ //RoomNumber already passed?
if(RepetitionWasSignaled == true){ //Repetition Button pressed?
SceneManager.LoadScene(roomNumber); //Yes - go to next normal room
}else{
CountOfRepeatedRoom = PassedRoomsAndCounter[i].y;
SceneManager.LoadScene(CountOfRepeatedRoom.ToString());
}
}else{
SceneManager.LoadScene(roomNumber);
}
}
}
}
}
Related
I'm writing the part of the code which recognizes the collision and checks if the health is more than 3, if it is less than 0, then a that window and all the processes should be stopped and "game over" window should be opened. Everything works the right way, but instead of opening one "game over" window it keeps opening many of them. I don't really understand what's the problem since I closed the view window. Here is that part of the code:
void Cactus::move()
{
//getting a list of all the cactuses currently coliding with the object
QList<QGraphicsItem*>colliding_items=collidingItems();
// if one of the colliding items is a cactus, then destroy both the object and the cactus
for (int i = 0, n = colliding_items.size(); i < n; ++i)
{
if (typeid(*(colliding_items[i])) == typeid(GraphicsActor))
{
//check if the health is greater than 0
if(view->health.getHealth()>0)
{
//decrease the health
view->health.decrease();
// remove the cactus
scene()->removeItem(this);
// delete the cactus from the heap
delete this;
return;
}
//if the health is smaller than 0
else
{
//if the score you got is greater than the best score before
if(view->score.getScore()>view->score.getBestScore())
{
//assign the current score to the best score
view->score.assignBest();
}
scene()->removeItem(this);
delete this;
view->setFinished(true);
//close the game
view->close();
//open gameOver window
GameOver window1;
window1.exec();
}
}
}
//move cactus down
setPos(x(),y()+5);
//delete the cactus when it goes out of the screen
if(pos().y()>400)
{
scene()->removeItem(this);
delete this;
}
}
Sorry if the code is sloppy, I've only been working with QT for the past couple of weeks. I'm working on a small game while studying, and right now I'm working on when the player buys an item from the shop it will be placed it into the character bag.
The Problem is when I buy the item once, it works fine. But if I delete the item after purchase then repurchase the same item again it will put two of the same item into the array even though I purchased one.
I have 3 files used for this. Inventory.cpp, GameScreen.cpp, Shops.cpp.
GameScreen.cpp is the main file. Here I just initialize everything.
void GameScreen::initGame(QString &characterName, QString &characterProfession){
//PASS CHARACTERNAME AND CHARACTERPROFESSION INTO INVENTORY
inv.initCharacter(characterName, characterProfession);
//INIT BAG
inv.initBag();
//INIT MONEY
inv.initMoney();
//SHOPS INITS
mos.initShop();
mos.passMoneyToShop(inv.gold, inv.silver, inv.copper);
}
This will open the shop window. The Item connect is apart of my problem.
void GameScreen::on_mapOneShopB_clicked()
{
mos.setModal(true);
//SEND THE ITEM INTO BAG
connect(&mos, SIGNAL(getItemFromMapOneShop(const QString&)), &inv, SLOT(bagAddElement(const QString&)));
mos.show();
mos.exec();
}
Moving into Shops.cpp. I use polymorphism in this file and that's the reason why you see MapOneShop:: instead of Shops::. Sorry about the confusion. But moving on, I hit the button and it subtracts the item price from my amount of gold.
void MapOneShop::on_buyB_clicked()
{
//ONLY WORKS IF I HIT THE ITEM NAME COLUMN THEN HIT BUY
gold -= itemPrice[ui->treeWidget->currentColumn()];
//UPDATE INFORMATION
updateInformationVAndMoneyAfterBuy();
}
It then moves into updateInformationVAndMoneyAfterBuy(); which checks that I spent money, and If I did it will emit the item I need. I just emit back to GameScreen.cpp inside of void GameScreen::on_mapOneShopB_clicked() and pass them into Inventory.cpp.
void MapOneShop::updateInformationVAndMoneyAfterBuy()
{
//UPDATE INFORMATIONV FIRST TO CHECK MONEY CHANGES
if(goldCheck != gold)
{
emit getUpdatedMoneyFromShop(gold, silver, copper);
//ITEM NAME IS WHERE I STORE THE NAMES OF THE ITEMS
emit getItemFromMapOneShop(this->itemName[ui->treeWidget->currentColumn()]);
}
}
Now moving into Inventory.cpp. When the item gets passed into bagAddElement after deleting then repurchasing, I get two of the same items even though only 1 should be passed in. I am using a dynamic array for this. Below I will also show the void Inventory::on_deleteB_clicked, void Inventory::bagDeleteAt and also void Inventory::bagLWPrint functions. The items value is my array holding the shopItem strings.
void Inventory::bagAddElement(const QString& shopItem)
{
//I USE THIS TO CHECK THE VALUE shopItem.
qDebug()<<"bagAddElement: " << shopItem;
//IF THE CURRENT POSITION IN THE BAG
//IS BIGGER THAN THE CURRENT SIZE
//IT WILL INCREASE THE BAG FOR US
if(nrOfEl >= bagSize)
{
bagExpand();
}
//CHECK FOR VALUES INSIDE ARRAY AND CHECK IF THEY ARE NULL
//IF SO, IT WILL ADD THE ITEM INTO THE NULL POSITION
for(int i = 0; i < bagSize; i++)
{
if(items[i] == nullptr)
{
nrOfEl = i;
items[nrOfEl++] = shopItem;
break;
}
}
//UPDATE WIDGET LIST
bagLWPrint();
}
Here I pass the currently selected row value inside bagLW and pass it into void Inventory::bagDeleteAt.
void Inventory::on_deleteB_clicked()
{
//BagLW IS A LIST WIDGET
bagDeleteAt(bagLW->currentRow());
}
Now we look for the what's inside items[row] and set it to nullptr. Then we go into void Inventory::bagLWPrint.
void Inventory::bagDeleteAt(int row)
{
if(items[row] == nullptr)
{
//IF THE ITEM IS ALREADY NULL WILL PRINT A MESSAGE
QMessageBox::information(this,"Bag","No item in that slot");
}
else
{
//SET CURRENTLY SELECTED ITEM TO NULL
items[row] = nullptr;
bagLWPrint();
}
}
I clear bagLW and refill it with the updated array.
void Inventory::bagLWPrint()
{
bagLW->clear();
for(int i = 0; i < bagSize; i++)
{
if(items[i] != nullptr)
{
bagLW->addItem(items[i]);
}
if(items[i] == nullptr)
{
bagLW->addItem(items[i]);
}
}
}
Other notes.
-The item only gets doubled when inserted into void Inventory::bagAddElement.
-I tried adding another item inside of void GameScreen::initGame and it did not double after deleting and re-entering.
Sorry for such a long question. And any help would be much, much appreciated.
void Inventory::bagExpand()
{
//1: INCREASE BAGSPACE
bagSize *= 2;
//2: CREATE TEMP ARRAY
QString *tempItems = new QString[bagSize];
//3: COPY OVER VALID VALUES FROM OLD ARRAY
for(int i = 0; i < nrOfEl; i++)
{
tempItems[i] = items[i];
}
//4: DELETE OLD ARRAY MEMORY
delete[] items;
//5: POINT OLD ARRAY POINTER TO NEW ARRAY LOCATION
items = tempItems;
//PRINT BAGLW - (UDPATE)
bagLWPrint();
qDebug()<<"Bag has increased";
}
The problem is that you connect and re-connect the getItemFromMapOneShop signal on every button click. That means that on first click, you add it once (signal triggered, 1 slot connected). On the second click, you add it twice (signal triggered, 2 slots connected). And so on.
QObjects manage a list of all connected slots per signal, and call each of them. Connecting a slot multiple times will call it that many times
You should connect the singal only once, e.g. in the constructor; or disconnect the signal when no longer used
As #Andéon Evain pointed out, you could also use Qt::UniqueConnection. This will not add a duplicate connection if it already exists (considering sender, signal, receiver, slot). That might be useful for cases where it's unknown if already connected; not in your simple case
My Debugger (gdb) Is Saying That I Have a Segfault Error, But Cannot Tell Me Where It Is, Says ?? () For the Function.
I started Getting an Error in a very specific circumstance where I click on a weapon type item, then click on another usable item where my program segfaults. I removed most pointers from my code because at first I thought that was the problem, but it didn't change anything. I Could Not Find a Similar Bug online And Debugging Wasn't Very Helpful Because It Can't Tell Me Where Exactly The Error Is Coming From.
Relavant Player.h
class Player{
private:
int HP; //player's Health Points
int SP; //player's Special Points
int maxHP; //maximum value for the player's health points
int maxSP; //maximum value for the player's special points
uint32_t money; //how much money the player has
float speed; //speed the player will move at (pixels per frame)
bool menuOpen; //boolean which is true when the inventory Menu is open
sf::Vector2f pos; //player's position
//tests if the player is colliding with any items
//in the room, accepts the memory address of the room
bool checkForItems(Room* r);
std::vector<int> ItemInventory; //the player's inventory of items.
std::vector<TextButton> itemButtons; //vector of TextButtons that correspond with each unique item in the player's inventory
std::map<std::string, int> ItemsList; //map that stores each unique item's name and it's quantity
Control openMenu; //control to open the menu
void ItemAttributes(int id); //makes the items do something depending on what was passed
bool removeItem(int id); //removes an item from the player's inventory
void useItem(Item it); //takes an Item* and passes it's ID to ItemAttributes
void updateButtons(); //updates the buttons based on the player's inventory
Item* EquipedWeapon; //stores the player's currently equipped weapon
//enum to store the player's direction for rotations
enum direction {
up,
down,
left,
right
} currentDirection;
void setRotation();
public:
//constructor for the player, initializes maxHP, maxSP, and their position:
Player(int maxhp, int maxsp, sf::Vector2f position);
//getters:
int ItemButtonsTextSearchC(const std::wstring& text); //returns the index in itemButtons for a TextButton which *contains* the text parameter
int ItemButtonsTextSearch(const std::wstring& text); //returns the index in itemButtons for a TextButton which equals the text parameter
//setters:
void setMoney(int amount); //sets the money variable
void setHP(int hp); //sets the HP variable
void setSP(int sp); //sets the SP variable
void menu(); //inventory menu, handles all things related to the player's inventory
void draw(); //draws the player to the screen
};
Methods In Player.cpp That Cause The Problem:
void Player::menu(){
//iterate through all the items listed in itemsList:
for(auto& p : ItemsList){
//get a pointer to the item by it's name:
Item item = *Materials::getItemFromName(p.first);
//convert the item's name to a wstring for easier use in parameters:
std::wstring wItemName = std::wstring(p.first.begin(), p.first.end());
//get the index of the item's corresponding button
//by searching the itemButtons vector for a button
//whose text matches this item's name:
int bIndex = ItemButtonsTextSearch(wItemName);
if(bIndex != -1){
//store the button's position:
sf::Vector2f buttonPosition = itemButtons.at(bIndex).getPosition();
//default the Y values to 150, we need a separate Y for each one
//because there are 4 columns of buttons for each type of item
float weaponY = 150, usableY = 150, collectibleY = 150, moneyY = 150;
//switch statement to determine the position of the button:
switch(item.getType()){
case Item::Weapon:
buttonPosition.x = 100;
buttonPosition.y = weaponY;
//increment by 20 to give space between buttons:
weaponY += 20.0f;
break;
case Item::Usable:
buttonPosition.x = 375;
buttonPosition.y = usableY;
//increment by 20 to give space between buttons:
usableY += 20.0f;
break;
case Item::Collectible:
buttonPosition.x = 650;
buttonPosition.y = collectibleY;
//increment by 20 to give space between buttons:
collectibleY += 20.0f;
break;
case Item::Money:
buttonPosition.x = 925;
buttonPosition.y = moneyY;
//increment by 20 to give space between buttons:
moneyY += 20.0f;
break;
}
//set the button's position now that it's X has been determined:
itemButtons.at(bIndex).setPosition(buttonPosition);
/*
* below we will set the button's text to represent
* it's corresponding item's name as well as it's
* quantity then draw the button to the screen so
* that the client can see how many of each item
* they have, but then we change it back so that it
* doesn't break any comparisons with the button's
* Text (ItemButtonsTextSearch for example):
*/
//text representing item's quantity to append to the end of the the item's name:
std::string QuantityText = "\tx" + std::to_string(p.second);
//wide string that will be the button's text:
std::wstring wQText = wItemName + std::wstring(QuantityText.begin(), QuantityText.end());
//set the button's text (it takes wchar_t* so we call .c_str() on wQText):
itemButtons.at(bIndex).setText(wQText.c_str());
//draw the button with the temporary text to the screen:
itemButtons.at(bIndex).draw();
//poll if the button was clicked, and if it was,
//we will call useItem on it's corresponding Item:
if(itemButtons.at(bIndex).pollClicked()){
useItem(item);
}
//change the button's text back to what it was, note: there
//is a possibility of the button being removed after calling
//useItem() because when an item's quantity hits 0, the
//button corresponding with that item is removed, therefore
//we need a check after the useItem() call to make sure that
//we don't get an index out of bounds error:
if(ItemButtonsTextSearchC(wQText) != -1)
itemButtons.at(bIndex).setText(wItemName.c_str());
}
}
}
void Player::useItem(Item it){
int itemID = it.getItemID();
ItemAttributes(itemID);
}
void Player::ItemAttributes(int id){
switch(id){
case 0: //sword
//EquipedWeapon = Materials::getItem(id);
break;
case 1: //ultra potion of healing
healHP(50);
removeItem(id);
break;
}
}
bool Player::removeItem(int id){
//this will be set to true as soon as we find the item:
bool found = false;
//loop through ItemInventory and remove the first occurance of id
//if it exists, otherwise found will remain false:
for(int i = 0; i < ItemInventory.size(); i++){
if(ItemInventory.at(i) == id){
ItemInventory.erase(ItemInventory.begin() + i);
found = true;
break;
}
}
//if the item was not found in the inventory, there is no need to
//continue, we can just return false because we know that it isn't
//in the player's inventory so it can't be removed in the first place:
if(!found)
return false;
//get an iterator for the item ID's corresponding name in itemsList:
auto itr = ItemsList.find(Materials::itemNames[id]);
//check to make sure the item is actually listed; it will be
//but this is a safeguard in case something breaks:
if(itr != ItemsList.end()){
//decrement the item's quantity:
itr->second--;
//if there are none remaining, we remove it from the itemsList entirely:
if(itr->second <= 0)
ItemsList.erase(itr);
}
//update the buttons based on the new changes:
updateButtons();
//return true because if it got to this point,
//the item was found and removed:
return true;
}
int Player::ItemButtonsTextSearchC(const std::wstring& text){
if(itemButtons.size() > 0){
for(int i = 0; i < itemButtons.size(); i++){
std::wstring bTxt = itemButtons.at(i).getText();
if(bTxt.find(text) != std::string::npos)
return i;
}
}
return -1;
}
int Player::ItemButtonsTextSearch(const std::wstring& text){
if(itemButtons.size() > 0){
for(int i = 0; i < itemButtons.size(); i++){
std::wstring bTxt = itemButtons.at(i).getText();
if(bTxt == text)
return i;
}
}
return -1;
}
void Player::updateButtons(){
//first we clear the vector of itemButton:
itemButtons.clear();
//loop to go through each unique item in ItemsList map
//and make a button for each one:
for(auto& p : ItemsList){
//convert the item's name into a wstring (textbutton constructor takes wchar_t*, wstring is easier to work with):
std::wstring wName = std::wstring(p.first.begin(), p.first.end());
//add the new button to itemButtons
TextButton btn(sf::Vector2f(0, 0), sf::Color::Magenta, sf::Color::White, wName.c_str(), 18);
//make sure button presses only register once
btn.setWasClicked(true);
//add the button to the itemButtons vector:
itemButtons.push_back(btn);
}
}
bool Player::checkForItems(Room* r){
//itemIndex will == the ID of any item we collided with, if there
//was no item it returns -1
int itemIndex = r->checkForItemCollision(player.getGlobalBounds());
if(itemIndex >= 0){
//get item ID from the item we just collided with:
int itemID = r->getItem(itemIndex).collect();
//remove the item from the room and add it's ID to ItemInventory:
r->removeItem(itemIndex);
ItemInventory.push_back(itemID);
//get the item's name and add it to itemsList if it doesn't exist.
std::string itemName = Materials::itemNames[itemID];
//if the item's name is listed in itemsList, we increment it's
//quantity, else we add it and initialize it's quantity to 1:
if(ItemsList.count(itemName) != 0){
ItemsList.at(itemName)++;
} else {
ItemsList.insert(std::make_pair(itemName, 1));
}
//update the buttons in case a new item was obtained:
updateButtons();
//return true because item was found:
return true;
}
//return false, item wasn't found:
return false;
}
When I click a button, it should delete the first occurance of that item's numeric ID from itemInventory, then in itemsList it should decrement the quantity (the map's value) and if that's <= 0, it should remove that entirely. UpdateButtons clears the entire vector of buttons and makes new ones from itemsList, one button for each key. The Item class has an enum for what type of item it is, the sword (item ID 0) is a weapon, the potion (item ID 1) is a usable item, when i click on the sword (does nothing currently), then add a usable item (the potion) and click the new button that was created for usable, it has an error. This doesn't happen unless I click the sword's button first, in any other circumstance it doesn't error when I use all of the item, then add more to my inventory and use them all again. I suspect it's an error with how i'm updating buttons and removing the keys, but I can't find it. All Item Types are in the same vector of buttons, and the item type pretty much only determines where the button will be positioned.
In Player::menu, you have a loop, for(auto& p : ItemsList). Within that loop, you call a sequence (useItem(item) -> ItemAttributes(itemID) -> removeItem(id) -> ItemsList.erase(itr)) that can modify the ItemsList map you are iterating thru. This invalidates the iterators currently referring to p, so when you try access the next element in the map you get Undefined Behavior because the (internally used) iterator is no longer valid.
One possible remedy is to change your for loop to use your own iterators, and increment the iterator at the top of the loop body (before you modify the map):
for (auto it = ItemsList.begin(); it != ItemsList.end(); ) {
auto &p = *it;
++it;
// rest of for loop
}
i am trying to programm Minesweeper with Qt in c++11.
If i press a button with 0 bombs, i want to check for buttons around this button and if they have 0 bombs, too. If they have 0 bombs, i want to check the buttons. (picture: red square)
This is my button-class:
#ifndef ABUTTON_H
#define ABUTTON_H
#include "QPushButton"
#include "QMouseEvent"
class AButton : public QPushButton
{
Q_OBJECT
public:
AButton(QWidget* parent);
//AButton();
~AButton();
bool& set(bool state); //set bomb state
bool get(); //get bomb state
void increment_counter(); //increment counter for surrounding bombs
int get_counter(); //get bomb counter
bool get_locked(); //is it locked (->flagged)
void set_locked(bool); //set it to locked
AButton* get_Button(char c); //get Button above, beneath, left, right
void set_Button(AButton* Button, char c); //set Button above, ...; char is for setting the right one
private:
bool bomb; //is button a bomb
int Nachbar_Bomben; // how many bombs around this button
bool locked; // is the button locked
AButton* b_links; //pointer to the button to the left
AButton* b_rechts; //pointer to the button to the right
AButton* b_oben; //pointer to the button above
AButton* b_unten; //pointer to the button beneath
public slots:
void mousePressEvent(QMouseEvent *event);
signals:
void rightclicked();
void leftclicked();
};
#endif // ABUTTON_H
This is what happens if a button is clicked:
void Layout::ButtonClicked()
{
char Buffer [50];
AButton *clickedButton = qobject_cast <AButton*>(sender()); //which button
if (!clickedButton->get_locked())
{
clickedButton->setChecked(1); //set button to checked
{
if (clickedButton->get()) //Is button a bomb?
{
clickedButton->setText(QString ("B"));
Fehlermeldung *Fehler = new Fehlermeldung(); //make error window
Fehler->show();
}
else
{
if(clickedButton->get_counter() == 0) //has this button 0 bombs?
{
check_for_surrounding_bombs(clickedButton); //start the recursiv check, if there are buttons with 0 bombs around
}
else
{
sprintf(Buffer, "%i", clickedButton->get_counter());
clickedButton->setText(QString (Buffer)); //write how many bombs are in this button
}}}}}
My problem is, that i get a SegFault by calling the function "check_for_surrounding_bombs".
void Layout::check_for_surrounding_bombs(AButton* clickedButton) //function doesnt work
{
if (clickedButton->get_Button('o')) //does the button above exist?
{
if (clickedButton->get_Button('o')->get_counter()== 0) //has this button 0 bombs
{
clickedButton->get_Button('o')->setText(QString ("")); // write nothing in it
if (!clickedButton->get_Button('o')->get_locked()) //if it isnt locked (= set flag)
{
clickedButton->get_Button('o')->setChecked(1); //set the button to checked
}
check_for_surrounding_bombs(clickedButton->get_Button('o')); //do the same thing for the button above
}
//... the function does the same with the buttons to the left, right, beneath
I am unsure if my recursiv-approach is the right way.
The debugger gives me this error when calling the function "check_for_surrounding_bombs(clickedButton);":
enter image description here
Implementation of the get_Button member fct.
AButton* AButton::get_Button(char c)
{
if (c == 'o')
return b_oben; //return button above
else if (c == 'u')
return b_unten; //return button beneath
else if (c == 'l')
return b_links; //return button to the left
else if (c == 'r')
return b_rechts; //return button to the right
else
return 0;
}
Any idea?
Thank you in advance.
The crash is probably caused by a stack overflow. This occurs because your recursive solution has no mechanism to simplify the problem.
If you change the state of each button you have visited before recursing, then the problem would become bounded and your problem mostly go away.
A recursive solution requires some stack for each step in the solution. This is a relatively limited resource, as the stack has a bound, and can't grow into memory used for another purpose. So this case, if you had a grid layout with 100x100 elements, you could have 10,000 steps.
As such I would look to another non-recursive solution, where you create a vector or list of items left to visit, and add items to that.
It is still imperative
Don't add a location twice to the list.
Don't visit a location again, after it has been visited.
What would be the best way of counting how many times a bool flag was changed from false to true inside a game update loop? For example if I have this simple example below, where if you hold button "A" pressed the Input class sets the enable bool of the Game class to true and if you release it sets it to false and a counter inside the Game class that counts how many times enable was changed from true to false. For example if you press "A" and release twice counter should update to 2. Having Game::Update() updating at 60fps the counter would be wrong with the current approach. To fix it I moved the check and the counter inside SetEnable instead of the Update loop.
// Input class
// Waits for input
void Input::HandleKeyDown()
{
// Checks if key A is pressed down
if (key == KEY_A)
game.SetEnable(true);
}
void Input::HandleKeyUp()
{
// Checks if key A is released
if (key == KEY_A)
game.SetEnable(false);
}
// Game class
void Game::SetEnable(bool enable)
{
if(enable == enable_)
return;
enable_ = enable;
//Will increment the counter as many times A was pressed
if(enable)
counter_ += 1;
}
void Game::Update()
{
// Updates with 60fps
// Will increment the counter as long as A is pressed
/*
if(enable_ == true)
counter_ += 1;
*/
}
void Game::Update()
{
if (key == KEY_A && ! enable_)
{
enable_ = true;
++counter_;
}
else if (key == KEY_B)
enable_ = false;
}
If I get you right, you want to count how many times enable_ changes. Your code has a small flaw, imagine this example:
enable_ = false
counter = 0
update gets called, key is A -> enable_ = true, counter = 1
update gets called, key is B -> enable_ = false, counter remains 1
Function that might fix this can look, for example, like this:
void Game::Update() {
if (key == KEY_A && !enable_) { // key is A and previous state is false
++counter;
enable_ = true;
}
if (key == KEY_B && enable_) { // key is B and previous state is true
++counter;
enable_ = false;
}
}