Example #1
0
    def __init__(self, data, param):
        Grid.__init__(self, data, param)

        self.param.m = self.param.partitionsHTree[1]
        self.param.maxHeightHTree = 2

        logging.debug("Grid_pure: size: %d" % self.param.m)
Example #2
0
    def __init__(self, require, level):
        pygame.init()
        self.win = pygame.display.set_mode((800, 500))
        pygame.display.set_caption("QIX")
        self.gridSize = 80
        self.coord = [40, 79]
        self.width = 5
        self.velocity = 5
        self.x = self.coord[0] * self.velocity
        self.y = self.coord[1] * self.velocity
        self.block = Block()
        self.grid = Grid(self.gridSize, self.block)
        self.player = Player(self.coord, self.velocity, self.grid)
        self.spark = Spark([40, 0], self.velocity, self.grid, 0)
        self.spark2 = Spark([40, 0], self.velocity, self.grid, 1)
        if level > 1:
            self.spark3 = Spark([0, 40], self.velocity, self.grid, 3)
        if level > 2:
            self.spark4 = Spark([0, 40], self.velocity, self.grid, 2)
        self.level = level
        if self.level > 5:
            self.qix = Qix([40, 40], self.velocity, self.grid, 3)
        else:
            self.qix = Qix([40, 40], self.velocity, self.grid,
                           30 - self.level * 5)
        self.claimed = 0
        self.requiredClaimed = require

        # print(self.block.getWhite())
        if self.level == 1:
            self.startScreen()
        else:
            self.game()
Example #3
0
    def make_grid(self, init_position):

        grid_group = []
        grid_position = []
        safe_grid = []
        grid_size = (36, 36)
        grid_x = round(init_position[0] + grid_size[0] / 2) + 6
        grid_y = round(init_position[1] + grid_size[1] / 2) + 9
        for row in range(17):
            grid_position.append([])
            for col in range(33):
                if ((0 <= col <= 1) or (31 <= col <= 32)) and (6 <= row <= 9):
                    grid = Grid((grid_x, grid_y),
                                SAFE_GRID_TILE,
                                grid_size,
                                is_safe_grid=True)
                    safe_grid.append(grid)
                    grid_group.append(grid)
                else:
                    grid_group.append(
                        Grid((grid_x, grid_y), SPECIAL_TILE, grid_size))
                grid_position[row].append((grid_x, grid_y))
                grid_x += grid_size[0]
            grid_y += grid_size[1]
            grid_x = round(init_position[0] + grid_size[0] / 2) + 6

        return grid_group, safe_grid, grid_position
Example #4
0
 def clean(self):
     self.searched = False
     self.start = None
     self.goal = None
     self.ready = False
     self.grid = Grid(ROW_NUM, COL_NUM)
     self.path = []
 def __init__(self, canvas):
     self.grid_size = 30
     self.ui = UIDrawer(canvas, self.grid_size, self.grid_size)
     self.grid = Grid(self.grid_size, self.grid_size, self.ui)
     self._algorithm = DijkstraAlgorithm(self.grid, self.ui)
     self.visualize = True
     self.init()
Example #6
0
    def __init__(self, data, param):
        Grid.__init__(self, data, param)

        self.param.m = self.param.part_size
        self.param.maxHeightHTree = 2

        logging.debug("Grid_standard: size: %d" % self.param.m)
Example #7
0
    def test_multiple_1x1(self):
        bp = Blueprint(**BlueprintDict(entities=[
            get_entity_dict("transport-belt", 0.5, 0.5),
            get_entity_dict("transport-belt", 1.5, 1.5),
        ]))
        g = Grid(bp)
        self.assertEqual(2, g.width)
        self.assertEqual(2, g.height)
        self.assertEqual(bp.entities[0], g[0, 0])
        self.assertEqual(bp.entities[1], g[1, 1])
        self.assertIsNone(g[0, 1])
        self.assertIsNone(g[1, 0])

        bp = Blueprint(**BlueprintDict(entities=[
            get_entity_dict("transport-belt", -2.5, -2.5),
            get_entity_dict("transport-belt", -2.5, 2.5),
            get_entity_dict("transport-belt", 2.5, -2.5),
            get_entity_dict("transport-belt", 2.5, 2.5),
        ]))
        g = Grid(bp)
        self.assertEqual(6, g.width)
        self.assertEqual(6, g.height)
        self.assertEqual(bp.entities[0], g[0, 0])
        self.assertEqual(bp.entities[1], g[0, 5])
        self.assertEqual(bp.entities[2], g[5, 0])
        self.assertEqual(bp.entities[3], g[5, 5])
Example #8
0
 def __init__(self, level, map, roomRes, imagePath=""):
     self.roomResolution = roomRes
     self.level = level
     self.moves = 0
     self.grid = Grid(map, roomRes)
     self.player = self.grid.getPlayer()
     self.eventHandlers = RoomEventHandlers(self)
Example #9
0
def test_get_value():
	g_1 = Grid(3,3)
	assert g_1.get_value(2,2) == 0
	g_1.array[2][2] = 3
	assert g_1.get_value(2,2) == 3
	assert g_1.get_value(10, 10) == -1
	assert g_1.get_value(-5, -3) == -1
