Skip to main content
 首页 » 编程设计

python之如何重用代码来跟踪 Python 中三角形板上的棋子运行

2024年10月17日8fff_TT

我正在用 Python 做一个项目,其中一部分涉及对游戏中的棋盘状态进行排名。这款名为 Sneaky Statues 的游戏类似于 Connect Four,在该游戏中,您可以通过连续获得四个棋子来获胜。我对棋盘的天真估计是你在一排有多少 block 棋子(所以 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 sequential 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) 

据我所知,它是有效的,但我实际上是在重复三遍。我的问题是,对于我来说,编写此函数的最 Pythonic 方式是什么,这样我就可以减少重复自己的话?

请您参考如下方法:

这可能不是最好的,但乍一看我发现您可以将所有循环组合到一个具有三个参数的函数中:

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)