예제 #1
0
    def __init__(self, width, height, initial_state=None):
        """
		Creates a new world with the given dimensions.

		Arguments:
			[int] width: The width of the world.
			[int] height: The height of the world.

		Kwargs:
			[???] initial_state: Unimplemented.
		"""
        super(World, self).__init__()

        self.width = int(width)
        self.height = int(height)

        # Create a random initial state
        if initial_state is None:
            # Create a world of dead cells
            self.world = [[Cell() for c in range(self.width)]
                          for r in range(self.height)]

            # Randomly create live cells
            for y in range(self.height):
                for x in range(self.width):
                    if random.getrandbits(1):
                        self.world[y][x].set_alive()
                        self.world[y][x].set_random_color()
                        self.inform_neighbors(self.world, x, y)
예제 #2
0
 def __init__(self):
     self.non_attacking_moves = 0
     column = []
     for i in range(self.LENGTH):
         row = []
         for j in range(self.WIDTH):
             x = Cell()
             if i % 2 == j % 2:
                 x.cell_colour = "b"
             else:
                 x.cell_colour = "w"
             if i == 0 or i == 1:
                 x.token = "R"
             elif i == 2:
                 if j > 4:
                     x.token = "R"
                 elif j < 4:
                     x.token = "G"
                 else:
                     x.token = " "
             else:
                 x.token = "G"
             row.append(x)
         column.append(list(row))
     self.board = column
예제 #3
0
파일: main.py 프로젝트: imdany/pyconway
def update(cellList):
    newList = []
    for r, row in enumerate(cellList):
        newList.append([])
        for c, cell in enumerate(row):
            newList[r].append(
                Cell(gameDisplay, r, c, cell.checkNeighbors(cellList)))
    return newList[::]
예제 #4
0
 def boundary_condition(self, row_index, column_index):
     if self.bc == "periodic":
         return self.grid[(row_index + self.number_of_rows) % self.number_of_rows][(column_index + self.number_of_columns) % self.number_of_columns]
     elif self.bc == "absorbing":
         if row_index >= self.number_of_rows or column_index >= self.number_of_columns or row_index < 0 or column_index < 0:
             return Cell()
         else:
             return self.grid[row_index][column_index]
예제 #5
0
 def fill_board(self):
     self.board = []
     for x in range(0, self.height):
         row = []
         for y in range(0, self.width):
             cell = Cell(x, y)
             row.append(cell)
         self.board.append(row)
예제 #6
0
    def test_cell_set_next_status_while_live_neighbours_3_and_current_status_dead(
            self):
        coordinate = Coordinate(2, 2)
        cell = Cell(coordinate, False)
        live_neighbour_count = 3

        next_status = cell.calculate_next_status(live_neighbour_count)
        assert next_status == True
예제 #7
0
	def __init__(self, dimension_x=7, dimension_y=7):
		self.dimension_x = dimension_x
		self.dimension_y = dimension_y
		self.data = list()
		for i in range(self.dimension_x):
			self.data.append([])
			for j in range(self.dimension_y):
				self.data[i].append(Cell())
예제 #8
0
    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))
예제 #9
0
 def setUp(self):
     self.colony = []
     for x in range(4):
         for y in range(4):
             self.colony.append(Cell((x, y), False))
     self.manager = self.colony[0].manager
     self.tested_cell = self.manager.get((1, 1))
     self.tested_cell.born()
예제 #10
0
    def init_cells(self):
        for i in range(0, self.grid_size):
            cell_row = []
            for j in range(0, self.grid_size):
                cell = Cell(i, j, self.dimens, self.grid_size)

                cell_row.append(cell)
            self.cells.append(cell_row)
예제 #11
0
 def createCell(self, xPos, yPos):
     """
         Creates a new cell for a given position.
         :param xPos: The x-position on the grid.
         :param yPos: the y-position on the grid
         :return: (nothing)
     """
     self.cells.append(Cell(self.screen, xPos, yPos))
예제 #12
0
 def __init__(self, rows):
     self.board = []
     self.flag = False
     for i in range(0, rows):
         for j in range(0, rows):
             self.board.append(Cell(i, j, self.board))
     self.assign_mines(10)
     self.calculate_values()
