【问题标题】:Best pattern to reduce excessive conditionals减少过多条件的最佳模式
【发布时间】:2015-04-10 04:46:32
【问题描述】:

我有一个游戏的以下代码,它通过随机选择一个来管理项目的显示模式,根据选择的模式创建项目,然后为它们设置动画。

问题是由于庞大的规模,清理代码和管理更改可能很麻烦,我最近一直在研究设计模式,我想知道哪个最适合在这里应用,到目前为止我已经考虑了策略和命令尽可能多的选择

“策略模式用于创建可互换的算法系列,在运行时从中选择所需的进程。”似乎我可以根据选择的模式来应用项目的定位。

通过查看之前的问题,当被问及减少 if/else 的数量时,命令模式出现了很多。

" 命令模式用于在命令对象中表达请求,包括要进行的调用及其所有必需的参数。然后可以立即执行命令或保留以供以后使用。"

不过,我不知道我是否会在没有相关性的地方找到相关性,所以我想我想问问这种模式是否可以应用于以下场景。

下面是相关代码,我特别有兴趣了解这个,因为几乎相同的代码重复敌人。

        /**
     * Set items pattern.  
     * 
     */

    private function setItemsPattern():void
    {
        // Change until enough flight distance has been accumulated.
        if (patternChange > 0)
        {
            patternChange -= playerSpeed * elapsed;
        }
        else
        {
            // As the player moves, change item patterns.

            if ( Math.random() < 0.7 )
            {
                // If  < normal item chance (0.7), get a random pattern.
                pattern = Math.ceil(Math.random() * 4); 
            }
            else
            {
                // If random number is > normal item chance (0.3), create special item.

                pattern = Math.ceil(Math.random() * 2) + 9;
            }

            if (pattern == GameConstants.ITEM_PATTERN_VERTICAL)  
            {
                // Vertical 
                patternStep = 15;
                patternChange = Math.random() * 500 + 500;
            }
            else if (pattern == GameConstants.ITEM_PATTERN_HORIZONTAL)
            {
                // Horizontal 
                patternOnce = true;
                patternStep = 40;
                patternChange = patternGap * Math.random() * 3 + 5;
            }
            else if (pattern == GameConstants.ITEM_PATTERN_ZIGZAG)
            {
                // ZigZag
                patternStep = Math.round(Math.random() * 2 + 2) * 10;
                if ( Math.random() > 0.5 )
                {
                    patternDirection *= -1;
                }
                patternChange = Math.random() * 800 + 800;
            }
            else if (pattern == GameConstants.ITEM_PATTERN_RANDOM)
            {
                // Random 
                patternStep = Math.round(Math.random() * 3 + 2) * 50;
                patternChange = Math.random() * 400 + 400;
            }
            else  
            {
                patternChange = 0;
            }
        }
    }

    /**
     * Creates items - called by createPattern() 
     * 
     */

    private function createItems():void
    {

        var itemToTrack:Item;

        switch (pattern)
        {
            case GameConstants.ITEM_PATTERN_HORIZONTAL:
                // Horizontal.
                if (Math.random() > 0.9)
                {
                    // Asignes items not too close to border.
                    patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;
                }


                itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);
                this.addChild(itemToTrack);


                // Sets pos
                itemToTrack.x = stage.stageWidth + itemToTrack.width ;
                itemToTrack.y = patternPosY;

                // Marks item for animation
                itemsToAnimate.push(itemToTrack);


                break;

            case GameConstants.ITEM_PATTERN_VERTICAL:
                // Vertical
                if (patternOnce == true)
                {
                    patternOnce = false;


                    patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;


                    patternLength = (Math.random() * 0.4 + 0.4) * stage.stageHeight;
                }


                patternPosYstart = patternPosY; 


                while (patternPosYstart + patternStep < patternPosY + patternLength && patternPosYstart + patternStep < stage.stageHeight * 0.8)
                {


                    itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);
                    this.addChild(itemToTrack);



                    itemToTrack.x = stage.stageWidth + itemToTrack.width;
                    itemToTrack.y = patternPosYstart;


                    itemsToAnimate.push(itemToTrack)


                    patternPosYstart += patternStep;
                }
                break;

            case GameConstants.ITEM_PATTERN_ZIGZAG:
                // ZigZag

                if (patternDirection == 1 && patternPosY > gameArea.bottom - 50)
                {
                    patternDirection = -1;
                }
                else if ( patternDirection == -1 && patternPosY < gameArea.top )
                {
                    patternDirection = 1;
                }

                if (patternPosY >= gameArea.top && patternPosY <= gameArea.bottom)
                {


                    itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);
                    this.addChild(itemToTrack);


                    itemToTrack.x = stage.stageWidth + itemToTrack.width;
                    itemToTrack.y = patternPosY;


                    itemsToAnimate.push(itemToTrack)


                    patternPosY += patternStep * patternDirection;
                }
                else
                {
                    patternPosY = gameArea.top;
                }

                break;

            case GameConstants.ITEM_PATTERN_RANDOM:

                // Random, creates N amount of items on screen.
                if (Math.random() > 0.3)
                {

                    patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;


                    while (patternPosY + patternStep < gameArea.bottom)
                    {


                        itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);
                        this.addChild(itemToTrack);


                        itemToTrack.x = stage.stageWidth + itemToTrack.width;
                        itemToTrack.y = patternPosY;


                        itemsToAnimate.push(itemToTrack)


                        patternPosY += Math.round(Math.random() * 100 + 100);
                    }
                }

                break;

            case GameConstants.ITEM_PATTERN_SPEED:

                // special item

                patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;


                itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_MANA);
                this.addChild(itemToTrack);


                itemToTrack.x = stage.stageWidth + itemToTrack.width;
                itemToTrack.y = patternPosY;


                itemsToAnimate.push(itemToTrack);

                break;

            case GameConstants.ITEM_PATTERN_STR:

            // special item

                patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;



                itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_REFERENCIA);
                this.addChild(itemToTrack);

                itemToTrack.x = stage.stageWidth + itemToTrack.width;
                itemToTrack.y = patternPosY;


                itemsToAnimate.push(itemToTrack);

                break;


        }
    }


    /**
     * Animates the vector itemsToAnimate. 
     * 
     */


    private function animateItems():void
    {

            var itemToTrack:Item;

            for(var i:uint = 0;i<itemsToAnimate.length;i++)
            {
                itemToTrack = itemsToAnimate[i];

                if (itemToTrack != null)
                {

                    if (referencia > 0 && itemToTrack.itemType <= GameConstants.ITEM_TYPE_REFERENCIA)
                    {

                        itemToTrack.x -= (itemToTrack.x - brujaX) * 0.2;
                        itemToTrack.y -= (itemToTrack.y - brujaY) * 0.2;


                    }
                    else
                    {

                        itemToTrack.x -= playerSpeed * elapsed; 
                    }


                    if (itemToTrack.x < -80 || gameState == GameConstants.GAME_STATE_OVER)
                    {
                        disposeItemTemporarily(i, itemToTrack);
                    }
                    else
                    {

                        brujaItem_xDist = itemToTrack.x - brujaX;
                        brujaItem_yDist = itemToTrack.y - brujaY;
                        brujaItem_sqDist = brujaItem_xDist * brujaItem_xDist + brujaItem_yDist * brujaItem_yDist;

                        if (brujaItem_sqDist < 5000)
                        {

                            if (itemToTrack.itemType == GameConstants.ITEM_TYPE_1)
                            {
                                scoreItems += itemToTrack.itemType;
                                hud.itemScore = scoreItems;
                                if (!Sounds.muted) Sounds.sndPag.play();
                            }

                            else if (itemToTrack.itemType == GameConstants.ITEM_TYPE_MANA) 
                            {

                                scoreItems += 1;


                                mana = 5;
                                if (isHardwareRendering) particleMana.start(mana);

                                if (!Sounds.muted) Sounds.sndMana.play();
                                if (!Sounds.muted) Sounds.sndRisa.play();
                            }

                            else if (itemToTrack.itemType == GameConstants.ITEM_TYPE_REFERENCIA) 
                            {

                                scoreItems += 1;

                                referencia = 20;
                                partRef = 0.5;
                                if (isHardwareRendering) particleRef.start(partRef);

                                playRandomRef();

                            }

                            if(referencia > 0){referencia--;}


                            disposeItemTemporarily(i, itemToTrack);
                        }
                    }
                }
            }
        }

