基础架构设计
采用面向对象编程模式,核心类包括Farm(农场管理)、Crop(作物基类)和GameEngine(游戏循环)。Farm类负责土地网格管理和玩家交互,Crop类派生不同作物子类实现多态生长逻辑12。
作物系统实现
通过继承体系定义10种作物,包含3天成熟的小麦到10天成熟的西瓜,每个子类需重写生长阶段渲染方法。作物数据存储于结构体,包含购买价、出售价和生长阶段天数参数15。
经济系统模块
采用单例模式实现钱包系统,包含金币增减方法和交易日志。作物出售价格采用基础价±随机浮动机制,通过rand()函数生成5%-15%的价格波动14。
时间管理系统
基于游戏循环的虚拟时间流速,每帧更新作物生长进度。采用时间戳差值计算实现离线生长功能,玩家再次登录时可结算未收获作物的生长进度15。
代码:
#include <iostream>
#include <vector>
#include <memory>
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';
}
};
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;
}
}
};
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;
}
- 主程序实现作物基类与小麦子类
- Farm类管理5x5土地网格的种植逻辑
- Makefile配置C++11标准编译环境
功能扩展建议
- 添加天气系统影响作物生长速度2
- 实现存档功能通过文件流保存游戏状态4
- 引入害虫事件增加随机挑战性5
- 添加商店系统支持工具升级
672

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



