2013-07-10 5 views
7

캠프 중 하나가 결과를 표시하는 데 문제가있는 텍스트 기반 비디오 게임 코드를 만든 기술 캠프를 감독합니다. 프로그램이 올바르게 컴파일되고 실행되는 동안 "치료"가 선택되면 플레이어의 건강 상태에 추가되지 않으며 사용자가 "공격"을 선택하면 0이됩니다. 나는 프로그래밍에 대한 지식이 제한되어 있으며, 내가 할 수있는 최선을 다해 도움을 주려고 노력하고 있으므로 여기에서 그의 경험이 즐겁고 만족 스러울 것입니다. 도움이나 조언을 제공 할 수 있다면 우리는 그렇게 감사 할 것입니다. 일반적으로텍스트 기반 어드벤처 게임

// 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

'srand'는 프로그램 시작시 한 번만 사용하도록 알려줍니다. – chris

+1

는'user.getHeal'는 건강에 아무것도하지 않고 그렇지 않으면 사용하지 마십시오. 건강이 어떻게 바뀔지는 모르겠다. – chris

+1

만 재생성를 제공하고 재생성 아직 건강에 연결되지 않았습니다. turn-based iteration은 어디에 있습니까? Regen이 거기에서 일하기로되어 있습니다. 아이들을 도와 주려고 및 재미있는 방법으로 프로그램 학습을 장려 –

답변

2

, 문제의이 종류를 접근하는 방법 중 하나가 라인으로 라인을 어떻게되는지 검토하고 각 행이 무엇을 결정하는 것입니다 : 여기에 코드입니다. 때로는 길기 때문에 (여러 번, 정말로), 당신이 무엇이든 놓치지 않도록하는 훌륭한 일도합니다. 이 특별한 경우에는 치유 문제를 살펴보십시오.

switch 문을 입력하고 사례 1 (치료)을 클릭하면 코드에서 수행하는 첫 번째 작업은 user.getHeal()의 결과를 healthAdded에 할당하는 것입니다. 여기서부터하는 일은 getHeal()에 "들어가서"무엇을하는지 봅니다. getHeal()은 재생 횟수를 얻고 재생 횟수를 할당합니다. 그런 다음 regen을 인쇄하고 regen에 저장 한 값을 반환합니다.

이제 getHeal()이하는 것을 알았으므로 첫 번째 행에서 무엇을하는지 완전히 말할 수 있습니다. getHeal()에 내장 된 regen 값을 사용하여이를 healthAdded에 할당합니다.

사례 1 : 다음은 중단되기 전에 healthAdded에 값을 인쇄합니다. 성명서. 쉬는 시간; 경우 완료 1.

코드이었다 빠른 목록 형태로했다 그럼 :

  • 값을

이 두 번 당신이하고 싶었던 무엇

  • 인쇄를 치유 생성 사용자의 건강을 수정했다 regen 값을 기반으로하므로 getHeal()에서 빌드 한 재생 횟수로 user.health 값을 변경하면 단계가 누락됩니다.

    공격 손상의 문제는 비슷합니다. 코드에서 목표와 같은 것을 코드가 실제로하는 것과 비교해보십시오.

  • 6

    나는 한 번에 할 수있는 한 최선을 다해 도움을줍니다. 내 라인 번호가 너와 약간 다를 수 있으므로 조금만 둘러 보시기 바랍니다. 에서

    :

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

    그래서 당신은 통과 할 수 void :

    115  user.setRegen(void); 
    

    setRegenfloat 걸릴 선언된다. 덧붙여 말하자면 C++에서 명시적인 void을 전달하는 것이 아니라 매개 변수가없는 함수를 호출 할 때 아무 것도 전달하지 않는 것이 일반적입니다. 그러나 명시적인 void은 정상입니다.

    getHeal() 함수는 문자를 치유하기 위해 임의의 값을 계산하지만 실제로는 health 멤버 변수를 증가시키지 않습니다.당신은이 방법으로 치유를 구현 (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 
    

    당신은 또한 상대의 건강을 감소되지 않습니다.

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

    : 또한 getAttack()에 대한 선언 (프로토 타입)을 변경해야합니다

    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 } 
    

    : 당신이 할 수있는 한 가지 방법은 getAttack()에 상대에 대한 참조를 전달하고 거기를 수정하는 것입니다 ... 그리고 그것은 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; 
    

    . 그것은 단지 하나의 행동을 받아 들여 실행하고 종료합니다. 게임 중 하나가 죽을 때까지 반복되면 게임이 더 재미있을 수 있습니다. 임의의 숫자를 사용하는 경우

    마지막 한가지는, 프로그램의 실행의 시작 부분에 일반적으로, srand 정확히 하나를 호출합니다. character이 생성 될 때마다 호출하고 있습니다.

    Hererand 사용에 대한 내 이전의 대답 중 하나에 대한 뻔뻔한 플러그입니다.

    내가 당신을 위해 몇 가지 수정을했다. 다음과 같은 코드를 가진 link to ideone이 있습니다 :

    // 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

    도움을 주셔서 대단히 감사합니다. @ 존 디 블링 (Jon Dibling), 일단 캠퍼가 변경 사항을 구현하고 난 후 몇 가지 작업을 추가하면 캠퍼스가 얼마나 황홀했는지 알 수 있었으면 좋겠습니다. 그만한 가치가있었습니다! – user2569892

    +1

    굉장합니다. 캠프에 나는 그의 코드에 깊은 인상을 받았습니다. 그는 프로그래밍의 진정한 미래를 누릴 수 있습니다! –

    관련 문제