引言
农场类游戏因其轻松愉快的玩法和简单的机制,成为编程初学者的理想练习项目。本文将带你一步步用C++实现一个基础农场游戏,涵盖面向对象编程、游戏循环和用户交互等核心概念。
游戏功能规划
- 作物生长系统:模拟不同作物的生长周期
- 土地管理:5x5的可种植土地网格
- 时间推进:按天计算作物生长进度
- 用户交互:通过菜单进行操作
代码实现
1. 基类与派生类设计
class Crop {
protected:
std::string name;
int growthDays;
float buyPrice;
float sellPrice;
int currentGrowth;
public:
virtual void grow() = 0;
virtual char getSymbol() const = 0;
virtual ~Crop() = default;
};
class Wheat : public Crop {
public:
Wheat() {
name = "Wheat";
growthDays = 3;
buyPrice = 10;
sellPrice = 15;
currentGrowth = 0;
}
void grow() override {
if(currentGrowth < growthDays) currentGrowth++;
}
char getSymbol() const override {
return currentGrowth == growthDays ? 'W' : 'w';
}
};
2. 农场管理系统
class Farm {
private:
std::vector<std::vector<std::unique_ptr<Crop>>> land;
int width;
int height;
public:
Farm(int w, int h) : width(w), height(h), land(h, std::vector<std::unique_ptr<Crop>>(w)) {}
void plantCrop(int x, int y, Crop* crop) {
if(x >= 0 && x < width && y >= 0 && y < height) {
land[y][x].reset(crop);
}
}
void update() {
for(auto& row : land) {
for(auto& crop : row) {
if(crop) crop->grow();
}
}
}
void display() const {
for(const auto& row : land) {
for(const auto& crop : row) {
std::cout << (crop ? crop->getSymbol() : '.') << " ";
}
std::cout << std::endl;
}
}
};
3. 游戏主循环
class GameEngine {
private:
Farm farm;
int dayCount;
public:
GameEngine() : farm(5, 5), dayCount(0) {}
void run() {
while(true) {
displayMenu();
handleInput();
updateGame();
}
}
void displayMenu() const {
std::cout << "\nDay " << dayCount << "\n";
farm.display();
std::cout << "\n1. Plant wheat\n2. Next day\n3. Exit\n";
}
void handleInput() {
int choice;
std::cin >> choice;
switch(choice) {
case 1: {
int x, y;
std::cout << "Enter position (x y): ";
std::cin >> x >> y;
farm.plantCrop(x, y, new Wheat());
break;
}
case 3:
exit(0);
}
}
void updateGame() {
farm.update();
dayCount++;
}
};
int main() {
GameEngine engine;
engine.run();
return 0;
}
游戏玩法说明
- 启动游戏后,会显示5x5的空白土地
- 选择1种植小麦,输入坐标(x y)
- 选择2推进到下一天,观察作物生长
- 选择3退出游戏
扩展建议
- 添加更多作物类型(玉米、胡萝卜等)
- 实现天气系统影响生长速度
- 添加经济系统和商店功能
- 实现存档/读档功能
结语
通过这个简单的农场游戏项目,你学习了C++的面向对象编程、智能指针使用和游戏循环设计。尝试按照扩展建议添加新功能,这将帮助你巩固编程技能。
465

被折叠的 条评论
为什么被折叠?



