def __init__(self, name, **kw): Cell.__init__(self, name) self.cellDim = kw.get('dimension', 3) # dimension of finite element cell self.degree = kw.get('degree', 1) # degree of finite-element cell self.order = kw.get('order', -1) # order of finite-element cell self.configure() return
def simulation(size, cells, iterations, frame_time, centers=((500, 500),)): environment = np.zeros((size, size)) firing_queue = [] for coordinates in centers: cell = Cell(coordinates[0], coordinates[1]) cells.append(cell) cell.is_autonomous = True for cell in cells: environment[cell.x, cell.y] += 1 for iteration in range(iterations): print 'iteration %d' % iteration simulation_frame(cells, frame_time, environment, firing_queue) plt.matshow(environment, fignum=(iteration + 1), cmap=plt.cm.gray) plt.savefig('Results/%d-seconds.png' % ((iteration + 1) * 5)) plt.close() tmp = [] for cell in firing_queue: if cell.firing_timer < Constants.INFLUENCE_TIME: tmp.append(cell) firing_queue = tmp return 0
def generateIbfFromProtobuf(self, ibfPbuf, dataBitSize): newIbf = Ibf(self.k, self.m) newIbf.zero(dataBitSize) for c in ibfPbuf.cells: realCell = Cell(0,0) realCell.cellFromProtobuf(c.count, c.hashprod, c.data) newIbf.cells[c.cellIndex] = realCell return newIbf
def createGrid(self): for row in range(0, self.numberOfRows): cellRow = [] for columns in range(0,self.numberOfColumns): cell = Cell(self.cellWidth,self.cellHeight,self.margin) cell.setGrid(self) cellRow.append(cell) self.cellMatrix.append(cellRow)
def start_td(self, attrs): self.__flush() self.in_td = True cell = Cell() for key, value in attrs: if key == 'rowspan': cell.rowspan = int(value) elif key == 'colspan': cell.colspan = int(value) self.cells.append(cell)
def parse(self, board): """ Pasa los valores de una matriz de enteros 9 x 9 a la matriz de celdas @param board matriz de 9x 9 enteros. """ for i in range(0,9): for j in range(0,9): c = Cell(i,j,board[i][j]) if board[i][j] != 0: c.setOccupied(True) self.setCell(i,j,c)
def __init__(self, x, y, pasX, pasY): """ Construit un agent simple, pour une bille. @param x: position en x @param y: position en y @param pasX: le déplacement en x @param pasY: le déplacement en y """ Cell.__init__(self,x,y) self.pasX = int(pasX) self.pasY = int(pasY) self.color = choice(['blue', 'red', 'green', 'magenta'])
def generateIbfFromProtobuf(self, ibfPbuf, dataBitSize, k=0, m=0): if k == 0: k = self.k if m == 0: m = self.m newIbf = Ibf(k, m) newIbf.zero(dataBitSize) for c in ibfPbuf.cells: realCell = Cell(0,0) realCell.cellFromProtobuf(c.count, c.hashprod, c.data) newIbf.cells[c.cellIndex] = realCell return newIbf
def __init__(self, master, numRows, numCols ): Frame.__init__(self, master) self.master = master self.cells = [] index = 0 for i in range(0, numCols): for j in range(0, numRows): button = Cell(self, index) button.grid(row=j, column=i) self.cells.append(button) index += 1 self.rows = numRows self.columns = numCols
def __init__(self, numbers=None): # we keep list of cells and dictionaries to point to each cell # by various locations self.rows = {} self.columns = {} self.boxes = {} self.cells = [] # looping rows for row in xrange(0, 9): # looping columns for col in xrange(0, 9): # calculating box box = 3 * (row / 3) + (col / 3) # creating cell instance cell = Cell(row, col, box) # if initial set is given, set cell value if not numbers is None: cell.value = numbers.pop(0) else: cell.value = 0 # initializing dictionary keys and corresponding lists # if they are not initialized if not row in self.rows: self.rows[row] = [] if not col in self.columns: self.columns[col] = [] if not box in self.boxes: self.boxes[box] = [] # adding cells to each list self.rows[row].append(cell) self.columns[col].append(cell) self.boxes[box].append(cell) self.cells.append(cell)
def test_calculate_neighbours(self): b = Board(5, 3) b._mapa = [[100, -1, -1, -1, -2], [-2, -1, 100, -1, -1], [-2, -1, -1, -1, 0]] c = Cell(column=0, row=0, board=b) assert_equal(c.calculate_neighbours(),2) assert_equal(c.neighbours, 2) c = Cell(column=0, row=2, board=b) assert_equal(c.calculate_neighbours(),2) assert_equal(c.neighbours, 2) c = Cell(column=2, row=1, board=b) assert_equal(c.calculate_neighbours(),8) assert_equal(c.neighbours, 8) c = Cell(column=4, row=0, board=b) assert_equal(c.calculate_neighbours(),3) assert_equal(c.neighbours, 3)
def test_is_bomb(self): b = Board(5, 2) b._mapa = [[100, -2, -2, -2, -2], [-2, -1, 100, -2, -2]] c = Cell(column=0, row=0, board=b) assert_equal(c.is_bomb(), False) c = Cell(column=1, row=0, board=b) assert_equal(c.is_bomb(), False) c = Cell(column=1, row=1, board=b) assert_equal(c.is_bomb(), True)
def test_is_walkable(self): type0 = CellType('Test0', True, 'Test') type1 = CellType('Test1', False, 'Test') cell0 = Cell(0, 0, type0) self.assertFalse(cell0.is_walkable(None)) cell1 = Cell(0, 0, type1) self.assertTrue(cell1.is_walkable(None)) cell1.creature = 1 self.assertFalse(cell1.is_walkable(None))
def test_set_state(self): b = Board(5, 3) b._mapa = [[100, -1, -1, -1, -2], [-2, -1, 100, -1, -1], [-2, -1, -1, -1, 0]] c = Cell(column=0, row=0, board=b) c.set_state(10) assert_equal(b._mapa, [[10, -1, -1, -1, -2], [-2, -1, 100, -1, -1], [-2, -1, -1, -1, 0]]) assert_equal(c.state_on_board, 10) b._mapa = [[100, -1, -1, -1, -2], [-2, -1, 100, -1, -1], [-2, -1, -1, -1, 0]] c = Cell(column=2, row=2, board=b) c.set_state(7) assert_equal(b._mapa, [[100, -1, -1, -1, -2], [-2, -1, 100, -1, -1], [-2, -1, 7, -1, 0]]) assert_equal(c.state_on_board, 7)
def initialRead(self): """ initialize the calculator with size of the spreadsheet args: None return: cells with 0 in-degree """ for row in xrange(self.row): for col in xrange(self.col): value = sys.stdin.readline() new_cell = Cell(self.calId(row,col), value) new_cell.evaluate(self.cellBook) if not new_cell.evaluated: self.dependencyGraph[new_cell.getId()] = new_cell.getDependency() self.cellsWithDepen.append(new_cell.getId()) self.cells[new_cell.getId()] = new_cell
def prepare_grid(self): return [[Cell(row, column) for column in range(self.columns)] for row in range(self.rows)]
#!/usr/bin/python from constants import * from Cell import Cell from Wire import Wire wires = [] for i in range(numCols): for j in range(numRows): cells.append(Cell(i, j)) numTries = 100 for i in range(numWires): tries = 0 start = cells[random.randint(0, len(cells) - 1)] while start.open is False: tries += 1 if tries > numTries: break start = cells[random.randint(0, len(cells) - 1)] wire = Wire(start) wire.create_wire() if len(wire.cells) > minLineLength: wires.append(wire) def draw_grid(): ctx.set_source_rgba(0, 0, 0, 0.2) ctx.set_line_width(2) for i in range(numCols):
def __init__(self): self.__cells = [[None for col in range(7)] for row in range(7)] for i in range(len(self.__cells)): for j in range(len(self.__cells[0])): self.__cells[i][j] = Cell()
def test_get_possible_values(self): row = [1, 2, 3, None, None, None, 7, None, 9] column = [None, None, None, None, 1, 2, 3, None, 8] square = [None, None, None, None, None, None, None, None, 6] self.assertListEqual([4, 5],Cell.get_possible_values(row, column, square))
def initSudoku(self, sudoku): for i in range(0, 9, 1): for j in range(0, 9, 1): cell = Cell(sudoku[i][j]) cell.setSectorNumber((3 * (i / 3)) + (j / 3)) self.sudokuArr[i][j] = cell
def __init__(self, name, **kw): Cell.__init__(self, name) self.degree = kw.get('degree', 1) self.order = kw.get('order', -1) self.configure() return
def bladeWalker(self, checkerTown, dir1, dir2, row, col): if (row + dir1 >= 0 and row + dir1 <= 7 and col + dir2 >= 0 and col + dir2 <= 7): if (checkerTown[row + dir1][col + dir2] == None): self.targets.append(Cell(row + dir1, col + dir2)) elif (checkerTown[row + dir1][col + dir2].team != self.team): self.targets.append(Cell(row + dir1, col + dir2))
def __init__(self): self.cells = [[Cell() for i in range(7)] for j in range(7)]
def __init__(self, record): self.__cell = Cell() self.turn = C.BLACK self.record = record self.b = [] self.w = []
args = parser.parse_args() if args.SIZE % 2 != 1: raise InvaridNumber("奇数を入力してください") print("分裂方法:{}".format(args.func)) print("フィールドの大きさ:{}".format(args.SIZE)) print("最大許容細胞数:{}".format(args.MAXNUM)) print("おおよその細胞周期:{}".format(args.AVERAGE)) print("細胞周期のばらつき:{}".format(args.DISPERSION)) print("環境収容力:{}".format(args.ENV)) Janitor.receive_value(args.func, args.AVERAGE, args.DISPERSION, args.SIZE, args.MAXNUM, args.ENV) Janitor.set_field() Janitor.set_heatmap() Cell.set_first_cell(Janitor.field, Janitor.on) Janitor.first_heatmap_graph() while Janitor.n < Janitor.MAXNUM: for cell in Cell.celllist: if cell.dead == 0: cell.waittime_minus() cell.decide_prolife() else: pass Cell.radial_prolife(Janitor.field, Janitor.on, Janitor.func) Cell.countall(Janitor.heatmap) Janitor.refresh_heatmap()
def __getitem__(self, key): key = key.lower() cell = self.cells.get(key, Cell(self)) return cell
def __init__(self, sizeX, sizeY, canvas, tk, firstCell, lastCell): self.cellSize = self.screenWidth / sizeX self.sizeX = sizeX self.sizeY = sizeY self.allCells = [[Cell for i in range(sizeY)] for j in range(sizeX)] self.canvas = canvas self.noGUI = noGUI for x in range(sizeX): for y in range(sizeY): cell = Cell(x, y, self.cellSize, self, canvas) self.allCells[x][y] = cell cell.draw(canvas, tk) if noGUI == False: canvas.pack() self.tk = tk self.firstCell = firstCell self.lastCell = lastCell self.cellMax = sizeX * sizeY arg_1 = "%d" % sizeX arg_2 = "%d" % sizeY if noGUI == True and quiet == False: print "Generowanie labiryntu: 0000 / %04d" % self.cellMax process = subprocess.Popen(["bash", "generate_maze.sh", arg_1, arg_2], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while True: out = process.stdout.readline() if out == '' and process.poll() != None: break if out != '': self.interpretRecivedCellData(out[1:-2]) if noGUI == True: print "Struktura labiryntu:" if printASCII == False: sys.stdout.write(self.getMazeReadableDataToString()) else: self.printMazeInASCII() if fileSave == True: self.saveToFile('w', self.getMazeReadableDataToString()) if findPath == -1 and noGUI == False: res = tkMessageBox.askyesno( "Generator labiryntu", "Czy chcesz aby zostala znaleziona najkrotsza sciezka w labiryncie?" ) if res == True: res = tkMessageBox.askyesno( "Generator labiryntu", "Czy chcesz wybrac punkt startowy i koncowy sciezki?") if res == True: tkMessageBox.showinfo( "Generator labiryntu", "Kliknij na komorke, ktora ma byc punktem startowym") self.selectFirst = True else: self.findShortestWay() elif findPath == 1 or (findPath == -1 and noGUI == True): self.findShortestWay()
from Cell import Cell asdf = Cell(100, "AIR") # asdf.temp = 88 print(asdf.get_temp()) print(asdf.category) print(asdf)
def create_field(self): """Creates an empty field.""" self.field = sp.empty((self.height, self.width), dtype=object) for i in range(self.height): for j in range(self.width): self.field[i, j] = Cell(i, j, self)
def calcTargets(self, checkerTown): self.targets = [] # Run a recurssive function in all directions self.bladeWalker(checkerTown, 1, 1, self.row, self.col) self.bladeWalker(checkerTown, -1, 1, self.row, self.col) self.bladeWalker(checkerTown, 1, -1, self.row, self.col) self.bladeWalker(checkerTown, -1, -1, self.row, self.col) self.bladeWalker(checkerTown, 1, 0, self.row, self.col) self.bladeWalker(checkerTown, -1, 0, self.row, self.col) self.bladeWalker(checkerTown, 0, 1, self.row, self.col) self.bladeWalker(checkerTown, 0, -1, self.row, self.col) # store variables for King's original position and such oldRow = self.row oldCol = self.col # castling situation if (self.touched == False): if (isinstance(checkerTown[self.row][self.col - 4], Rook) and checkerTown[self.row][self.col - 4].touched == False): if (checkerTown[self.row][self.col - 1] == None and checkerTown[self.row][self.col - 2] == None and checkerTown[self.row][self.col - 3] == None): self.targets.append(Cell(self.row, self.col - 2)) if (isinstance(checkerTown[self.row][self.col + 3], Rook) and checkerTown[self.row][self.col + 3].touched == False): if (checkerTown[self.row][self.col + 1] == None and checkerTown[self.row][self.col + 2] == None): self.targets.append(Cell(self.row, self.col + 2)) # now that all targets have been calculated, iterate through them all and # check amIGonnaDie() with a board and position changed targetsToRemove = [] castleLeft = False castleLeftStep = True castleRight = False castleRightStep = True castleLeftCell = Cell(-1, -1) castleRightCell = Cell(-1, -1) for cell in self.targets: if (cell.row == oldRow and cell.col == (oldCol - 2)): castleLeft = True castleLeftCell = cell if (cell.row == oldRow and cell.col == (oldCol + 2)): castleRight = True castleRightCell = cell originalPiece = checkerTown[cell.row][cell.col] checkerTown[cell.row][cell.col] = self checkerTown[self.row][self.col] = None self.row = cell.row self.col = cell.col threat1, threat2 = self.amIGonnaDie(checkerTown) if (threat1 != -1 and threat2 != -1): if (cell.row == oldRow and cell.col == (oldCol - 2)): castleLeft = False if (cell.row == oldRow and cell.col == (oldCol + 2)): castleRight = False if (cell.row == oldRow and cell.col == (oldCol - 1)): castleLeftStep = False if (cell.row == oldRow and cell.col == (oldCol + 1)): castleRightStep = False targetsToRemove.append(cell) # reset the board to its original config checkerTown[oldRow][oldCol] = self checkerTown[cell.row][cell.col] = originalPiece self.row = oldRow self.col = oldCol # re-run amIGonnaDie with the King's original values useless1, useless2 = self.amIGonnaDie(checkerTown) inCheck = False if (useless1 != -1 and useless2 != -1): inCheck = True if (castleLeft == True and (castleLeftStep == False or inCheck)): self.targets.remove(castleLeftCell) if (castleRight == True and (castleRightStep == False or inCheck)): self.targets.remove(castleRightCell) # now iterate through targetsToRemove and remove them from targets for toRemove in targetsToRemove: self.targets.remove(toRemove) return inCheck
return var g = Game() print(g.board.safe_print()) while g.state == 'in_game': kontroler = False while kontroler == False: try: x, y = input('coordinates (row column):').split() x = int(x) - 1 if x < 0 or x > g.board.height - 1: raise ValueError y = int(y) - 1 if y < 0 or y > g.board.width - 1: raise ValueError kontroler = True except ValueError: print('Error, accepted format: "X Y", try again…') c = Cell(row=x, column=y, board=g.board) c.check() print(g.board.safe_print()) if g.board.to_win == 0: print('WINNER') exit() if g.board.state == 'loser': print('ITS OVER') g.state = 'loser' print(g.board.print()) exit()
def build_body(self, rows, columns): for i in range(rows): self.body.append(list()) for j in range(columns): self.body[i].append(Cell((i, j)))
def test_check(self): b = Board(5, 2) b._mapa = [[-1, -2, -2, -2, -2], [-2, -2, -2, -2, -2]] c = Cell(column=0, row=0, board=b) returned = c.check() assert_equal(b.state, 'loser') assert_equal(c.state_on_board, 100) assert_equal(b._mapa[c.row][c.column], 100) assert_equal(returned, 100) b = Board(5, 2) b._mapa = [[100, -2, -2, -2, -2], [-2, -2, -2, -2, -2]] c = Cell(column=0, row=0, board=b) assert_true(not c.check()) b = Board(5, 2) b._mapa = [[5, -2, -2, -2, -2], [-2, -2, -2, -2, -2]] c = Cell(column=0, row=0, board=b) assert_true(not c.check()) b = Board(5, 2) b._mapa = [[-2, -2, -2, -2, -2], [-2, -2, -2, -2, -2]] c = Cell(column=0, row=0, board=b) assert_equal(c.check(),0) assert_equal(b._mapa, [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) b = Board(5, 2) b._mapa = [[-2, -2, -2, -2, -2], [-2, -2, -2, -2, -1]] c = Cell(column=0, row=0, board=b) assert_equal(c.check(),0) assert_equal(b._mapa, [[0, 0, 0, 1, -2], [0, 0, 0, 1, -1]]) b = Board(5, 2) b._mapa = [[-2, -2, -2, -2, -2], [-2, -2, -2, -2, -1]] c = Cell(column=3, row=1, board=b) assert_equal(c.check(),1) assert_equal(b._mapa, [[-2, -2, -2, -2, -2], [-2, -2, -2, 1, -1]])
def configure(self): Cell.configure(self) if self.order == -1: self.order = 2*(self.degree) + 1 return
def __init__(self, position=None): Cell.__init__(self, position)
# coding=utf-8 __author__ = 'voleg' from Cell import Cell DNACell1 = Cell() DNACell2 = Cell() h = Cell().hammingDistance(DNACell2) distance = h print("Hamming Distance = %s" % distance) DNACell11 = DNACell1.mutate(4) DNACell22 = DNACell2.mutate(4) print("Hamming Distance = %s " % Cell().hammingDistance(DNACell11))
def __init__(self,width,height,color,grid): Cell.__init__(self,width,height,grid.margin) self.color = color self.grid = grid self.setup()
def set_tail(self, new_tail: Cell): del self.body[self.last_tail] self.last_tail = new_tail.get_key()
def generateCell(self, coord, richness): self.map[coord] = Cell(self.index, richness) self.index += 1
class ReproductionGame(object): def __init__(self, record): self.__cell = Cell() self.turn = C.BLACK self.record = record self.b = [] self.w = [] def play(self): while True: if not self.__cell.getIsAblePutList(self.turn): self.turn = Cell.flip(self.turn) if not self.__cell.getIsAblePutList(self.turn): return self.__gameSet() continue while True: x = int(self.record[0][0]) y = int(self.record[0][1]) if self.__cell.isAblePut(self.turn, x, y): openness_list = openness.openness(self.createCellClone(), self.turn, x, y, self.turn) even_list = even_theory.update_theory_score( self, x, y, self.turn) self.__cell.putStone(self.turn, x, y) self.record.pop(0) move_list = the_law_of_the_move.nb_able_put_list( self, self.turn) stables_list = stable_stones.update_stable_stone(self) if self.getCount(C.BLACK) + self.getCount(C.WHITE) >= 35: self.b.append(self.getCount(C.BLACK)) self.w.append(self.getCount(C.WHITE)) self.turn = Cell.flip(self.turn) if len(self.record) == 0: array_conc_pre = [ list( range( 1, len( calc_score(stables_list, "黒確定", "白確定", "white")) + 1)), calc_score(openness_list, "黒開放度", "白開放度", "black"), calc_score(even_list, "黒偶数", "白偶数", "white"), calc_score(move_list, "黒着手", "白着手", "white"), calc_score(stables_list, "黒確定", "白確定", "white"), self.b, self.w, np.array(self.w) - np.array(self.b), np.cumsum(np.array(openness_list["黒開放度"])) - np.cumsum(np.array(openness_list["白開放度"])), np.cumsum(np.array(even_list["白偶数"])) - np.cumsum(np.array(even_list["黒偶数"])), np.cumsum(np.array(move_list["白着手"])) - np.cumsum(np.array(move_list["黒着手"])), ] array_conc_ndarray = np.array(array_conc_pre) ndarray_T = array_conc_ndarray.T # print(ndarray_T) # with open('records/data.csv', 'w') as f: with open('records/res.csv', 'a') as f: writer = csv.writer(f) writer.writerows([ndarray_T[-1]]) break else: print("ERROR!") print("座標 (x,y) = " + str(x) + "," + str(y) + " に石を置けません...") def __gameSet(self): b = self.__cell.getCount(C.BLACK) w = self.__cell.getCount(C.WHITE) return C.BLACK if w < b else C.WHITE if w > b else C.BLANK def createCellClone(self): # Gameが持つCellのクローンを返す # Returns: # Cell : フィールド__cellのクローン return self.__cell.createClone() def getStone(self, x, y): # 指定座標の石を返す # Args: # x (int) : x座標 # y (int) : y座標 # Returns: # int : BLACK or WHITE のいずれかを返す return self.__cell.getStone(x, y) def getStonePos(self, pos): return self.__cell.getStone(pos[0], pos[1]) def getIsAblePutList(self, stone): # 石を置ける場所をリストで返す # Args: # stone (int) : 石 # Returns: # (int,int) list : 石を置ける座標をタプルで表現し、そのリストを返す。 return self.__cell.getIsAblePutList(stone) def getCount(self, stone): # 石の個数を返す # Args: # stone (int) : 石 # Returns: # int : 個数を返す return self.__cell.getCount(stone)
def __init__(self, width, height, mode, players): super().__init__() self.logger = logging.getLogger("Board") logging.basicConfig( format='%(asctime)s - %(name)s: %(levelname)s - %(message)s', level=logging.INFO) self.logger.info("Creating Board") self.players = players self.current_player = 0 self.logger.info("Polishing Dice") self.dice = Dice() self.moves = self.dice.roll() self.mode = mode self.last_direction = None # The board self.board = [ [ Cell('red'), Cell('white'), Cell('blue'), Cell('red'), Headquarter('green'), Cell('white'), Cell('blue'), Cell('green'), Cell('white') ], [ Cell('white'), None, None, None, Cell('blue'), None, None, None, Cell('blue') ], [ Cell('blue'), None, None, None, Cell('white'), None, None, None, Cell('green') ], [ Cell('green'), None, None, None, Cell('green'), None, None, None, Cell('red') ], [ Headquarter('red'), Cell('white'), Cell('blue'), Cell('green'), Cell('black'), Cell('green'), Cell('red'), Cell('blue'), Headquarter('white') ], [ Cell('blue'), None, None, None, Cell('green'), None, None, None, Cell('blue') ], [ Cell('green'), None, None, None, Cell('white'), None, None, None, Cell('green') ], [ Cell('red'), None, None, None, Cell('red'), None, None, None, Cell('red') ], [ Cell('white'), Cell('blue'), Cell('red'), Cell('green'), Headquarter('blue'), Cell('white'), Cell('red'), Cell('green'), Cell('blue') ], ] self.width = width self.height = height self.cell_width = width / len(self.board) self.cell_height = height / len(self.board[0])
# else: # return self.heur4(a_cell) # return sqrt(pow(a_cell.getVertDist(), 2) + pow(a_cell.getHorizDist(), 2)) return 2*self.heur4(a_cell) # This function returns the heuristic evaluation for heuristic 6 # This function returns a non-admissable heuristic, heur5 * 3 # INPUT -> (Cell) the cell being evaluated # OUTPUT -> (int) heuristic calculaton def heur6(self, a_cell): return self.heur5(a_cell) * 3 if __name__ == "__main__": testCoord = Coord(1, 2) a_h = Heuristic(4, testCoord) cell = Cell(testCoord, 8) cell.setHorizVertDists(2, 1) # Horiz, vert print "Actual: ",a_h.heur5(cell), "Test: ", 4 print "Actual: ",a_h.heur6(cell), "Test: ", 12 print "Actual: ",a_h.heur4(cell), "Test: ", 3 print "Actual: ",a_h.heur3(cell), "Test: ", 2 print "Actual: ",a_h.heur2(cell), "Test: ", 1 print "Actual: ",a_h.heur1(cell), "Test: ", 0 print a_h1 = Heuristic(1, testCoord) a_h2 = Heuristic(2, testCoord) a_h3 = Heuristic(3, testCoord) a_h4 = Heuristic(4, testCoord) a_h5 = Heuristic(5, testCoord) a_h6 = Heuristic(6, testCoord)
def amIGonnaDie(self, checkerTown): # check if I am in check # there are 8 possible directions that could be hindering me, plus knights # check perpindicular directions for rooks and queens, and kings for one space # iterate over the entire board and set every piece to not critical for row in checkerTown: for piece in row: if (piece != None and piece.team == self.team): piece.critical = False # checking diagonally to the upper right (or 1,1 direction) for i in ([-1, 0, 1]): for j in ([-1, 0, 1]): if (i == 0 and j == 0): continue enemyRow, enemyCol, scoutRow, scoutCol = self.iSpy( checkerTown, self.row + i, self.col + j, i, j) if (i == 0 or j == 0): if (scoutRow != -1): if (enemyRow != -1): # scout found an enemy piece # check if it is a perpindicular moving piece making the scout critical if (isinstance(checkerTown[enemyRow][enemyCol], Rook) or isinstance(checkerTown[enemyRow][enemyCol], Queen)): # scout is critical, mark him as such checkerTown[scoutRow][scoutCol].critical = True checkerTown[scoutRow][scoutCol].criticalTargets = self.pleaseGodSaveTheKing( enemyRow, enemyCol) elif (enemyRow != -1): if (isinstance(checkerTown[enemyRow][enemyCol], Rook) or isinstance(checkerTown[enemyRow][enemyCol], Queen)): # enemy placing the king in check has been found # return its location self.godSaveTheKing = self.pleaseGodSaveTheKing( enemyRow, enemyCol) return enemyRow, enemyCol elif (isinstance(checkerTown[enemyRow][enemyCol], King)): if ((abs(enemyRow - self.row) + abs(enemyCol - self.col)) == 1): # enemy is a king one spot away so it could hypothetically put the king in check self.godSaveTheKing = self.pleaseGodSaveTheKing( enemyRow, enemyCol) return enemyRow, enemyCol else: if (scoutRow != -1): if (enemyRow != -1): # scout found an enemy piece # check if it is a diagonal moving piece making the scout critical if (isinstance(checkerTown[enemyRow][enemyCol], Bishop) or isinstance(checkerTown[enemyRow][enemyCol], Queen)): # scout is critical, mark him as such checkerTown[scoutRow][scoutCol].critical = True checkerTown[scoutRow][scoutCol].criticalTargets = self.pleaseGodSaveTheKing( enemyRow, enemyCol) elif (enemyRow != -1): if (isinstance(checkerTown[enemyRow][enemyCol], Bishop) or isinstance(checkerTown[enemyRow][enemyCol], Queen)): # enemy placing the king in check has been found # return its location self.godSaveTheKing = self.pleaseGodSaveTheKing( enemyRow, enemyCol) return enemyRow, enemyCol elif (isinstance(checkerTown[enemyRow][enemyCol], King)): if ((abs(enemyRow - self.row) + abs(enemyCol - self.col)) == 2): # enemy is a king one spot away so it could hupothetically put the king in check self.godSaveTheKing = self.pleaseGodSaveTheKing( enemyRow, enemyCol) return enemyRow, enemyCol elif (isinstance(checkerTown[enemyRow][enemyCol], Pawn)): if ((enemyRow - self.row) == self.direction): self.godSaveTheKing = self.pleaseGodSaveTheKing( enemyRow, enemyCol) return enemyRow, enemyCol rowTargets = [2, 2, -2, -2, 1, 1, -1, -1] colTargets = [1, -1, 1, -1, 2, -2, 2, -2] for i in range(0, 8): knightRow, knightCol = self.knightInShiningArmor( checkerTown, rowTargets[i], colTargets[i], self.row, self.col) if (knightRow != -1 and knightCol != -1): self.godSaveTheKing = [Cell(knightRow, knightCol)] return knightRow, knightCol return -1, -1
def generateMatriz(self): for i in range(self.rows): self.grid.append([]) for j in range(self.cols): cell = Cell(i, j) self.grid[i].append(cell)
def is_body(self, coord: Cell) -> bool: return coord.get_key() in self.body.keys()
def play(self): while True: if not self.__cell.getIsAblePutList(self.turn): self.turn = Cell.flip(self.turn) if not self.__cell.getIsAblePutList(self.turn): return self.__gameSet() continue while True: x = int(self.record[0][0]) y = int(self.record[0][1]) if self.__cell.isAblePut(self.turn, x, y): openness_list = openness.openness(self.createCellClone(), self.turn, x, y, self.turn) even_list = even_theory.update_theory_score( self, x, y, self.turn) self.__cell.putStone(self.turn, x, y) self.record.pop(0) move_list = the_law_of_the_move.nb_able_put_list( self, self.turn) stables_list = stable_stones.update_stable_stone(self) if self.getCount(C.BLACK) + self.getCount(C.WHITE) >= 35: self.b.append(self.getCount(C.BLACK)) self.w.append(self.getCount(C.WHITE)) self.turn = Cell.flip(self.turn) if len(self.record) == 0: array_conc_pre = [ list( range( 1, len( calc_score(stables_list, "黒確定", "白確定", "white")) + 1)), calc_score(openness_list, "黒開放度", "白開放度", "black"), calc_score(even_list, "黒偶数", "白偶数", "white"), calc_score(move_list, "黒着手", "白着手", "white"), calc_score(stables_list, "黒確定", "白確定", "white"), self.b, self.w, np.array(self.w) - np.array(self.b), np.cumsum(np.array(openness_list["黒開放度"])) - np.cumsum(np.array(openness_list["白開放度"])), np.cumsum(np.array(even_list["白偶数"])) - np.cumsum(np.array(even_list["黒偶数"])), np.cumsum(np.array(move_list["白着手"])) - np.cumsum(np.array(move_list["黒着手"])), ] array_conc_ndarray = np.array(array_conc_pre) ndarray_T = array_conc_ndarray.T # print(ndarray_T) # with open('records/data.csv', 'w') as f: with open('records/res.csv', 'a') as f: writer = csv.writer(f) writer.writerows([ndarray_T[-1]]) break else: print("ERROR!") print("座標 (x,y) = " + str(x) + "," + str(y) + " に石を置けません...")
def generateMatriz(self): for i in range(3): self.grid.append([]) for j in range(4): cell = Cell(i, j, self.r) self.grid[i].append(cell)
def __init__(self, w, h): self.width = w self.height = h self._map = libtcod.map_new(w, h) self.cells = [Cell() for coord in range(self.width * self.height)]