2013-07-10 11 views
7

Sto supervisionando un campo tecnologico in cui uno dei campeggiatori ha creato un codice per un videogioco basato su testo che ha problemi a visualizzare i risultati. Mentre il programma si compila e funziona correttamente, non si aggiungerà alla salute del giocatore quando viene scelto "heal" e otteniamo anche zero quando l'utente sceglie "attack". Ho una conoscenza limitata della programmazione e sto cercando di aiutarlo nel miglior modo possibile affinché la sua esperienza qui sia piacevole e appagante. Se potessi offrire qualsiasi aiuto o consiglio, saremmo così grati. Ecco il codice:Gioco di avventura basato sul testo

// Test for hard stuff.cpp : Defines the entry point for the console application. 
// 
// Bigger proj 
// Constructors will make characters with rolling statistics 

#include "stdafx.h" 
#include <iostream> 
#include <string> 
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

using namespace std; 
// declaring function for hit power 
//int power(int str, int def); 

    int command; 


class character 
{ 
public: 
    character(); 
    //~character(); 
    string name; 
    float str; 
    float def; 
    float health; // hit points 
    float regen; // health regen amount 
    float roll;  // for random value 
    float ouch;  // amount of attack damage 
    float getAttack(void); 
    float getHeal(void); 
    void setRegen(float reg); 
    //void setHeal(float healAmt); 

private: 


}; 

character::character() 
{ 
    srand(time_t(NULL)); 
    str = rand() % 30 + 5; 
    def = rand() % 30 + 5; 
    health = 100; 
    //Output to check the constructor is running properly 
    cout<< "Character has been created.\n"; 
} 

void character::setRegen(float reg) 
{ 
    regen = reg; 
} 


float character::getAttack() 
{ 
//defines the magnitude/power of attack 
    //function shows how much damage is inflicted 


    // ouch is how much damage is done 
    roll = rand() % 20 + 1; // range between 1 &20 

    if (roll <= 11) 
    { 
     ouch = str - (def /2); 
    } 

    else if ((roll <= 17) && (roll >= 12)) 
    { 
     ouch = (str * 2) - (def/2); 
    } 

    else if ((roll <= 20) && (roll >= 18)) 
    { 
     ouch = (str * 3) - (def/2); 
     //cout << "CRITICAL HIT!!"; 
    } 

    return ouch; 

} 

float character::getHeal() 
{ 
    //this is what happens when you chose to heal 
    regen = rand() % 20 + 3; 
    cout << "regen value= " << regen<< ".\n"; 
    return regen; 
} 

/*character::~character() 
{ 
    str = 0; 
    def = 0; 
    health = 0; 
    // Output to check the destructor is running properly 
    cout << "Character has been destroyed\n"; 
} */ 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    //Class objects 
    character user, computer; 
    //Hard code in a name for the computer's player 
    computer.name = "ZOID\n"; 

    float attackDamage; 
    float healthAdded; 

    user.setRegen(void); 

    //Recieve data for the user's player 
    cout<< "Please enter a name for your character:\n"; 
    cin>> user.name; 

    //Output name and stats to the user 
    cout<< "\nYour name is: " << user.name << endl; 
    cout << "here are your statistics: \n" 
     << "strength: " << user.str << endl 
     << "Defense: " << user.def << endl 
     << "Health:  " << user.health << endl; 

    cout<< "oh no an oppenent appeared!!!\n"; 
     cout<< "you will have to fight him!" << endl<< endl; 

    cout << "opponent's health: 100" << endl 

     << "what would you like to do: heal (1), attack(2), or run(3).\n"; 
    cin>> command; 




     switch(command) 
     { 
     case 1 : 

      healthAdded = user.getHeal(); 

      cout<< ""<<user.name <<" has regenerated " << healthAdded << " health.\n"; 

      break; 

     case 2 : 

      attackDamage = user.getAttack(); 

      cout << "" <<user.name <<" did " << attackDamage << " damage to the opponent!\n"; 

      break; 

     case 3: 

      cout<< ""<<user.name<<" got away!\n"; 

      break; 

     default: 
      cout<< "Please enter a valid choice!"; 

     } //end switch 

    return 0; 

} 
+1

dire loro di usare 'srand' solo una volta, all'inizio del programma. – chris

+1

'user.getHeal' non fa nulla per la salute e non lo usi altrimenti. Non vedo come la salute potrebbe cambiare. – chris

+1

Fornisce solo regen e regen non è ancora stato collegato alla salute. Dov'è l'iterazione basata su turni? Regen dovrebbe lavorare lì. –

