2016-09-30 1 views
2

私は以下のコードを持っており、効率が良いと感じています。これは3x3ボードであり、手動で行うことができますが、ボードが30x30以上の場合はどうなりますか?多くのif文を使わずにチック・タック・トーのゲームで勝った人を確認する式を作成するにはどうすればよいですか?

x = [[1, 2, 0],[2, 1, 0],[2, 1, 0]] 

for y in range (3): 
    if ((x[0][0] == x[1][0] == x[2][0] == y) or 

    (x[0][1] == x[1][1] == x[2][1] == y) or 

    (x[0][2] == x[1][2] == x[2][2] == y) or 

    (x[0][0] == x[0][1] == x[0][2] == y) or 

    (x[1][0] == x[1][1] == x[1][2] == y) or 

    (x[2][0] == x[2][1] == x[2][2] == y) or 

    (x[0][0] == x[1][1] == x[2][2] == y) or 

    (x[0][2] == x[1][1] == x[2][0] == y)): 

     if y==1: 
      print('Player 1 won!!!') 
     if y==2: 
      print('Player 2 won!!!') 
     if y==0: 
      print('Nobody won') 

条件を改善する方法はありますか?

答えて

0

あなたはこのようにファンクションジェネレータを使用することができます10これは役に立たないようだが、そのような機能であなたは1行で全細胞グループをチェックするallmapを使用することができます。

# will return True if each cell in <cells_group> belong to <player> 
all(map(cell_owner(<player>), <cells_group>) 

する前に、このやって、あなたは勝算ありとセルグループのリストを準備することができますリストを反復して、すべての/マップ関数を各グループに適用して、勝ったプレイヤーを決定する。以下は

テストpuposeのためのいくつかの余分な機能を備えた完全な例です。このコードは平方グリッドの任意のサイズのために働く必要があります

import random 


def gen_random_grid(size): 
    """just for test purpose: generate a randomly filled grid""" 
    return [[random.randint(0, 2) for col in range(size)] for row in range(size)] 

def print_grid(grid): 
    """just for test purpose: prints the grid""" 
    size = len(grid) 
    row_sep = "+{}+".format("+".join(["---"] * size)) 
    row_fmt = "|{}|".format("|".join([" {} "] * size)) 
    print(row_sep) 
    for row in grid: 
     print(row_fmt.format(*row)) 
     print(row_sep) 

def cell_owner(player): 
    """returns a function which can check is a cell belongs to provided player""" 
    def wrapped(cell): 
     return player == cell 
    return wrapped 

def get_winner(grid): 
    """determines if there is a winner""" 
    size = len(grid) 

    # prepare list of potentially winning cells groups 
    cells_groups_to_check = grid[:] # rows 
    cells_groups_to_check += [[grid[row][col] for row in range(size)] 
           for col in range(size)] #cols 
    cells_groups_to_check.append(
     [grid[index][index] for index in range(size)]) # diag 1 
    cells_groups_to_check.append(
     [grid[index][size - 1 - index] for index in range(size)]) # diag 2 

    winner = 0 
    for y in range(1, 3): # 0 is not a player, no need to test it 
     # for each player... 
     for group in cells_groups_to_check: 
      # ... check if a cells group is complete 
      if (all(map(cell_owner(y), group))): 
       winner = y 
       break 
     if winner: break 
    return winner 

# generate some random grids of different sizes 
TEST_GRIDS = [gen_random_grid(3) for _ in range(3)] 
TEST_GRIDS += [gen_random_grid(2) for _ in range(3)] 
TEST_GRIDS += [gen_random_grid(4) for _ in range(3)] 

# demonstration 
for grid in TEST_GRIDS: 
    print_grid(grid) 
    print("Winner is {}".format(get_winner(grid))) 

注意。

+0

私はあなたのコードを理解するのに苦労しています。私はまだ発電機に触れていない。しかし、それは動作するようです。どうもありがとう。 – BitByBit

0

あなたがnumpyののインポートについては気にしない場合、これは任意の正方格子とプレイヤーの任意の数のために働くでしょう:

import numpy as np 

def check(arr): 
    def check_one_dim(arr): 
     for player in np.arange(Nplayer)+1: 
     # instead of Nplayer you could write arr.max() 
      arrtest = arr == player 
      s = arrtest.astype(int).prod(axis=0) 
      t = arrtest.diagonal().astype(int).prod() 
      if (s == 1).any() or t == 1: 
       return player 
     else: 
      return 0 
    return max(check_one_dim(arr), check_one_dim(arr[::-1].T)) 

Nplayer = 2 
x = np.array([[1, 2, 0],[2, 1, 0],[2, 1, 0]]) 
winner = check(x) 
if winner > 0: 
    print("Player {}").format(winner) 
else: 
    print("No winner") 

私はそれが高速であることを確認していないが、あまり「IFS」があります。それは1であれば、あなたが値をチェックを受け入れる機能を取得するためにcell_owner(1)を呼び出すことができます

def cell_owner(player): 
    """returns a function which can check if a cell belongs to provided player""" 
    def wrapped(cell): 
     return player == cell 
    return wrapped 

:)

+0

'np.array([[0、2、1]、[0,2,1]、[0,2,0]])' 'の場合、このコードは、プレイヤー2がゲーム。 – cdlane

+0

これは、タイプ「s = ...」と「t = ...」に「arr」の代わりに「arr」があるためです。今それは正常に動作します。 –

関連する問題