-4

在 python 中,我想做的是有一个函数def players_move,它接受 len 5 的 raw_input 字符串,例如b1,i5检查移动是否合法,然后调用一个新函数cords(),该函数接受字符串并输出要在 2d 上更新的坐标木板。

以下是将字符串转换为坐标的内容。如果我要求它返回b[2],i[5]但我不能让它接受字符串然后输出 x 和 y 坐标而没有错误,或者它只返回字符串而不是坐标,它会起作用。

def cords ():
    move=raw_input('enter starting pos and end pos')        

    a=[[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0]]
    b=[[0,1],[1,1],[2,1],[3,1],[4,1],[5,1],[6,1],[7,1],[8,1]]
    c=[[0,2],[1,2],[2,2],[3,2],[4,2],[5,2],[6,2],[7,2],[8,2]]
    d=[[0,3],[1,3],[2,3],[3,3],[4,3],[5,3],[6,3],[7,3],[8,3]]
    e=[[0,4],[1,3],[2,4],[3,4],[4,4],[5,4],[6,4],[7,4],[8,4]]
    f=[[0,5],[1,3],[2,5],[3,5],[4,5],[5,5],[6,5],[7,5],[8,5]]
    g=[[0,6],[1,3],[2,6],[3,6],[4,6],[5,6],[6,6],[7,6],[8,6]]
    h=[[0,7],[1,3],[2,7],[3,7],[4,7],[5,7],[6,7],[7,7],[8,7]]
    i=[[0,8],[1,3],[2,8],[3,8],[4,8],[5,8],[6,8],[7,8],[8,8]]
    xx = move[0], int(move[1])
    #yy = move[3], int(move[4])
    xxx = xx[0],[xx[1]]
    #yyy= yy[3],[yy[4]]
    return xxx#,yyy    

我已将 raw_input 包含在函数中,使其在没有其他部分的情况下工作,它旨在输出坐标但它返回 ('b'[1]),'i'[5] 而不是 [1,1], [[3,8] 甚至更好的是它输出 [1][1],[3][8] 如果给定 b1,i5 它有一个错误如果尝试返回 x 和 y 它没有只需 x 即可正常工作,但没有错误有人可以帮忙吗?

然后我需要导入返回的值并在 update_board 函数中更新板子。

4

1 回答 1

0
import re
def get_move(move)  : 
    d = {}
    d['a']=[[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0]]
    d['b']=[[0,1],[1,1],[2,1],[3,1],[4,1],[5,1],[6,1],[7,1],[8,1]]
    d['c']=[[0,2],[1,2],[2,2],[3,2],[4,2],[5,2],[6,2],[7,2],[8,2]]
    #made example smaller

    def get_parts(part):
         parts = re.split("([a-zA-Z]+)",part)
     _,ltr,idx =parts
         try:
              return d[ltr.lower()][int(idx)]
         except KeyError:
              raise Exception("Letter {0} Does Not Exist".format(ltr))
         except IndexErrorError:
              raise Exception("Letter {0} Does Not Have Index {1}".format(ltr,idx))
    start,end = move.split(",")

    return get_parts(start),get_parts(end)
print  get_move(raw_input('enter starting pos and end pos'))

结果

enter starting pos and end posa3,c4
([3, 0], [4, 2])

编辑以允许不区分大小写

于 2012-09-15T06:48:52.117 回答