risposta

2

In generale, uno dei modi per affrontare questo tipo di problema è esaminare cosa succede riga per riga e determinare quali ogni linea fa. A volte è lungo (molte volte, davvero), ma fa anche un buon lavoro per assicurarti di non perdere nulla. In questo caso particolare, guardiamo al problema della cura.

Quando si inserisce l'istruzione switch e si preme il caso 1 (healing), questa prima cosa che il codice fa è assegnare i risultati di user.getHeal() a healthAdded. Quello che fai da qui è "Entra in" getHeal() e guarda cosa fa. getHeal() ottiene un numero di riferimento e lo assegna a rigenerare. Quindi stampa la rigenerazione e infine restituisce il valore memorizzato in rigenerazione.

Ora che sappiamo cosa fa getHeal(), possiamo tornare al nostro caso 1: e dire completamente cosa fa la prima linea. Prende il valore di rigenerazione incorporato in getHeal() e lo assegna a healthAdded.

caso 1: stampa il valore in saluteAggiunto prima dell'interruzione; dichiarazione. La pausa; finiture caso 1.

Così che cosa il vostro codice ha fatto in forma breve lista era:

  • generano guarire valore
  • stampa due volte

quello che si voleva fare era modificare la salute dell'utente in base al valore di rigenerazione, quindi hai un passaggio mancante: modifica del valore user.health con il numero di regen che hai creato in getHeal().

Il problema con il danno di attacco è simile, prova a confrontare ciò che vuoi che il codice faccia in termini obiettivi con quello che vedi che il codice sta effettivamente facendo.

6

Cercherò di aiutare nel miglior modo possibile un pezzo alla volta. I miei numeri di linea potrebbero essere leggermente diversi dai tuoi, quindi sentiti libero di guardarti intorno un po '.

In:

115  user.setRegen(void); 

setRegen è dichiarato di prendere una float:

