def init_sim(): global positions, goal_velocities, velocities global rad positions1, goal_velocities1, velocities1 = add_crowd(num) positions = positions1 goal_velocities = goal_velocities1 velocities = velocities1 # for i in range(5): # add_walker() # colliding() # print('positions') # print(positions) # intersecting() # add_crowd(int(num), ((0, s / 3.), (s / 3., 2. * s / 3.)), 0) # add_walker(((2. * s / 3, s / 3.), (s, 2. * s / 3.)), 0, (-1.5, 0)) # add_crowd(int(num), ((0, s / 3.), (s / 3., 2. * s / 3.)), 0) # add_walker(((s / 3., 0), (2. * s / 3., s / 5.)), 3.14 / 2., (0, 1.5)) # add_walker(((0, s / 2.), (0, s / 2.)), None, (1, 0)) # add_walker(((s, s / 2.), (s, s / 2.)), None, (-1, 0)) draw.init() draw.set_x_scale(0, env_size) draw.set_y_scale(0, env_size)
def start(): global screen global clock global quit global world global goals global players global camps pygame.init() screen = pygame.display.set_mode((world.width, world.height)) clock = pygame.time.Clock() random.seed(42) # initialize goals goals = [Goal(world.random_position()) for _ in range(0, num_goals)] # find ais and initialize players players = [] load_players() reset() # set up camps camps = world.generate_camps(players) # prepare graphics draw.init(players) quit = False main_loop()
def __init__(self): self.board = 0 self.mem = {} self.sol = {} self.intel = 0.90 draw.init() draw.showLoading() self.solve(0) #solves the whole board
def main(): """ Fonction principale, lançant tout le programme selon la configuration donnée. La configuration du programme est disponible dans le fichier `settings.yaml`. """ print("""Lancement du programme Assurez-vous que toutes les dépendances utilisées soient installées sur votre ordinateur ; si besoin entrez `pip install -r requirements.txt` dans votre console """) # Chargement de la configuration global SETTINGS try: SETTINGS = load_from_filename("settings.yaml") except AssertionError as e: print("Erreur lors du chargement de la configuration :\n" + e.args[0]) return # Démarrage du debug if SETTINGS.debug_mode: pr = cProfile.Profile() pr.enable() draw.init() pygame.init() screen = pygame.display.set_mode(SETTINGS.screen_size) pygame.display.set_caption("TIPE") circuit = circuit_creation(SETTINGS) if SETTINGS.manual_control: manual_loop(screen, circuit) else: last_network = AI_loop(screen, circuit) if SETTINGS.autosave: BackupManager().create(network=last_network) pygame.quit() if SETTINGS.debug_mode: pr.disable() s = io.StringIO() sortby = SortKey.CUMULATIVE ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() with open("stats_report.log", "w", encoding="utf-8") as f: f.write(s.getvalue())
def submit(): # 获取参数 # 关键词 keyword = keyword_input.get() # 人数 if people_num_input.get() == "": tkinter.messagebox.showerror("提示", "人数不得为空!") return people_num = int(people_num_input.get()) # 起始时间 # 用正则表达式匹配 pattern = re.compile(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})') time_start = time_start_input.get() match = pattern.match(time_start) if match == None: tkinter.messagebox.showerror("提示", "起始时间格式不对!") return time_end = time_end_input.get() match = pattern.match(time_end) if match == None: tkinter.messagebox.showerror("提示", "结束时间格式不对!") return # 公布时间 publish_time = publish_time_input.get() #奖品列表 gift_list = thing_list_input.get() if people_num < 1 or people_num > 8: tkinter.messagebox.showerror("提示","人数错误!") return people_list = draw.init(people_num, keyword, time_start, time_end) if len(people_list) == 0: tkinter.messagebox.showerror("提示","没有用户满足抽奖条件!") return # 展示页面 top1 = Toplevel() image = Image.open('mdbg.jpg') img = ImageTk.PhotoImage(image) canvas = Canvas(top1, width=image.width, height=image.height, bg='white') canvas.create_image(0, 0, image=img, anchor="nw") canvas.create_text(image.width / 2, 50, text="抽奖话题:"+keyword, font=('黑体', 20)) canvas.create_text(image.width / 2, 100, text="获奖名单", font=('黑体', 20)) height = 150 for i in range(0, len(people_list)): canvas.create_text(image.width / 2-100, height + i * 50, text="获奖用户", font=('黑体', 15)) canvas.create_text(image.width / 2 + 100, height + i * 50, text=people_list[i], font=('黑体', 15)) # 结尾 canvas.create_text(100, height + (people_num+2) * 50, text="奖品:"+gift_list, font=('黑体', 17)) canvas.create_text(100, height + (people_num+3) * 50, text="日期:"+publish_time, font=('黑体', 17)) canvas.create_text(image.width - 100, image.height-50, text="拖鞋旅游队", font=('黑体', 15)) canvas.pack() top1.mainloop()
def init(): globals.start_time = time.time() global clock clock = pygame.time.Clock() chara = frisk.Frisk() chara.load('file0') chara.set_ini_value("General", "time", 0.0) chara.save('') globals.chara = chara if os.path.exists('system_information_962'): globals.room = rooms.room_nothingness() elif False: # TODO: criteria for summoning Flowey EX and better room handling should go here globals.room = rooms.room_f_intro() else: globals.room = rooms.room_introstory() pygame.event.set_blocked( [pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP, pygame.MOUSEMOTION]) # we don't care for mouse interactions draw.init()
def initScreen(): """Initializes a fullscreen surface with white background. Returns: pygame.Surface: fullscreen surface with white background """ global background, screensize screen = draw.init() screensize = screen.get_size() background = pygame.Surface(screen.get_size()) # Fill the background white color. background.fill(WHITE) # Convert Surface object to make blitting faster. background = background.convert() return screen
def draw_screen(cam_streams_to_stop, cam_streams_to_draw, resolution, nr_of_columns, fixed_width, fixed_height, autostretch): resolution_width = int(resolution[0]) resolution_height = int(resolution[1]) nr_of_columns = int(nr_of_columns) #First stop all running streams for cam_stream_to_stop in cam_streams_to_stop: cam_stream_to_stop.stop_stream() #Setup global pygame_noconnectable_surface global pygame_noconnectable_surface #Start algorithm to start new streams fields = len(cam_streams_to_draw) if fields == 0: logger.error("No connectable streams detected") #Check if pygame_noconnectable_surface already exists before redrawing try: pygame_noconnectable_surface.get_parent() except: logger.debug( "pygame_noconnectable_surface does not exist, draw it") draw.destroy() pygamescreen = draw.init(resolution) pygame_noconnectable_surface = draw.placeholder( 0, 0, resolution_width, resolution_height, "images/noconnectable.png", pygamescreen) return else: draw.destroy() #Reset pygame_noconnectable_surface pygame_noconnectable_surface = 0 pygamescreen = draw.init(resolution) logger.debug("number of fields= " + str(fields)) #If you have less fields than columns then only set fields amount columns if fields <= nr_of_columns: nr_of_columns = fields #We calculate needed numbers of rows based on how many fields we have and how many columns per row we want nr_of_rows = math.ceil(float(fields) / nr_of_columns) default_fieldwidth = resolution_width / nr_of_columns default_fieldheight = int(resolution_height / nr_of_rows) normal_fieldwidth = default_fieldwidth normal_fieldheight = default_fieldheight if fixed_width is not None: total_actual_width = nr_of_columns * fixed_width if not total_actual_width > resolution_width: normal_fieldwidth = fixed_width logger.debug( "Detected advanced fixed_width config option, setting normal_fieldwidth to " + str(normal_fieldwidth)) else: logger.error( "Total sum of advanced fixed_width (nr_columns * fixed_width) option (" + str(total_actual_width) + ") is more then available width (" + str(resolution_width) + "), falling back to autocalculated width: " + str(normal_fieldwidth)) if fixed_height is not None: total_actual_height = nr_of_rows * fixed_height if not total_actual_height > resolution_height: normal_fieldheight = fixed_height logger.debug( "Detected advanced fixed_height config option, setting normal_fieldheight to " + str(normal_fieldheight)) else: logger.error( "Total sum of advanced fixed_height (nr rows * fixed_height) option (" + str(total_actual_height) + ") is more then available height (" + str(resolution_height) + "), falling back to autocalculated height: " + str(normal_fieldheight)) currentrow = 1 currentwindow = 1 currentrowlength = nr_of_columns x1 = 0 y1 = 0 x2 = normal_fieldwidth y2 = normal_fieldheight for cam_stream in cam_streams_to_draw: if currentwindow > currentrowlength: #This is a new row event x1 = 0 x2 = normal_fieldwidth y1 = y1 + normal_fieldheight y2 = y2 + normal_fieldheight currentrow = currentrow + 1 #Next row ends when we are at following currentwindow index number currentrowlength = currentrowlength + nr_of_columns else: #This is a window in the same row x1 = x1 + normal_fieldwidth x2 = x2 + normal_fieldwidth #If this is the first field/window override some settings if currentwindow == 1: x1 = 0 x2 = normal_fieldwidth #If this is the last field and we still have some screen space left, horizontally stretch it to use all space if currentwindow == fields: if fixed_width is None and autostretch is True: #Sometimes this will override to the same value if the window end was already at the end of the screen #Other times it will really override to the end of the screen x2 = resolution_width else: #Start calculation to display placeholders free_horizontal_pixels = resolution_width - x2 if free_horizontal_pixels > 0: logger.debug( "We have some unused screen and autostretch is disabled. Start drawing placeholders" ) nr_of_placeholders = free_horizontal_pixels / normal_fieldwidth count_placeholders = 0 placeholder_x = x1 + normal_fieldwidth placeholder_y = y1 while count_placeholders < nr_of_placeholders: draw.placeholder(placeholder_x, placeholder_y, normal_fieldwidth, normal_fieldheight, "images/placeholder.png", pygamescreen) count_placeholders = count_placeholders + 1 placeholder_x = placeholder_x + normal_fieldwidth logger.debug("cam stream name =" + cam_stream.name) cam_stream_name = "cam_stream" + str(currentwindow) # x1 #x coordinate upper left corner # y1 #y coordinate upper left corner # x2 #x coordinate absolute where window should end, count from left to right # y2 #y coordinate from where window should end, count from top to bottom of screen cam_stream.start_stream([x1, y1, x2, y2], pygamescreen) cam_stream.printcoordinates() currentwindow = currentwindow + 1
pos.change(Entity,pos.start) elif (info.Map[Position[0]][Position[1]] == 0):# om den nya positionen inte är i en vägg så updateras objektets position print("yes\n \n \n \n")# detta gör det enklarare att se att det inte var en vägg pos.change(Entity,Position) return True# ger tillbaka true elif info.Map[Position[0]][Position[1]]!=0:# annars om den gick in i en vägg så ändras inte värderna print("\n \n \n \n VÄGG") print(info.Map[Position[0]][Position[1]]) return False while (info.master==True):#så länge inte användaren vill avsluta så körs while loopen if info.game==True:#om spelet har startas så körs satsen if loop <0:#loop är endast mindre än noll när man har genererat ett nytt rum print("refresh") pos = position(draw.init())#updaterar pos med nya värden loop+=1#höjer variabeln loop med 1 för varje varv av loopen if keyboard.is_pressed(info.controls["controls"]["Pause"]) and info.menu_up== False:#om den pause tangenten trycks och menyn inte är uppen draw.menu()#se draw modulen step = [0,0]# en steg list med x-kordinater,y-kordinater try: # testar följande kod så att man inte får en emassa error när användaren trycker på en annan knapp #de föjade 4 satserna bestämmer i vilken rikning spelren vill gå och ändrar därefter steg kordinaterna if keyboard.is_pressed(info.controls["controls"]["Right"]): step[0]+=1 print("d") prevpress = True# prevpress ändras if keyboard.is_pressed(info.controls["controls"]["Left"]): step[0]-=1 print("a") prevpress = True
def main(): #random.seed(0) draw_api = draw.init() arctic = geometry.Arctic(HEXDEPTH) list_of_bears = [] player_bear = bear.Bear((0, 0), 0, BLUE, INVLIGHTBLUE, 'M') player_bear.put_trail(arctic) player_bear.destination = (0, 0) list_of_bears.append(player_bear) another_bear = bear.Bear((1, 0), 1, RED, INVLIGHTRED, 'F') another_bear.put_trail(arctic) list_of_bears.append(another_bear) yet_another_bear = bear.Bear((4, 4), -1, RED, INVLIGHTRED, 'F') yet_another_bear.put_trail(arctic) list_of_bears.append(yet_another_bear) #print(draw.get_hex_distance(player_bear.position,another_bear.position)) #print('{0:.2f}'.format(draw.get_hex_angle(player_bear.position,another_bear.position))+'°') fpsClock = pygame.time.Clock() redraw(draw_api, arctic, list_of_bears) set_purpose(arctic, list_of_bears) while True: for event in pygame.event.get(): if event.type == pg.QUIT: pygame.quit() sys.exit() if event.type == pg.KEYDOWN: if (event.key == pg.K_UP): co = -1 list_of_bears[0].destination = (0, 1) animate(draw_api, arctic, list_of_bears, fpsClock, co=co) arctic.move_forward() for b in list_of_bears: b.shift_forward() move_bears(arctic, list_of_bears) set_purpose(arctic, list_of_bears) redraw(draw_api, arctic, list_of_bears) if (event.key == pg.K_RIGHT): cr = 1 list_of_bears[0].turn_right() animate(draw_api, arctic, list_of_bears, fpsClock, cr=cr) arctic.turn_right() for b in list_of_bears: b.turn_left() b.rotate_right() move_bears(arctic, list_of_bears) set_purpose(arctic, list_of_bears) redraw(draw_api, arctic, list_of_bears) if (event.key == pg.K_LEFT): cr = -1 list_of_bears[0].turn_left() animate(draw_api, arctic, list_of_bears, fpsClock, cr=cr) arctic.turn_left() for b in list_of_bears: b.turn_right() b.rotate_left() move_bears(arctic, list_of_bears) set_purpose(arctic, list_of_bears) redraw(draw_api, arctic, list_of_bears) if (event.key == pg.K_DOWN): animate(draw_api, arctic, list_of_bears, fpsClock) arctic.remain() move_bears(arctic, list_of_bears) set_purpose(arctic, list_of_bears) redraw(draw_api, arctic, list_of_bears) if (event.key == pg.K_ESCAPE): print(sys.getsizeof(draw_api.get_h_lookup)) pygame.display.update()
def init(): global clock, game_dimensions, width, height, camera, player_id pygame.init() clock = 0 game_dimensions = width, height = 640, 480 draw.init(width, height) camera = Camera(width, height) entity_control.init() player_ship = load_texture('graphics\\ship.tif', 'player_ship') bullet1 = load_texture('graphics\\bullet_6x6.tif', 'bullet1') target1 = load_texture('graphics\\target_30x30.tif', 'target1') dust1 = load_texture('graphics\\layers\\dust_640x480_1.tif', 'dust1') dust2 = load_texture('graphics\\layers\\dust_640x480_2.tif', 'dust2') dust3 = load_texture('graphics\\layers\\dust_800x800_1.tif', 'dust3') planet1 = load_texture('graphics\\layers\\planet_154x154_1.tif', 'planet1') planet2 = load_texture('graphics\\layers\\planet_40x40_1.tif', 'planet2') starfield = load_texture('graphics\\layers\\starfield_640x480_1.tif', 'starfield') #test1 = load_texture('graphics\\layers\\test_640x480.tif', 'test1') shape = Polygon([Pnt(0,-15),Pnt(10,15), Pnt(-10,15)], Pnt()) player = entity.Player(player_ship, shape, 0.0005, 0.2, 0.005, bullet1) player_id = entity_control.register(player, 'player') """ orb = entity.Entity(bullet1, Circle(3)) orb_logic = logic.Orbital_Logic(Pnt(0,40), 0.004, 0) orb.socket_logic(orb_logic) player.add_child(orb) entity_control.register(orb) orb = entity.Entity(bullet1, Circle(3)) orb_logic = logic.Orbital_Relative_Logic(Pnt(0,30), 0) orb.socket_logic(orb_logic) player.add_child(orb) entity_control.register(orb) orb = entity.Entity(bullet1, Circle(3)) orb_logic = logic.Orbital_Static_Logic(Pnt(0,20), 0) orb.socket_logic(orb_logic) player.add_child(orb) entity_control.register(orb) """ enemy = entity.Enemy(target1, Circle(15), Pnt(300, 300), 0.0003, 0.2) enemy_logic = logic.Enemy_Basic_Logic('player') enemy.socket_logic(enemy_logic) entity_control.register(enemy) enemy = entity.Enemy(target1, Circle(15), Pnt(-300, 300), 0.0003, 0.2) enemy_logic = logic.Enemy_Basic_Logic('player') enemy.socket_logic(enemy_logic) entity_control.register(enemy) enemy = entity.Enemy(target1, Circle(15), Pnt(0, -300), 0.0003, 0.19) enemy_logic = logic.Enemy_Basic_Logic('player') enemy.socket_logic(enemy_logic) entity_control.register(enemy) entity_control.register(background.Background_scrolling(dust1, 0.5, 4)) entity_control.register(background.Background_scrolling(dust2, 1.0, 3)) entity_control.register(background.Background_scrolling(dust3, 2.0, 3)) entity_control.register(background.Background_object(Pnt(300, 100), planet1, 4, 2)) entity_control.register(background.Background_object(Pnt(550, -200), planet2, 6, 1)) entity_control.register(background.Background_scrolling(starfield, 20, 0)) for e in entity_control.yield_entities(): e.set_camera(camera)
import pygame, time, sys from Box2D import * import objects, draw draw.init() objects.init() # print body.position, body.angle while 1: objects.Step() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: sys.exit() if event.type == pygame.MOUSEBUTTONUP: objects.create_ball(draw.Inverse_Transform_Vertex(event.pos), 10) # time.sleep(0.1)
import pygame import draw import time screen = draw.init() screensize = screen.get_size() background = pygame.Surface(screen.get_size()) # Fill the background white color. background.fill((255, 255, 255)) # Convert Surface object to make blitting faster. background = background.convert() uk = 0.6 i = 0.1 p = 0.3 q = -0.3 chart = draw.arr_chart(screen, uk, i, p, q) screen.blit(chart, (0, 0)) pygame.display.flip() time.sleep(10) pygame.quit()
def particle_filter(n, control, measurements, true_pos, true_vel, dt, dynamics, config): p = numpy.random.uniform(-1, 1, size=(n, FACTORS, DIMENSION)) p[:, 0, :] # for verlet assume initially stationary. w = 1.0 / n + numpy.zeros(n) for u, m, tx, tv in zip(control, measurements, true_pos, true_vel): # Do dynamics drift_p = dynamics(p, u, dt, config) # compute weight based on measurements and existing weights w = likelihood(drift_p, m, w) print(numpy.sum(w)) if numpy.sum(w) == 0: print("boom") return w = w / numpy.sum(w) # resample p = resample(drift_p, w) draw.pyframe(p[:, 0, :], p[:, 1, :], tx, tv) draw.init() dt = .1 t = numpy.arange(0, 1000, dt) x = signal_x(t) v = signal_v(t) a = signal_a(t) particle_filter(20000, a, x + numpy.random.normal(0, .1, size=x.shape), x, v, dt, dynamics.dynamics, {"ACCEL_DRIFT": ACCEL_DRIFT})
import numpy as np import draw import sys from OpenGL.GLUT import glutMainLoop if __name__ == "__main__": draw.init(sys.argv) glutMainLoop()
from pygame.locals import * import time import pygame.time import pygame.font import pygame.image import collision import draw from random import randint pygame.init() clock = 0 size = width, height = 640, 480 draw.init(width,height) # shape = {'id': id, 'pos':[x,y], 'poly':[[x1,y1],[x2,y2],...]} # shape = {'pos':[x,y], 'type': type, 'data': xxxxx} # object = {'id': id, 'type':type, 'shape': shape} #shapes = {} object_dict = {'creep':{}, 'tower':{}, 'projectile':{}, 'particle':{}} large_dict = {'creep':-1, 'tower':-1, 'projectile':-1, 'particle':-1} kill_list = set() scale = 15