def __init__(self, parent): Cell.__init__(self, parent) Controller.__init__(self, self.parent.canvas, parent) self.offset_x = 0 self.offset_y = 0 self.update_request = False self.old_zoom = False
def testCellCanDetectWheatherAnotherCellIsNeighboured(): cellA = Cell(True, [2,2]) cellB = Cell(True, [3,2]) cellC = Cell(True, [4,3]) assert cellA.is_neighboured_to(cellB) == True, 'A Cell has not detected another cell correctly as neighbour' assert cellB.is_neighboured_to(cellC) == True assert cellA.is_neighboured_to(cellC) == False
def draw(self): if self.update_request: self.update_request = False self.request_update_body() self.clear_io_cache() Cell.draw(self)
def __init__(self): app = QApplication(sys.argv) QObject.__init__(self) super(Gui, self).__init__() self.app = app self.setupUi(self) self.gridLayoutWidget.setStyleSheet("background-color: " "rgb(117,117,117);") self.cell_matrix = [[None for y in range(9)] for x in range(9)] for f_x in range(3): for f_y in range(3): frame = QtWidgets.QFrame(self.gridLayoutWidget) widget = QtWidgets.QWidget(frame) widget.setStyleSheet("background-color: rgb(170,170,170);") # widget.setGeometry(QRect(160, 170, 160, 80)) gridLayout = QtWidgets.QGridLayout(widget) gridLayout.setContentsMargins(0, 0, 0, 0) for x in range(3): for y in range(3): cell = Cell(self) self.cell_matrix[(f_x*3)+x][(f_y*3)+y] = cell cell.setStyleSheet("QLabel{background-color: white;}") gridLayout.addWidget(cell, y, x) self.grid.addWidget(frame, f_y, f_x) self.show()
def __init__(self, level, pos): Cell.__init__(self, level, pos) self.tile = 2, 0 self.player_can_enter = False self.robot_can_enter = True
def explore_action(self): for neighbor in self.current_cell.get_neighbors(): row,col = neighbor.row, neighbor.col if self.cells[row][col] is None: dir_to = Cell.direction_to(self.current_cell, neighbor) if dir_to is not None: return Move(dir_to) oldest_cell = None oldest_time = 0 for row, i in zip(self.cells, range(len(self.cells))): for cell, j in zip(row, range(len(row))): if cell is None: dir_to = Cell.direction_to(self.current_cell, self.world.cells[i][j]) if dir_to is not None: return Move(dir_to) else: cell.step_time if cell.step_time > oldest_time: oldest_time = cell.step_time oldest_cell = cell if oldest_cell is not None: dir_to = Cell.direction_to(self.current_cell, oldest_cell) if dir_to is not None: return Move(dir_to) return Move(Direction.random_direction())
class CellTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testCoordinateCreated(self): self.coordinate = Coordinate() assert self.coordinate.set(1,2) == (1,2), 'Coordinate was created' assert self.coordinate.coordX == 1, 'Coordinate was created' assert self.coordinate.coordY == 2, 'Coordinate was created' def testCellCreated(self): coordinate = Coordinate(1,1) self.cell = Cell(coordinate) assert self.cell.exists() == False, 'Cell was not created' def testCellSetValue(self): coordinate = Coordinate(1,1) self.cell = Cell(coordinate) self.cell.setValue(True) assert self.cell.value == True, 'Cell has invalid value' def testGetNeigbours(self): myNeighbourListe = [(0,0), (0,1), (0,2), (1,0), (1,2), (2,0), (2,1), (2,2)] coordinate = Coordinate(1,1) self.cell = Cell(coordinate) generatedNeigbhourListe = self.cell.getNeighbours() assert generatedNeigbhourListe == myNeighbourListe, 'Cell has invalid value'
class Gol02Test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testCellCreated(self): self.cell = Cell() assert self.cell.exist() == True, 'Cell was not created' def testCellAddNeighbour(self): self.cell = Cell() self.cell2 = Cell() assert self.cell.add(self.cell2) == self.cell2, 'Cell has no neighbour' def testCellNumberOfNeighbours(self): self.cell = Cell() print self.cell.number_of_neighbours() assert self.cell.number_of_neighbours() == 0, 'Cell does not know about its neighbours' def testCellNumberOfNeighbours2(self): self.cell = Cell() self.cell2 = Cell() self.cell.add(self.cell2) print self.cell.number_of_neighbours() assert self.cell.number_of_neighbours() == 1, 'Cell does not know about its neighbours'
def setUp(self): self.grid = Grid() for row in range(1,10): for column in range(1,10): cell = Cell(row,column) cell.setValues([row,column]) self.grid.setCell(row, column, cell)
def testSetCellGetCell(self): testCell = Cell(1,1) testCell.setValues([1]) currentCell = self.grid.getCell(1,1) self.assertNotEqual(testCell, currentCell, "Incorrect setup, currentCell should not match") self.grid.setCell(1, 1, testCell) newCell = self.grid.getCell(1, 1) self.assertEqual(testCell, newCell, "Cells do not match")
def draw_io(self): Cell.draw_io(self) if not self.drawable: return for k in self.objects: self.objects[k].draw_io()
def __init__(self, level, pos, flow_dir=None): Cell.__init__(self, level, pos) self.tile = (3, 0) if flow_dir is None else (4, 0) self.rotate = 0 if flow_dir is None else flow_dir self.player_can_enter = False self.robot_can_enter = False self.flow_dir = flow_dir
def update(self): self.queue_draw() cellsToPop=[] for cell in self.cells: cell.update(self.currentState) if cell.type=="NormalCell": if cell.posX+cell.width<0 or (cell.status=="Dead" and len(cell.dyingParticles)<=0): cellsToPop.append(cell) for cell in cellsToPop: self.cells.pop(indexOf(self.cells,cell)) if cell==self.virus[0].targetCell: self.virus[0].targetCell=None if self.currentState=="Running": self.ticksToNextCell-=1 if self.ticksToNextCell<=0: self.ticksToNextCell=random.randint(self.minTimeToNextCell,self.maxTimeToNextCell) newCell=Cell(WINDOW_SIZE, random.randint(0,TRAINING_ZONE_LIMIT-CELL_HEIGHT)) newCell.velX=-random.random()*2 newCell.type="NormalCell" self.cells.append(newCell) #update virus for virus in self.virus: if not virus.isDead: virus.update(self.currentState) if len(self.cells)>0 and virus.targetCell==None: virus.targetCell=self.cells[len(self.cells)-1] #This is a temprorary decision function #Actual classification should do this self.classify_cell(widget=None) if virus.is_colliding_with(virus.targetCell): if not virus.targetCell.status: if virus.status=="Attacking": virus.targetCell.status="Dying" if virus.status=="Eating": virus.targetCell.status="BeingEaten" if virus.targetCell.status=="Dead": virus.targetCell=None for (cell,type) in self.trainingSet: for i in xrange(len(self.classificationList)): if type==self.classificationList[i]: rightLimit=self.divisionPoints[i] if i==0: leftLimit=0 else: leftLimit=self.divisionPoints[i-1] break cell.update(self.currentState,[leftLimit,rightLimit-cell.width,TRAINING_ZONE_LIMIT,WINDOW_SIZE-cell.height])
def __init__(self, level, pos, facing): Cell.__init__(self, level, pos) self.tile = 7, 3 + (facing % 2) self.player_can_enter = False self.robot_can_enter = False self.object_can_enter = False self.floor_tile = 0, 0
def _populate_cells(self): """Create empty cells""" for row in range(0, self.rows): self.cells.append([]) for column in range(0, self.columns): cell = Cell() cell.row = row cell.col = column self.cells[row].append(cell)
def tuples_to_objects(grid): size = len(grid) object_grid = [['x' for i in range(size)] for j in range(size)] for i in range(size): for j in range(size): object_grid[i][j] = Cell(i,j,size) object_grid[i][j].status = grid[i][j] return object_grid
def init_training_set(self): file = open("./resources/list.txt",'r') for linea in file.readlines(): newCell=Cell(0,0,0,0,"TrainCell", linea) newCell.width=20 newCell.height=20 newCell.velX=random.randint(1,5)/5.0 newCell.velY=random.random() type=None if linea[1]=="0": type="Target" elif linea[1]=="1": type="Enemy" elif linea[1]=="2": type="Food" if type=="Target": newCell.posX=random.randint(0,WINDOW_SIZE/3-newCell.width) elif type=="Enemy": newCell.posX=random.randint(WINDOW_SIZE/3,(WINDOW_SIZE/3)*2-newCell.width) elif type=="Food": newCell.posX=random.randint((WINDOW_SIZE/3)*2,WINDOW_SIZE-newCell.width) newCell.posY=random.randint(self.trainingZoneLimit,WINDOW_SIZE-newCell.height) self.trainingSet.append((newCell,type)) file.close()
def __init__(self, canvas, number_of_rows, number_of_coloumns, width, start_positions): self.canvas = canvas self.number_of_rows = number_of_rows self.number_of_coloumns = number_of_coloumns self.width = 10 self.cells = [] # <- Used to represent the cells, inner lists represent rows self.living_cells = [] # <- Represents the living cells in each step self.dying_cells = [] # <- Cells that are going to die in this step self.checked_cells = [] # <- Cells that already sentenced to death or life key = 0 for i in range(0, self.number_of_rows): row = [] for j in range(0, self.number_of_coloumns): cell = Cell(self.canvas, j * self.width, i * self.width, self.width, False, key) row.append(cell) key += 1 self.cells.append(row) for i in range(0, self.number_of_rows): # <- Set up the neighbours of a cell for j in range(0, self.number_of_coloumns): cell = self.cells[i][j] cell.left = self.cells[i][(j-1) % self.number_of_coloumns] cell.right = self.cells[i][(j+1) % self.number_of_coloumns] cell.top = self.cells[(i-1) % number_of_rows][j] cell.bottom = self.cells[(i+1) % number_of_rows][j] cell.topleft = self.cells[(i-1) % number_of_rows][(j-1) % self.number_of_coloumns] cell.topright = self.cells[(i-1) % number_of_rows][(j+1) % self.number_of_coloumns] cell.bottomleft = self.cells[(i+1) % number_of_rows][(j-1) % self.number_of_coloumns] cell.bottomright = self.cells[(i+1) % number_of_rows][(j+1) % self.number_of_coloumns]
def __init__(self, level, pos, facing=None): Cell.__init__(self, level, pos) self.tile = 9, 0 self.facing = facing self.robot_can_enter = False self.corner_tile = 10, 0 # diagonal dir the corner is facing, clockwise from northeast (optional) self.facing = facing
def __init__(self, level, pos, state): Cell.__init__(self, level, pos) self.tile = 11, 0 self.player_can_enter = not state self.robot_can_enter = not state self.object_can_enter = not state self.state = bool(state) self.off_tile = 0, 0 self.on_tile = 1, 0
def __init__(self, level, pos, facing, colour): Cell.__init__(self, level, pos) self.tile = 5, 2 + colour self.rotate = facing self.player_can_enter = False self.robot_can_enter = False self.object_can_enter = False self.floor_tile = 0, 0 self.colour = colour
def __init__(self, parent, game): self.board = [] self.game = game for row in range(self.BOARD_ROWS): rowcell = [] for column in range(self.BOARD_COLUMNS): image = PhotoImage(file='images/middleboard.gif') c = Cell(parent, self, self.game, image, row, column) c.grid(row=row, column=column) rowcell.append(c) self.board.append(rowcell)
def ImportGrid(file): reader = csv.reader(file) grid = Grid() rowCount = 1 for row in reader: for column in range(1,10): cell = Cell(rowCount,column) value = row[column-1] if value is not "": cell.setValues([int(value)]) grid.setCell(rowCount, column, cell) rowCount = rowCount + 1 return grid
class CellTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testIsAlive(self): self.cell = Cell() result = self.cell.isAlive() assert result == True, 'Cell is alive' def testIsDead(self): self.cell = Cell() self.cell.setStatus(False) result = self.cell.isAlive() assert result == False, 'Cell is dead' def testCountNeighbours(self): self.cell = Cell() self.neighbour = Cell() amount = self.cell.countNumberOfNeighbours() assert amount == 0, 'Number of Cell neighbours' def testAddNeighbour(self): self.cell = Cell() self.neighbour = Cell() self.cell.addNeighbour(self.neighbour) amount = self.cell.countNumberOfNeighbours() assert amount == 1, 'Neighbour is not added to the cell, amount ='+str(amount)
def select_targets(config): target_count = config['L'] balloon_count = config['B'] #all_cells = Cell.load_all_cells(config) target_cells = Cell.load_target_cells(config) selected_targets = random.sample(target_cells, balloon_count) if balloon_count < target_count else target_cells return selected_targets
def vector(first, other): ''' Returns the offset of a point compared to the agent's position ''' offset = Cell.sub_positions(other, first) abs_offset = map(abs,offset) max_val = max(abs_offset) vector = tuple(map(div,offset,(max_val,max_val))) return vector
class Gol03Test(unittest.TestCase): field = None cell = None def setUp(self): pass def tearDown(self): pass def testIsCellCreated(self): self.cell = Cell() assert self.cell.exist() == True, 'Cell was not created' def testIsCellAlive(self): self.field = Field() self.coordinate = [0,0] self.field.is_cell_alive(self.coordinate) == False, 'Cell is not alive' def testSetACellAlive(self): self.field = Field() self.coordinate = [0,0] self.field.append(self.coordinate) self.field.is_cell_alive(self.coordinate) == True, 'Cell is not alive' def testDoWeNeedAnotherPeriod(self): field = Field() cell = Cell() cell2 = Cell() field.append(Cell) field.append(cell2) assert field.number_of_neighbours() == 2, 'Field cant count its neighbours'
def update(self): """ Scan the map looking for threats and update the cell weights. """ steps = 3 # print [c.kind for c in self.threats] for threat in self.threats: directions = {'UP': 1, 'RIGHT': 1, 'DOWN': 1, 'LEFT': 1} for s in range(1, steps + 1): for k, d in enumerate(directions): if directions[d] == 0: continue cell = self.get_cell(threat.x, threat.y, s, d) # print cell.kind, cell.x, cell.y, cell.weight # print threat.x, threat.y, s, d, cell.kind # block that prevent the bot from advancing in that direction if cell.is_wall or cell.is_undestructible: directions[d] = 0 # do not put traps behind the player, but increase cells' cost # to alow user to turn instead of going back, when possible elif cell.kind == self.player.name: cell.weight = cell.weight + threat.weight directions[d] = 2 # TODO: try replacing all cells with trap blocks # blocks that can be replaced by bomb range blocks elif (cell.is_empty or cell.is_improvement) and directions[d] == 1: self.map[cell.y][cell.x] = Cell.trap(cell.x, cell.y, threat.weight, cell.parent) else: weight = 1 if directions[d] == 2 else threat.weight cell.weight = cell.weight + weight
def update_body(self, state=None): self.zoom = self.parent.zoom self.font = self.parent.font self.label_font = self.parent.label_font if self.old_zoom is not self.zoom: Cell.update_body(self, state=state) self.old_zoom = self.zoom for k in self.objects: self.objects[k].request_update_body() for k in self.objects: self.objects[k].draw() #update_request is invalid since all cell were allready redrawn (and it is triggered by Cell.update_body()) self.update_request = False
def createGrid(self): col = 0 row = 50 cell_num = 0 for y in xrange(44): for x in xrange(74): cell_num +=1 cell = Cell(self, [col, row], cell_num) if row == 50 or row == 480 or col == 0 or col == 730: cell.edge = True #if row == 60 or row == 470 or col == 10 or col == 720: #cell.alive = True self.sprites.add(cell) col += 10 row += 10 col = 0
def drink_action(self): local_drink = self.get_drink_action() if local_drink is not None: return local_drink else: best_cell = self.find_closest(lambda cs: cs.has_water()) if best_cell is not None: dir_to = Cell.direction_to(self.current_cell, best_cell) if dir_to is not None: return Move(dir_to) return self.explore_action()
def populateWorld(self): cellCount = self.width * self.height aliveCells = cellCount * self.fill_percentage / 100 aliveChance = aliveCells / cellCount self.game_field = [[[] for column in range(self.width)] for row in range(self.height)] for row in range(self.height): for cell in range(self.width): state = 1 if (random() <= aliveChance) else 0 self.game_field[row][cell] = Cell(state, row, cell)
def __init__(self, rows, columns): self._rows = rows self._columns = columns self._grid = [[Cell() for column in range(0, columns)] for row in range(0, rows)] for row in range(0, rows): for column in range(0, columns): self.findNeighbour(column, row) self.generate() self.drawBoard()
def create_board(self): for i in range(self.height): row = [] for j in range(self.width): row.append( Cell( (self.x + (j * self.cell_width), self.y + (i * self.cell_height), self.cell_width, self.cell_height), state=None, )) self.board.append(row)
def __init__(self, rows, columns, load): self._rows = rows self._columns = columns self._grid = [[Cell() for column in range(0, columns)] for row in range(0, rows)] for row in range(0, rows): for column in range(0, columns): self.findNeighbour(column, row) if not load: self.generate()
def __init__(self, size, walls=True): self.size = size self.start = (0, 0) self.end = (0, 0) self.grid = list() # Inicializa 'grid' de acuerdo a 'size'. for i in range(size[0]): row = list() for j in range(size[1]): row.append(Cell(pos=(i, j), walls=walls)) self.grid.append(row)
def get_cell(self, x, y): """ :param x: x-coordinate of a cell :type x: int :param y: y-coordinate of a cell :type y: int :return: the cell of coordinates (x,y) in the game's grid :type: cell :UC: 0 <= x < width of game and O <= y < height of game """ assert 0<= x < self.get_width() and 0<= y < self.get_height(), "cell must be within the grid" return Cell()
def update(self, x, y, flag= False): # self.env[self.vacc.y][self.vacc.x] = '-' self.vacc = Cell(x, y) self.env[self.vacc.y][self.vacc.x] = 'C' print() print() if flag: print("Cleaned dirt at position: ({}, {})".format(x, y)) time.sleep(1) for lis in self.env: print(lis)
def __init__(self, width, height): self.width = width self.height = height self.cells = [] self.symmetry = Symmetry.No for y in range(height): row = [] for x in range(width): row.append(Cell(x, y)) self.cells.append(row) self.linkCells() return
def list_concat_copy(A, B): if A is not None: temp_a = A temp_b = B C1 = Cell(temp_a.data) temp_C1 = C1 while temp_a.next is not None: temp_a = temp_a.next temp_C1.next = Cell(temp_a.data) temp_C1 = temp_C1.next temp_C1.next = Cell(temp_b.data) temp_C1 = temp_C1.next while temp_b.next is not None: temp_b = temp_b.next temp_C1.next = Cell(temp_b.data) temp_C1 = temp_C1.next return temp_C1
def prepare_grid(self): grid = [] for row in range(self.rows): grid.append([]) for column in range(self.columns): if self.mask[(row, column)]: grid[row].append(Cell(row, column)) else: grid[row].append(None) return grid
def create_world(self, terminals, blocks=None): count = 0 for j in range(self.row): cells = [] for i in range(self.column): if self.is_terminal(i, j, terminals): terminal = self.__get_terminal(i, j, terminals) cell = Cell("T", reward=terminal["reward"], utility=terminal["reward"]) cells.append(cell) elif self.is_block(i, j, blocks): cell = Cell("B") cells.append(cell) else: cell = Cell("S", name="s{0}".format(count)) cells.append(cell) count += 1 self.grid_matrix.append(cells) # append each row to the matrix self.create_neighbors()
def __init__(self, size): self.cols, self.rows = size self.x_spacing = pygame.display.get_surface().get_size()[0] / self.cols self.y_spacing = pygame.display.get_surface().get_size()[1] / self.rows self.cells = [] for i in range(self.cols): self.cells.append([]) for j in range(self.rows): self.cells[i].append( Cell(i * self.x_spacing, j * self.y_spacing, self.x_spacing, self.y_spacing, random.randint(0, 1)))
def input_living_cells(self): inp = input("Insert number of cells") print() for i in range(int(inp)): coord = input("Insert cell coordinates") coord = coord.split(" ") self.coord_list.append(int(coord[0])) self.coord_list.append(int(coord[1])) cell = Cell(int(coord[0]), int(coord[1]), True) self.living_cells.append(cell) print()
def build_map(): for i in range(-90, 91): for j in range(-180, 181): id = i.__str__() + "/" + j.__str__() upper_left = Point(i, j) upper_right = Point(i + 1, j) lower_left = Point(i, j + 1) lower_right = Point(i + 1, j + 1) coordinates = Coordinates(upper_right, upper_left, lower_right, lower_left) new_cell = Cell(id, coordinates) map_cells.update({id: new_cell})
def generate_row(self, initial_number, new_row): """ Generated a row of 9 Cell elements Keyword arguments: initial_number -- Pivot to generate the row new_row -- Row position return list of Cells [Cell1, Cell2 ... Cell9] """ row_generated = [] row_generated.append(Cell(initial_number, False, MAP_ROW[new_row], 0)) new_number = initial_number + 1 column = 1 for row in range(1, 9): if new_number > 9: new_number = 1 row_generated.append( Cell(new_number, False, MAP_ROW[new_row], column)) new_number += 1 column += 1 return row_generated
def __init__(self, rows, cols, width, height, screen): self.rows = rows self.cols = cols self.width = width self.height = height self.screen = screen self.size = height / rows self.gridBase = [[None for j in range(cols)] for i in range(rows)] for i in range(rows): for j in range(cols): self.gridBase[i][j] = Cell(i, j, cols, rows, self)
def _get_expected_result_for_get_scoring_matrix_method(self): n_row = 4 n_col = 4 expected_result = np.empty((n_row, n_col), dtype = Cell) expected_result_values = [0, -2, -4, -6, -2, 5, 3, 1, -4, 3, 1, -1, -6, 1, -1, 6] expected_result_directions = [None, Direction.LEFT, Direction.LEFT, Direction.LEFT, Direction.UP, Direction.DIAG, Direction.LEFT, Direction.LEFT, Direction.UP, Direction.UP, Direction.UP|Direction.LEFT, Direction.UP|Direction.LEFT, Direction.UP, Direction.UP, Direction.UP|Direction.LEFT, Direction.DIAG] for i in range(0, n_row): for j in range(0, n_col): k = i * n_row + j expected_result[i, j] = Cell() expected_result[i, j].value = expected_result_values[k] expected_result[i, j].directions = expected_result_directions[k] return expected_result
def __str__(self): """ Overloaded function called when the grid is printed """ output = '+' + "---+" * self.columns + '\n' for row in self.each_row(): top = '|' bottom = '+' for cell in row: if cell is None: # This clause handles the case where there is no cell object # at the specified location because it has been masked cell = Cell(-1, -1) body = '{:3s}'.format(self.contents_of(cell)) east_boundary = ' ' if cell.isLinked(cell.cellEast) else '|' top = top + body + east_boundary south_boundary = ' ' if cell.isLinked( cell.cellSouth) else '---' corner = '+' bottom = bottom + south_boundary + corner output = output + top + '\n' output = output + bottom + '\n' return output
def __init__(self, puzzle_file): # Initialize the board by reading in numbers from numbers.txt values = utils.read_puzzle(puzzle_file) self.board = [] self.board_size = len(values) for row_num, row in enumerate(values): new_row = [] for column_num, value in enumerate(row): cell = Cell(value, row_num, column_num, self) new_row.append(cell) self.board.append(new_row)
def __init__(self, width, height): """Initialize the Board class. width -- number of columns height -- number of rows """ self.width = width self.height = height self.live_cells = [] # generate an n * n grid where n = self.width = self.height self.grid = [[Cell((x, y), self) for y in range(self.width)] for x in range(self.height)]
def arg_escape(now, sp): # 找到逃跑的角度 i = sp ars = Cell(now.id, cross_scr(dec(now.pos, i.pos)), dec(now.veloc, i.veloc), now.radius) args = get_arg(ars.veloc) + sgn(scal( ars.pos, ars.veloc)) * pi / 2 # 找到一个合适的垂直喷射角度 args = r_arg(args) sgn1 = sgn(scal(ars.veloc, ars.pos)) sp1 = Cell(now.id, [now.pos[0], now.pos[1]], [now.veloc[0], now.veloc[1]], now.radius) sp2 = Cell(now.id, [i.pos[0], i.pos[1]], [i.veloc[0], i.veloc[1]], i.radius) sp1.move(Consts["FRAME_DELTA"]) sp2.move(Consts["FRAME_DELTA"]) eject(sp1, args) ars2 = Cell(now.id, cross_scr(dec(sp1.pos, sp2.pos)), dec(sp1.veloc, sp2.veloc), now.radius) sgn2 = sgn(scal(ars2.pos, ars2.veloc)) if (sgn1 * sgn2 < 0): args = r_arg(get_arg(ars.pos) + pi) return args
def reset(): global visited global cells global cur_cell global cur_c_x global cur_c_y cur_cell = Cell(0, 0, size, screen_size[0], screen_size[1]) visited = [] cells = [] cur_c_x = 0 cur_c_y = 0 init()
def reset(): global visited global cells global cur_cell global cur_c_x global cur_c_y cur_cell = Cell(0, 0, size, WIDTH, HEIGHT) visited = [] cells = [] cur_c_x = 0 cur_c_y = 0 init()
def __init__(self, grid: Grid) -> None: if not is_valid_grid(grid): # если грид не 9 на 9 - поднимаем ошибку raise ValueError('Incorrect grid. Expected grid 9x9') self.__rows = [[Cell(item) for item in row] for row in grid] self.__columns = [[self.__rows[j][i] for j in range(9)] for i in range(9)] self.__squares = [] for i, j in product((0, 3, 6), (0, 3, 6)): self.__squares.append([ self.__rows[x][y] for x in range(i, i + 3) for y in range(j, j + 3) ])
def init_board(self): """ Update board with new Cell instances """ for row in range(self.size): for column in range(row + 1): self.set_cell(Cell(row, column, True)) # Remove pegs where there should be holes self.init_holes() self.set_neighbours()
def newCells(data): for cell in data.cells: cell.counter += 1 if cell.counter >= cell.time: cell.counter = 0 x, y = movePossible(data, cell.x, cell.y) if x == -1: continue else: (newX, newY) = x, y Res, Moi, Foo = get_cell_mutation(data) Res += cell.resistance if Res < 0: Res = 0 if Res > 1: Res = 1 Moi += cell.moist if Moi < 0: Moi = 0 if Moi > 1: Moi = 1 Foo += cell.hunger if Foo < 0.25: Foo = 0.25 if Foo > 1: Foo = 1 new = Cell(data, Res, Moi, Foo, newX, newY) R, G, B = data.rgbImage.getpixel((cell.x, cell.y)) R, G, B = R / 256, 1 - G / 256, B / 256 if (dist2(cell.x, cell.y, data.width // 2, data.height // 2) < data.buffer**2): R, B, G = 0, 0.5, 1 new.updateSurvive(R, B, G, data.radiation) if new.survivability > 0: new.spread(B) data.cells.append(new) data.dict[(new.gridRow, new.gridCol)] = (new.x, new.y)
def __init__(self, size): self.grid = [] self.floors = [] for i in range(0, size): row = [] for j in range(0, size): if 1 < i < 5 and j == 2 or 0 < j < 6 and i == 1 or i == 2 and j == 4: cell = Cell(i, j, "wall") row.append(cell) elif 4 < j < 10 and i == 6 or 3 < i < 7 and j == 5: cell = Cell(i, j, "wall") row.append(cell) elif 5 < i < 9 and j == 1 or 1 < j < 6 and i == 8: cell = Cell(i, j, "wall") row.append(cell) elif 0 < i < 5 and 6 < j < 8 or j == 8 and 5 < i < 9 or i == 2 and j == 8 or i == 4 and j == 9: cell = Cell(i, j, "wall") row.append(cell) elif i == 6 and 1 < j < 4 or i == 4 and j == 3 or i == 3 and j == 0 or i == 0 and j == 7: cell = Cell(i, j, "wall") row.append(cell) else: cell = Cell(i, j, "floor") row.append(cell) self.floors.append([i, j]) self.grid.append(row)
class TestCell(unittest.TestCase): def test_set_valid_value(self): self.cell = Cell(9) value: int = 1 self.cell.set_value(value) self.assertEqual(value, self.cell.value) #if the value is valid, then there should be no possiblities. self.assertEqual(0, len(self.cell.possibilities)) def test_invalid_max_value(self): with self.assertRaises(RuntimeError): Cell(17) def test_set_unknown_value(self): self.cell = Cell(9) value: int = -1 self.cell.set_value(value) self.assertEqual(value, self.cell.value) # All values are possible. self.assertEqual(9, len(self.cell.possibilities)) def test_bad_value(self): self.cell = Cell(9) value: int = 100 with self.assertRaises(RuntimeError): self.cell.set_value(value)
def setUpClass(self): """Basic Cell class setup. Creating a mini 4 cell neighbourhood, and calling the get_neighbours class to set up neighbours on all cells. Doesn't call get_neighbours on C4, as to save it for a later test.""" self.C1 = Cell(0,0, state=0) self.C2 = Cell(1,0, state=0) self.C3 = Cell(0,1, state=0) self.C4 = Cell(1,1, state=1) self.Board = [[self.C1, self.C2], [self.C3, self.C4]] self.C1.get_neighbours(self.Board) self.C2.get_neighbours(self.Board) self.C3.get_neighbours(self.Board)