Example #10
0
 def density(self):
     print "[Density Grid]",
     self.PCL.reset()
     self.Density = Grid(self.shape, self.x0y0, self.cellsize, self.nodata)
     [[self.__converter__(xyz, mode="density") for xyz in XYZ]
      for XYZ in self.PCL.input.a()]
     return self.Density
Example #11
0
def test_init():
    g_1 = Grid()
    assert g_1.array == []
    g_2 = Grid(2, 1)
    assert len(g_2.array) == 2
    assert len(g_2.array[1]) == 1
    assert g_2.array[0][0] == 0
Example #12
0
	def __init__(self, points=(), left=0.0, right=1.0,
				start=0.0, end=1.0,
				id=u'', classes=(),
				lineidprefix=u'', lineclasses=()):
		"""
		@param points: A sequence of points to draw grid lines at
		@param left: The leftmost coordinate to begin drawing grid lines at
		@param right: The rightmost coordinate to stop drawing grid lines at

		@param start: The starting coordinate of the axis
		@param end: The ending coordinate of the axis
		
		@param id: The unique ID to be used in the SVG document
		@type id: string
		@param classes: Classnames to be used in the SVG document
		@type classes: string or sequence of strings

		@param lineidprefix: The prefix for each grid line's ID
		@type lineidprefix: string
		@param lineclasses: Classnames to be applied to each grid line
		@type lineclasses: string or sequence of strings
		"""

		Grid.__init__(self, points, start, end, id, classes, lineidprefix, lineclasses)

		self.left = left
		self.right = right
    def getMove(self, grid: Grid):
        if grid.isWin() or grid.isLose():
            return None

        actions = grid.getAvailableMoves()
        maxQValue = self.getQValue(grid, actions[0])
        maxAction = actions[0]

        for action in actions:
            QValue = self.getQValue(grid, action)
            if QValue >= maxQValue:
                maxQValue = QValue
                maxAction = action
            # print(maxQValue)

        nextState = util.getANewGrid(grid, action)

        reward = nextState.score

        if not nextState.isTerminal():
            self.update(grid, action, nextState, reward)

        #print(grid.mat)
        #print(reward)
        #print(maxQValue)
        #print(selectedAction)

        return maxAction
 def __init__(self, Name, Player_Number):
     self.Name = Name.title()
     if Player_Number > 0 and Player_Number < 3:
         self.Player_Num = Player_Number
     else:
         raise Exception("Invalid Player Number:", Player_Number)
     self.Player = True
     self.Ships = {}
     patrol_boat = Ship("Patrol Boat")
     submarine = Ship("Submarine")
     destroyer = Ship("Destroyer")
     battleship = Ship("Battleship")
     aircraft_carrier = Ship("Aircraft Carrier")
     self.Ships["Patrol Boat"] = patrol_boat
     self.Ships["Submarine"] = submarine
     self.Ships["Destroyer"] = destroyer
     self.Ships["Battleship"] = battleship
     self.Ships["Aircraft Carrier"] = aircraft_carrier
     #{"Patrol Boat": patrol_boat, "Submarine": submarine...}
     self.Ships_Remaining = self.get_ships_alive()
     self.Guesses = {}
     #Guesses = {"A1": "Hit", "B2": "Miss"...}
     grid = Grid()
     self.Grid = grid
     guess_grid = Grid()
     self.Guess_Grid = guess_grid
Example #15
0
class TileTraveller():

    def __init__(self):
        self.points = 0
        self.position = Position(0,0)
        self.grid = Grid(4,3)

    def playGame(self):
        print("Enert Q at anytime to quit")
        while True:
            if(self.grid.isInEnd(self.position)):

                print("\nYou have Won!\n\n")
                self.position = Position(0,0)
                self.point = 0
                self.grid = Grid(4,3)
                
            print(self.grid.getPossibilities(self.position))
            input_str = input("Enter your choice: ").lower()
            if(input_str == "q"):
                exit()
            elif(input_str == "g"):
                got_coins = self.grid.getCoins(self.position)
                self.points += got_coins
                if got_coins > 0:
                    print("You found " + str(got_coins) + " coins!")
                else:
                    print("There are no coins!")
            else:
                print(self.grid.move(self.position, input_str))
Example #16
0
 def setUp(self):
     """Creates a Grid object for the tests"""
     self.grid = Grid(None, None, None, None, None, None)
     self.display = Mock()
     screenWidth, screenHeight = (500, 500)
     # Sets the return value for function get_size
     self.display.get_size.return_value = (screenWidth, screenHeight)
Example #17
0
class GridManager:
	# Constructor
	def __init__(self):
		self.__grid = Grid()
		self.__gamePlayer = GamePlayer()
		self.__userPlayer = UserPlayer()

	# Start Game
	def startGame(self):
		# Will continue toggling between
		# Game and User turns until the
		# Grid is Full (which is a loss)
		# or a 2048 tile is encountered
		# (which is a win)
		while (not self.__grid.gridContains(2048)):
			self.__gamePlayer.makeMove(self.__grid)

			self.__grid.printGrid()

			if (not self.__userPlayer.makeMove(self.__grid)):
				print "User Lost!"
				break

		if (self.__grid.gridContains(2048)):
			print "User Won!"