【问题讨论】:

  • 如果动画之间存在某种因果关系,许多链式条件听起来像是可以通过策略或状态模式解决的问题。在结构上,Command 和 Strategy 非常相似,不同之处在于 Command 封装了单个动作,而 Strategy 对算法的封装相同。
  • 首先,不要使用幻数(1、2、3、4),而是定义一些常量或使用枚举。其次,在查看模式之前,请尝试进行一些重构。我很确定你可以申请这个refactoring.com/catalog/replaceConditionalWithPolymorphism.html
  • @Fuhrmanator 谢谢,我也会调查一下。此外,我确实在其他地方使用常量,例如 SPECIAL_ITEM,但出于某种原因,我从未想过使用 PATTERN_VERTICAl 例如。我真的很感谢你把这个显而易见的事情指向我。

标签: actionscript-3 design-patterns refactoring


【解决方案1】:

您的函数 setItemsPattern 和 createItems 都包含一个 switch-case 语句,因此您可以创建一个包含两个函数来处理 switch-case 工作的基类。

例如,你得到这样的基类

Class BaseBehavior
{

    //if the variable shouldn't be accessed by other class, change public to protected
    public var patternOnce:Boolean;

    public var patternStep:int;

    public var patternChange:int;

    public var patternDirection:int;

    public var itemToTrack:Object;

    public var gameArea:Object;

    //used in setItemsPattern function 
    public function initPatternData():void {};

   //used in createItems function 
    public function createItems():void {};

    public function dispose():void {};
}

