Change a variable within a function each time you call it

4

This program must cause two bots to attack each other, first one then the other, and I made an attack function but I do not know how to make it general for when I call it the first time the variables that are inside the function correspond to those of robot A, then attack the robot b and call the function again and the variables must match those of robot B.

#include "pch.h"
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct Bots
{
    const int regen = 5;
    int hp = rand() % 50 + 50;
    int attack = rand() % 10 + 10;
    int shield = 100;
    int mana = 10;
};

void BotsAttack();

int main()
{
    int remain;
    srand(time(NULL));
    Bots botA;
    Bots botB;


    if (botA.shield < 100 || botA.mana < 100)
    {
    botA.shield += 5;
    botA.mana += 5;
    }

    _getch();

}

void BotsAttack() {
    if (botA.mana >= botA.attack)
    {
        if (botA.attack > botB.shield)
        {
            remain = botB.shield - botA.attack;
            botB.hp += remain;
            botB.shield = 0;
            printf("El BotA ataca con %d de danyo.\nDestruye el escudo y la vida restante del BotB es %d", botA.attack, botB.hp);
        }
        else
        {
            botB.shield -= botA.attack;
            printf("El BotA ataca con %d e impacta con el escudo de l BotB pero no lo destruye", botA.attack);
        }
    }
    else
    {
        printf("Bot A no pudo atacar por que no le alcanza el mana\n");
    }
}
    
asked by Humberto Escorce 07.10.2018 в 17:53
source

2 answers

5

The simplest solution would be to implement the function BotsAttack() that accepts two parameters, one reference to the attacking bot and the other to the defending bot:

void BotsAttack(Bots &atacante, Bots &defensor) {
    int remain;
    if (atacante.mana >= atacante.attack)
    {
        if (atacante.attack > defensor.shield)
        {
            remain = defensor.shield - atacante.attack;
            defensor.hp += remain;
            defensor.shield = 0;
            printf("El atacante ataca con %d de danyo.\nDestruye el escudo y la vida restante del defensor es %d", atacante.attack, defensor.hp);
        }
        else
        {
            defensor.shield -= atacante.attack;
            printf("El atacante ataca con %d e impacta con el escudo de l BotB pero no lo destruye", atacante.attack);
        }
    }
    else
    {
        printf("El atacante no pudo atacar por que no le alcanza el mana\n");
    }
}

and then you can make calls in main() of BotsAttack(botA, botB) for A to attack B and then BotsAttack(botB, botA) for the opposite case.

A more "object-oriented" solution but without encapsulation would be to implement methods in your struct Bots, methods such as attackBot(el_otro) , regenerarse() and a constructor. The code will test it with clang ++ in MacOSx but it should work fine in MS VC ++

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string>

struct Bots
{
    const int regen = 5;

    std::string name;
    int hp;
    int attack;
    int shield;
    int mana;

    //Contructor con inicializacion
    Bots(std::string name_):
        name   {name_},
        hp     {rand() % 50 + 50},
        attack {rand() % 10 + 10},
        shield {100},
        mana   {10}
    {
    }

    //Metodo para mostrar su estado
    void showStats(){
        printf(" Stats para [%s] > [hp: %d] [attack: %d] [shield: %d] [mana: %d]\n",
            name.c_str(), hp, attack, shield, mana);
    }

    // Metodo de regeneracion
    void regenerate() 
    {
        if (this->shield < 100 || this->mana < 100) {
            this->shield += regen;
            this->mana += regen;
            printf(" [%s] >  se pudo regenerar [hp: %d] [attack: %d] [shield: %d] [mana: %d]\n",
                name.c_str(), hp, attack, shield, mana);
        }
    }

    //This ataca al otro
    void attackBot(Bots &other)
    {
        int remain;

        if (this->mana >= this->attack) {
            if (this->attack > other.shield) {
                remain = other.shield - this->attack;
                other.hp += remain;
                other.shield = 0;
                printf(" El %s ataca con %d de danyo.\nDestruye el escudo y la vida restante del %s es %d \n",
                 this->name.c_str(), this->attack,other.name.c_str(), other.hp);
            } else {
                other.shield -= this->attack;
                printf(" El %s ataca con %d e impacta con el escudo de el %s pero no lo destruye\n",
                 this->name.c_str(), this->attack, other.name.c_str());
            }
        } else {
            printf(" %s no pudo atacar por que no le alcanza el mana\n", this->name.c_str());
        }
    }
};


int main()
{
    int turno = 1;     //Contador de turnos
    srand(time(NULL)); //Semilla

    Bots botA("Bot A");//nuevo bot con nombre Bot A
    Bots botB("Bot B");    

    //ciclo de ataques
    while(botA.hp >= 0 && botB.hp >= 0){ //Verificar si estan vivos
        printf("====TURNO #%d =====================\n", turno);
        printf("----INICIO-----------\n");
        botA.showStats(); //Mostramos caracteristicas 
        botB.showStats();
        printf("----Regeneracion-----\n");
        botA.regenerate(); 
        botB.regenerate();
        printf("----Ataque-----------\n");
        botA.attackBot(botB); // A ataca B
        botB.attackBot(botA); // B ataca A

        turno++;
    } //Siguinte turno

    // la vida de alguno de los dos es menor o igual a 0 
    printf("====FIN #%d =====================\n", turno);
    botA.showStats();
    botB.showStats();

}
    
answered by 07.10.2018 в 19:51
3

Before sharing my suggestion, I would like to point out some details of your code:

  • Headers <stdio.h> , <stdlib.h> and <time.h> are from not from < a href="/ questions / tagged / c% 2b% 2b" class="post-tag" title = 'show questions with the tag "c ++"'> c ++ . The headers of C have a version adapted to C ++ that has the prefix c and lacks extension. If you really need to use the C headers (which will never be the case) you should use the C ++ equivalents <cstdio> , <cstdlib> and <ctime> . Read this thread to find out why.
  • The header <conio.h> ni siquera is standard C and does not exist in C ++, see this thread to know why.
  • The functions rand() and srand() belong to the C libraries, it is not recommended to use those utilities in C ++ because they may not be portable and may offer questionable results and performance, therefore is being studied deprecarlo . From the C ++ 11 standard there is a complete library of generation of pseudo-random numbers that you should use instead. Read this thread to find out why.
  • The printf function is the console write function of C, in C ++ a stream object is used: std::cout .

Proposal.

You can create an attack function that tells you who is attacking and who is attacked:

void Atacar(Bot &atacante, Bot &atacado) {
    if (atacante.mana >= atacante.attack)
    {
        if (atacante.attack > atacado.shield)
        {
            remain = atacado.shield - atacante.attack;
            atacado.hp += remain;
            atacado.shield = 0;

            std::cout << "El atacante ataca con" << atacante.attack
                      << " de danyo.\nDestruye el escudo y la vida restante"
                         " del atacado es " << atacado.hp;
        }
        else
        {
            atacado.shield -= atacante.attack;

            std::cout << "El atacante ataca con" << atacante.attack
                      << " e impacta con el escudo de el atacado pero"
                         " no lo destruye";
        }
    }
    else
    {
        std::cout << "Bot atacante no pudo atacar por que no le alcanza el mana\n";
    }
}

With the previous code, when you want A to attack B, you must make this call:

Atacar(BotA, BotB);

And when you want to make B attack A:

Atacar(BotB, BotA);
    
answered by 07.10.2018 в 19:38