Example #18
0
class Game:
    def __init__(self, code):
        self.score = 0
        self.steps = 0
        self.grid = Grid(0, {0: '.', 1: '|', 2: 'X', 3: '_', 4: 'o'})
        self.engine = Intcode_computer(code)
        self.last_input = 'neutral'
        self.play('neutral')

    def play(self, hold):
        positions = ['left', 'neutral', 'right']
        input = positions.index(hold) - 1
        self.last_input = hold
        self.engine.compute([input])
        self.parse_outputs(self.engine.outputs)
        self.steps += 1

    def parse_outputs(self, outputs):
        i = 0
        while i < len(outputs) - 2:
            x, y, tile = outputs[i], outputs[i + 1], outputs[i + 2]
            if x == -1:
                self.score = tile
            else:
                self.grid.put((x, -y), tile)
                if tile == 4:
                    self.ball = (x, y)
                if tile == 3:
                    self.paddle = (x, y)
            i += 3

    def __str__(self):
        return f'score: {self.score}, ball: {self.ball}, last input: {self.last_input}\n{self.grid}'
Example #19
0
 def __init__(self, code):
     self.score = 0
     self.steps = 0
     self.grid = Grid(0, {0: '.', 1: '|', 2: 'X', 3: '_', 4: 'o'})
     self.engine = Intcode_computer(code)
     self.last_input = 'neutral'
     self.play('neutral')
Example #20
0
    def dfs(self, grid):
        time.sleep(0.001)
        stack = []
        isVisited = self.isVisited
        if grid.isWall:
            return False

        # target found
        if grid is self.targetGrid:
            self.grid = grid
            print("target Found ! x: ", grid.x, " y: ", grid.y)
            return True

        self.setVisited(isVisited, grid)
        self.pushStack(stack, grid)

        if self.isPathVisible.get():
            self.startGrid.drawColor(self.screen, Color.BLUE)
            grid.drawColor(self.screen, Color.SKYBLUE)
            pygame.display.update()

        while stack:
            targetFound = self.dfs(stack.pop())
            if targetFound:
                return True

        return False
Example #21
0
    def __init__(self, screen, model):
        self.wn = screen

        self.WIDTH = screen.window_width()
        self.HEIGHT = screen.window_height()
        self.model = model

        self.bg = Bg(self, math_pos=(-289, 0), sign_pos=(282, 220))

        self.grid = Grid(self, self.wn, 28, 28, model)
        self.grid.initialize_all_pixels()

        self.player = Player(self)
        self.last_pos = -self.WIDTH // 4

        self.balloons = []
        self.balloon_speed = 0.3
        self.static_balloon_speed = 0.3
        self.new_balloon_cord = 100
        self.score = ScoreBoard()

        Balloon(self, self.balloon_speed)

        # Register the collective dead balloon image
        self.wn.register_shape('./assets/dead_balloon.gif')
Example #22
0
    def __init__(self, data, param):
        Grid.__init__(self, data, param)

        self.param.m = self.param.partitionsHTree[1]
        self.param.maxHeightHTree = 2

        logging.debug("Grid_pure: size: %d" % self.param.m)
Example #23
0
class Robot():
    def __init__(self):
        self.heading = 'N'
        self.grid = Grid(default_val=0)
        self.painted_panels = set()
        self.pos = (0, 0)

    def read_color(self):
        return self.grid.get(self.pos)

    def paint(self, color):
        if self.read_color() != color:
            self.grid.put(self.pos, color)
            self.painted_panels.add(self.pos)

    def update_heading(self, change):
        directions = ['N', 'E', 'S', 'W']
        idx = directions.index(self.heading)
        if change == 'R':
            self.heading = directions[(idx + 1) % 4]
        elif change == 'L':
            self.heading = directions[(idx - 1) % 4]

    def move(self, dist=1):
        x, y = self.pos
        if self.heading == 'N':
            y = y + dist
        elif self.heading == 'E':
            x = x + dist
        elif self.heading == 'S':
            y = y - dist
        elif self.heading == 'W':
            x = x - dist
        self.pos = x, y
def clone_grid(grid: Grid) -> Grid:
    size = grid.size
    copy = Grid(size)
    for i in range(size):
        for j in range(size):
            copy.map[i][j] = grid.map[i][j]
    return copy
 def loadReferenceImage(self, path = ''):
     ref_grid = Grid()
     #if self.grid.ext_color:
         #self.ref_name = 'ext_'+self.ref_name
     ref_grid.image2Grid(path+self.ref_name, ext_colors=self.grid.ext_color)
     ref_grid.visualize()
     return ref_grid
Example #26
0
 def ascii_to_grid(self, ascii):
     string = ''.join([chr(i) for i in ascii])
     grid = Grid(' ')
     for y, row in enumerate(string.splitlines()):
         for x, char in enumerate(row):
             grid.put((x, -y), char)
     return grid
Example #27
0
    def test_single_1x1(self):
        bp = Blueprint(**BlueprintDict(entities=[
            get_entity_dict("transport-belt", 0.5, 0.5),
        ]))
        g = Grid(bp)
        self.assertEqual(1, g.width)
        self.assertEqual(1, g.height)
        self.assertEqual(bp.entities[0], g[0, 0])

        bp = Blueprint(**BlueprintDict(entities=[
            get_entity_dict("transport-belt", 1.5, 0.5),
        ]))
        g = Grid(bp)
        self.assertEqual(1, g.width)
        self.assertEqual(1, g.height)
        self.assertEqual(bp.entities[0], g[0, 0])

        bp = Blueprint(**BlueprintDict(entities=[
            get_entity_dict("transport-belt", -0.5, 0.5),
        ]))
        g = Grid(bp)
        self.assertEqual(1, g.width)
        self.assertEqual(1, g.height)
        self.assertEqual(bp.entities[0], g[0, 0])

        bp = Blueprint(**BlueprintDict(entities=[
            get_entity_dict("transport-belt", -1.5, 0.5),
        ]))
        g = Grid(bp)
        self.assertEqual(1, g.width)
        self.assertEqual(1, g.height)
        self.assertEqual(bp.entities[0], g[0, 0])
