Пример #1
0
def _process(json_data, use_cloud, quit_on_first=True, ignore_pickle=False, debug_info=None):
    slv = Solver(quit_on_first=quit_on_first, use_cloud=use_cloud, ignore_pickle=ignore_pickle, debug_info=debug_info)
    st = State()

    st.load_from_json(json_data)
    slv.set_state(st)

    filelist = []
    if use_cloud:
        # fetch remote pickle if exists
        filelist = cloud.files.list()
        pf = '%s.pickle' % st.__hash__()
        pffull = os.path.join('var', 'graphs', pf)
        if pf in filelist:
            cloud.files.get(pf, pffull)

    slv.solve()

    if use_cloud:  # upload solution
        cloud.files.put(pffull, pf)

    # the image, save it to cloud
    png = '%s.png' % st.__hash__()
    pngfull = os.path.join('var', 'graphs', png)
    if png not in filelist:  # irrelevent? FIXME , pngfull does not exist, since we never synced it.
        slv.draw_graph(filename=pngfull)
        if use_cloud:
            cloud.files.put(pngfull, png)
    else:
        print "Graph Image %s already exists" % pngfull

    ret = (slv.l_shortest)
    return ret
Пример #2
0
def edit_map(state, event, button):
    if not state:
        return False
    t = state.map.get_tile_at(event.pos[0], event.pos[1])
    if not t:
        return False
    update_snake = button.value in SNAKE_VALUES
    coords = state.map.get_coords()
    if not update_snake:
        coords[t.x][t.y] = button.value
    m = Map(coordinates=coords)
    coords_snakes = state.map.get_coords(snakes=True)
    if update_snake or button.value == '0':
        coords_snakes[t.x][t.y] = button.value
    ss = Snake.make_snakes(m, coords_snakes)
    s = State(m, ss)
    s.save_to_json("data/maps/tempstate.json")
    return True
Пример #3
0
 def _refresh_levels(self):
     maps = self.app.levels
     i = 0
     spacing = 20
     x_o = 50
     y_o = 50
     for fn in maps:
         fn = os.path.basename(fn)
         state = State()
         state.load_from_json_file(os.path.join(os.getcwd(), 'data', 'maps', fn))
         thumb = state.get_thumbnail(resman=self.app.resman)
         per = BUTTONS_PER_ROW
         col = i % per
         row = floor(i / per)
         x = x_o + col * (LevelButton.w + spacing)
         y = y_o + row * (LevelButton.w + spacing)
         b = LevelButton(fn, thumb, x, y, levelnr=i + 1)
         self.levelbuttons.append(b)
         i = i + 1
Пример #4
0
    def reload_buttons(self):
        self.buttons = []
        self.buttons.append([])
        for v in ['G','B','Y','R','O','P']:
            b = ToolbarButton(self,v,action='setsnake')
            self.buttons[0].append(b)
        self.buttons.append([])
        for v in ['g','b', 'y', 'r', '0','1']:
            b = ToolbarButton(self,v,action='settile')
            self.buttons[1].append(b)

        ## NEW MAP button
        self.buttons.append([])
        v = 12; b = ToolbarButton(self,v,action='mapsize',label=str(v))
        self.buttons[2].append(b)
        """
        # we don't need so many NEW MAP buttons #
        for v in xrange(3,11):
            b = ToolbarButton(self,v,action='mapsize',label=str(v))
            self.buttons[2].append(b)
        self.buttons.append([])
        for v in xrange(11,19): # second row of map buttons
            b = ToolbarButton(self,v,action='mapsize',label=str(v))
            self.buttons[3].append(b)
        """

        # add buttons for loading map with screenshots
        self.buttons.append([])
        # maps = glob.glob(os.path.join(os.getcwd(),'data','maps')+"/*.png")
        # maps += glob.glob(os.path.join(os.getcwd(),'data','maps')+"/*.json")
        # sort_nicely(maps) # sort (natural order) by first integer - state graph size
        maps = self.ingameState.app.resman.get_levels()
        row = 3 
        for fn in maps:
            fn = os.path.basename(fn)
            state = State(None,None)
            if fn.endswith("png"):
                state.load_from_file(fn)
            else:
                state.load_from_json_file(os.path.join(os.getcwd(),'data','maps',fn))
            thumb = state.get_thumbnail(a=60,resman=self.ingameState.app.resman)
            #t_w, t_h = thumb.get_size()
            #thumb = pygame.transform.scale(thumb,(t_w/2,t_h/2))
            b = ToolbarButton(self,fn,action='mapload',surface=thumb)
            if len(self.buttons[row]) > self.surface.get_width() / WIDTH_OF_BUTTON:
                self.buttons.append([])
                row = row + 1
            self.buttons[row].append(b)
        self.current_button = None
        self.hover_button = None