예제 #13
0
 def new_list_living(self):
     new_list = []
     for index1 in range(self.width):
         for index2 in range(self.height):
             cell = Cell(index1, index2)
             if cell.is_to_be_alive(self):
                 new_list.append([cell.x, cell.y])
     return new_list
예제 #14
0
 def discover(self):
     print("Louis has started. Running cell discovery ...")
     arduino = Arduino()
     num_cells = arduino.discover()
     print(num_cells)
     cells = [Cell(i) for i in range(1, num_cells + 1)]
     print("Cell discovery completed. " + str(num_cells) + " cells found.")
     return arduino, cells
예제 #15
0
def get_maze(dim, p):
    maze = []
    for row in xrange(dim):
        maze.append([])
        for col in xrange(dim):
            if random.random() < p:
                # occupied cell
                maze[row].append(Cell(1))
            else:
                # empty cell
                maze[row].append(Cell(0))

    # start cell
    maze[0][0] = Cell(0)
    # goal cell
    maze[dim - 1][dim - 1] = Cell(0)
    return maze
예제 #16
0
 def __init__(self):
     self.numrows = 100
     self.numcols = 100
     self.startCoordinate = Coordinate(0, self.numcols - 1)
     self.goalCoordinate = Coordinate(self.numrows - 1, self.numcols - 1)
     self.cells = [[Cell(i, j) for j in range(self.numcols)]
                   for i in range(self.numrows)]
     self.setBlockedTerrain(30)
예제 #17
0
    def __init__(self, width, height, w):
        self.width = width
        self.height = height
        self.w = w 
        self.cols = self.width // self.w
        self.rows = self.height // self.w

        self.grid = [Cell(i, j) for j in range(self.rows) for i in range(self.cols)]
예제 #18
0
    def createBg(self):
        image = Image.open("source\pattern\pattern.png")
        pixel = image.load()

        # переносим изменения на поле
        for x in range(0, self.size[0]):
            for y in range(0, self.size[1]):
                if pixel[x, y][0] == 0:
                    self.cell[x][y] = Cell(Type().ground, Type().forest)
                elif pixel[x, y][0] == 50:
                    self.cell[x][y] = Cell(Type().ground, Type().steppe)
                elif pixel[x, y][0] == 100:
                    self.cell[x][y] = Cell(Type().ground, Type().mountain)
                elif pixel[x, y][0] == 255:
                    self.cell[x][y] = Cell(Type().void)
                self.unit[x][y].type = Type().void
                self.building[x][y].type = Type().void

        image = Image.new("RGBA", (self.plates_size[0] * self.size[0],
                                   self.plates_size[1] * self.size[1]),
                          (255, 255, 255))
        pixel = image.load()

        for x in range(0, self.size[0]):
            for y in range(0, self.size[1]):
                cell_l = self.cell[x][y]
                for _x in range(
                        x * self.plates_size[0],
                        min((x + 1) * self.plates_size[0], image.size[0])):
                    for _y in range(
                            y * self.plates_size[1],
                            min((y + 1) * self.plates_size[1], image.size[1])):
                        if cell_l.type == Type().void:
                            clr = self.imageVoid[0].get_at(
                                (_x % self.plates_size[0],
                                 _y % self.plates_size[1]))
                        else:
                            clr = self.imageGround[cell_l.subType].get_at(
                                (_x % self.plates_size[0],
                                 _y % self.plates_size[1]))
                        pixel[_x, _y] = (clr[0], clr[1], clr[2], clr[3])

        image.save("source/pattern/bg.png")
        self.background = pygame.image.load("source/pattern/bg.png")

        self.clearStepBuffer()
예제 #19
0
    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))
예제 #20
0
def findProd(index, cSize, rSize):
	clist = [2, 0, 1]

	prodColumn = clist[index % 3]
	prodRow = (index - 1) / 3
	rowStart = 3

	return Cell(columns((cSize * prodColumn) + 1), (rSize * prodRow) + (prodRow + rowStart))
예제 #21
0
 def __init__(self, width, height):
     self.width = width
     self.height = height
     self.cells = dict()  # type: Dict[Coord, Cell]
     for y in range(height):
         for x in range(width):
             coord = Coord(x, y)
             self.cells[coord] = Cell()