Example #28
0
    def get_grid(self, string):

        grid = Grid(' ')
        for y, row in enumerate(string.splitlines()):
            for x, char in enumerate(row):
                grid.put((x, -y), char)
        return grid
Example #29
0
    def __init__(self, parent):
        AbsolutePanel.__init__(self)
        self.userGrid = Grid()
        self.userGrid.createGrid(6, 6)
        self.userGrid.addTableListener(self)

        self.userGrid.setBorderWidth(2)
        self.userGrid.setCellPadding(4)
        self.userGrid.setCellSpacing(1)
        self.userGrid.setColLabelValue(0, "Username")
        self.userGrid.setColLabelValue(1, "First Name")
        self.userGrid.setColLabelValue(2, "Last Name")
        self.userGrid.setColLabelValue(3, "Email")
        self.userGrid.setColLabelValue(4, "Department")
        self.userGrid.setColLabelValue(5, "Password")

        self.newBtn = Button("New")
        self.deleteBtn = Button("Delete")
        self.deleteBtn.setEnabled(False)

        self.add(self.userGrid)
        self.add(self.newBtn)
        self.add(self.deleteBtn)

        return
Example #30
0
    def __init__(self,
                 points=(),
                 top=0.0,
                 bottom=1.0,
                 start=0.0,
                 end=1.0,
                 id=u'',
                 classes=(),
                 lineidprefix=u'',
                 lineclasses=()):
        """
		@param points: A sequence of points to draw grid lines at
		@param top: The top coordinate to begin drawing grid lines at
		@param bottom: The bottom coordinate to stop drawing grid lines at

		@param start: The starting coordinate of the axis
		@param end: The ending coordinate of the axis
		
		@param id: The unique ID to be used in the SVG document
		@type id: string
		@param classes: Classnames to be used in the SVG document
		@type classes: string or sequence of strings

		@param lineidprefix: The prefix for each grid line's ID
		@type lineidprefix: string
		@param lineclasses: Classnames to be applied to each grid line
		@type lineclasses: string or sequence of strings
		"""

        Grid.__init__(self, points, start, end, id, classes, lineidprefix,
                      lineclasses)

        self.top = top
        self.bottom = bottom
    def Load(self, display_surf):
        self.setBgColor(display_surf)

        try:
            xmlPrevious = self.xmlActivity.getElementsByTagName(
                'prevScreen')[0]
            self.previous = True
            self.PrevGrid = Grid()
            self.PrevGrid.Load(1, 1, Constants.ACTIVITY_WIDTH,
                               Constants.ACTIVITY_HEIGHT, Constants.MARGIN_TOP,
                               Constants.MARGIN_LEFT, display_surf)
            self.styleCell = StyleCell(xmlPrevious)
            self.printxmlCellinCell(self.PrevGrid.Cells[0], xmlPrevious,
                                    self.styleCell)
        except:
            pass
        '''Loading constants for the activity'''
        xmlTextGrid = self.xmlActivity.getElementsByTagName('document')[0]

        self.TextGrid = TextGrid(xmlTextGrid, self.mediaInformation,
                                 self.pathToMedia)

        self.targets = self.TextGrid.Load(display_surf, xmlTextGrid)

        opt = xmlTextGrid.getElementsByTagName('optionList')

        if len(opt) > 0:
            self.options = True
        else:
            self.options = False
Example #32
0
    def play(self, grid: Grid):
        """
        """
        #print(self.name)
        empty_square = grid.get_empty_square()
        max_value = -float('inf')
        best_move = []

        for available_pos_index, available_pos in enumerate(empty_square):
            #print(possible_grid[possible_result_index])
            grid.add_a_pawn(self, available_pos[0], available_pos[1])
            value, branch = self.minmax(grid, self.depth, self.adversary)
            branch.set_pos(available_pos)
            self.tree.add(branch)
            if value > max_value:
                max_value = value
                best_move = [empty_square[available_pos_index]]
            elif value == max_value:
                best_move.append(empty_square[available_pos_index])
            grid.cancel_move()

        self.tree.set_value(max_value)
        pos = random.choice(best_move)
        #print(self.color, best_move, len(best_move), len(empty_square))
        self.turn += 1
        self.tree.write_in_file("./tree/tree " + str(self.name) +
                                str(self.turn) + " turn")
        self.tree = Tree()
        return pos
Example #33
0
def test():
    grid = Grid(0.0, 1.0, 1000, 2)
    f = Half(grid)
    for i in range(1, 1000):
        for k in grid.over_elems_real(Center()):
            temp = f.Mid(k)
            f[k] += 1.0
