坦克移动问题python解法

某次战役中,为便于信息交互,我军侦察部门将此次战役的关键高地座标设定为(x=0,y=0)并规定,每向东增加100米,x加1,每向北增加100米,y加1。

同时,我军情报部门也破译了敌军向坦克发送的指挥信号,其中有三种信号(L,R,M)用于控制坦克的运动,L 和 R 分别表示使令坦克向左、向右转向,M 表示令坦克直线开进100米,其它信号如T用于时间同步,P用于反转信号,既出现p,后面的信号向左变为向右,向右变为向左,向前变为向后,反之亦然。

一日,我军侦察兵发现了敌军的一辆坦克,侦察兵立即将坦克所在座标(P, Q)及坦克前进方向(W:西,E:东,N:北,S:南)发送给指挥部,同时启动信号接收器,将坦克接收到的信号实时同步发往指挥部,指挥部根据这些信息得以实时掌控了该坦克的位置,并使用榴弹炮精准地击毁了该坦克。

假设,侦察兵发送给指挥部的信息如下:坦克座标:(11,39)坦克运行方向:W,坦克接收到的信号为:MTMPRPMTMLMRPRMTPLMMTLMRRMP,请通过编程计算出坦克所在的位置。

class Tank:
    option = {'E': 'self.x_add(1)', 'S': 'self.y_add(-1)', 'W': 'self.x_add(-1)', 'N': 'self.y_add(1)'}
    direction_list = 'ESWN'

    def __init__(self, x, y, direction, signal=''):
        self.__x = x
        self.__y = y
        self.__direction = direction
        self.__signal = signal
        self.__reverse_flag = True

    def x_add(self, step):
        self.__x += step

    def y_add(self, step):
        self.__y += step

    # 设置反转标识
    def reverse(self):
        self.__reverse_flag = False if self.__reverse_flag else True

    # 根据反转标识,获取反转后的指令
    def correct(self, order):
        if self.__reverse_flag:
            return order
        else:
            return 'R' if order == 'R' else 'L'

    # 根据方向移动
    def move(self):
        exec(self.option[self.__direction])

    # 设置前进方向
    def set_direction(self, order):
        self.correct(order)
        index = self.direction_list.index(self.__direction)
        if order == 'L':
            self.__direction = self.direction_list[(index - 1) % 4]
        else:
            self.__direction = self.direction_list[(index + 1) % 4]

    # 分析信号
    def analysis(self):
        for order in self.__signal:
            if order == 'M':
                self.move()
            elif order in ('L', 'R'):
                self.set_direction(order)
            elif order == 'P':
                self.reverse()
            else:
                print('Time')

        print('location:(%d,%d),direction:%s' % (self.__x, self.__y, self.__direction))


tank = Tank(11, 39, 'W', 'MTMPRPMTMLMRPRMTPLMMTLMRRMP')
tank.analysis()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章