예제 #22
0
 def fill_cells(self):
     for k in range(self.i_max * self.j_max):
         ith, jth = self.grid_cells.get_index(self.i_max, self.j_max, k)
         self.cells[ith][jth] = Cell((ith, jth),
                                     self.grid_cells.cells_center[k],
                                     self.grid_cells.valid[k])
         if self.grid_cells.valid[k]:
             self.valid_cells.append(self.cells[ith][jth])
예제 #23
0
    def test_next_state_will_be_dead_if_all_neighbors_are_alive(self):
        cell = Cell([self.alive_cell] * Cell.NUMBER_OF_NEIGHBORS)
        cell.set_alive()

        cell.prepare_next_state()
        cell.update_state()

        self.assertFalse(cell.alive)
예제 #24
0
    def initialice_cells(self, V0):
        if V0 == None:
            for i in range(self.n):
                cell = Cell(i, self.V0, 5)
                self.cells.append(cell)
                cell.F.append(self.F0)
                cell.V.append(self.V0)
        else:
            idx = 0
            for i in V0:
                cell = Cell(idx, i, 5)
                self.cells.append(cell)
                cell.F.append(self.F0)
                cell.V.append(i)
                idx += 1

        print("Cells initialized")
예제 #25
0
 def setUp(self):
     cells = []
     cell_string = '1.73...5.'
     for i, cell_value in enumerate(cell_string):
         int_val = 0 if cell_value == '.' else int(cell_value)
         c = Cell(0, i, 0, int_val)
         cells.append(c)
     self.u = UniqueCellArea(0, cells)
예제 #26
0
 def prepare_grid(self):
     grid_array = []
     for row in range(self.rows):
         row_array = []
         for column in range(self.columns):
             row_array.append(Cell(row, column))
         grid_array.append(row_array)
     return grid_array
예제 #27
0
파일: main.py 프로젝트: imdany/pyconway
def createCellList():
    newList = []
    # Populate Initial
    for j in range(GRID_H):
        newList.append([])
        for i in range(GRID_W):
            newList[j].append(Cell(gameDisplay, i, j, choice([0, 1])))
    return newList
예제 #28
0
 def __init__(self, rows, cols):
     self.rows = rows
     self.cols = cols
     # I have two options for creating a matrix:
     self.board = np.ndarray((self.rows, self.cols), dtype=Cell)  # it works but I dont use it
     self.matrix = [[Cell(i, j, False, False) for j in range(cols)] for i in range(rows)]
     self.initializeboard()  # If you use board, use this method. I dont use it since I'm using matrix
     self.generateMines()
예제 #29
0
 def cell_copy(cell):
     new = Cell()
     new.id = cell.id
     new.pos = cell.pos.copy()
     new.veloc = cell.veloc.copy()
     new.radius = cell.radius
     new.dead = cell.dead
     return new
예제 #30
0
    def relay(client_reference, cell_to_next, decrypted):
        """Method to Relay information to another relay, and stream information back."""
        if client_reference["bounce_socket"] is None:
            # There is no next hop registered to this client.
            return
        sock = client_reference["bounce_socket"]
        if util.RELAY_DEBUG:
            print("bouncing cell's decrypted..")
            print(decrypted)
            print("payload")
            print(cell_to_next.payload)
            print(cell_to_next.type)

        sock.send(cell_to_next.payload)  # send over the cell
        while True:
            try:
                their_cell = sock.recv(32768)  # await answer
            except socket.timeout:
                their_cell = "request timed out!"
            their_cell = pickle.loads(their_cell)
            if util.RELAY_DEBUG:
                print(f"Relay reply received type: {their_cell.type}")
            if their_cell.type != CellType.FINISHED:
                print("Got answer back.. as a relay.")
                encrypted, init_vector = util.aes_encryptor(
                    client_reference["key"],
                    Cell(their_cell, ctype=CellType.CONNECT_RESP))
                client_reference["sock"].send(
                    pickle.dumps(
                        Cell(encrypted,
                             IV=init_vector,
                             ctype=CellType.CONTINUE)))
                print("Relayed a packet.")
            else:
                print("Received the last packet.")
                encrypted, init_vector = util.aes_encryptor(
                    client_reference["key"],
                    Cell(their_cell, ctype=CellType.FINISHED))
                client_reference["sock"].send(
                    pickle.dumps(
                        Cell(encrypted,
                             IV=init_vector,
                             ctype=CellType.FINISHED)))
                print("Relayed the last packet for this communication")
                break
        print("Relay success.\n\n\n\n\n")