Пример #5
0
    def _populate_graph_bfs(gr,root,points,quit_on_first=False):
        # BFS algo from http://en.wikipedia.org/wiki/Breadth-first_search
        from Queue import Queue
        q = Queue()

        s = State()
        s.load_from_json(root)

        q.put(s)

        h = hashlib.md5(root).hexdigest()
        gr.graph['visited'].append(h)

        while not q.empty():
            # debug output
            o = gr.order(); p0 = points[0]
            if o >= p0:
                points.remove(p0) # so it's only called once
                print "Order >= %s, Visited: %s, Finals: %s" % (p0, len(gr.graph['visited']), len(gr.graph['finals']))

            s = q.get()
            hs = hashlib.md5(s.to_json()).hexdigest()
            gr.add_nodes_from([hs])

            if s.is_complete():
                gr.graph['finals'].append(hs)

            for ns in s.get_neighbour_states():
                hns = hashlib.md5(ns.to_json()).hexdigest()
                if not gr.has_node(hns):
                    gr.add_nodes_from([hns])
                gr.add_edge(hs,hns)
                if hns not in gr.graph['visited']:
                    gr.graph['visited'].append(hns)
                    q.put(ns)

            if len(gr.graph['finals']) and quit_on_first:
                break # found first
Пример #6
0
 def AddStateFromName(self, stateName, index):
     state = State(label=stateName, index=index)
     self.AddState(state)
Пример #7
0
    def _populate_graph(gr,root,depth=0,max_depth=0,found_new=0,has_one=False,debug_info=None,quit_on_first=None):
        """Recursively called"""
        global points

        sxp_digest = hashlib.md5(root).hexdigest()
        if sxp_digest in gr.graph['visited']:
            return -3
        gr.graph['visited'].append(sxp_digest)


        o = gr.order(); p0 = points[0]
        if o >= p0:
            points.remove(p0) # so it's only called once
            print "Order >= %s, Visited: %s, Finals: %s" % (p0, len(gr.graph['visited']), len(gr.graph['finals']))

        if max_depth and depth >= max_depth:
            return 3

        # its a try-catch so that no 'video system not initalized' error comes when running in console mode
        try:
            # process message queue
            pygame.event.pump()
        except:
            pass

        found_new = 0
        s = State()
        s.load_from_json(root)
        nss = s.get_neighbour_states()
        nssx = []
        completed = []
        for ns in nss:
            j = ns.to_json()
            nssx.append(j)
            if ns.is_complete():
                completed.append(j)
            ns.release()
        del nss
        s.release()
        del s

        Solver._attach_debugs(debug_info,gr,depth=depth)

        for nsx in nssx:
            digest = hashlib.md5(nsx).hexdigest()
            if not gr.has_node(digest):
                gr.add_nodes_from([digest])
                found_new = found_new + 1
                if nsx in completed:
                    gr.node[digest]['complete'] = True
                    has_one = True
                    gr.graph['finals'].append(digest)
                # else: # once again, drawing will fail if we set this.
                #     gr.node[digest] = None # help with memory? otehrwsise a {} is stored there

            if not gr.has_edge(sxp_digest,digest):
                gr.add_edge(sxp_digest,digest) # attr_dict={} by default. memory. and otherwise drawing does not work
            if has_one and quit_on_first:
                return 42

        for nsx in nssx:
            if not found_new: # if no new neighbours were found during the previous iteration
                return 7
            if quit_on_first and len(gr.graph['finals']) and not max_depth:
                return 8
            Solver._populate_graph(gr,nsx,depth=depth+1,max_depth=max_depth,found_new=found_new,debug_info=debug_info,quit_on_first=quit_on_first) # recurse