python 将两种功能合二为一

cgvd09ve  于 2023-02-18  发布在  Python
关注(0)|答案(2)|浏览(116)

如何将函数mark_blockmark_cell合并为一个函数?

import numpy as np

class Board:

    def __init__(self):
        self.cells = np.zeros((3, 3, 3, 3))
        self.block = np.zeros((3, 3))

    def mark_block(self, main_row, main_col, player):
        self.block[main_row][main_col] = player

    def mark_cell(self, main_row, main_col, row, col, player):
        self.cells[main_row][main_col][row][col] = player

编辑:没有if语句也可以这样做吗?

35g0bw71

35g0bw711#

import numpy as np

class Board:

    def __init__(self):
        self.cells = np.zeros((3, 3, 3, 3))
        self.block = np.zeros((3, 3))

    def mark(self, main_row, main_col, player, row=None, col=None):
        if row is None and col is None:
            self.block[main_row][main_col] = player
        else:
            self.cells[main_row][main_col][row][col] = player
xvw2m8pv

xvw2m8pv2#

class Board:

    def __init__(self):
        self.cells = np.zeros((3, 3, 3, 3))
        self.block = np.zeros((3, 3))

    def mark_move(self, main_row, main_col, row, col, player):
        self.cells[main_row][main_col][row][col] = player
        if np.all(self.cells[main_row][main_col]):
            self.block[main_row][main_col] = player

mark_move方法同时更新单元格和区块数组。如果区块中的所有单元格都被占用,则区块数组中相应的元素将被设置为玩家的值。np.all函数检查数组中的所有元素是否都是non-zero,这表明区块中的所有单元格都被占用。

相关问题