这里是垂直类

Class VerticalBehavior extends BaseBehavior
{

    override public function initPatternData():void
    {
          patternStep = 15;

          patternChange = Math.random() * 500 + 500;
    }

    override public function createItems():void 
    {
         if (Math.random() > 0.9)
         {
              // Asignes items not too close to border.
             patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;
         }

         itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);

         // Sets pos
         itemToTrack.x = stage.stageWidth + itemToTrack.width ;
         itemToTrack.y = patternPosY;
    }

}

其他子类大体相同。

现在你需要一个工厂类来创建子类

 Class BehaviorFactory
 {

      public static function create(type:int):BaseBehavior
      {
           switch(type)
           {
              case 1://vertical
                  return new VerticalBehavior();

              case 2:
                  return ...

               ...
           }
      }
 }

完成这些工作后,您可以在旧的逻辑代码中使用它们

private var behavior:BaseBehavior;

private function setItemsPattern():void
{
    if (behavior && behavior.patternChange > 0)
    {
        behavior.patternChange -= playerSpeed * elapsed;
    }
    else
    {
        // As the player moves, change item patterns.

        if ( Math.random() < 0.7 )
        {
            // If  < normal item chance (0.7), get a random pattern.
            pattern = Math.ceil(Math.random() * 4); 
        }
        else
        {
            // If random number is > normal item chance (0.3), create special item.

            pattern = Math.ceil(Math.random() * 2) + 9;
        }

        //here to create the sub class

        //dispose old behavior
        if (behavior)
        {
             behavior.dispose();
        }

        behavior = BehaviorFactory.create(pattern);

}


private function createItems():voidh
{
     //you may check behavior is null here
     var itemToTrack:Item = behavior.createItems();

      this.addChild(itemToTrack);

      // Marks item for animation
      itemsToAnimate.push(itemToTrack);
}

最后,如果要添加新类型,只需要创建一个子行为类,并将其添加到工厂类中即可。但要注意,如果行为中的变量增加太多,可能需要使用组合类。

【讨论】:

  • 所以基本上这是一个接口/父类,它定义了模式的基本行为,然后每个子类扩展这个行为以满足每个模式的需要。然后在使用此模式的类上,通过工厂创建行为,具体取决于随机选择的模式(如上面评论中所述,现在将是一个常量)。我想把所有这些都放在一个包裹上会更好吗?我不希望有这么多类做相同但略有不同(如果这甚至有意义的话)。我也会研究复合模式。
  • 想象一下你在这里有了更多的 switch-case 功能,比如 7,其他人很难阅读你的代码并对其进行处理,他们必须更改所有 switch-case 才能实现工作。
  • 我明白了,我会接受您的答复,感谢您抽出宝贵时间!
猜你喜欢
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 1970-01-01
相关资源
最近更新 更多