设为首页 加入收藏

TOP

3.4.1 Hero's Inventory程序简介
2013-10-07 14:42:52 来源: 作者: 【 】 浏览:55
Tags:3.4.1 Hero' Inventory 程序 简介

3.4  使用数组

虽然string对象提供了非常不错的使用字符序列的方法,但是数组可以用于任意类型的元素。也就是说,可以用数组存储一个整型序列来表示一个高分列表,也能够存储程序员自定义类型的元素,如RPG游戏中某个角色可能持有的物品构成的序列。

3.4.1  Hero's Inventory程序简介

Hero's Inventory程序维护一个典型RPG游戏中主人公的物品栏。像大多数RPG游戏一样,主人公来自一个不起眼的小村庄,他的父亲被邪恶的军阀杀害(如果他的父亲不去世的话就没有故事了)。现在主人公已经成年,是时候复仇了。

本程序中,主人公的物品栏用一个数组来表示。该数组是一个string对象的序列,每个string对象表示主人公拥有的一个物品。主人公可以交易物品,甚至发现新的物品。程序如图3-4所示。

从Course Technology网站(www.courseptr.com/downloads)或本书合作网站(http://www. tupwk.com.cn/downpage)上可以下载到该程序的代码。程序位于Chapter 3文件夹中,文件名为heros_inventory.cpp。

 
(点击查看大图)图3-4  主人公的物品栏是存储在数组中的string对象序列
  1. // Hero's Inventory  
  2. // Demonstrates arrays  
  3. #include <iostream> 
  4. #include <string> 
  5. using namespace std;  
  6. int main()  
  7. {  
  8. const int MAX_ITEMS = 10;  
  9. string inventory[MAX_ITEMS];  
  10. int numItems = 0;  
  11. inventory[numItems++] = "sword";  
  12. inventory[numItems++] = "armor";  
  13. inventory[numItems++] = "shield";  
  14. cout << "Your items:\n";  
  15. for (int i = 0; i < numItems; ++i)  
  16. {  
  17. cout << inventory[i] << endl;  
  18. }  
  19. cout << "\nYou trade your sword for a battle axe.";  
  20. inventory[0] = "battle axe";  
  21. cout << "\nYour items:\n";  
  22. for (int i = 0; i < numItems; ++i)  
  23. {  
  24. cout << inventory[i] << endl;  
  25. }  
  26. cout << "\nThe item name '" << inventory[0] << "' has ";  
  27. cout << inventory[0].size() << " letters in it.\n";  
  28. cout << "\nYou find a healing potion.";  
  29. if (numItems < MAX_ITEMS)  
  30. {  
  31. inventory[numItems++] = "healing potion";  
  32. }  
  33. else  
  34. {  
  35. cout << "You have too many items and can't carry another.";  
  36. }  
  37. cout << "\nYour items:\n";  
  38. for (int i = 0; i < numItems; ++i)  
  39. {  
  40. cout << inventory[i] << endl;  
  41. }  
  42. return 0;  
  43. }  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇3.3.5 索引string对象 下一篇3.3.9 使用empty()成员函数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: