def init_pygame(self, window_size=()): import render if window_size: render.window_size = window_size self.render = render.Render(self) Tasklet(self.render.initialize)() Tasklet(self.render.loop)()
def get_ck_soup(url, tag=None, selenium=False): if not selenium: r = render.Render(url) html = unicode(r.frame.toHtml()) return BeautifulSoup(html, "html.parser") else: return BeautifulSoup(render.selenium_render(url, tag), "html.parser")
def main(): # Creates render and profiler render = rn.Render() render.set_render_folder_path(RENDER_FOLDER_PATH) profiler = core.Profiler() # Creates command dispatcher (local or remote) cmd_dispatcher = get_command_dispatcher() # Initialize dispatcher (context and scene) cmd_dispatcher.set_context(time=START_TIME, frame_dt=FRAME_TIMESTEP, num_substep=NUM_SUBSTEP, num_frames=NUM_FRAMES) scenes.rabbit.assemble(cmd_dispatcher, render) #scenes.cat.assemble(cmd_dispatcher, render) #scenes.multiwire.assemble(cmd_dispatcher, render) #scenes.beam.assemble(cmd_dispatcher, render) #scenes.wire.assemble(cmd_dispatcher, render) #scenes.rabbit_cat.assemble(cmd_dispatcher, render) # Simulate frames for frame_id in range(NUM_FRAMES + 1): profiler.clear_logs() if frame_id == 0: cmd_dispatcher.initialize() else: cmd_dispatcher.solve_to_next_frame() render.show_current_frame(cmd_dispatcher, frame_id) render.export_current_frame(str(frame_id).zfill(4) + " .png")
async def join(ctx, code=None): index = -1 for m in range(0, len(savegame[0])): if savegame[0][m][0] == code: index = m if index == -1: await ctx.author.send("Please enter a valid code.") else: savegame[0][index][1].append([ctx.author.id, False, 0, 0, []]) savegame[1].append([ctx.author.id, code]) await ctx.author.send("The game will start shortly") userindex = -1 for m in range(0, len(savegame[0][index][1])): if savegame[0][index][1][m][0] == ctx.author.id: userindex = m while not savegame[0][index][2][0]: await asyncio.sleep(0.1) while True: await asyncio.sleep(waitperframe) render.Render(ctx, savegame[0][index][1][userindex][2], savegame[0][index][1][userindex][3], "VIEW") with open("./TEMP/" + str(ctx.author.id) + "GETMAPTESTTEMP.png", 'rb') as fp: await ctx.author.send(file=discord.File(fp, 'FullShipget.jpg')) if savegame[0][index][2][0]: break await ctx.author.send(Messages["Host_gameend"])
def main(): print("Starting...") run = True blue = True hero = Hero() spider = Spider() button = subButtons.Attack() menuIMG = p.image.load("assets/menuBG.png") SCREEN.blit(menuIMG, (0, 520)) renderScr = render.Render(SCREEN, hero, spider) while run: SCREEN.fill((0, 0, 0)) renderScr.renderMenu() renderScr.checkHoover() renderScr.renderHealth(SCREEN) # Deal with events for e in p.event.get(): if e.type == p.QUIT: run = False if e.type == p.MOUSEBUTTONUP: renderScr.checkClicked() if e.type == p.KEYDOWN and e.key == p.K_ESCAPE: run = False p.display.flip() #Updates display CLOCK.tick(60) #Framerate
async def creategame(ctx): CODE = "DONE" savegame[0].append([CODE, [[ctx.author.id, True, 0, 0, []]], [False]]) savegame[1].append([ctx.author.id, CODE]) code = CODE index = -1 for m in range(0, len(savegame[0])): if savegame[0][m][0] == code: index = m userindex = -1 for m in range(0, len(savegame[0][index][1])): if savegame[0][index][1][m][0] == ctx.author.id: userindex = m while not savegame[0][index][2][0]: await asyncio.sleep(0.1) while True: await asyncio.sleep(waitperframe) render.Render(ctx, savegame[0][index][1][userindex][2], savegame[0][index][1][userindex][3], "VIEW") with open("./TEMP/" + str(ctx.author.id) + "GETMAPTESTTEMP.png", 'rb') as fp: await ctx.author.send(file=discord.File(fp, 'FullShipget.jpg')) if savegame[0][index][2][0]: break await ctx.author.send(Messages["Host_gameend"])
def __Draw(self, xxx_todo_changeme): (width_hint, height_hint) = xxx_todo_changeme surf = pygame.Surface((width_hint, height_hint)) bbox = Rect(0, 0, width_hint, height_hint) extra.Tile_Texture(surf, "006metal.jpg", surf.get_rect()) margin = 8 w = bbox.width - (margin * 2) th = None y = margin + bbox.top control_rects = [] max_width = 0 first_item = True for (num, name, hotkeys) in self.options: if (name == None): # a gap if (first_item): img = resource.Load_Image("header.jpg") img_r = img.get_rect() img_r.center = bbox.center img_r.top = y surf.blit(img, img_r.topleft) extra.Edge_Effect(surf, img_r) max_width = img_r.width + (margin * 2) y += img_r.height y += margin * 2 continue txt = render.Render(name, 18, (50, 200, 20), (200, 200, 0)) if (th == None): th = txt.get_rect().height + (margin * 2) tw = txt.get_rect().width + (margin * 2) if (tw > max_width): max_width = tw x = bbox.left + margin r = Rect(x, y, w, th) x += self.Justify(w, txt.get_rect().width) extra.Tile_Texture(surf, "greenrust.jpg", r) extra.Edge_Effect(surf, r) self.Enhancement_Interface(surf, num, r, margin) surf.blit(txt, (x, y + margin - 1)) y += th + margin control_rects.append((num, r)) first_item = False # Finalise drawing extra.Line_Edging(surf, bbox, True) return (surf, control_rects, (max_width, y))
def render(self): first_person_render = self._base_env.render(mode="rgb_array") top_render = self._base_env.render(mode="rgb_array", view="top") image = render.concatenate([ Image.fromarray(first_person_render), Image.fromarray(top_render) ], "horizontal") image.thumbnail((320, 240)) image = render.Render(image) image.write_text("Env ID: {}".format(self.env_id)) return image
def __init__(self, settings, gui): if isinstance(settings, Config.Config_World): self.settings = settings self.gui = gui if isinstance(settings.screen, Config.Config_Screen): render.start(self.settings.screen.x_pos, self.settings.screen.y_pos, self.settings.screen.x_size, self.settings.screen.y_size, 1000) # creating city grid for b in range(2): self.x_location += 100 self.y_location = 90 for z in range(3): self.y_location -= 20 # self.x_location += 20 for i in range(2): self.y_location -= 10 self.x_location -= 20 self.c = random.randint(0, 1) for t in range(2): self.c2 = random.randint(0, 1) b_location = P3.P3(self.x_location, self.y_location, 0) # print(b_location) buildings.extend([ Building.Building(b_location, 10, random.randrange(20, 65), 10, (self.c, 0, self.c2)) ]) self.x_location += 10 if isinstance(settings, Config.Config_World): flock = settings.flocks[0] if isinstance(flock, Config.Config_Flock): self.F1 = Flock.Flock(flock.count, World.make_force_field(buildings), flock.center, flock.radius) self.render = render.Render(self.F1) gui.set_tick_method(self.tick)
def play(players, print_info=True, animate_render=True, util={}): g = game.Game(*players, record_turns=True, util=util) for i in xrange(settings.max_turns): if print_info: print(' running turn %d ' % (g.turns + 1)).center(70, '-') g.run_turn() if print_info: # only import render if we need to render the game; # this way, people who don't have tkinter can still # run headless import render render.Render(g, game.settings, animate_render) print g.history return g.get_scores()
def Draw(self, output, rect): # Draw label text on left hand side r = self.surface.get_rect() r.center = rect.center r.left = rect.left output.blit(self.surface, r.topleft) # Draw label area r2 = Rect((0, 0), self.label_box_size) r2.center = rect.center r2.right = rect.right pygame.draw.rect(output, BLACK, r2) # Obtain & draw label text (value_text, colour) = self.get_value_fn() surf = render.Render(value_text, LABEL_SIZE, colour) r3 = surf.get_rect() r3.center = r2.center r3.right = r2.right output.blit(surf, r3.topleft)
def main(): print("===============================================================") print("========================= FORTREE ===========================") print("===============================================================") ft = "" ft = Fortree() ft.print_var() if (ft.fortree_type == "CALL_TREE" or ft.fortree_type == "DEF_TREE" or ft.fortree_type == "DEP_TREE"): ft.build_tree() #clean duplicates ft.tree_arr = np.unique(ft.tree_arr, axis=0) if (np.size(ft.tree_arr) > 2): # write tree ftree = rd.Render(ft.output_name) ftree.write_header() if ft.show_only_def: for element in ft.tree_arr: if (ft.fortree_type == "CALL_TREE" and element[2] != "ND"): ftree.write(element[0], element[1]) else: ftree.write(element[0], element[1]) else: for element in ft.tree_arr: ftree.write(element[0], element[1]) ftree.write_footer() ftree.render() else: print("No child.") elif (ft.fortree_type == "CALL_GRAPH"): ft.build_graph()
def play(players, print_info=True, animate_render=True, play_in_thread=False): if play_in_thread: g = game.ThreadedGame(*players, print_info=print_info, record_actions=True, record_history=True) else: g = game.Game(*players, print_info=print_info, record_actions=True, record_history=True) if print_info: # only import render if we need to render the game; # this way, people who don't have tkinter can still # run headless import render g.run_all_turns() render.Render(g, game.settings, animate_render) print g.history return g.get_scores()
#!/usr/bin/env python3 import sys import storage import scanner import render TITLE = 'Test Cases Report Generator' if __name__ == '__main__': print(TITLE) if len(sys.argv) >= 2: exclude_dirs = sys.argv[2:] root_dir = sys.argv[1] _storage = storage.Storage() _scanner = scanner.Scanner(_storage, root_dir, exclude_dirs) _render = render.Render(_storage, root_dir, exclude_dirs) result = _render.render() with open('report.html', 'w') as out: out.write(result) out.flush() else: print( 'Error: at least one parameter should be passed - a path to directory with tests to scan.' 'All the following parameters are subpaths to be excluded.')
async def viewmap(ctx, x, y): render.Render(ctx, int(x), int(y), "VIEW") with open("./TEMP/" + str(ctx.author.id) + "GETMAPTESTTEMP.png", 'rb') as fp: await ctx.send(file=discord.File(fp, 'FullShipget.jpg'))
import render import json if __name__ == '__main__': user_config_file = open('./user_config.json', 'r', encoding='utf-8') system_config_file = open('./system_config.json', 'r', encoding='utf-8') user_json = json.loads(user_config_file.read()) system_json = json.loads(system_config_file.read()) user_config_file.close() system_config_file.close() r = render.Render(user_json, system_json) r.build() # print(r.blog_list)
def main(): #################Initializing############# global touch, running pygame.init() info = pygame.display.Info() screen_width, screen_height = info.current_w, info.current_h screen_width = 1000 screen_height = 600 renderer = render.Render(screen_width, screen_height, False) screen_width, screen_height = renderer.getDimHalf() pygame.display.set_caption("Hopper") clock = pygame.time.Clock() space = pymunk.Space() screen = renderer.get_render_target() space.gravity = ( 0.0, -900.0 ) ###################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! draw_options = pymunk.pygame_util.DrawOptions(screen) ########## Adding system to the world################### ################################################################### #############Collision handler################## ch = space.add_collision_handler(0, 2) ch.pre_solve = detect_touching ch2 = space.add_collision_handler(0, 1) ch2.post_solve = end_game ###############Control variables initialization##### Torque = 0 A = open('maps//1302_2.xml', 'r') All = [] map = [] colorMap = [] doc = xmltodict.parse(A.read()) for i in doc['map']['Hopper']: X = float(doc['map']['Hopper']['position']['x']) Y = float(doc['map']['Hopper']['position']['y']) [body, contact, spring] = add_player(space, (X, Y)) for i in doc['map']['Polygon']: Temp = [] List = [0, 1, 2, 3] for j in List: Temp.append( (float(i['vertices']['x'][j]), float(i['vertices']['y'][j]))) friction = (float(i['params']['friction'])) red = (float(i['params']['red'])) green = (float(i['params']['green'])) blue = (float(i['params']['blue'])) colorMap.append((red, green, blue)) add_object(space, Temp, friction) map.append(Temp) A.close() replay = True All = [] cnt = 0 length = 0 #pygame.mouse.set_visible(0) NewMousePos = 0 Sensitivity = 1 / screen_width Random = 0 cubic = add_cubic(space, (300, 300)) while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) elif event.type == KEYDOWN and event.key == K_ESCAPE: sys.exit(0) MousePos = pygame.mouse.get_pos()[0] RightButton = pygame.mouse.get_pressed()[2] LeftButton = pygame.mouse.get_pressed()[0] Jump = pygame.key.get_pressed()[K_SPACE] if (replay): pass #A.write(str(MousePos)+","+str(RightButton)+","+str(Jump)+"\n") else: if (cnt < flength): MousePos = int(All[cnt][0]) RightButton = int(All[cnt][1]) Jump = int(All[cnt][2]) cnt += 1 Angle = contact.angle AngleSpeed = contact.angular_velocity if (RightButton): body.position = (X, Y) contact.position = (X, Y - 100) running = True body.velocity = (0, 0) contact.velocity = (0, 0) contact.angle = 0 contact.angular_velocity = 0 NewMousePos = 0 jump = Jump * 20 deltaVector = body.position - contact.position length = deltaVector.length NewMousePos += pygame.mouse.get_rel()[0] print(body.velocity.x) if (touch): Random = random.uniform(-1, 1) cK = (deltaVector.normalized().cross((-1, 0))) if (cK < 0.3): cK = 0.3 cK = 1 spring.damping = 200 spring.rest_length = 100 + (20 / cK + jump) if (LeftButton): spring.rest_length = 100 # + (20/cK + jump) Torque = 0 else: spring.rest_length = 100 spring.damping = 600 DesiredSpeed = (MousePos - screen_width) / screen_width DesiredDisplacement = (-body.velocity[0] / 1000 + DesiredSpeed) if (abs(DesiredDisplacement) > 0.98): DesiredDisplacement = math.copysign( 0.98, DesiredDisplacement) ######Linear controller DesiredAngle = math.asin(DesiredDisplacement) ErrorAngle = DesiredAngle + Angle Torque = ErrorAngle * 1000000 + AngleSpeed * 100000 if (abs(Torque) > 10000000): Torque = math.copysign(10000000, Torque) if not running: Torque = 0 spring.rest_length = 100 #Torque = 0 #print(Torque) applyTorque(body, Torque) applyTorque(contact, -Torque) ################################################################################## touch = 0 Distance = 0 # space.debug_draw(draw_options) renderer.setCameraPos(body.position[0], -body.position[1]) renderer.setCameraAffection(1) renderer.setColor(223, 162, 12) renderer.drawCircle(body.position[0], -body.position[1], 20) renderer.drawCircle(contact.position[0], -contact.position[1], 4) renderer.setColor(221, 5, 223) newVector = [] # for v in [(-50,-50),(-50,50),(50,50),(50,-50)]: # v = Vec2d(v[0],v[1]) # x,y = v.rotated(cubic.angle) # newVector.append(Vec2d(cubic.position.x+x+500,300-cubic.position.y-y)) # pygame.draw.polygon(renderer.get_render_target(),(0,255,0),newVector) for v in [(-50, -50), (-50, 50), (50, 50), (50, -50)]: v = Vec2d(v[0], v[1]) + cubic.position newVector.append(v) renderer.drawPolygon(newVector[0][0], newVector[0][1], newVector[1][0], newVector[1][1], newVector[2][0], newVector[2][1], newVector[3][0], newVector[3][1]) #renderer.drawLine(body.position[0],-body.position[1],contact.position[0],-contact.position[1]) Rotation_vector = contact.rotation_vector Rotation_vector.rotate_degrees(-90) renderer.drawLine(contact.position[0] - Rotation_vector[0] * length, -contact.position[1] + Rotation_vector[1] * length, contact.position[0], -contact.position[1]) renderer.setColor(86, 125, 70) drawMap(renderer, map, colorMap) renderer.draw(running) draw_mouse_displacement(renderer.get_render_target(), MousePos, screen_width, screen_height) space.step(0.016666666666666666) clock.tick(60)
class Menu: def __init__(self, menu_options, force_width=0): self.options = menu_options self.control_rects = [] self.hover = None self.bbox = None self.selection = None self.update_required = True width_hint = height_hint = 10 if (force_width > 0): width_hint = force_width # Two attempts at drawing required. (discard1, discard2, (width_hint, height_hint)) = self.__Draw( (width_hint, height_hint)) if (width_hint < 150): width_hint = 150 if (force_width > 0): width_hint = force_width (self.surf_store, self.control_rects, (discard1, discard2)) = self.__Draw((width_hint, height_hint)) self.bbox = Rect(0, 0, width_hint, height_hint) def Get_Command(self): return self.selection def Select(self, snum): self.update_required = True self.selection = snum def Mouse_Move(self, spos): if ((spos == None) or (not self.bbox.collidepoint(spos))): self.hover = None return self.update_required = True (x, y) = spos old_sel = self.hover self.hover = None x -= self.bbox.left y -= self.bbox.top for (num, r) in self.control_rects: if (r.collidepoint(x, y)): self.hover = num if (old_sel != self.hover): sound.FX("click_s") return def Mouse_Down(self, spos): self.Mouse_Move(spos) if (self.hover != None): self.selection = self.hover sound.FX("click") def Key_Press(self, k): for (num, name, hotkeys) in self.options: if ((hotkeys != None) and (k in hotkeys)): self.selection = num self.update_required = True sound.FX("click") return def Draw(self, output, centre=None): if (self.update_required): self.update_required = False if (centre == None): self.bbox.center = output.get_rect().center else: self.bbox.center = centre self.bbox.clamp_ip(output.get_rect()) output.blit(self.surf_store, self.bbox.topleft) for (num, r) in self.control_rects: r = Rect(r) r.top += self.bbox.top r.left += self.bbox.left if (num == self.selection): pygame.draw.rect(output, (255, 255, 255), r, 1) elif (num == self.hover): pygame.draw.rect(output, (0, 180, 0), r, 1) def __Draw(self, (width_hint, height_hint)): surf = pygame.Surface((width_hint, height_hint)) bbox = Rect(0, 0, width_hint, height_hint) extra.Tile_Texture(surf, "006metal.jpg", surf.get_rect()) margin = 8 w = bbox.width - (margin * 2) th = None y = margin + bbox.top control_rects = [] max_width = 0 first_item = True for (num, name, hotkeys) in self.options: if (name == None): # a gap if (first_item): img = resource.Load_Image("header.jpg") img_r = img.get_rect() img_r.center = bbox.center img_r.top = y surf.blit(img, img_r.topleft) extra.Edge_Effect(surf, img_r) max_width = img_r.width + (margin * 2) y += img_r.height y += margin * 2 continue txt = render.Render(name, 18, (50, 200, 20), (200, 200, 0)) if (th == None): th = txt.get_rect().height + (margin * 2) tw = txt.get_rect().width + (margin * 2) if (tw > max_width): max_width = tw x = bbox.left + margin r = Rect(x, y, w, th) x += self.Justify(w, txt.get_rect().width) extra.Tile_Texture(surf, "greenrust.jpg", r) extra.Edge_Effect(surf, r) self.Enhancement_Interface(surf, num, r, margin) surf.blit(txt, (x, y + margin - 1)) y += th + margin control_rects.append((num, r)) first_item = False # Finalise drawing extra.Line_Edging(surf, bbox, True) return (surf, control_rects, (max_width, y))
# command line argument management if len(sys.argv) >= 4: nickname = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) elif len(sys.argv) == 3: host = 'localhost' nickname = sys.argv[1] port = int(sys.argv[2]) elif len(sys.argv) == 2: host = 'localhost' port = 1337 nickname = sys.argv[1] else: host = 'localhost' port = 1337 nickname = raw_input('Veuillez indiquer votre nickname : ') # queues initialization: communication between network threads and game logic thread (which is in render) send_queue = Queue.Queue() receive_queue = Queue.Queue() # network connection network.connection_start((host, port), send_queue, receive_queue) print('network engine is running') # render's operations have to be in the main thread. display = render.Render(send_queue, receive_queue, '../shared/village.map', nickname) display.run()
return False window.fill(BACKGROUND_COLOR) message_to_screen("Snake Game", [200, 150], (0, 0, 0), True) message_to_screen("Press S to start the Game, press Q to quit the Game", [50, 210], (0, 0, 0), True) pygame.display.update() clock.tick(5) # Create all the game object snake = gameobject.Snake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2) lof = gameobject.ListOfFruit() lob = gameobject.ListOfBomb() h_box = hitbox.hitbox() g = game.Game(snake, lof, lob) render_g = render.Render() gameLoop = start() while gameLoop: window.fill(BACKGROUND_COLOR) render_g.render_game(window, g) if snake.snake_body[0].location.x < 0 or snake.snake_body[0].location.y < 0 or snake.snake_body[0].location.x > SCREEN_WIDTH or snake.snake_body[0].location.y > SCREEN_HEIGHT: gameLoop = start() if gameLoop == True: snake = gameobject.Snake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2) lof = gameobject.ListOfFruit() lob = gameobject.ListOfBomb() h_box = hitbox.hitbox() g = game.Game(snake, lof, lob)
def doMonitor(): try: print "Starting ..." sys.stdout.flush() p = protocol.Protocol(config.getSerialDevice(), config.getProtocolVersionsDirectory(), config.getNewStyleSerialCommunication()) s = storage.Storage(config.getDatabaseFile()) j = json.Json(os.path.join(config.getRenderOutputPath(), "actual_values.json")) r = render.Render(config.getDatabaseFile(), config.getRenderOutputPath()) c = None # ThreadedExec for copyCommand aReport = report.Report(config) t = thresholdMonitor.ThresholdMonitor(config, aReport) print "Up and running" sys.stdout.flush() counter = 0 renderInterval = config.getRenderInterval() copyCommand = config.getCopyCommand() copyInterval = config.getCopyInterval() while 1: startTime = time.time() try: values = p.query() except Exception, e: # log the error and just try it again in 120 sec - sometimes the heatpump returns an error and works # seconds later again # If the query takes longer than 2 minutes, we get a negative value ... maybe a problem in rare contitions logError(e) t.gotQueryError() time.sleep(120 - (time.time() - startTime)) continue # store the stuff s.add(values) # write the json file everything, as it does not use much cpu j.write(values) # render it if the time is right ... it takes a lot of cpu on small embedded systems if counter % renderInterval == 0: r.render() # upload it somewhere if it fits the time if copyCommand and counter % copyInterval == 0: if c and c.isAlive(): print "Error: External copy program still running, cannot start it again" sys.stdout.flush() else: c = threadedExec.ThreadedExec(copyCommand) c.start() counter += 1 # at last check the values if something needs to reported t.check(values) # lets make sure it is aways 60 secs interval, no matter how long the last run took sleepTime = 61 - (time.time() - startTime) if sleepTime < 0: print "System is too slow for 60 sec interval by %d seconds" % abs(int(sleepTime)) else: time.sleep(sleepTime) except Exception, e: # make sure the error got logged logError(e)
render.SetupScalebarLegend(location=(65.0, -33.0, 0.0), fontSize=fontSize, length=10) # Find out paths matName = os.path.splitext(matPath.split("/")[-1])[0] if "/output/" + matName in matPath: simulationPath = matPath[:matPath.index("/output/" + matName)] # Render persp render.CameraPerspSetup(location=[25.0, -80.0, 70.0], rotation=[0.8, 0.0, 0]) bpy.data.scenes[ 'Scene'].render.filepath = simulationPath + "/render_persp/" + matName + ".png" if not os.path.isdir(simulationPath + "/render_persp"): os.mkdir(simulationPath + "/render_persp") render.Render() # Annotate persp render pngPath = bpy.data.scenes['Scene'].render.filepath growthIter = int(re.match('g(\d{4})r\d{4}', matName).group(1)) relaxationIter = int(re.match('g\d{4}r(\d{4})', matName).group(1)) subprocess.call([ 'convert', '-antialias', '-pointsize', '20', '-font', 'courier-bold', '-annotate', '0x0+30+50', "{:<18} {:>6.2f} h\n{:<18} {:>6.1f} s".format( 'Growth time:', growthIter * growthTimeStep / 3600.0, 'Relaxation time:', relaxationIter * relaxationTimeStep), pngPath, pngPath ]) # Save bpy.ops.wm.save_as_mainfile(filepath=simulationPath + "/render_persp/" +
# -*- coding: utf-8 -*- import render render = render.Render() print render.getDom("https://detail.tmall.com/item.htm?id=540638557308", "true", 5) # print render.getDom("http://www.163.com","true",5)
import test_128 os.environ['SDL_VIDEO_WINDOW_POS'] = f'{(tk.Tk().winfo_screenwidth() - SETTINGS.WIDTH) // 2},' \ f'{(tk.Tk().winfo_screenheight() - SETTINGS.HEIGHT) // 4}' pygame.init() pygame.display.set_caption('Ray casting') sc = pygame.display.set_mode(SETTINGS.SIZE) sc_map = pygame.Surface(SETTINGS.map_size) clock = pygame.time.Clock() pygame.mouse.set_visible(False) map = map.Map() player = player_test.TestPlayer(map.flat_map) render = render.Render(sc, sc_map) npc_0 = npc.NPC(sc, (4062, 1270), 'bruda') npc_1 = npc.NPC(sc, (3936, 570), 'bruda_1') npc_2 = npc.NPC(sc, (4417, 554), 'bruda_2') npc_3 = npc.NPC(sc, (721, 841), 'bruda_3') npc_4 = npc.NPC(sc, (719, 595), 'bruda_4') ray_cast = raycast_mp.RayCast(map.map) with Pool(processes=4) as pool: fps = [] t = time.time() for i, v in enumerate(test_128.test_list, 0):
def __init__(self, text, colour): Space_Item.__init__(self, 0) self.text = text self.surface = render.Render(text, LABEL_SIZE, colour) (self.width, self.height) = self.surface.get_rect().size
def main(): #################Initializing############# global touch, running pygame.init() info = pygame.display.Info() screen_width, screen_height = info.current_w, info.current_h screen_width = 1000 screen_height = 600 renderer = render.Render(screen_width, screen_height, False) screen_width, screen_height = renderer.getDimHalf() pygame.display.set_caption("Hopper") clock = pygame.time.Clock() space = pymunk.Space() space.gravity = ( 0.0, -900.0 ) ###################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ########## Adding system to the world################### ################################################################### #############Collision handler################## ch = space.add_collision_handler(0, 2) ch.post_solve = detect_touching ch2 = space.add_collision_handler(0, 1) ch2.post_solve = end_game ###############Control variables initialization##### Torque = 0 A = open('maps//1302_1.xml', 'r') All = [] map = [] colorMap = [] doc = xmltodict.parse(A.read()) for i in doc['map']['Hopper']: X = float(doc['map']['Hopper']['position']['x']) Y = float(doc['map']['Hopper']['position']['y']) [body, contact, spring] = add_player(space, (X, Y)) for i in doc['map']['Polygon']: Temp = [] List = [0, 1, 2, 3] for j in List: Temp.append( (float(i['vertices']['x'][j]), float(i['vertices']['y'][j]))) friction = (float(i['params']['friction'])) red = (float(i['params']['red'])) green = (float(i['params']['green'])) blue = (float(i['params']['blue'])) colorMap.append((red, green, blue)) add_object(space, Temp, friction) map.append(Temp) replay = True All = [] cnt = 0 length = 0 if (replay): A = open('replay.txt', 'w') else: A = open('replay.txt', 'r') Temp = A.read().splitlines() for i in Temp: All.append(i.split(',')) flength = len(All) cnt = 0 #pygame.mouse.set_visible(0) NewMousePos = 0 Sensitivity = 1 / screen_width while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) A.close() elif event.type == KEYDOWN and event.key == K_ESCAPE: sys.exit(0) A.close() MousePos = pygame.mouse.get_pos()[0] RightButton = pygame.mouse.get_pressed()[2] Jump = pygame.key.get_pressed()[K_SPACE] if (replay): A.write( str(MousePos) + "," + str(RightButton) + "," + str(Jump) + "\n") else: if (cnt < flength): MousePos = int(All[cnt][0]) RightButton = int(All[cnt][1]) Jump = int(All[cnt][2]) cnt += 1 Angle = contact.angle AngleSpeed = contact.angular_velocity if (RightButton): body.position = (X, Y) contact.position = (X, Y - 100) running = True body.velocity = (0, 0) contact.velocity = (0, 0) contact.angle = 0 contact.angular_velocity = 0 NewMousePos = 0 jump = Jump * 20 deltaVector = body.position - contact.position length = deltaVector.length NewMousePos += pygame.mouse.get_rel()[0] if (touch): cK = (deltaVector.normalized().cross((-1, 0))) if (cK < 0.7): cK = 0.7 spring.damping = 200 spring.rest_length = 100 + 20 / cK + jump Torque = 0 else: spring.rest_length = 100 spring.damping = 600 DesiredSpeed = (MousePos - screen_width) / screen_width DesiredDisplacement = (-body.velocity[0] / 1000 + DesiredSpeed) if (abs(DesiredDisplacement) > 0.98): DesiredDisplacement = math.copysign( 0.98, DesiredDisplacement) ######Linear controller DesiredAngle = math.asin(DesiredDisplacement) ErrorAngle = DesiredAngle + Angle Torque = ErrorAngle * 1000000 + AngleSpeed * 70000 #1000000 if (abs(Torque) > 10000000): Torque = math.copysign(10000000, Torque) if not running: Torque = 0 spring.rest_length = 100 #Torque = 0 applyTorque(body, Torque) applyTorque(contact, -Torque) ################################################################################## touch = 0 Distance = 0 renderer.setCameraPos(body.position[0], -body.position[1]) renderer.setCameraAffection(1) renderer.setColor(223, 162, 12) renderer.drawCircle(body.position[0], -body.position[1], 20) renderer.drawCircle(contact.position[0], -contact.position[1], 4) renderer.setColor(221, 5, 223) renderer.drawLine(body.position[0], -body.position[1], contact.position[0], -contact.position[1]) renderer.setColor(86, 125, 70) drawMap(renderer, map, colorMap) renderer.draw(running) draw_mouse_displacement(renderer.get_render_target(), MousePos, screen_width, screen_height) space.step(0.016666666666666666) clock.tick(60) print(clock.get_fps())
dest="distance_as_color", default=False) parser.add_option("--dist_range", type="int", dest="dist_range", default=30) (options, args) = parser.parse_args() # print(options) with open(options.scene, 'r', encoding='utf8') as yaml_file: cfg = yaml.load(yaml_file) camera = camera.Camera() camera.load(cfg['camera']) camera.init() scene = scene.Scene(camera) scene.load(cfg['scene']) color_mode = utils.ColorModes.UNIFORM if options.normal_as_color is True: color_mode = utils.ColorModes.NORMAL elif options.distance_as_color is True: color_mode = utils.ColorModes.DISTANCE render = render.Render( np.array([options.resolution_x, options.resolution_y]), options.trace_depth, scene, color_mode, options.dist_range) render.render() # render.draw() render.save(options.output)