Files
CINC/objects/Crop.js
T

159 lines
3.7 KiB
JavaScript

// 作物类:表示游戏中的农作物
export default class Crop extends Phaser.GameObjects.Sprite {
constructor(scene, x, y, cropType, growthTime) {
super(scene, x, y, 'crop');
// 设置作物属性
this.cropType = cropType;
this.growthTime = growthTime; // 生长时间(毫秒)
this.plantedTime = Date.now();
this.isHarvestable = false;
this.growthStage = 0; // 0: 种子, 1: 幼苗, 2: 成长中, 3: 成熟
// 创建作物纹理
this.createCropTexture();
// 添加到场景
scene.add.existing(this);
// 设置碰撞体
this.setSize(16, 16);
// 设置交互性
this.setInteractive({
useHandCursor: true
});
// 绑定点击事件
this.on('pointerdown', () => {
this.onCropClicked();
});
// 开始生长计时器
this.startGrowthTimer();
}
/**
* 创建作物纹理
*/
createCropTexture() {
// 根据作物类型和生长阶段创建不同的纹理
const textureKey = `${this.cropType}_${this.growthStage}`;
if (!this.scene.textures.exists(textureKey)) {
const canvas = document.createElement('canvas');
canvas.width = 16;
canvas.height = 16;
const ctx = canvas.getContext('2d');
// 根据作物类型设置基础颜色
let baseColor;
switch (this.cropType) {
case 'wheat':
baseColor = '#FFFF00'; // 黄色
break;
case 'carrot':
baseColor = '#FF6B35'; // 橙色
break;
default:
baseColor = '#00FF00'; // 绿色
}
// 根据生长阶段绘制不同的形状
ctx.fillStyle = baseColor;
switch (this.growthStage) {
case 0: // 种子
ctx.fillRect(6, 10, 4, 4);
break;
case 1: // 幼苗
ctx.fillRect(7, 8, 2, 6);
ctx.fillRect(5, 6, 6, 2);
break;
case 2: // 成长中
ctx.fillRect(6, 5, 4, 8);
ctx.fillRect(3, 3, 10, 3);
break;
case 3: // 成熟
ctx.fillRect(5, 2, 6, 10);
ctx.fillRect(2, 0, 12, 4);
break;
}
// 添加边框
ctx.strokeStyle = '#000000';
ctx.lineWidth = 1;
ctx.strokeRect(0, 0, 16, 16);
// 将canvas添加为纹理
this.scene.textures.addCanvas(textureKey, canvas);
}
// 设置纹理
this.setTexture(textureKey);
}
/**
* 开始生长计时器
*/
startGrowthTimer() {
// 计算每个生长阶段的时间
const stageTime = this.growthTime / 4;
// 设置每个生长阶段的定时器
for (let i = 1; i <= 3; i++) {
this.scene.time.delayedCall(stageTime * i, () => {
this.updateGrowthStage(i);
});
}
// 设置成熟定时器
this.scene.time.delayedCall(this.growthTime, () => {
this.isHarvestable = true;
});
}
/**
* 更新生长阶段
*/
updateGrowthStage(stage) {
this.growthStage = stage;
this.createCropTexture();
}
/**
* 作物被点击时的处理函数
*/
onCropClicked() {
// 调用场景的显示作物详情方法
this.scene.showCropDetails(this);
// 阻止事件冒泡,防止触发角色移动
return false;
}
/**
* 收获作物
*/
harvest() {
// 触发收获事件
this.scene.events.emit('crop-harvested', this);
// 销毁作物
this.destroy();
}
/**
* 获取作物信息
*/
getInfo() {
return {
type: this.cropType,
growthStage: this.growthStage,
isHarvestable: this.isHarvestable,
plantedTime: this.plantedTime,
growthTime: this.growthTime
};
}
}