2016-11-20 9 views
0

私はPythonでプロジェクトをやっていますが、その中にはゲームのボード状態のランク付けが含まれています。このゲーム、Sneaky Statuesは、4つのピースを連続して獲得することで勝つ4つを接続するのと似ています。ボードの私の素朴な見積もりは、あなたが連続して何枚あるかです(1,2,3または4のいずれか)。ボードは三角形であるため、縦に並んでいるか、斜めにどちらの方向にもピースを持つことができます。これは今、私が使っている部分を見つけるために使っている関数です。Pythonでコードを効果的に再利用する方法

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) 

私の仕事は分かりますが、基本的には3回繰り返しています。私の質問は、私が自分自身を少なくするために、この機能を書くための最も無作法な方法は何ですか?

答えて

1

これが最善の可能性はないですが、一目で私はあなたが3つの引数持つ単一の関数にすべてのループを組み合わせることができますことを参照してください。

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) 
関連する問題