Example #34
0
    def test_single_1x2(self):
        bp = Blueprint(**BlueprintDict(entities=[
            get_entity_dict("splitter", 1, 0.5),
        ]))
        g = Grid(bp)
        self.assertEqual(2, g.width)
        self.assertEqual(1, g.height)
        self.assertEqual(bp.entities[0], g[0, 0])
        self.assertEqual(bp.entities[0], g[1, 0])

        bp = Blueprint(**BlueprintDict(entities=[
            get_entity_dict("splitter", 0.5, 1, direction=2),
        ]))
        g = Grid(bp)
        self.assertEqual(1, g.width)
        self.assertEqual(2, g.height)
        self.assertEqual(bp.entities[0], g[0, 0])
        self.assertEqual(bp.entities[0], g[0, 1])

        bp = Blueprint(**BlueprintDict(entities=[
            get_entity_dict("splitter", -1, 0.5),
        ]))
        g = Grid(bp)
        self.assertEqual(2, g.width)
        self.assertEqual(1, g.height)
        self.assertEqual(bp.entities[0], g[0, 0])
        self.assertEqual(bp.entities[0], g[1, 0])
Example #35
0
    def __init__(self, PORT_HTTP, PORT_UNICAST):
        self.IP, BROADCAST = network.getIP_BC(
        )  # get the IP and BROADCAST address of this machine based in the 'ifconfig'
        # IP, BROADCAST = '172.16.1.13', '172.16.1.63'
        self.PORT_HTTP = PORT_HTTP
        self.BUFFER_SIZE = 2048  # Normally 1024, but we want fast response
        self.servers = {}

        # only get the upTime and count of request. Both for the path virtual 'status.json'
        self.upTime = Operation.Operation(None, None, None).getCurrentDate()
        self.reqCount = 0

        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.s.bind((self.IP, PORT_HTTP))
        except socket.error:
            self.s.bind((self.IP, 0))
            self.PORT_HTTP = self.s.getsockname()[1]

        grid = Grid(self.IP, PORT_HTTP, PORT_UNICAST, BROADCAST,
                    self.servers)  # create the grid class
        grid.start()  # execute thread

        self.s.listen(5)
        self.running()
Example #36
0
def make_maze(xd, yd, seed):
    xd = int(xd)
    yd = int(yd)
    seed = sanitize_seed(seed)

    random.seed(seed)

    master = Grid(xd, yd)
    candidates = master.get_all_nodes()

    while len(candidates) > 0:
        next = []
        random.shuffle(candidates)

        for node in candidates:
            dirs = node.get_valid_directions()
            if len(dirs) > 0:
                dir = random.choice(dirs)
                node.connect_node(dir)
            if len(dirs) > 1:
                next.append(node)

        candidates = next

    return master.printable()
Example #37
0
 def make_grid(self):
     if not(self.Density): self.PCL.reset(); self.Density = Grid(self.shape, self.x0y0, self.cellsize, self.nodata)
     if not(self.Intensity): self.PCL.reset(); self.Intensity = Grid(self.shape, self.x0y0, self.cellsize, self.nodata)
     [[self.__converter__(xyz, mode="both") for xyz in XYZ] for XYZ in self.PCL.input.a()]
     print "[Grid = Intensity / Density] ...";
     self.Gridded = Grid(self.shape, self.x0y0, self.cellsize, self.nodata)
     self.Gridded.Z = self.Intensity.Z / self.Density.Z
     return self.Gridded
Example #38
0
File: Map.py Project: john2x/tetrys
 def __init__(self, width, height):
     self.width = width
     self.height = height
     self.block = None
     
     self.grid = Grid(width, height)
     self.__add_borders(self.grid)
     self.background = Grid(width, height)
     self.grid.copy_content_into(self.background)
Example #39
0
    def __init__(self, raw_grid):
        Grid.__init__(self, raw_grid)
        # Inherits Grid class
        self.number_of_iterations_yet = 0
        self.gamma = 0.7
        # gamma : discount factor

        self.errant_probability = 0.1
        # two errant outcomes
        self.intended_probability = 0.8
Example #40
0
def getNewPuzzle():
	global difficulty_setting
	new_grid = Grid(db_read, difficulty_setting)
	new_puzzle = new_grid.generate_puzzle()
	clues = new_grid.clues
	missing_letters = new_grid.missing_letters

	#we return three things in the data - a new puzzle, a list of clues for that puzzle, and the missing letters to the answer of that puzzle
	print missing_letters
	return json.dumps({'puzzle': new_puzzle, 'clues': clues, 'answers' : missing_letters})
Example #41
0
 def initializeGrid(self, M, n):
     """Grid initizialed by funtions startLevel and startState
     Function takes the number of species M and dims of the
     2-D lattice (n by n)"""
     grid = Grid()
     for i in range(n):
         row = []
         for j in range(n):
             row.append(Cell(self,self.startLevel(M), self.startState()))
         grid.append(row)
     return grid
def main():
    """Manages the huddling simulation"""
    sim = Simulate(60)
    grid = Grid()

    # Iterate board
    iterations = 150
    for i in range(0, iterations):
        sim.step()
        grid.update(sim.penguins)
        # time.sleep(0.1)
        sim.save("iter_" + str(i))
    time.sleep(3)
