返回

打造 Egret 游戏商城全纪录,助力开发者一臂之力

前端

各位游戏开发者,大家好!今天,我将带领大家一起来实现一个完整的 Egret 游戏商城。本文将从零开始,一步一步地指导大家如何创建商城皮肤、设置 list 组件、添加购买按钮,以及如何管理游戏道具、统计交易记录等。希望能够帮助大家快速开发和完善自己的游戏项目。

首先,我们需要创建两个皮肤,分别是商城皮肤 (ShopSkin.exml) 和列表子项皮肤 (ShopItemSkin.exml)。这两个皮肤可以根据自己的需要进行设计,这里我提供一个简单的参考示例:

  1. ShopSkin.exml
<e:Skin class="skins.ShopSkin" width="100%" height="100%">
    <e:Scroller id="scroller" width="100%" height="100%">
        <e:List id="list" width="100%" itemRendererSkinName="skins.ShopItemSkin"/>
    </e:Scroller>
</e:Skin>
  1. ShopItemSkin.exml
<e:Skin class="skins.ShopItemSkin">
    <e:Group>
        <e:Image id="icon" width="80" height="80" source="resources/icon.png"/>
        <e:Label id="name" text="商品名称" size="20"/>
        <e:Label id="price" text="商品价格" size="20"/>
        <e:Button id="buyButton" label="购买" skinName="skins.ButtonSkin"/>
    </e:Group>
</e:Skin>

接下来,我们需要在 Egret 项目中使用这两个皮肤。首先,在 Main.exml 文件中添加如下代码:

<e:SkinPart name="scroller" type="e:Scroller"/>
<e:SkinPart name="list" type="e:List"/>

然后,在 Main.ts 文件中添加如下代码:

private scroller:eui.Scroller;
private list:eui.List;

protected createChildren():void {
    super.createChildren();
    this.scroller = this.skin.scroller;
    this.list = this.skin.list;
    this.initList();
}

private initList():void {
    let data:Array<any> = [
        {icon:"resources/icon1.png", name:"商品1", price:10},
        {icon:"resources/icon2.png", name:"商品2", price:20},
        {icon:"resources/icon3.png", name:"商品3", price:30},
    ];
    this.list.dataProvider = new eui.ArrayCollection(data);
}

这样,我们就完成了商城皮肤的创建和 list 组件的设置。接下来,我们需要添加购买按钮的事件监听器。在 Main.ts 文件中添加如下代码:

private buyButton:eui.Button;

protected createChildren():void {
    super.createChildren();
    this.scroller = this.skin.scroller;
    this.list = this.skin.list;
    this.initList();
    this.buyButton = this.list.getChildAt(0).getChildAt(3) as eui.Button;
    this.buyButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onBuy, this);
}

private onBuy(e:egret.TouchEvent):void {
    console.log("购买成功!");
}

这样,我们就完成了购买按钮的添加和事件监听器的注册。最后,我们需要管理游戏道具和统计交易记录。这部分内容需要根据具体的项目需求来实现,这里就不再赘述了。

希望本教程能够帮助大家快速实现一个完整的 Egret 游戏商城。如果您有任何问题或建议,欢迎在下方留言。