用更简洁的逻辑替换switch语句

问题描述 投票:1回答:2

我有一大堆代码

        switch (newDir)
        {
            case "left":
                {
                    this.dx = -1; this.dy = 0;
                    break;
                }
            case "up":
                {
                    this.dx = 0; this.dy = 1;
                    break;
                }
            case "right":
                {
                    this.dx = 1; this.dy = 0;
                    break;
                }
            case "down":
                {
                    this.dx = 0; this.dy = -1;
                    break;
                }
            default: // never happens
                break;
        }

这意味着设置我的游戏中的对象移动的方向。我觉得它很可读,不言自明,但对我来说太笨重了。我想知道你们是否知道一种奇特的方式让我巩固它

this.dx = ... ; 
this.dy = ... ; 

也许是涉及按位运算符或映射等的东西。

javascript algorithm optimization
2个回答
4
投票

将对象用作地图

var directions = {
  'left': {
    dx : -1, dy : 0
  },
  'right': {
    dx : 1, dy : 0
  },
  'up': {
    dx : 0, dy : 1
  },
  'down': {
    dx : 0, dy : -1
  }
};

this.dx = directions[newDir].dx;
this.dy = directions[newDir].dy;

0
投票

只是为了它...

dir_map = {right:0,up:1,left:2,down:3}
dirs = [[1,0],[0,1],[-1,0],[0,-1]]

dir = dir_map[newDir] // and keep it as number from now on. Never get back to string.
this.dx += dirs[dir][0]
this.dy += dirs[dir][1]

即使需要中性方向:

if (dir != null) {
    this.dx += dirs[dir][0]
    this.dy += dirs[dir][1]
}
© www.soinside.com 2019 - 2024. All rights reserved.