Example #43
0
    def __init__(self,parent):
        AbsolutePanel.__init__(self)
        self.userGrid = Grid()
        self.userGrid.createGrid(6, 6)
        self.userGrid.addTableListener(self)

        self.userGrid.setBorderWidth(2)
        self.userGrid.setCellPadding(4)
        self.userGrid.setCellSpacing(1)
        self.userGrid.setColLabelValue(0,"Username")
        self.userGrid.setColLabelValue(1,"First Name")
        self.userGrid.setColLabelValue(2,"Last Name")
        self.userGrid.setColLabelValue(3,"Email")
        self.userGrid.setColLabelValue(4,"Department")
        self.userGrid.setColLabelValue(5,"Password")

        self.newBtn = Button("New")
        self.deleteBtn = Button("Delete")
        self.deleteBtn.setEnabled(False)

        self.add(self.userGrid)
        self.add(self.newBtn)
        self.add(self.deleteBtn)

        return
Example #44
0
 def __init__(self):
     self.user_requested_exit = False
     self.player_turn = 1
     self.grid = Grid()
     self.is_a_winner = False
     print 'Welcome to TicTacToe!'
     print 'Here is the grid'
Example #45
0
	def __init__(self, window):
		self.window = window
		self.colours = {'white' : (255, 255, 255, 0), 'outerspace': (65, 74, 76, 0) }
		pyglet.gl.glClearColor(*self.colours['outerspace'])
		
		#Load images, create batch-groups, a batch
		pyglet.resource.path = ['tiles']
		pyglet.resource.reindex()
		#self.explosion_stream = open('explosion2strip.png', 'rb')
		#self.explosion = pyglet.image.load('explosion1strip.png')
		self.hexWater = pyglet.resource.image('hex.png')
		self.hexMud = pyglet.resource.image('hexDirt.png')
		self.hexUnwalkable = pyglet.resource.image('hexUnwalkable.png')
		self.ship = pyglet.resource.image('ship.png')
		self.background = pyglet.graphics.OrderedGroup(0)
		self.foreground = pyglet.graphics.OrderedGroup(1)
		self.effectslayer = pyglet.graphics.OrderedGroup(2)
		self.cellbatch = pyglet.graphics.Batch()
		
		self.grid = Grid(12, 8)	
		
		self.hexView = HexView(self.grid, 64, 55, 17, 0, 0) #todo: something to get this centered in the screen automatically
		self.screenCoordinates = self.hexView.screenCoordinates()
		
		self.selectedCell = None
		self.phase = 1
		self.movingUnit = False #True if a unit is being moved
		self.currentFaction = "Viper"
 def test_row_block_reduction(self):
     grid = Grid(
         StringIO(
             ".179.36..\n....8....\n9.....5.7\n.72.1.43.\n...4.2.7.\n.6437.25.\n7.1....65\n....3....\n..56.172.\n"
         )
     )
     prepareRemainingCandidates(grid)
     self.assertItemsEqual([2, 3, 4, 5, 6], grid.candidates[0][1])
     self.assertItemsEqual([2, 3, 4, 5], grid.candidates[1][1])
     self.assertItemsEqual([3, 6], grid.candidates[2][1])
     self.assertEqual(1, self.lockedCandidatesResolution.row_block_reduction(grid, 6, 0))
     self.assertItemsEqual([2, 4, 5, 6], grid.candidates[0][1])
     self.assertItemsEqual([2, 4, 5], grid.candidates[1][1])
     self.assertItemsEqual([6], grid.candidates[2][1])
     self.assertEqual(
         ".179.36..\n..6.8....\n9.....5.7\n.72.1.43.\n...4.2.7.\n.6437.25.\n7.1....65\n....3....\n..56.172.\n",
         grid.display(),
     )
Example #47
0
 def __init__(self, size = 4):
     self.grid = Grid(size)
     self.possibleNewTiles = [2, 4]
     self.probability = defaultProbability
     self.initTiles  = defaultInitialTiles
     self.computerAI = None
     self.playerAI   = None
     self.displayer  = None
     self.over       = False
Example #48
0
File: Map.py Project: john2x/tetrys
 def add_block(self, block, pos = (5, 0), grid = None, settling = False):
     '''places a Block object into a Grid object'''
     if self.block == None:
         print 'adding block', block.shape
     temp = Grid(self.width, self.height)
     if grid == None:
         grid = self.grid
         
     grid.copy_content_into(temp)
     self.block = block
     self.block.pos = pos
     for y in range(pos[1], pos[1] + self.block.size[1]):
         for x in range(pos[0], pos[0] + self.block.size[0]):
             if self.block.grid[y - pos[1]][x - pos[0]] > 0:
                 if settling and temp.content[y][x] == 10:
                     pygame.event.post(pygame.event.Event(GAME_OVER))
                 temp.content[y][x] = self.block.grid[y - pos[1]][x - pos[0]]
     temp.copy_content_into(grid)
