Maplewing

8/19 C++: Class Example - PVP

Aug 18th, 2015
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. using namespace std;
  5.  
  6. class Player{
  7.     private:
  8.         // 資料(變數部分)
  9.         string name;
  10.         int hp;
  11.         int atk;
  12.    
  13.     public:
  14.         // 方法(函式部分)
  15.             // 建構式
  16.             Player(string n, int h, int a){
  17.                 name = n;
  18.                 hp = h;
  19.                 atk = a;
  20.             }
  21.            
  22.             // Get函式
  23.             string getName(){
  24.                 return name;
  25.             }
  26.            
  27.             int getHP(){
  28.                 return hp;
  29.             }
  30.            
  31.             // 行為
  32.             void attack(Player &p){
  33.                 p.hp -= atk;
  34.                 cout << name << "攻擊了" << p.name << "!" << endl;
  35.                 cout << p.name << "受到了" << atk << "點的傷害!" << endl;
  36.                 cout << p.name << "剩下了" << p.hp << "點血量!" << endl;
  37.             }
  38.            
  39.             /*
  40.                 C語言: (x) bool (int: 1, 0)
  41.                 C++語言: bool (true, false)
  42.             */
  43.             bool isDead(){
  44.                 if( hp > 0 ){
  45.                     return false;
  46.                 }
  47.                 else {
  48.                     return true;
  49.                 }
  50.             }
  51. };
  52.  
  53. int main(){
  54.     srand( time(NULL) );
  55.    
  56.     Player p1("勇者", rand() % 1000, rand() % 1000);
  57.     Player p2("乂煞氣a魔王乂", rand() % 1000, rand() % 1000);
  58.    
  59.     while( !p1.isDead() && !p2.isDead() ){
  60.         p1.attack(p2);
  61.         p2.attack(p1);
  62.     }
  63.    
  64.     if( !p1.isDead() ){
  65.         cout << p1.getName() << "贏了!" << endl;
  66.     }
  67.     else if( !p2.isDead() ){
  68.         cout << p2.getName() << "贏了!" << endl;
  69.     }
  70.     else {
  71.         cout << "平手!" << endl;
  72.     }
  73.    
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment