def check_inputs(): invalid_positions = [ 0, 1, 2, 3, 4, 5, 6, 7, 14, 21, 28, 35, 42, 13, 20, 27, 34, 41, 48, 43, 44, 45, 46, 47 ] key = input() if key == 'w': Player.pos -= 7 elif key == 's': Player.pos += 7 elif key == 'a': Player.pos -= 1 elif key == 'd': Player.pos += 1 for position in invalid_positions: if position == Player.pos: if key == 'w': Player.pos += 7 elif key == 's': Player.pos -= 7 elif key == 'a': Player.pos += 1 elif key == 'd': Player.pos -= 1 print('You hit a wall!') if key == 'q': exit() remove = Render() remove.remove_player()
def tick(self, viz=False): self.timeline += 1 n = len(self.agents) for i, agent in enumerate(reversed(self.agents)): observ, optimalAction = self.observe() action = agent.forward(observ) self.update(agent, action, optimalAction) agent.backward(optimalAction) # erase dead if agent.entropy < self._minEntropy: del self.agents[n - i - 1] # sort according to entropy self.sortAgents() # hybrid or erase if len(self.agents) < self.agentNum: self.addAgent(self.hybrid(self.agents[0], self.agents[1])) elif len(self.agents) > self.agentNum: del self.agents[-1] elif np.random.rand() > 1 - self.eraseProb: idx = np.random.randint(0, len(self.agents)) del self.agents[idx] if viz and len(self.agents) > 0: if self.renderObj is None: self.renderObj = Render() self.renderObj.update(self.agents[0])
def main(window, handle_events): ## window = Window() ## window.init() world = World() world.stage = 1 p1 = Platform(600, 300, 400, 50) world.add_item(p1) p2 = Platform(500, 600, 800, 100) world.add_item(p2) """ vert order: 0 3 1 2 """ rest_length, stiffness, damping = 200, 10, 1 spring = Spring(p1, p2, lambda vs: vs[1], lambda vs: vs[0], rest_length, stiffness, damping) world.add_spring(spring) spring = Spring(p1, p2, lambda vs: vs[2], lambda vs: vs[3], rest_length, stiffness, damping) world.add_spring(spring) spring = Spring( p1, p2, lambda vs: (vs[1] + vs[3]) / 2, lambda vs: (vs[1] + vs[3]) / 2, rest_length, 10 * stiffness, damping ) world.add_spring(spring) font_path = os.path.join(data_dir(), "fonts", "vinque", "vinque.ttf") fnt = font.Font(font_path, 36) surface = fnt.render("The adventures of...", True, (255, 255, 255)) word = Word(p2, surface, (200, 50)) world.add_word(word) fnt = font.Font(font_path, 48) text = "Woger the wibbly wobbly wombat" words = [fnt.render(word, True, (255, 255, 255)) for word in text.split()] word_positions = ((200, 75), (500, 75), (175, 250), (350, 250), (550, 250)) for surface, position in zip(words, word_positions): word = Word(p1, surface, position) world.add_word(word) fnt = font.Font(font_path, 24) surface = fnt.render("space to continue, use awwow keys in game to weach owanges", True, (0, 0, 0)) word = Word(p2, surface, (40, 550)) world.add_word(word) render = Render(window, world) while True: quit = handle_events(window, world) if quit: break world.update() render.draw_world() display.flip()
def render_model_net(root, output_dir, output_views=12, use_dodecahedron=False): # traversal the directors sub_dirs = sorted(get_immediate_subdirectories(root)) render = Render() for sub_dir in sub_dirs: print("dealing " + sub_dir + "...") # make output dirs out_sub_dir = output_dir + "/" + sub_dir make_dir_not_exist(out_sub_dir + "/test") make_dir_not_exist(out_sub_dir + "/train") # ready to convert source_dir = root + "/" + sub_dir for d in ["/test", "/train"]: print(d) curr_dir = source_dir + d off_files = list(get_off_file_in_dir(curr_dir)) for i, off_file in enumerate(off_files): render.render_and_save(curr_dir + "/" + off_file, out_sub_dir + d, output_views, use_dodecahedron) if i % 10 == 0: print("%d/%d" % (i, len(off_files)))
def main(): args = init_args() try: dict_data = json.loads(open(args.json_file).read()) except IOError: print('Error: no such file {}'.format(args.json_file)) exit() mantle = JSONMantle() mantle.class_prefix = args.prefix if args.prefix else '' if args.author: mantle.meta_data['author'] = args.author # Get the file base name file_basename = os.path.basename(args.json_file) # Eliminating filename extension class_name = file_basename.split('.')[0] mantle.generate_properties(dict_data, class_name) render_h, render_m = mantle.get_template_data() render = Render(render_h, render_m, args.output_dir) render.render_objc()
def stars(): width = 800 height = 600 r = Render(width, height) def star(s, y, size): c = random.randint(0, 255) r.set_color(color(c, c, c)) if size == 1: r.point(x, y) elif size == 2: r.point(x, y) r.point(x + 1, y) r.point(x, y + 1) r.point(x + 1, y + 1) elif size == 3: r.point(x, y) r.point(x + 1, y) r.point(x, y + 1) r.point(x - 1, y) r.point(x, y - 1) for x in range(width - 4): for y in random(height - 4): if random.random() < 0.001: star(x + 2, y + 2, random.randint(1, 3)) r.display('out.bmp')
def main(): from render import Render from tree import Tree from time import time render = Render(SIZE, FRONT, BACK, TRUNK, TRUNK_STROKE, GRAINS) render.ctx.set_source_rgba(*FRONT) render.ctx.set_line_width(ONE) while True: render.clear_canvas() tree = Tree(MID, 0.9, INIT_BRANCH, -pi * 0.5, ONE, ONE, BRANCH_SPLIT_ANGLE, BRANCH_PROB_SCALE, BRANCH_DIMINISH, BRANCH_SPLIT_DIMINISH, BRANCH_ANGLE_MAX, BRANCH_ANGLE_EXP) i = 1 while tree.Q: i += 1 tree.step() map(render.branch2, tree.Q) if not i % 1000: print i render.sur.write_to_png( '/media/var/andreas_tree/test_52_{:10.0f}.png'.format(time()))
def save_DET(dc, path, file_name, plot_options={}): if isinstance(dc, DataContainer): dc = [dc] rd = Render(plot_type="det") fig = rd.plot(dc, display=False, plot_options=plot_options) fig.savefig("{}/{}".format(path, file_name)) rd.close_fig(fig)
def __init__(self): self.render = Render(self) self.totals = {} self.pure8 = False self.mirror = True self.createScore() self.calcMapping()
def save_DET(dc, path, file_name, no_ppf, plot_options={}): if type(dc) is {}.values().__class__: dc = list(dc) if isinstance(dc, DataContainer): dc = [dc] rd = Render(plot_type="det") fig = rd.plot(dc, display=False, plot_options=plot_options, no_ppf=no_ppf) fig.savefig("{}/{}".format(path, file_name)) rd.close_fig(fig)
def __init__(self, planet, agents, viz=True): self._minEntropy = 1 self._invEntropy = 5 self.viz = viz self.planet = planet self.agents = [self.addAgent(agent) for agent in agents] self._agent = None if viz: self.renderObj = Render()
def test_export_aaf(): r = Render( JSON_EXAMPLE, './tmp', no_clean=True, # readable=True, verbose=False, vcodec='aaf') r.export()
def test_export_fcpxml(): r = Render( JSON_EXAMPLE, './tmp', no_clean=True, # markers=True, # readable=True, verbose=False, vcodec='fcpxml') r.export()
def renderTrainAndTestSet(blenderFiles, renderedDir, num_samples_train, num_samples_test, num_rotations_train, num_rotations_test, res_x, res_y, cameraPositions): global renderList renderedDir = os.path.abspath(renderedDir) renderList.append( Render(blenderFiles, renderedDir + "_train", num_samples_train, num_rotations_train, cameraPositions, res_x, res_y)) renderList.append( Render(blenderFiles, renderedDir + "_test", num_samples_test, num_rotations_test, cameraPositions, res_x, res_y))
def __init__(self, name): self.progressbar_pos = [0, 0] self.progressbar_dir = 'e' self.name = name self.progressbar_on = False self.thread = None self.crossword = Crossword.load(name) # WINDOW CONFIG self.window = tkinter.Tk() self.window.title('Generátor osemsmeroviek') self.window.resizable(False, False) self.window.lift() self.window.focus_force() self.window.bind('<Escape>', lambda e: self.close()) self.width = self.crossword.x_size * 20 + 18 self.height = self.crossword.y_size * 20 + 18 self.canvas = tkinter.Canvas(self.window, height=self.height, width=self.width) self.canvas.pack(side='right') Render.draw_table(self.canvas, self.crossword) # WORD LIST self.word_list = tkinter.Listbox(self.window, width='22') self.word_list.pack(side='top', anchor='n') for word in self.crossword.words: self.word_list.insert('end', word.word) if len(self.crossword.words): Render.draw_letters(self.canvas, self.crossword) tkinter.Button(self.window, text='Zmazať slovo', command=self.delete_selected, width='18').pack(side='top', anchor='n') # SPACER tkinter.LabelFrame(self.window, text='', height='10').pack(side='top') # NEW WORD self.nw_entry = tkinter.Entry(self.window, width='22') self.nw_entry.pack(side='top', anchor='n') self.nw_entry.bind('<Return>', lambda e: self.add_word()) tkinter.Button(self.window, text='Pridať slovo', command=self.add_word, width='18').pack(side='top', anchor='n') # SPACER tkinter.LabelFrame(self.window, text='', height='12').pack(side='top') # GENERATE AND SAVE tkinter.Button(self.window, text='Generovať', command=self.generate, width='18').pack(side='top', anchor='s') self.save_btn = tkinter.Button(self.window, text='Uložiť', command=self.save, width='18', state='disabled') self.save_btn.pack(side='top', anchor='s')
def dispatch(self): if (not self.params.has_key("id")) or (not self.params.has_key("type") or (not self.params.has_key("text"))): return Render.render_400() try: pa = self.params speech_obj = Speech(pa["id"], pa["text"], pa["lan"], pa["type"]) speech_obj.speak() # response back to client response = Render(speech_obj) return response.render() except Exception, e: return Render.render_400(e)
def __init__(self, save_prev_names: bool = False): self.game_field = [str(i + 1) for i in range(9)] self.moves_count = 0 if not save_prev_names: self.first_player, self.second_player = None, None self.victory_counter = [0, 0] self.curr_player_mark = "O" self.render = Render() logging.basicConfig(level=logging.INFO, format="%(asctime)s, %(levelname)s - %(message)s", datefmt="%d-%b-%y %H:%M:%S", filename="game_logs.log")
def run(self): # get data data = TextDataset(self.src) # preprocess r = RuleBased() e = Evaluate() # nltk as baseline print("Processsing NLTK as baseline ... ") nltk_sentences = r.get_nltk_tokenized_sentences(data.clean_text) query_list = [s.split(" ") for s in nltk_sentences] begin, end, indexed_sentences = e.find_query_index(data.clean_idx_tokens, query_list) evaluation = e.evaluate(data, begin, end) result = {"key":"nltk", "begin":begin, "end":end, "sentences":indexed_sentences, "evaluation":evaluation} self.results.append(result) #import pdb; pdb.set_trace() # #rule_based methods print("Processsing rule based (Subject) ... ") filtered = r.filter_subject(nltk_sentences) query_list = [s.split(" ") for s in filtered] begin, end, indexed_sentences = e.find_query_index(data.clean_idx_tokens, query_list) evaluation = e.evaluate(data, begin, end) result = {"key":"has_subject", "begin":begin, "end":end, "sentences":indexed_sentences, "evaluation":evaluation} self.results.append(result) print("Processsing rule based (Verb)... ") filtered = r.filter_verb(nltk_sentences) query_list = [s.split(" ") for s in filtered] begin, end, indexed_sentences = e.find_query_index(data.clean_idx_tokens, query_list) evaluation = e.evaluate(data, begin, end) result = {"key":"has_verb", "begin":begin, "end":end, "sentences":indexed_sentences, "evaluation":evaluation} self.results.append(result) print("Processsing rule based (Subject & Verb)... ") filtered = r.filter_subject(nltk_sentences) filtered = r.filter_verb(filtered) query_list = [s.split(" ") for s in filtered] begin, end, indexed_sentences = e.find_query_index(data.clean_idx_tokens, query_list) evaluation = e.evaluate(data, begin, end) result = {"key":"has_subjectVerb", "begin":begin, "end":end, "sentences":indexed_sentences, "evaluation":evaluation} self.results.append(result) # write result print("Writing data to: " + str(self.dst) + "\033[1m" + str(self.filename) + "\033[0m") render = Render(self.dst, self.filename, data, data.ground_truth, self.results) render.save()
def draw(self, px_per_mm): inf = array([0, 0]) points = [inf.copy()] sup = inf.copy() for attr in ("hip", "shoulder", "elbow", "wrist", "top_of_ht"): point = getattr(self, attr) points.append(point) for i in range(2): sup[i] = max(sup[i], point[i]) inf[i] = min(inf[i], point[i]) render = Render(inf, sup, px_per_mm) render.polyline(points, "black") return render
def get(self, request, **kwargs): to_date = request.GET.get('to_date') if request.GET.get( 'to_date') else datetime.datetime.today().date() from_date = request.GET.get('from_date') if request.GET.get( 'from_date') else to_date.replace(day=1) data_list = [] route_list = [] tickets = TicketSale.objects.filter(applied_date__range=(from_date, to_date)) if tickets: for row in tickets: route_list.append(row.vehicle_id.route_id) route_list = list(dict.fromkeys(route_list)) for route in route_list: vehicle_list = [] route_text = RouteInfo.objects.get(pk=route) vehicle_count = VehicleInfo.objects.filter(route=route).count() vehicle = VehicleInfo.objects.filter(route_id=route) for row in vehicle: vehicle_list.append(row.id) ticket_count = 0 for row in vehicle_list: count = TicketSale.objects.filter(vehicle_id=row).count() ticket_count += count data_dict = dict() data_dict['route'] = route_text data_dict['total_ticket'] = ticket_count data_dict['total_vehicle'] = vehicle_count data_list.append(data_dict) return Render.render('pdf/major_route_forecast.html', { 'query': data_list, 'university': client })
def get(self, request, **kwargs): to_date = request.GET.get('to_date') if request.GET.get( 'to_date') else datetime.datetime.today().date() from_date = request.GET.get('from_date') if request.GET.get( 'from_date') else to_date.replace(day=1) query = PurchaseInvoice.objects.filter( entry_date__range=(from_date, to_date)).values('entry_date').annotate( amount=Sum('amount'), vendor=F('vendor_id'), purchase_id=F('id')) for row in query: products = PurchaseProduct.objects.filter( purchase_id=row['purchase_id']) all_products = '' i = 1 for p in products: if i == len(products): all_products = all_products + p.product_name else: all_products = all_products + p.product_name + ',' i += 1 row['products'] = all_products row['vendor'] = Vendor.objects.get(pk=row['vendor']).name return Render.render( 'pdf/date_wise_purchase_report.html', { 'query': query, 'university': client, 'from_date': from_date, 'to_date': to_date })
def __init__(self, title, xLabel, yLabel, file): self.file = file self.dVal = None plt.xlabel(title) plt.ylabel(xLabel) plt.title(yLabel) self.dVal = Render.load(file)
def get(self, request, ticket_number): tickets = TicketSale.objects.get(ticket_number=ticket_number) prev = tickets.ticket_number[2:] # import pdb; pdb.set_trace() tickets.invoice = 'PI-' + prev params = {'university': client, 'tickets': tickets, 'request': request} return Render.render('pdf/sale_invoice.html', params)
async def req1(req): print("req1", req.url) if '/get/' in req.path or '/do/' in req.path or '/post/' in req.path: return ext = req.path.split('.')[-1] if ext in ('mp3', 'js', 'jpg', 'css', 'ttf', 'png', 'woff', 'woff2', 'ico', 'gif', 'map', 'mem', 'pck', 'mp4', 'csv'): pfil = './web' + req.path return await response_file( location=pfil, headers={"cache-control": "public,max-age=216000"}) elif ext in 'html': pfil = './web' + req.path tmp = Render(pfil) rtn = await tmp.parse() return response_html( body=rtn, headers={"cache-control": "public,max-age=216000"}) elif ext in 'py': pfil = '.' + req.path # /w*.py y /vs_widgets will be served not server side .py if (req.path[:2] == '/w' or "/vs_widgets" in req.path) and ".." not in req.path: return await response_file( pfil, headers={"cache-control": "public,max-age=216000"}) else: return response_text("error") else: return response_text("error")
def main(): model = init_model( os.path.dirname(os.path.abspath(__file__)), getpass.getuser(), os.uname().nodename ) def resize(signum, frame): Render(model) # Re-renders Terminal in case of SIGWINCH(resize) event signal.signal(signal.SIGWINCH, resize) while not model.exit: try: Render(model) try: model = EventHandler(model, blesses.get_key()) except KeyboardInterrupt: model = replace(model, exit=1) except Exception as e: with open("crash.json", "w+") as f: f.write(json.dumps(asdict(model),indent=4)) raise e
def start(self): logging.getLogger(__name__).info("Start of script") self.load_configuration() role = self.configuration.role(self.args.role) if role: logging.getLogger(__name__).info("Processing role: {r}".format(r=role.name)) renders = [] for file_entry in role.file_entries: render = Render.from_file_entry(file_entry) if render: renders.append(render) # any renders had errors, don't continue if not self.render_ok(renders): sys.exit(1) # Renders are OK, but don't write anything if self.args.dry_run: logging.getLogger(__name__).info("Dry run: OK") sys.exit(0) # Renders are OK and we want to write files for render in renders: render.to_file()
def build(default, resume): Renderer = Render() if default: try: posts = parse.Post_parser() Renderer.Render_posts(posts) logging.info(" Build successful. Check your output folder.") except: logging.exception(" Build failed :(") elif resume: try: details = parse.Resume_parser() Renderer.Render_resume(details) logging.info(" Build successful. Check your output folder.") except: logging.exception(" Build failed :(")
def start_game(): #needs to be called before pygame.init pygame.mixer.pre_init(22050, -16, 2, 1024) window = Window() window.init() pygame.init() sounds = Sounds() sounds.init() window.sounds = sounds pygame.mixer.set_num_channels(32) # meta game loop while True: sounds.play_music("intro", loop=1) intro_main(window, handle_events) # so we can mix more channels at once. pygame defaults to 8. #sounds.play("jump1") #sounds.play("hit1") #sounds.play("goal1") sounds.set_music_tracks(['track-one', 'track-two']) world = World() world.stage = 2 populate(world, window) def count_leaves(): no_leaves = 0 for item in world.items: if item.role == "Bough": no_leaves = no_leaves + 1 return no_leaves CleanUp_Event = pygame.event.Event(CLEANUP, message="Cleaning Up Your shit") pygame.time.set_timer(CLEANUP, 1000) TickTock = pygame.event.Event( TICK_TOCK, message="TickTock goes the Ticking Clock") pygame.time.set_timer(TICK_TOCK, int(90000 / count_leaves())) AddCherry = pygame.event.Event(ADDCHERRY, message="Ooooo Cherry") pygame.time.set_timer(ADDCHERRY, int(90000 / 5)) AddOwange = pygame.event.Event(ADDOWANGE, message="Ooooo owange") pygame.time.set_timer(ADDOWANGE, int(1000 * 5)) for i in range(3): event.post(AddOwange) pygame.time.set_timer(BIRDY, 1000 * 7) render = Render(window, world) quit = runloop(window, world, render) if quit: return
def get(self, request, **kwargs): to_date = request.GET.get('to_date') if request.GET.get( 'to_date') else datetime.datetime.today().date() from_date = request.GET.get('from_date') if request.GET.get( 'from_date') else to_date.replace(day=1) query = TicketSale.objects.filter( applied_date__range=(from_date, to_date)).values('issued_for').annotate( total_amount=Sum('total_amount'), paid_amount=Sum('paid_amount'), due=F('total_amount') - F('paid_amount'), ) # for row in query: # tickets = TicketSale.objects.filter(issued_for=row['issued_for']) # all_tickets = '' # i = 1 # for t in tickets: # if i == len(tickets): # all_tickets = all_tickets + t.ticket_number # else: # all_tickets = all_tickets+t.ticket_number+',' # i += 1 # row['ticket_number'] = all_tickets return Render.render( 'pdf/passenger_wise_ticket_details.html', { 'query': query, 'university': client, 'from_date': from_date, 'to_date': to_date })
def get(self, request, **kwargs): vehicle_id = request.GET['vehicle'] total = 0 # import pdb; pdb.set_trace() if vehicle_id: query = PurchaseInvoice.objects.filter( vehicle_id_id=int(vehicle_id)).values('entry_date').annotate( amount=Sum('amount'), vendor=F('vendor_id'), purchase_id=F('purchase_id'), ) for row in query: row['vehicle'] = VehicleInfo.objects.get( pk=vehicle_id).vehicle_number row['vendor'] = Vendor.objects.get(pk=row['vendor']).name total += row['amount'] else: query = PurchaseInvoice.objects.values('entry_date').annotate( amount=Sum('amount'), vendor=F('vendor_id'), vehicle=F('vehicle_id'), purchase_id=F('purchase_id')) for row in query: row['vehicle'] = VehicleInfo.objects.get( pk=row['vehicle']).vehicle_number row['vendor'] = Vendor.objects.get(pk=row['vendor']).name total += row['amount'] # import pdb; pdb.set_trace() return Render.render('pdf/vehicle_wise_purchase_report.html', { 'query': query, 'university': client, 'total': total })
def __init__(self, numDrones, numMobileRobs): self.drones = self.initDrones(numDrones) self.mobilerobots = self.initMobileRobs(numMobileRobs) self.numCollectionPts = 20 self.areaLength = 20 # in meters self.timeStep = timeStep self.collectionPts = self.genCollectionPts(self.numCollectionPts) #CONSTANTS self.screen_width = screenWidth self.screen_height = screenHeight #MAIN LOOP self.display = Render(len(self.drones), len(self.mobilerobots), self.drones, self.mobilerobots, self.collectionPts)
def test_render(): r = Render( JSON_EXAMPLE, './tmp', no_clean=True, silent_log=True, thread_alloc=2, # readable=True, verbose=False, vcodec='h264') # r.socketThread.daemon = True r.socketThread.start() r.render(False) r.keep_socket_open = False r.socketThread.join() print("ahh")
def do_render_cache(cursor=None): thq = Thread.all() if cursor: thq.with_cursor(cursor) thread = thq.get() if not thread: logging.info("stop thread clean") return board = thread.parent_key().name() render = Render(board=board, thread = thread.key().id()) for idx,post in enumerate(thread.posts): post['text_html'] = markup( board=board, postid=post.get("post"), data=escape(post.get('text', '')), ) if idx == 0: render.create(post) else: render.append(post) if len(thread.posts) > 1: thread.put() else: thread.delete() render.save() deferred.defer(do_render_cache, thq.cursor())
def process(thread_key): logging.info('process %r' % thread_key) thread = db.get(thread_key) render = Render(thread = thread) for idx,post in enumerate(thread.posts): if 'text' in post: post['text_html'] = markup( board=thread.board, postid=post.get("post"), data=escape(post.get('text', '')), ) if 'rainbow_html' in post: post.pop("rainbow_html") post['rainbow'] = rainbow.make_rainbow(post['rainbow']) if 'image' in post and not post.get("key"): post.pop("image") post['name'] = 'Kuroneko' if idx == 0: render.create(post) else: render.append(post) thread.put() render.save()
def main(): game = Game() render = Render(game) timer = pygame.time.Clock() players = [] # add player tank = Tank() tank.pos = Vec2d(200, 200) p1 = HumanPlayer('Ray', tank) p1.Mapping = HumanPlayer.MappingSet1 tank2 = Tank() tank2.pos = Vec2d(400, 200) p2 = HumanPlayer('Pest', tank2) p2.Mapping = HumanPlayer.MappingSet2 players += [p1, p2] for p in players: game.add_player(p) # add obstacle for pos, col in zip([(100, 400), (500, 400)], ['blue', 'red']): obs = ObstacleBlock((100, 100), pos, Color(col)) game.obstacles.append(obs) timer.tick() FPS = config.FPS dt = 1.0/FPS while 1: for e in pygame.event.get(): if e.type == QUIT: return elif e.type == KEYDOWN: for p in players: p.on_keydown(e.key) if e.key == K_b or (e.mod & KMOD_LCTRL) and e.key == K_q: return elif e.type == KEYUP: for p in players: p.on_keyup(e.key) game.loop(dt) render.draw() game.fps = timer.tick(FPS)
def main(): init() host, AI = parseOptions() field = FieldClient() field.connect(host) if AI: snake = AI.SnakeAI(field) print 'join', AI field.join(snake) sSize = config.screen_size #the screen size fSize = config.field_size1 # the field size frame_rate = config.frame_rate screen = pygame.display.set_mode(sSize, 0, 32) pygame.display.set_caption('SnakeAIC') render = Render(field, screen) timer = pygame.time.Clock() quit = False while not quit: for event in pygame.event.get(): if event.type == pygame.QUIT: quit = True field.sync() render.render() # for debug # render.render_path(snake._path) # render.render_coor() # pygame.display.flip() timer.tick(2*frame_rate) # print timer.get_fps() field.disconnect() quitclean() print "Bye"
def main(): from render import Render from tree import Tree from time import time render = Render(SIZE, FRONT, BACK, TRUNK, TRUNK_STROKE,GRAINS) render.ctx.set_source_rgba(*FRONT) render.ctx.set_line_width(ONE) while True: render.clear_canvas() tree = Tree(MID, 0.9, INIT_BRANCH, -pi*0.5, ONE, ONE, BRANCH_SPLIT_ANGLE, BRANCH_PROB_SCALE, BRANCH_DIMINISH, BRANCH_SPLIT_DIMINISH, BRANCH_ANGLE_MAX, BRANCH_ANGLE_EXP) i = 1 while tree.Q: i += 1 tree.step() map(render.branch2,tree.Q) if not i%1000: print i render.sur.write_to_png('/media/var/andreas_tree/test_52_{:10.0f}.png'.format(time()))
def delete_post(board, thread_num, post_num, rape_msg): last_deletion = False th = Thread.get(db.Key.from_path( "Board", board, "Thread", thread_num )) [post] = [p for p in th.posts if p.get('post') == post_num] logging.info("found: %r" % post) key = post.get("key") if key: post.pop("key", None) post.pop("image", None) info = blobstore.BlobInfo.get( blobstore.BlobKey(key)) info.delete() try: th.images.remove(post.get("key")) except: pass logging.info("removed image %r" % post) else: last_deletion = True post['text'] = 'Fuuuuuu' post['text_html'] = 'Fuuuuuu' post['rainbow_html'] = u'<b>' + rape_msg + '</b>' th.put() Cache.delete( ( dict(Board=board), ) ) r = Render(board, thread_num) #kind of shit: r.create(th.posts[0]) for a_post in th.posts[1:]: r.append(a_post) r.save() #FIXME: update records in memcache return last_deletion
def run(self): #test_entity = Entity('test-include') character = Entity('character') self.characters = [character for m in xrange(4)] self.renderer = Render(self) self.current_camera = 0 while True: dt = self.clock.tick() / 1000.0 for e in pygame.event.get(): if e.type == pygame.QUIT: sys.exit() elif e.type == pygame.KEYDOWN: if e.key == pygame.K_TAB: self.current_camera = (self.current_camera +1)%4 if e.key == pygame.K_a: #self.cameras[self.current_camera].props.dx = 1 pass elif e.type == pygame.KEYUP: if e.key == pygame.K_a: #self.cameras[self.current_camera].props.dx = 0 pass if e.type == pygame.JOYAXISMOTION or \ e.type == pygame.JOYBALLMOTION or \ e.type == pygame.JOYBUTTONDOWN or \ e.type == pygame.JOYBUTTONUP or \ e.type == pygame.JOYHATMOTION or \ e.type == pygame.KEYDOWN or \ e.type == pygame.KEYUP: event = InputEvent(e) for entity in self.entities_to_update: if e.type == pygame.JOYAXISMOTION: entity.handle('move', event) else: entity.handle('input', event) for entity in self.entities_to_draw_tiles: entity.handle('draw-tiles',self.world_surface) for entity in self.entities_to_update: entity.handle('update', dt) self.renderer.render()
def get(self): user = users.get_current_user() username = None if not user: login = users.create_login_url(self.request.uri) else: if User.find(user) is None: User.create(user) self.redirect('/profile') username = user.nickname() login = users.create_logout_url(self.request.uri) params = { 'title': 'Main Page', 'login': login, 'username': username } self.response.out.write(Render.render('index.html', params))
def __setup(self, eyeshift=[-3.0, 3.0], stereo=False): """ Initialize parameters for OpenGL and ready the texture for rendering """ # Set the projection settings for OpenGL # self.projection = Projection(self.width, self.height, eyeshift) # Prepare OpenGL and display textures for rendering self.render = Render(self.width, self.height, eyeshift, stereo) # Create the Vertex Buffer Objects needed self.render.create_VBO(self.width, self.height) # Create the shaders as necessary self.render.create_shaders() # Initiate the variable that will hold the current image to # be rendered self.current_img = None # Instantiate the stimuli class and setup the order in which # to display the stimuli for practice or for the experimental # block self.stimulus = Stimuli() # Now setup the stimuli if hasattr(self, 'practice'): self.stimulus.setup(self.practice) else: self.stimulus.setup() # Ready the next stimuli block self.stimulus.run_state() # Keep a list of possible stimuli rotations about the Z-axis # self.z_rotation = [0] if not STIMULI_ONLY: self.inclinometer = Inclinometer() self.inclinometer.set_offset_Y() self.slants = [] print 'Setting up of the experiment took %s seconds'\ % get_time(self.exp_start, time()) # Run the state that is required self.run_state()
def get(self): user = users.get_current_user() if user: user_db = User.find(user) blob_key = user_db.car_photo_blob_id if blob_key is not None: car_url = '/serve/%s' % blob_key.key() else: car_url = '/img/car.jpg' params = { 'title': 'Main Page', 'upload_url': blobstore.create_upload_url('/upload'), 'nick': user_db.nick, 'car_number': user_db.car_number, 'car_url': car_url, 'login': users.create_logout_url(self.request.uri), 'username': user.nickname() } self.response.out.write(Render.render('profile.html', params)) else: self.redirect('/')
def delete_post(board, thread_num, post_num, rape_msg): last_deletion = False th = Thread.load(thread_num, board) [post] = [p for p in th.posts if p.get('post') == post_num] logging.info("found: %r" % post) key = post.get("key") if key: post.pop("key", None) post.pop("image", None) info = blobstore.BlobInfo.get( blobstore.BlobKey(key)) if info: info.delete() try: th.images.remove(post.get("key")) except: pass logging.info("removed image %r" % post) else: last_deletion = True post['text'] = 'Fuuuuuu' post['text_html'] = 'Fuuuuuu' post['rainbow_html'] = u'<b>' + rape_msg + '</b>' th.put() Cache.remove("board", board) r = Render(thread=th) #kind of shit: r.create(th.posts[0]) for a_post in th.posts[1:]: r.append(a_post) r.save() return last_deletion
def do_render_cache(cursor=None): thq = Thread.all() if cursor: thq.with_cursor(cursor) thread = thq.get() if not thread: logging.info("stop thread clean") return board = thread.board render = Render(board=board, thread = thread.id) for idx,post in enumerate(thread.posts): if 'text' in post: post['text_html'] = markup( board=board, postid=post.get("post"), data=escape(post.get('text', '')), ) if 'rainbow_html' in post: post.pop("rainbow_html") post['rainbow'] = rainbow.make_rainbow(post['rainbow']) if 'image' in post and not post.get("key"): post.pop("image") post['name'] = 'Kuroneko' if idx == 0: render.create(post) else: render.append(post) if len(thread.posts) > 1: thread.put() else: thread.delete() render.save() deferred.defer(do_render_cache, thq.cursor())
def main(window, handle_events, score): ## window = Window() ## window.init() world = World() world.stage = 3 p1 = Platform(600, 300, 400, 50) world.add_item(p1) p2 = Platform(500, 600, 800, 100) world.add_item(p2) """ vert order: 0 3 1 2 """ rest_length, stiffness, damping = 200, 10, 1 spring = Spring(p1, p2, lambda vs:vs[1], lambda vs:vs[0], rest_length, stiffness, damping) world.add_spring(spring) spring = Spring(p1, p2, lambda vs:vs[2], lambda vs:vs[3], rest_length, stiffness, damping) world.add_spring(spring) spring = Spring(p1, p2, lambda vs: (vs[1] + vs[3])/2, lambda vs: (vs[1] + vs[3])/2, rest_length, 10*stiffness, damping) world.add_spring(spring) font_path = os.path.join(data_dir(), "fonts", "vinque", "vinque.ttf") ## fnt = font.Font(font_path, 36) ## surface = fnt.render('The adventures of...', True, (255,255,255)) ## word = Word(p2, surface, (200, 50)) ## world.add_word(word) fnt = font.Font(font_path, 48) text = 'You scored' words = [fnt.render(word, True, (0,0,0)) for word in text.split()] word_positions = ( (150, 60), (550, 60), ) for surface, position in zip(words, word_positions): word = Word(p1, surface, position) world.add_word(word) fnt = font.Font(font_path, 96) surface = fnt.render('% 2d' %score, True, (255,255,255)) word = Word(p2, surface, (230, 350)) world.add_word(word) fnt = font.Font(font_path, 24) surface = fnt.render('space to play again, escape to quit', True, (0,0,0)) word = Word(p2, surface, (200, 550)) world.add_word(word) render = Render(window, world) while True: quit = handle_events(window, world) if quit == 2: # non-esc keypressed return False if quit: return quit world.update() render.draw_world() display.flip()
def save_post(request, data, board, thread, ip): def board_increment(): board_db = BoardCounter.get_by_key_name(board) if not board_db: board_db = BoardCounter(key_name = board, thread = []) board_db.counter += 1 board_db.put() return board_db.counter postid = db.run_in_transaction(board_increment,) # create new thread new = False if thread == 'new': new = True if data.get("sage"): raise NotFound() # FIXME: move to form thread = postid posts = [] thread_db = Thread.create(thread, board) thread_db.posts = [] thread_db.subject = data.get("subject")[:SUBJECT_MAX] else: thread = int(thread) thread_db = Thread.load(thread, board) if not thread_db: raise NotFound() rb = rainbow.make_rainbow(ip, board, thread) data['rainbow'] = rb data['overlay'] = board in OVER data['text_html'] = markup( board=board, postid=postid, data=escape(data.get('text')), ) # save thread and post number data['post'] = postid data['thread'] = thread now = datetime.now() data['time'] = now.strftime("%Y-%m-%d, %H:%M") data['timestamp'] = int(now.strftime("%s")) img_key = data.get("key") if img_key: blob_key = blobstore.BlobKey(img_key) blob_info = blobstore.BlobInfo.get(blob_key) data['image'] = { "size" : blob_info.size, "content_type" : blob_info.content_type, "full" : images.get_serving_url(img_key), "thumb" : images.get_serving_url(img_key, 200), } for fname in OPTIONS.get(board, []): func = globals().get('option_'+fname) if func: func(request, data) thread_db.posts.append(data) thread_db.put() r = Render(thread=thread_db) r.post_html = '' r.add(data, new) # WARNING: side effect on data r.save() deferred.defer(save_post_defer, thread_db.boards, thread, r.post_html, data.get('text_html'), postid, len(thread_db.posts), data.get("sage"), ) # send notify thread_flag = 'new' if new else 'sage' if data.get("sage") else 'bump' match_msg = Post(board = board, thread = thread, thread_flag = thread_flag) match_msg.data = dict( board = board, thread = thread, html = r.post_html, text = data.get('text'), last = postid, count = len(thread_db.posts), evt = 'newpost' ) matcher.match(match_msg, topic='post', result_task_queue='postnotify') return postid, thread
class Colors: __borg_state = {} __account_colors_id = "account_colors" __color_id = "colors" def __init__(self, config): self.__dict__ = self.__borg_state self.config = config self.api = GW2_API(config) self.ds = DataStore(config) self.render = Render(config) def colorize(self): """Generate the embedded pages pertaining to an account's colors""" # Start by getting all the colors this account has my_colors = self.api.get("account/dyes") # Now, load previous color data old_colors = self.ds.get(self.__account_colors_id) # Find new colors new_colors = set(my_colors) - set(old_colors.get('colors', {})) # Now, obtain color details on each color temp_colors = self.api.get_with_limit("colors", { "ids" : my_colors }, "ids", 200) listings = self.api.get_with_limit("commerce/listings", { "ids" : [c['item'] for c in temp_colors] }, "ids", 200) colors_by_id = {} colors_by_set = {} for c in temp_colors: colors_by_id[c['item']] = c cat = c['categories'][-1] if cat not in colors_by_set: colors_by_set[cat] = [] colors_by_set[cat].append(c['item']) listings_by_id = {} for l in listings: listings_by_id[l['id']] = l data = {} color_library = {} total_value = 0 rarities = [] for rarity in colors_by_set.keys(): if rarity not in color_library: color_library[rarity] = [] if rarity not in rarities: rarities.append(rarity) colors_by_set[rarity].sort() for c in colors_by_set[rarity]: cost = 0 if c in listings_by_id: cost = listings_by_id[c]['sells'][0]['unit_price'] color_library[rarity].append({ "dye" : colors_by_id[c], "price" : cost }) total_value += cost # Hackish way to ensure we sort rarities right rarities_sorted = [] if "Starter" in rarities: rarities_sorted.append("Starter") rarities.remove("Starter") if "Common" in rarities: rarities_sorted.append("Common") rarities.remove("Common") if "Uncommon" in rarities: rarities_sorted.append("Uncommon") rarities.remove("Uncommon") if "Rare" in rarities: rarities_sorted.append("Rare") rarities.remove("Rare") if len(rarities) > 0: rarities.sort() rarities_sorted.extend(rarities) data = { 'colors' : color_library, 'value' : total_value, 'rarities' : rarities_sorted } # Finally, render return self.render.render(self.__color_id, data)
class Viewer(Window): """ Create the Window and process OpenGL """ # ------------------------------------------------------------------ # HANDLE INITIALIZATION # ------------------------------------------------------------------ def __init__(self, participant, *args, **kwargs): """ Setup window using default settings, disable visibility of the mouse cursor Setup the window for stimulus """ # Record the start of the experiment self.exp_start = time() super(Viewer, self).__init__(*args, **kwargs) # Clear the scene as soon as the window is loaded self.clear() # Disable visibility of the mouse self.set_mouse_visible(False) if STIMULI_ONLY: self.states = [self.__display_stimuli] else: # INITIATE THE STATES REQUIRED FOR THE EXPERIMENT # Declare all the possible action states for Viewer self.states = [ self.__display_message, self.__ready_block ] # Set requirement of practice self.practice = participant['practice'] # Set to True, when it is break time self.on_break = False # Set to True, when the experiment has run its course self.ended = False self.directory = participant['dir'] self.session = participant['day'] self.data = [] # Initiate reaction time list self.reaction_times = [] # If practice is required, add the states required onto itself # to create 2 blocks if self.practice: self.states += self.states # Add a __display_message state at the end to show the thank # you message self.states += [self.__display_message] # Set the state to be used self.run_state = self.states.pop(0) if participant: # Set the initial parameters for the window self.__setup(participant['eyeshift'], participant['stereo']) else: self.__setup() # Set the draw module self.on_draw = self.__draw def __setup(self, eyeshift=[-3.0, 3.0], stereo=False): """ Initialize parameters for OpenGL and ready the texture for rendering """ # Set the projection settings for OpenGL # self.projection = Projection(self.width, self.height, eyeshift) # Prepare OpenGL and display textures for rendering self.render = Render(self.width, self.height, eyeshift, stereo) # Create the Vertex Buffer Objects needed self.render.create_VBO(self.width, self.height) # Create the shaders as necessary self.render.create_shaders() # Initiate the variable that will hold the current image to # be rendered self.current_img = None # Instantiate the stimuli class and setup the order in which # to display the stimuli for practice or for the experimental # block self.stimulus = Stimuli() # Now setup the stimuli if hasattr(self, 'practice'): self.stimulus.setup(self.practice) else: self.stimulus.setup() # Ready the next stimuli block self.stimulus.run_state() # Keep a list of possible stimuli rotations about the Z-axis # self.z_rotation = [0] if not STIMULI_ONLY: self.inclinometer = Inclinometer() self.inclinometer.set_offset_Y() self.slants = [] print 'Setting up of the experiment took %s seconds'\ % get_time(self.exp_start, time()) # Run the state that is required self.run_state() # ------------------------------------------------------------------ # HANDLE KEYBOARD EVENTS # ------------------------------------------------------------------ def on_key_press(self, symbol, modifier): if symbol == key.ESCAPE: self.render.disable_GL_STATE() self.render.unbind_all() if not STIMULI_ONLY: self.inclinometer.close() self.__compile_data() exit(1) elif symbol == key.SPACE: if not self.on_break or self.states[0] == self.__display_message: if self.run_state == self.__display_stimuli: if hasattr(self, 'reaction_times'): self.reaction_times.append(time() - self.stimuli_presented) press_time = time() self.slants.append(self.inclinometer.get_Y() + 90.0) print get_time(press_time, time()) Beep(2500, 500) # If there are still some states to be run # We continue onto them if self.states: if not self.run_state == self.__display_fix: # Move to the next state self.run_state = self.states.pop(0) # And run it self.run_state() # Else we exit the experiment else: exit(1) # ------------------------------------------------------------------ # HANDLE STATES # ------------------------------------------------------------------ def __display_message(self): """ Display the message as necessary """ # If the experiment has not already ended, we prepare the next # stimulus if not self.ended and not self.on_break: # Get the next stimuli colormap and heightmap ready self.stimulus.run_state() # Tell the Render instance not attempt to render stimuli self.render_stimuli = False # If the experimental has ended, we display the message: # Thank you for your participation in the experiment! if self.ended: self.current_img = self.render.messages['thank_you'] self.inclinometer.close() self.__compile_data() # If the practice block needs to be run, we display the message: # Please press [SPACE] to begin the practice block elif self.practice: self.current_img = self.render.messages['begin_practice'] # If it is break time during the experimental block, we display # the message: # Take a break, please elif not self.practice and self.on_break: self.current_img = self.render.messages['break'] # We then schedule the end of the break, to take place after # a certain number of seconds, set by BREAK_DURATION schedule_once(self.__end_break, BREAK_DURATION) # If the experimental block can be run, we display the message: # Please press [SPACE] to begin the formal experiment elif not self.practice and not self.on_break: self.__compile_data(False) self.current_img = self.render.messages['begin_exp'] # Set the shaders to not be used, bind the VBO using bind_message # and assign current_img as the texture self.__ready_texture(False, self.render.bind_message) def __ready_block(self): """ Extend the list of states so as to include the state change as the practice or experimental block is run """ # Add further states in accordance with whether practice or # the formal experiment is to run states = [] for i in range(0, len(self.stimulus.order) + 1): # Interchange between fixation point display and the stimuli states.append(self.__display_fix) states.append(self.__display_stimuli) # Add the newly created states to the front of the list of states self.states = states + self.states # If it is not the practice block, we must schedule a break # The interval to a break is determined by the setting: BREAK_INTERVAL schedule_once(self.__break_time, BREAK_INTERVAL) if states: # Pop the foremost state and run it self.run_state = self.states.pop(0) self.run_state() def __display_fix(self): """ Display the fixation point """ # Tell the Render instance not attempt to render stimuli self.render_stimuli = False # Set current_img to the fixation point image self.current_img = self.render.fix_image # Set the shaders to not be used, bind the VBO using bind_message # and assign current_img as the texture self.__ready_texture(False, self.render.bind_message) # Ready the change over in state schedule_once(self.__next_state, FIX_DUR) def __display_stimuli(self): """ Display the stimuli images in order """ if not STIMULI_ONLY: temp_data = [] for data in self.stimulus.current: temp_data.append(data) self.data.append(temp_data) # Set current_img to the next stimulus image to be displayed self.current_img = self.stimulus.colormap[self.stimulus.current[0]] # Set the shaders to be used, bind the VBO and assign current_img # as the texture # Use the shader only if allowed by ENABLE_SHADER self.__ready_texture(True, self.render.bind_stimuli) # Randomly choose rotation for stimuli about the X-axis # from the list of POSSIBLE_SLANTS # num = randint(0, len(POSSIBLE_SLANTS) - 1) # self.render.rotation['X'] = POSSIBLE_SLANTS[num] self.render.scale['Z'] = self.stimulus.current[1] self.render.rotation['X'] = self.stimulus.current[2] # Randomly choose rotation for stimuli about the Z-axis # from the list of possible Z-axis rotations # num = randint(0, len(self.z_rotation) - 1) # self.render.rotation['Z'] = self.z_rotation[num] # If there are no more stimulus to present in this block if not self.stimulus.run_state(): # If the practice block is currently ongoing # We must now prepare for the experimental block if self.practice: # Since we just finished the practice block # We can set self.practice to False now self.practice = False # Prepare the experimental block self.stimulus.run_state() # If the practice block is not running, it must be the # experimental block that has ended else: # Set ended to true self.ended = True def __break_time(self, dt): """ Add a __display_message state into self.states to display a break """ if self.states and not self.ended: # Set on_break to True, as we are now on a break self.on_break = True # If the next state is to display the fixation point, we can # schedule the break before the next stimuli process begins if self.states[0] == self.__display_fix: # Place the __display_message state before the other states self.states = [self.__display_message] + self.states # If the next state is to display the stimuli, we must schedule # the break after it is completed elif self.states[0] == self.__display_stimuli: # We pop out the __display_stimuli state self.states.pop(0) # We then add it back in, with the __display_message state self.states = [self.__display_stimuli, self.__display_message] +\ self.states def __end_break(self, dt): """ Add a __display_message state into self.states to display the end of the break """ # Set on_break to False, as the break has now ended self.on_break = False # Tell the Render instance not attempt to render stimuli self.render_stimuli = False # Set the current_img to the resume_exp image self.current_img = self.render.messages['resume_exp'] # Set the shaders to not be used, bind the VBO using bind_message # and assign current_img as the texture self.__ready_texture(False, self.render.bind_message) schedule_once(self.__break_time, BREAK_INTERVAL) def __next_state(self, dt=FIX_DUR): """ Move onto the next state and run it """ self.run_state = self.states.pop(0) self.run_state() def __ready_texture(self, shader_use, bind_function): """ Set the shader use, call the binding function for the Vertex Buffer Objects and assign the texture as necessary """ # Set the use of the shaders self.__shader_use(shader_use) # Call the appropriate VBO binding function bind_function() if ENABLE_SHADER: i = self.stimulus.current[0] if shader_use: textures = [self.current_img, self.stimulus.heightmap[i], self.stimulus.normalmap[i]] else: textures = [self.current_img] for img in textures: # Assign the texture self.render.assign_texture(img, img.width, img.height) else: # Assign the texture self.render.assign_texture(self.current_img, self.current_img.width, self.current_img.height) # ------------------------------------------------------------------ # HANDLE SHADER USE # ------------------------------------------------------------------ def __shader_use(self, use): """ If the shader is enabled and is set to be used for the rendering, run it. Otherwise pass boolean value [use] to not use shaders in the rendering, even if ENABLE_SHADER is set to True """ # Store identification of stimuli or non-stimuli image rendering self.render_stimuli = use # If the shader is enabled, pass values to the shader if ENABLE_SHADER: i = self.stimulus.current[0] # Pass stimuli colormap and heightmap to shaders self.render.pass_to_shaders(self.render.shader, use, self.current_img, self.stimulus.heightmap[i], self.stimulus.normalmap[i]) # ------------------------------------------------------------------ # HANDLE RENDERING # ------------------------------------------------------------------ def __draw(self): """ Overwriting Window's own on_draw() module This will simply call upon self.render.draw() after all the states have been set """ # for i in range(0, len(self.projection.eyeshiftset)): # Set the view # self.projection.set_perspective(50.0) # projection = self.projection.set_projection_matrix(self.projection.\ # eyeshiftset[1]) # Call the general draw module in Render if self.render_stimuli: self.render.draw(self.render_stimuli, self.render.rotation['X']) # for i in [-1, 0, 1]: # for j in [0, 1, 2]: # self.render.translation['X'] = i * SCALE_X # self.render.translation['Y'] = j * SCALE_Y # self.render.draw(self.render_stimuli) self.stimuli_presented = time() else: self.render.draw() # Return success of rendering return EVENT_HANDLED def __compile_data(self, exp_ended=True): if exp_ended: total_exp_time = get_time(self.exp_start, time()) print 'The experiment ran for %s seconds' % total_exp_time compiled_data = {} for count, data in enumerate(self.data): if count < len(self.reaction_times): compiled_data[count] = {} compiled_data[count]['image'] = data[0] compiled_data[count]['height_ratio'] = data[1] compiled_data[count]['slant'] = data[2] compiled_data[count]['rt'] = self.reaction_times[count] compiled_data[count]['answer'] = self.slants[count] else: break if compiled_data: self.data = [] self.reaction_times = [] self.slants = [] path = 'session' if not exp_ended: path = 'practice' ext = '' loop = 0 while True: t = join(self.directory, '%s_%d%s.json' % (path, self.session, ext)) if not isfile(t): path = t break ext = chr(65 + loop) loop += 1 with open(path, 'wb') as f: dump(compiled_data, f)
def save_post(request, data, board, thread): board_db = Board.get_by_key_name(board) if not board_db: board_db = Board(key_name = board, thread = []) board_db.counter += 1 # create new thread new = False if thread == 'new': new = True if data.get("sage"): raise NotFound() # FIXME: move to form thread = board_db.counter posts = [] thread_db = Thread.create(thread, board) thread_db.posts = [] thread_db.subject = data.get("subject")[:SUBJECT_MAX] else: thread = int(thread) if thread in board_db.thread and not data.get("sage"): board_db.thread.remove(thread) thread_db = Thread.load(thread, board) if not thread_db: raise NotFound() if not data.get("sage"): board_db.thread.insert(0, thread) per_page = get_config('aib.ib', 'thread_per_page') pages = get_config('aib.ib', 'board_pages') board_db.thread = board_db.thread[:per_page*pages] rb = rainbow.make_rainbow(request.remote_addr, board, thread) data['rainbow'] = rb data['overlay'] = board in OVER data['text_html'] = markup( board=board, postid=board_db.counter, data=escape(data.get('text', '')), ) # save thread and post number data['post'] = board_db.counter data['thread'] = thread now = datetime.now() data['time'] = now.strftime("%Y-%m-%d, %H:%M") data['timestamp'] = int(now.strftime("%s")) img_key = data.get("key") if img_key: blob_key = blobstore.BlobKey(img_key) blob_info = blobstore.BlobInfo.get(blob_key) data['image'] = { "size" : blob_info.size, "content_type" : blob_info.content_type, "full" : images.get_serving_url(img_key), "thumb" : images.get_serving_url(img_key, 200), } for fname in OPTIONS.get(board, []): func = globals().get('option_'+fname) if func: func(request, data) thread_db.posts.append(data) db.put( (thread_db, board_db)) Cache.remove("board", board) r = Render(board, thread) r.add(data, new) r.save() deferred.defer(rss.add, board, thread, board_db.counter, data.get("text_html") ) if not new: deferred.defer( watchers_post_notify, board, thread, r.post_html, len(thread_db.posts), board_db.counter ) return board_db.counter, thread
class Game(object): def __init__(self): self.screen_size = (500,500) self.map_size = (128,128) self.tile_size = (5,5) self.world_size = (self.tile_size[0] * self.map_size[0], self.tile_size[1] * self.map_size[1]) self.grid = Grid(self.world_size[0],self.world_size[1]) GridGenerator(self.grid,Vec2(self.tile_size[0],self.tile_size[1])) pygame.init() self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode((500,500)) self.component_manager = componentmanager.ComponentManager() self.component_manager.register_component('MovementComponent', MovementComponent()) self.component_manager.register_component('ExampleComponent', ExampleComponent()) self.component_manager.register_component('TileDraw', TileDraw()) self.component_manager.register_component('InputMovementComponent', InputMovementComponent()) self.entity_manager = EntityManager() self.resource_manager = ResourceManager(os.path.join(sys.path[0], 'res')) self.resource_manager.register_loader('definition', LoadEntityDefinition) self.resource_manager.register_loader('sprite', LoadImage) self.input_manager = InputManager() self.input_manager.init_joysticks() self.entities_to_update = [] self.entities_to_input = [] self.entities_to_draw_tiles = [] def register_for_updates(self, entity): self.entities_to_update.append(entity) def register_for_input(self, entity): self.entities_to_input.append(entity) def register_for_draw_tiles(self,entity): self.entities_to_draw_tiles.append(entity) def run(self): #test_entity = Entity('test-include') character = Entity('character') self.characters = [character for m in xrange(4)] self.renderer = Render(self) self.current_camera = 0 while True: dt = self.clock.tick() / 1000.0 for e in pygame.event.get(): if e.type == pygame.QUIT: sys.exit() elif e.type == pygame.KEYDOWN: if e.key == pygame.K_TAB: self.current_camera = (self.current_camera +1)%4 if e.key == pygame.K_a: #self.cameras[self.current_camera].props.dx = 1 pass elif e.type == pygame.KEYUP: if e.key == pygame.K_a: #self.cameras[self.current_camera].props.dx = 0 pass if e.type == pygame.JOYAXISMOTION or \ e.type == pygame.JOYBALLMOTION or \ e.type == pygame.JOYBUTTONDOWN or \ e.type == pygame.JOYBUTTONUP or \ e.type == pygame.JOYHATMOTION or \ e.type == pygame.KEYDOWN or \ e.type == pygame.KEYUP: event = InputEvent(e) for entity in self.entities_to_update: if e.type == pygame.JOYAXISMOTION: entity.handle('move', event) else: entity.handle('input', event) for entity in self.entities_to_draw_tiles: entity.handle('draw-tiles',self.world_surface) for entity in self.entities_to_update: entity.handle('update', dt) self.renderer.render()
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ def status(message): message = " " + message print (time.clock()), print message status("Initializing Canvas() object.") screen = Canvas() # use default values for the Etch-a-sketch status("Initializing Render() object.") image_to_draw = Render() # defaults to NullPath #status("Loading image.") #image_to_draw.load_image() status("Setting path generator strategy.") #image_to_draw.set_path_generator(HelloWorld) image_to_draw.set_path_generator(RasterPath) status("Loading image.") image_to_draw.open_image() status("Generating path.") image_to_draw.generate_path()
def main(args): os.chdir(os.path.dirname(os.path.realpath(__file__))) desired_lang = os.environ.get('LANGUAGE', 'en')[:2] cfg = config.Parse() if 'language' in cfg: desired_lang = cfg['language'] else: cfg['language'] = desired_lang language.select(desired_lang) # Hint the window manager to put the window in the center of the screen os.putenv('SDL_VIDEO_CENTERED', '1') pygame.init() pygame.joystick.init() for i in range(pygame.joystick.get_count()): pygame.joystick.Joystick(i).init() # Ignore mouse motion (greatly reduces resources when not needed) pygame.event.set_blocked(pygame.MOUSEMOTION) pygame.mouse.set_visible(False) available_maps = glob.glob(os.path.join(MAPS_DIR, '*.map')) available_maps = [os.path.basename(m) for m in available_maps] available_maps.sort() selected = { 'players_count': 1, 'map': available_maps[0], 'exit': False, 'toggle_fullscreen': None, 'language': None, 'fullscreen': False, 'new_settings_applied': False, } render = Render(fullscreen=cfg.get('fullscreen', False)) if args.debug: render.show_fps = True while 42: selected['new_settings_applied'] = False selected = menu.main_menu(cfg, render, available_maps, selected) if selected['exit']: break if selected['toggle_fullscreen'] is not None: render.toggle_full_screen(selected['toggle_fullscreen']) selected['toggle_fullscreen'] = None continue if selected['language'] is not None: language.select(selected['language']) selected['language'] = None continue if selected['new_settings_applied']: continue pygame.mixer.init(buffer=512) game_loop( cfg, render, players_count=selected['players_count'], map_name=selected['map'] ) pygame.mixer.stop() render.quit() pygame.quit() sys.exit(0)
global g_changed g_changed = changed g_time = time.clock() def restart(): global render global point_generator point_generator = PointGenerator() point_generator.changeXFunc() point_generator.changeYFunc() if random.random() > 0.5: render.swapColors(); repaint() #main setup render = Render(g_width, g_height) pygame.mouse.set_visible(False) pygame.display.toggle_fullscreen() #create and draw first polyline restart() #main loop while True: try: #check idle time if time.clock() - g_time > 60: if g_changed: render.save() restart()
def __init__(self, config): self.__dict__ = self.__borg_state self.config = config self.api = GW2_API(config) self.ds = DataStore(config) self.render = Render(config)
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ def status(message): message = " " + message print (time.clock()), print message # screen = Canvas() # use default values for the Etch-a-sketch status("Initializing Render() object.") image_to_draw = Render() status("Setting path generator strategy.") #image_to_draw.set_path_generator(HelloWorld) image_to_draw.set_path_generator(RasterPath) status("Loading image.") image_to_draw.open_image() status("Generating path.") image_to_draw.generate_path() # status("Closing image.") # image_to_draw.close_image()
def save_post(request, data, board, thread): board_db = Board.get_by_key_name(board) if not board_db: board_db = Board(key_name = board, thread = []) board_db.counter += 1 # create new thread new = False if thread == 'new': new = True if data.get("sage"): raise NotFound() # FIXME: move to form thread = board_db.counter posts = [] thread_db = Thread.create(thread, board) thread_db.posts = [] thread_db.subject = data.get("subject")[:SUBJECT_MAX] else: thread = int(thread) #if thread not in board_db.thread: # raise NotFound() if thread in board_db.thread and not data.get("sage"): board_db.thread.remove(thread) thread_db = Thread.load(thread, board) if not thread_db: raise NotFound() if not data.get("sage"): board_db.thread.insert(0, thread) board_db.thread = board_db.thread[:THREAD_PER_PAGE*BOARD_PAGES] rb = rainbow.make_rainbow(request.remote_addr, board, thread) data['rainbow'] = rb data['rainbow_html'] = rainbow.rainbow(rb) data['text_html'] = markup( board=board, postid=board_db.counter, data=escape(data.get('text', '')), ) # FIXME: move to field data['name'] = data.get("name") or "Anonymous" # save thread and post number data['post'] = board_db.counter data['thread'] = thread now = datetime.now() data['time'] = now.strftime("%Y-%m-%d, %H:%M") data['timestamp'] = int(now.strftime("%s")) img_key = data.get("key") if img_key: blob_key = blobstore.BlobKey(img_key) blob_info = blobstore.BlobInfo.get(blob_key) data['image'] = { "size" : blob_info.size, "content_type" : blob_info.content_type, "full" : images.get_serving_url(img_key), "thumb" : images.get_serving_url(img_key, 200), } for fname in board_options.get(board, []): func = globals().get('option_'+fname) if func: func(request, data) thread_db.posts.append(data) db.put( (thread_db, board_db)) Cache.delete( ( dict(Board=board), ) ) memcache.set("threadlist-%s" % board, board_db.thread) memcache.set("post-%s-%d" %(board, board_db.counter), data) r = Render(board, thread) r.add(data, new) r.save() key = "update-thread-%s-%d" % (board, thread) if not new: send = { "html" : r.post_html, "evt" : "newpost" , "count" : len(thread_db.posts), "last" : board_db.counter, } watchers = memcache.get(key) or [] for person in watchers: logging.info("send data to key %s" % (person+key)) channel.send_message(person+key, dumps(send)) return board_db.counter, thread
def main(): from modules.path import Path from modules.helpers import get_limit_indices from modules.export import Exporter from render import Render from fn import Fn fn = Fn(prefix='./res/') exporter = Exporter() render = Render(SIZE, BACK, FRONT) render.set_line_width(LINE_WIDTH) #the = 0.5*PI*ones(NMAX) xy = column_stack((ones(NMAX)*START_X,linspace(START_Y,STOP_Y,NMAX))) draw_start,draw_stop = get_limit_indices(xy,top=START_Y,bottom=STOP_Y) # last_xy = xy[draw_start:draw_stop,:] # draw_circles = render.circles for i in count(): ## gradient-like distribution of lines pix = sqrt(1+i)*ONE ## linear distribution of lines #pix = PIX_BETWEEN*ONE path = Path(xy,pix) path.trace(-PIHALF) path.noise() path.interpolate(int(pix/ONE)*2) xy = path.xy_interpolated ## remove nodes above and below canvas canvas_start,canvas_stop = get_limit_indices(xy,top=0.,bottom=1.) xy = xy[canvas_start:canvas_stop,:] ## render nodes above STOP_Y and below START_Y draw_start,draw_stop = get_limit_indices(xy,top=START_Y,bottom=STOP_Y) #draw_circles(xy[draw_start:draw_stop,:],\ #ones(draw_stop-draw_start)*ONE) render.path(xy[draw_start:draw_stop,:]) exporter.add(xy[draw_start:draw_stop,:]) xmax = xy[:,0].max() if (xmax>STOP_X): break print 'num',i,'points', len(path.xy_circles),'x', xmax name = fn.name() render.transparent_pix() render.write_to_png(name+'.png') exporter.export(name+'.2obj')