如何在Python中有效地重用代码

时间:2016-11-20 03:04:19

标签: python

我在python中做一个项目,其中一部分涉及在游戏中对棋盘状态进行排名。这个游戏,Sneaky Statues,类似于连接四个你赢得连续四个棋子。我对板子的天真估计是你连续多少件(所以1,2,3或4)。板子是一个三角形,所以你可以在一个方向上连续地或者在任何一个方向上对角线。这是我现在用来查找碎片的功能。

def score(player):

    player_x = sorted(player, key=lambda statue: statue.x) #player's pieces sorted by x coordinate
    player_y = sorted(player, key=lambda statue: statue.y)
    max_score = [0]

    count = 1
    #pieces are in a horizontal line if they share a y coord and have sequential x coords
    for cur_s, next_s in zip(player_x, player_x[1:]):
        if cur_s.x + 1 == next_s.x and cur_s.y == next_s.y:
            count += 1
        else:
            max_score.append(count)
            count = 1
    max_score.append(count)

    count = 1
    #pieces are diagonal if they share an x and have sequental y's
    for cur_s, next_s in zip(player_y, player_y[1:]):
        if cur_s.y + 1 == next_s.y and cur_s.x == next_s.x:
            count += 1
        else:
            max_score.append(count)
            count = 1
    max_score.append(count)

    count = 1
    #they are diagonal if both x's and y's are sequential
    for cur_s, next_s in zip(player_y, player_y[1:]):
        if cur_s.y + 1 == next_s.y and cur_s.x + 1 == next_s.x:
            count += 1                                                                                                                                                               
        else:
            max_score.append(count)
            count = 1
    max_score.append(count)

    return max(max_score)

据我所知告诉它的工作但我基本上重复了三次。我的问题是,对于我来说,编写这个函数最简单的方式是什么,这样我才能重复自己?

1 个答案:

答案 0 :(得分:1)

这可能不是最好的,但初看起来我看到你可以将所有循环组合成一个有三个参数的函数:

def score(player):

    player_x = sorted(player, key=lambda statue: statue.x) #player's pieces sorted by x coordinate
    player_y = sorted(player, key=lambda statue: statue.y)
    max_score = [0]

    def take_count(player, x_offset, y_offset):
        count = 1
        for cur_s, next_s in zip(player, player[1:]):
            if cur_s.x + x_offset == next_s.x and cur_s.y + y_offset == next_s.y:
                count += 1
            else:
                max_score.append(count)
                count = 1
        max_score.append(count)

    #pieces are in a horizontal line if they share a y coord and have sequential x coords
    take_count(player_x, 1, 0)

    #pieces are diagonal if they share an x and have sequental y's
    take_count(player_y, 0, 1)

    #they are diagonal if both x's and y's are sequential
    take_count(player_y, 1, 1)

    return max(max_score)