Example #49
0
    def generate_field(self, width, height):
        self.gridmatch = {}
        self.map_width = width
        self.map_height = height

        # Create a 2 dimensional list that will act as a data grid for the Map
        grid = Grid(self.map_height, self.map_width, 0)
        grid.load_grid()

        self.gridmatch = {
        "a1" :"Jane is living with her Aunt Reed and cousins at Gateshead, being bullied and tormented by John Reed in particular.",
        "a2" :"Jane finally can't take it anymore and fights back against John.",
        "a3" :"Jane is locked in the 'red-room,' the bedchamber in which her uncle died, as a punishment, and has a traumatic, eerie experience.",
        "a4" :"Jane is sent to Lowood Institute, a religious school for orphan girls.",
        "a5" :"Jane studies hard and eventually becomes a teacher at Lowood.",
        "a6" :"Jane gets a spot of wanderlust and applies to be a governess.",
        "a7" :"Jane gets a job at Thornfield as the governess to a little French girl named Adèle Varens.",
        "a8" :"Jane meets the master of Thornfield, Mr. Rochester, and quickly falls in love with him.",
        "a9" :"Jane has a series of eerie experiences related to a mysterious locked room on the third floor of Thornfield and a creepy woman’s laugh that she hears coming from behind the door.",
        "a10" :"Mr. Rochester teases Jane by pretending to be interested in a local debutante, Blanche Ingram.",
        "a11" :"Jane goes back to Gateshead to tend Mrs. Reed on her deathbed.",
        "a12" :"Jane returns to Thornfield and eventually becomes engaged to Mr. Rochester.",
        "a13" :"Jane and Rochester’s wedding is interrupted by two men who reveal that Rochester is already married.",
        "a14" :"Jane leaves Thornfield and wanders alone on the moors, friendless and starving.",
        "a15" :"Arriving at Moor House, Jane is taken in by Diana, Mary, and St. John Rivers.",
        "a16" :"After regaining her strength, with St. John’s help, Jane gets a job as a teacher in a village school in Morton and moves to her own cottage.",
        "a17" :"Jane discovers that she and the Rivers siblings are cousins and that she has inherited £20,000.",
        "a18" :"St. John Rivers asks Jane to marry him and go with him to India on a missionary trip.",
        "a19" :"Jane mysteriously hears Rochester calling her from a great distance.",
        "a20" :"Jane returns to Thornfield and marries Mr. Rochester.",
        "a21" :"Jane and Rochester have a son.",
        "b1" : "Rochester",
        "c1" :"Bertha Mason"}

        for y in range(0, self.map_height):
            for x in range(0, self.map_width):
                tile_image = pygame.surface.Surface((self.block_width, self.block_height))
                if grid.grid[x][y] == 0:
                    maptile=MapTile(BLACK, x*self.block_width, y*self.block_height, self.block_width, self.block_height, 0)
                #elif self.gridmatch.has_key(grid.grid[x][y]):
                elif grid.grid[x]
                    maptile=MapTile(WHITE, x* self.block_width, y* self.block_height, self.block_width, self.block_height, self.gridmatch.get(grid.grid[x][y]))
                #self.tiles.append(maptile)
                self.block_list.add(maptile)
Example #50
0
	def __init__(self, size = 4):
		# init some variables
		self.grid = Grid(size)
		self.possibleNewTileValue = [2, 4]
		self.possibility = defaultPossibility
		self.initTiles = defaultInitialTiles
		self.computerAI = None
		self.playerAI = None
		self.displayer = None
		self.over = False
    def setup(self, parameters):
        self._parameters = parameters
        print("** Simulation parameters: %s" % self._parameters)

        self.jam_counter = 0

        self._grid = Grid(parameters.grid_width, parameters.grid_height)
        self._agents = [Agent(i, self) for i in xrange(parameters.n_agents)]

        self._timelord = TimeLord()
        self._timelord.setup(self._parameters.steps_per_day)
 def test_block_column_reduction(self):
     grid = Grid(StringIO("500200010001900730000000800050020008062039000000004300000000000080467900007300000"))
     prepareRemainingCandidates(grid)
     self.assertItemsEqual([2, 4, 5, 6, 7, 8], grid.candidates[7][6])
     self.assertItemsEqual([2, 5], grid.candidates[7][7])
     self.assertItemsEqual([2, 4, 5, 6, 8], grid.candidates[7][8])
     self.assertItemsEqual([1, 2, 3, 4, 5, 6, 7], grid.candidates[8][6])
     self.assertItemsEqual([1, 2, 3, 5], grid.candidates[8][7])
     self.assertItemsEqual([1, 2, 4, 5, 6], grid.candidates[8][8])
     self.assertEqual(1, self.lockedCandidatesResolution.block_column_reduction(grid, 6, 6))
     self.assertItemsEqual([4, 5, 6, 7, 8], grid.candidates[7][6])
     self.assertItemsEqual([5], grid.candidates[7][7])
     self.assertItemsEqual([4, 5, 6, 8], grid.candidates[7][8])
     self.assertItemsEqual([1, 3, 4, 5, 6, 7], grid.candidates[8][6])
     self.assertItemsEqual([1, 3, 5], grid.candidates[8][7])
     self.assertItemsEqual([1, 4, 5, 6], grid.candidates[8][8])
     self.assertEqual(
         "5..2...1...19..73.......8...5..2...8.62.39........43............8.46795...73.....",
         grid.display(lineBreak=False),
     )
def main():
    '''
      Controller which starts the game.
    '''
    possible_color = ['red','blue','green','yellow','orange','brown','black']
    grid_size = 8
    players = []
    no_of_players = input("How many players")
    if no_of_players < 7 and no_of_players >1:
        count = 0
        while count < no_of_players:
            color = possible_color[count]
            name = 'Player_'+str(count)
            print 'color',color,'name',name
            players.append(Player(color,name))
            count += 1
        grid = Grid(grid_size,players)
        grid.play()
    else:
        print (" That no of players are not permitted")    