20 class character 
21 { 
22 public: 
. 
. 
. 
34  void setRegen(float reg); 

quindi non si può passare void. Per inciso, in C++ è consuetudine passare semplicemente nulla quando si chiama una funzione che non accetta parametri, piuttosto che passare un esplicito void. Tuttavia, l'esplicito void è OK.

La funzione getHeal() calcola una quantità casuale per curare il carattere con, ma in realtà non incrementa la variabile membro health.Si potrebbe implementare la guarigione in questo modo, vedere la linea 92:

87 float character::getHeal() 
88 { 
89  //this is what happens when you chose to heal 
90  regen = rand() % 20 + 3; 
91  cout << "regen value= " << regen<< ".\n"; 
92  health += regen; 
93  return regen; 
94 } Z 

Inoltre, non stanno riducendo la salute dell'avversario quando si attacca. Un modo si potrebbe fare questo è di passare un riferimento per l'opponente a getAttack() e modificare lì:

58 float character::getAttack(character& opponent) 
59 { 
60 //defines the magnitude/power of attack 
61  //function shows how much damage is inflicted 
62 
63 
64  // ouch is how much damage is done 
65  roll = rand() % 20 + 1; // range between 1 &20 
66 
67  if (roll <= 11) 
68  { 
69   ouch = str - (def /2); 
70  } 
71 
72  else if ((roll <= 17) && (roll >= 12)) 
73  { 
74   ouch = (str * 2) - (def/2); 
75  } 
76 
77  else if ((roll <= 20) && (roll >= 18)) 
78  { 
79   ouch = (str * 3) - (def/2); 
80   //cout << "CRITICAL HIT!!"; 
81  } 
82 
83  opponent.health -= ouch; 
84 
85  return ouch; 
86 
87 } 

Avrete anche bisogno di modificare la dichiarazione (prototipo) per getAttack():

20 class character 
21 { 
22 public: 
. 
. 
. 
32  float getAttack(character& opponent); 

... e come viene chiamato in main():

152   case 2 :  
153  
154    attackDamage = user.getAttack(computer); 
155  
156    cout << "" <<user.name <<" did " << attackDamage << " damage to the opponent!\n"; 
157 
158    break; 

ho anche notato che il programma non fa circuito a tutti. Accetta solo un'azione, la esegue e termina. Il gioco potrebbe essere più divertente se è in loop fino a quando uno dei giocatori è morto.

Un'ultima cosa, quando si utilizzano numeri casuali, si chiama srand esattamente uno, in genere all'inizio della corsa del programma. Lo stai chiamando ogni volta che viene creato un character.

Here è uno spinotto spudorato per una delle mie precedenti risposte sull'utilizzo di rand.

Ho apportato alcune modifiche per voi. Qui è un link to ideone con lo stesso codice, come di seguito:

// Test for hard stuff.cpp : Defines the entry point for the console application. 
// 
// Bigger proj 
// Constructors will make characters with rolling statistics 

//#include "stdafx.h" 
#include <iostream> 
#include <string> 
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

using namespace std; 
// declaring function for hit power 
//int power(int str, int def); 

    int command; 


class character 
{ 
public: 
    character(); 
    //~character(); 
    string name; 
    float str; 
    float def; 
    float health; // hit points 
    float regen; // health regen amount 
    float roll;  // for random value 
    float ouch;  // amount of attack damage 
    float getAttack(character& opponent); 
    float getHeal(void); 
    void setRegen(float reg); 
    bool IsAlive() const; 
    //void setHeal(float healAmt); 

private: 


}; 

character::character() 
{ 
    str = rand() % 30 + 5; 
    def = rand() % 30 + 5; 
    health = 100; 
    //Output to check the constructor is running properly 
    cout<< "Character has been created.\n"; 
} 

bool character::IsAlive() const 
{ 
    return health > 0.0f; 
} 

void character::setRegen(float reg) 
{ 
    regen = reg; 
} 


float character::getAttack(character& opponent) 
{ 
//defines the magnitude/power of attack 
    //function shows how much damage is inflicted 


    // ouch is how much damage is done 
    roll = rand() % 20 + 1; // range between 1 &20 

    if (roll <= 11) 
    { 
     ouch = str - (def /2); 
    } 

    else if ((roll <= 17) && (roll >= 12)) 
    { 
     ouch = (str * 2) - (def/2); 
    } 

    else if ((roll <= 20) && (roll >= 18)) 
    { 
     ouch = (str * 3) - (def/2); 
     //cout << "CRITICAL HIT!!"; 
    } 

    opponent.health -= ouch; 

    return ouch; 

} 

float character::getHeal() 
{ 
    //this is what happens when you chose to heal 
    regen = rand() % 20 + 3; 
    cout << "regen value= " << regen<< ".\n"; 
    health += regen;  
    return regen; 
} 
/*character::~character() 
{ 
    str = 0; 
    def = 0; 
    health = 0; 
    // Output to check the destructor is running properly 
    cout << "Character has been destroyed\n"; 
} */ 


int main() 
{ 
    srand(time_t(NULL)); 
    //Class objects 
    character user, computer; 
    //Hard code in a name for the computer's player 
    computer.name = "ZOID\n"; 

    float attackDamage; 
    float healthAdded; 

    user.setRegen(42.0); 

    //Recieve data for the user's player 
    cout<< "Please enter a name for your character:\n"; 
    cin>> user.name; 

    //Output name and stats to the user 
    cout<< "\nYour name is: " << user.name << endl; 
    cout << "here are your statistics: \n" 
     << "strength: " << user.str << endl 
     << "Defense: " << user.def << endl 
     << "Health:  " << user.health << endl; 

    cout<< "oh no an oppenent appeared!!!\n"; 
     cout<< "you will have to fight him!" << endl<< endl; 

    cout << "opponent's health: 100" << endl; 


    while (user.IsAlive() && computer.IsAlive()) 
    { 
     cout << "Str: " << user.str << "\t" 
      << "Def: " << user.def << "\t" 
      << "Health: " << user.health << "\t" 
      << "\n"; 

     cout << "what would you like to do: heal (1), attack(2), or run(3).\n"; 
     cin>> command; 

     switch(command) 
     { 
     case 1 : 

      healthAdded = user.getHeal(); 

      cout<< ""<<user.name <<" has regenerated " << healthAdded << " health.\n"; 

      break; 

     case 2 : 

      attackDamage = user.getAttack(computer); 

      cout << "" <<user.name <<" did " << attackDamage << " damage to the opponent!\n"; 

      break; 

     case 3: 

      cout<< ""<<user.name<<" got away!\n"; 

      break; 

     default: 
      cout<< "Please enter a valid choice!"; 

     } //end switch 
    } 
    return 0; 

} 
+0

Grazie mille per il vostro aiuto @ John Dibling, vorrei che aveste visto quanto estatico fosse il camper una volta che abbiamo implementato le vostre modifiche e aggiunto alcune altre cose per farlo funzionare. Ne è valsa la pena! – user2569892

+1

fantastico. dì al campeggiatore che sono rimasto molto colpito dal suo codice. potrebbe avere un vero futuro nella programmazione! –

Problemi correlati