def load_startfield(self, filename): """ Returns list with startfield as Field object. filename: name of file startfield return: [Field] """ filename = f"data/startfields/{filename}" with open(filename, "r") as f: field_data = f.readlines() field_size = len(field_data) for i, line in enumerate(field_data): field_data[i] = line.strip().split() new_field = [] for row in field_data: new_field_row = [] for cell in row: if cell == "E": new_field_row.append(Cell("E", "", 0)) else: if len(cell) == 3: id = cell[0] direction = cell[1] vehicle_size = cell[2] else: id = cell[:2] direction = cell[2] vehicle_size = cell[3] new_field_row.append(Cell(id, direction, vehicle_size)) new_field.append(new_field_row) return [Field(field_size, new_field)]
def create_new_field(self, cell, i, j, k): """ Creates field with vehicle on new position. cell: Cell object in Field.field i: Index of row Cell in Field.field j: Index of column Cell in Field.field return: Field """ pos = 1 if k > 0: pos = -1 new_field = self.make_copy() new_cell = Cell(cell.id, cell.direction, cell.vehicle_size) if cell.direction == "H": new_field[i][j + k] = new_cell new_field[i][j + k + (1 * pos)] = new_cell if cell.vehicle_size == 3: new_field[i][j + k + (2 * pos)] = new_cell for m in range(cell.vehicle_size, (self.size)): index_to_check = j + k + (m * pos) if index_to_check <= (self.size - 1) and new_field[i][index_to_check].id == cell.id: new_field[i][index_to_check] = Cell("E", "", 0) else: new_field[i + k][j] = new_cell new_field[i + k + (1 * pos)][j] = new_cell if cell.vehicle_size == 3: new_field[i + k + (2 * pos)][j] = new_cell for m in range(cell.vehicle_size, (self.size)): index_to_check = i + k + (m * pos) if index_to_check <= (self.size - 1) and new_field[index_to_check][j].id == cell.id: new_field[index_to_check][j] = Cell("E", "", 0) new_field_object = Field(self.size, new_field) return new_field_object
def set_cells_from_csv(self): """Set the elements of the csv list into the cell list""" i = 0 for line in self._get_CSV_Grid(): j = 0 for cellcsv in line: #If the cell in the csv is not empty if cellcsv == "": pass elif cellcsv == "P": self._cells[i][j] = Cell(j, i) self._cells[i][j].element = Element("MacGyver") self.playerCoordinates = (j, i) elif cellcsv == "G": self._cells[i][j] = Cell(j, i) self._cells[i][j].element = Element("Guardian") self.guardianCoordinates = (j, i) else: symbolDict = readJSON.json_to_dictionary( "resources", "element.json") elementName = Element.getNameFromSymbolInDict( symbolDict, cellcsv) self._cells[i][j] = Cell(j, i) self._cells[i][j].element = Element(elementName) j = j + 1 i = i + 1
def fillTableWithElements(self): "We are going to fill the table with all the cell objects" listRow = list() i = 0 j = 0 #We read each line and cell of grille_csv and add the real class element #in a table (list of lists) for row in self._get_grille_csv(): j = 0 listCell = list() for cell in row: #We search which element is equal to the symbol in the current cell k = 0 findSomething = False for element in self._get_elements(): if cell == element.symbol: #If it is a scroll, we instanciate the scroll with its message if cell == "P": scroll = Scrolls("No message yet.") scroll.loadScrollFromFile(j, i, self) currentCell = Cell(j, i, scroll) elif cell == "B": box = Box() currentCell = Cell(j, i, box) else: currentCell = Cell(j, i, element) listCell.append(currentCell) findSomething = True #We set the coordinates of elements in level attributes : start, end, spikes, scrolls self.setElementsCoordinates(cell, j, i) #We need to get the number elements minus 1 to get a functional #filling table method nbElementsInTheLevel = len(self._get_elements()) if findSomething == False and k >= nbElementsInTheLevel - 1: currentCell = Cell(j, i, None) listCell.append(currentCell) k = k + 1 j = j + 1 i = i + 1 listRow.append(listCell) #Now that our elements are in each case. We set the attributes : grille, spikes, scrolls self._set_grille(listRow)
def get_dict_of_coordinates_from_string(coordinates_list_string): """ Parses the tuples of coordinates from input file and returns the dictionary, where: - Key -> the tuple of coordinates of active cell - Value -> instance of the Cell class """ # Look for tuples in input file and parse them coordinates_tuple_pattern = r'\([-]{0,1}\d+, [-]{0,1}\d+\)' coordinates_tuples_parsed = re.findall(coordinates_tuple_pattern, coordinates_list_string) active_cells_dict = {} # Iterate through every tuple and parse both X and Y coordinate from it for coordinates_tuple_parsed in coordinates_tuples_parsed: coordinate_single_pattern = r'[-]{0,1}\d+' coordinates_parsed = re.findall(coordinate_single_pattern, coordinates_tuple_parsed) try: # Create a tuple consists X and Y coordinates as an Integer coordinates_tuple = (int(coordinates_parsed[0]), int(coordinates_parsed[1])) active_cells_dict[coordinates_tuple] = Cell( coordinates_tuple[0], coordinates_tuple[1], True, 0) except Exception as e: print( f'Some error occured, skipping current cell coordinates. Error: {e}' ) # If the dict is empty, raise BadInitCoordinateError if not active_cells_dict: raise BadInitCoordinatesError() return active_cells_dict
def __init__(self, nums, xy, partition, numOfClim): # размеры Карты self.sizeX, self.sizeY = xy # разбиение. На сколько кусочков будет поделена одна еденица измерения self.partition = int(partition) if self.partition <= 0: raise Exception("Неверно задано значение разбиения. class Map") # погода. Погода управляет такими состояниями как солнце,влажность, ветер ... её характеристики зависят от климата self.weather = Weather(numOfClim) # количество делений, на которые разбито поле x, y = self.sizeX * self.partition, self.sizeY * self.partition # массив клеток Карты self.cells = [] for i in range(y): self.cells.append([Cell() for i in range(x)]) # объекты, от которых создаются остальные растения этого же типа self.typesOfPlant = [PlantSpruce(), PlantMaple()] # список всех растений, находящихся на карте в настоящий момент self.plantsList = [] self._setPlantsList(nums)
def __init__(self, h, w, count_of_mines): self.size = (h, w) self.count_of_mines = count_of_mines self.marked_cells = 0 self.true_marked_cells = 0 self.field = [] for i in range(self.size[0]): self.field.append([]) for j in range(self.size[1]): self.field[i].append(Cell((i, j)))
def make_copy(self): """ Returns copy of Field.field from self Return: [[Cell]] """ copy = [] for i in range(self.size): copy.append([]) for i, row in enumerate(self.field): for cell in row: copy[i].append(Cell(cell.id, cell.direction, cell.vehicle_size)) return copy
def __init__(self, _pygame, block_size, max_x): self.__block_size = block_size self.obj = _pygame.Surface( (self.__block_size * 10 + 11, self.__block_size * 20 + 22)) self.obj.fill((255, 255, 255)) self.pos = ((max_x - (self.__block_size * 10 + 11)) / 2, 15) self.cell = [] for i in range(10): self.cell.append([]) for j in range(20): self.cell[i].append([]) self.cell[i][j] = Cell(_pygame, self.__block_size)
def _set_cells(self, size_width, size_height): """Set the list of the cells of the level""" i = 0 while i < size_height: rowCells = list() j = 0 while j < size_width: rowCells.append(Cell(j, i)) j = j + 1 i = i + 1 self._cells.append(rowCells)
def __init__(self): # create dices self.dices = Dices() # create community array to store community cards self.community = [] self._init_communities() # create chance array to store chance cards self.chance = [] self._init_chances() # create bank self.bank = Bank() # create cells self.cells = [] for key, value in CELLS.items(): self.cells.append(Cell(value))
def calculate_next_step(self, cells, candidates=True): """ For every cell in `self.active_cells` and `self.active_cells_candidates take their closest surroundings. - If the active cell has coordinates (3, 2), the surrounding elements for discussion will have coordinates: (2, 1), (3, 1), (4, 1), (3, 1), (3, 3) etc. but NOT (3, 2). - If there is an active cell on discussed coordinates, inrement the number of its neighbours. Otherwise, if we are discussing the surroundings of the cells which belong to `self.active_cells dictionary`, mark the coordinates as possible active cell for the next iteration due to one of the rules of the Game Of Life. """ for coordinates, cell in cells.items(): for y in range(cell.pos_y - 1, cell.pos_y + 2): for x in range(cell.pos_x - 1, cell.pos_x + 2): if (x, y) == coordinates: continue if (x, y) in self.active_cells: cell.number_of_neighbours += 1 elif candidates: self.active_cells_candidates[(x, y)] = Cell( x, y, False, 0)
def __init__(self, canvas, rows, cols): self.canvas = canvas self.rows, self.cols = rows, cols self.cell_size = cell_size = 30 self.grid = [[Cell(x, y, cell_size) for x in range(cols)] for y in range(rows)] self.canvas.bind("<ButtonPress-1>", lambda event: Grid.show_dfs(event, self)) self.canvas.bind("<ButtonPress-3>", lambda event: Grid.delete_cell(event, self)) for r in range(rows): for c in range(cols): dy = [-1, -1, 0, 0, 1, 1] dx = [0, 1, -1, 1, 0, 1] for d in range(6): ny = r + dy[d] nx = c + dx[d] if ny < 0 or ny >= rows or nx < 0 or nx >= cols: continue self.grid[r][c].add_adjacent(self.grid[ny][nx]) self.cell_by_item_tag = dict()
def get_cells(cls) -> List[Cell]: cells = [] for rank in chess.RANK_NAMES: for file in chess.FILE_NAMES: cells.append(Cell(rank=rank, file=file)) return cells
def reset(self): """Initiate key variables""" self.MAX_UMBRELLAS = 5 self.MAX_BLOCKERS = 5 self.MAX_LADDERS = 8 self.Max_Lemmings = random.randint(15,20) self.not_floor = True self.platforms = [] self.grid = [] self.lemmings = [] self.dead_lemmings_list = [] self.saved_lemmings = [] self.lemmings_amount = self.Max_Lemmings print(self.Max_Lemmings) if not self.end_game and self.next_level: self.level += 1 else: self.level = 1 self.end_game = False self.next_level = False self.marker = Marker(self.level, 0, 0, 0, 0, 0, 0) # create matrix for i in range(self.row): self.grid.append([]) for j in range(self.col): cell = Cell(i, j) self.grid[i].append(cell) # Creating the platform list random with validations for i in range(0, 7): repeated = True width = random.randint(5, 10) while repeated: y = random.randint(0, 12) y_list = [] if self.platforms: for platform in self.platforms: y_list.append(platform[1]) if y in y_list: repeated = True else: repeated = False else: repeated = False xrepeated = True while xrepeated: x = random.randint(0, 11) if x + width >= 16: xrepeated = True else: xrepeated = False self.platforms.append([width, y, x]) # adding the platforms into the cells for platform in self.platforms: for i in range(platform[0]): # print("Y: ",platform[1]) # print("X: ", platform[2]+i) self.grid[platform[1]][platform[2] + i].floor = True # create exit door random while self.not_floor: y = random.randint(0, 13) x = random.randint(0, 15) if self.exist_floor(x * 16, y * 16): self.exit_gate = Gate(y, x, False) self.grid[y][x].gate = self.exit_gate self.not_floor = False else: self.not_floor = True # create entry door random self.not_floor = True while self.not_floor: y = random.randint(0, 13) x = random.randint(0, 15) if self.exist_floor(x * 16, y * 16) and not self.exist_exit_gate(x * 16, y * 16): self.entry_gate = Gate(y, x, True) self.grid[y][x].gate = self.entry_gate self.not_floor = False else: self.not_floor = True