Example #54
0
 def __init__(self, master):
     Frame.__init__(self, master)
     self.master = master
     self.running = True
     self.grid()
     self.create_widgets(master)
     self.grid = Grid(self.canvas, 40)
     self.val = 0
     self.draw_every_steps = 1
     self.draw_step = 0
     master.after(100, self.animation)
Example #55
0
    def reorderGrid(self, grid):
        """The lowest level species shoud have the highest occurence, make it
        so"""
        numbers = []
        for i in range(self.M):
            numbers.append([i, 0])
        for row in grid:
            for cell in row:
                numbers[cell.Level][1] += 1
        numbers = sorted(numbers, key=lambda x: x[1], reverse=True)

        new_Grid = Grid()
        for row in grid:
            new_row = []
            for cell in row:
                for i in range(len(numbers)):
                    if numbers[i][0] == cell.Level:
                        new_row.append(Cell(self, i, cell.State))
                        break
            new_Grid.append(new_row)
        return new_Grid
def all_grids():
    mg = MongoDB()
    mg.connect()
    griddb = GridDB()
    print('querying grid volumes...')
    results = mg.group_by([{'$match': {'created_at': {'$gt': datetime.strptime('2012-10-15T20:00:02Z', '%Y-%m-%dT%H:%M:%SZ'),
                                                      '$lt': datetime.strptime('2012-11-15T20:00:02Z', '%Y-%m-%dT%H:%M:%SZ')}}}])   # print(results)
    griddb.add(results)

    ret = Grid.get_raw_pandas_ts(results, 'D')

    STL.seasonal_decomposition(ret)
class World():
    # avoid ctor parameters since this is a singleton
    def __init__(self):
        pass

    def update_counter(self):
        self.jam_counter+=1

    def get_counter(self):
        return self.jam_counter

    def reset_counter(self):
        self.jam_counter = 0

    def setup(self, parameters):
        self._parameters = parameters
        print("** Simulation parameters: %s" % self._parameters)

        self.jam_counter = 0

        self._grid = Grid(parameters.grid_width, parameters.grid_height)
        self._agents = [Agent(i, self) for i in xrange(parameters.n_agents)]

        self._timelord = TimeLord()
        self._timelord.setup(self._parameters.steps_per_day)

    def get_parameters(self):
        return self._parameters

    def get_grid(self):
        return self._grid

    def print_grid(self):
        return self._grid.print_grid()

    def update_grid(self):
        self._grid.update_grid()

    def get_agents(self):
        return self._agents
Example #58
0
class TicTacToe(object):

    def __init__(self):
        self.user_requested_exit = False
        self.player_turn = 1
        self.grid = Grid()
        self.is_a_winner = False
        print 'Welcome to TicTacToe!'
        print 'Here is the grid'

    def start(self):
        while self.game_has_to_continue():
            self.grid.display()
            print 'Alright Player {}, your turn:'.format(self.player_turn)
            if not self.process_player_input(raw_input()):
                continue
            self.switch_player_turn()

        if self.user_requested_exit:
            print "Bye bye!"
        elif self.is_a_winner:
            self.grid.display()
            self.switch_player_turn()
            print "Congratulation Player {}, you won!".format(self.player_turn)
        else:
            print "Game Over, nobody wins."

    def process_player_input(self, player_input):
        if player_input == "quit":
            self.user_requested_exit = True
            return True
        if not self.grid.process_player_move(self.player_turn, player_input):
            print 'Sorry, you cannot play this'
            return False
        return True

    def game_has_to_continue(self):
        if self.no_winner() and self.grid.is_not_full() and self.user_wants_to_continue():
            return True
        return False

    def no_winner(self):
        if not self.grid.no_winner():
            self.is_a_winner = True
            return False
        return True

    def switch_player_turn(self):
        if self.player_turn == 1:
            self.player_turn = 2
        else:
            self.player_turn = 1

    def user_wants_to_continue(self):
        return not self.user_requested_exit
Example #59
0
class GameOfLifeTUI() :

    def __init__(self,xDim,yDim) :
        self.myGrid = Grid(xDim,yDim)
        self.xDim = xDim
        self.yDim = yDim
        self.myGrid.gliderSetup()

    def run(self) :
       # on purpose an endless loop
       self.clearScreen()
       while True :
          self.displayGrid()
          self.myGrid.update()
          time.sleep(1)
          self.clearScreen()

    def displayGrid(self) :
       print(self.myGrid)

    def clearScreen(self) :
       print("\033[H\033[2J")
Example #60
0
 def __init__(self, **kwargs):
     pygame.init()
     self.screen_info = pygame.display.Info()
     self.screen_size = kwargs.get("screen_size", (0, 0))
     self.resizable = kwargs.get("resizable", True)
     if self.resizable:
         self.screen = pygame.display.set_mode(self.screen_size, RESIZABLE)
     else:
         self.screen = pygame.display.set_mode(self.screen_size)
     self.rect = Rect((0, 0), self.screen.get_size())
     self.layout = kwargs.get("layout", None)
     if self.layout == "grid":
         Grid.__init__(self)
         self.layout = Grid
     elif self.layout == "flow":
         Flow.__init__(self)
         self.layout = Flow
     elif self.layout == "place" or self.layout is None:
         Place.__init__(self)
         self.layout = Place
     self.fullscreen = kwargs.get("fullscreen", False)
     self.last_screen_size = self.rect.size