Exemple #1
0
def main():

    # To assign camera by name: put string(s) in list
    eye_cam_names = [
        "USB 2.0 Camera", "Microsoft", "6000", "Integrated Camera",
        "HD USB Camera"
    ]
    world_src = [
        "Logitech Camera", "(046d:081d)", "C510", "B525", "C525", "C615",
        "C920", "C930e"
    ]
    eye_src = (eye_cam_names,
               0), (eye_cam_names, 1
                    )  #first match for eye0 and second match for eye1

    # to assign cameras directly, using integers as demonstrated below
    # eye_src =  4 , 5 #second arg will be ignored for monocular eye trackers
    # world_src = 1

    # to use a pre-recorded video.
    # Use a string to specify the path to your video file as demonstrated below
    # eye_src = '/Users/mkassner/Downloads/000/eye0.mkv' , '/Users/mkassner/Downloads/eye.avi'
    # world_src = "/Users/mkassner/Downloads/000/world.mkv"

    # Camera video size in pixels (width,height)
    eye_size = (640, 480)
    world_size = (1280, 720)

    # on MacOS we will not use os.fork, elsewhere this does nothing.
    forking_enable(0)

    #g_pool holds variables. Only if added here they are shared across processes.
    g_pool = Global_Container()

    # Create and initialize IPC
    g_pool.pupil_queue = Queue()
    g_pool.quit = Value(c_bool, 0)
    g_pool.timebase = Value(c_double, 0)
    g_pool.eye_tx = []
    # make some constants avaiable
    g_pool.user_dir = user_dir
    g_pool.version = get_version(version_file)
    g_pool.app = 'capture'
    g_pool.binocular = binocular

    p_eye = []
    for eye_id in range(1 + 1 * binocular):
        rx, tx = Pipe(False)
        p_eye += [
            Process(target=eye,
                    args=(g_pool, eye_src[eye_id], eye_size, rx, eye_id))
        ]
        g_pool.eye_tx += [tx]
        p_eye[-1].start()

    world(g_pool, world_src, world_size)

    # Exit / clean-up
    for p in p_eye:
        p.join()
Exemple #2
0
def main():
    # To assign camera by name: put string(s) in list

    # Parse command line arguments
    parser = argparse.ArgumentParser(description='GUI for gaze tracking and pupillometry')
    parser.add_argument('-eye', dest='eye_file', type=str, help="Work with existing video recording, instead of live feed", default='')
    parser.add_argument('-world', dest='world_file', type=str, help="Work with existing video recording, instead of live feed", default='')

    args = parser.parse_args()

    # to use a pre-recorded video.
    # Use a string to specify the path to your video file as demonstrated below
    if args.eye_file == '':
        eye_src = ["UI154xLE-M", "USB Camera-B4.09.24.1", "FaceTime Camera (Built-in)", "Microsoft", "6000","Integrated Camera"]
        # to assign cameras directly, using integers as demonstrated below
        # eye_src = 1
    else:
#        print "Using provide file: %s" % args.filename
        eye_src = args.eye_file

    if args.world_file == '':
        world_src = ["Logitech Camera","(046d:081d)","C510","B525", "C525","C615","C920","C930e"]
        # to assign cameras directly, using integers as demonstrated below
        # world_src = 0
    else:
        world_src = args.world_file

    # Camera video size in pixels (width,height)
    eye_size = (260,216) #(1280,1024)
    world_size = (640,480)


    # on MacOS we will not use os.fork, elsewhere this does nothing.
    forking_enable(0)

    # Create and initialize IPC
    g_pool = Temp()
    g_pool.pupil_queue = Queue()
    g_pool.eye_rx, g_pool.eye_tx = Pipe(False)
    g_pool.quit = RawValue(c_bool,0)
    # this value will be substracted form the capture timestamp
    g_pool.timebase = RawValue(c_double,0)
    # make some constants avaiable
    g_pool.user_dir = user_dir
    g_pool.rec_dir = rec_dir
    g_pool.version = version
    g_pool.app = 'capture'
    # set up subprocesses
    p_eye = Process(target=eye, args=(g_pool,eye_src,eye_size))

    # Spawn subprocess:
    p_eye.start()
    if platform.system() == 'Linux':
        # We need to give the camera driver some time before requesting another camera.
        sleep(0.5)

    world(g_pool,world_src,world_size)

    # Exit / clean-up
    p_eye.join()
Exemple #3
0
def main():
    # To assign camera by name: put string(s) in list
    eye_cam_names = ["USB 2.0 Camera","Microsoft", "6000","Integrated Camera"]
    world_src = ["Logitech Camera","(046d:081d)", "(046d:0991)", "C510","B525", "C525","C615","C920","C930e"]
    # world_src = ["USB 2.0 Camera","Microsoft", "5000","Integrated Camera"]
    eye_src = (eye_cam_names,0),(eye_cam_names,1) #first match for eye0 and second match for eye1

    # to assign cameras directly, using integers as demonstrated below
    # eye_src =  4 , 5 #second arg will be ignored for monocular eye trackers
    # world_src = 1

    # to use a pre-recorded video.
    # Use a string to specify the path to your video file as demonstrated below
    # eye_src = '/Users/mkassner/Downloads/eye.avi' , '/Users/mkassner/Downloads/eye.avi'
    # world_src = "/Users/mkassner/Desktop/2014_01_21/000/world.avi"

    # Camera video size in pixels (width,height)
    eye_size = (640,480)
    world_size = (1280,720)


    # on MacOS we will not use os.fork, elsewhere this does nothing.
    forking_enable(0)

    #g_pool holds variables. Only if added here they are shared across processes.
    g_pool = Global_Container()

    # Create and initialize IPC
    g_pool.pupil_queue = Queue()
    g_pool.quit = Value(c_bool,0)
    g_pool.timebase = Value(c_double,0)
    g_pool.eye_tx = []
    # make some constants avaiable
    g_pool.user_dir = user_dir
    g_pool.rec_dir = rec_dir
    g_pool.version = get_version(version_file)
    g_pool.app = 'capture'
    g_pool.binocular = binocular


    p_eye = []
    for eye_id in range(1+1*binocular):
        rx,tx = Pipe(False)
        p_eye += [Process(target=eye, args=(g_pool,eye_src[eye_id],eye_size,rx,eye_id))]
        g_pool.eye_tx += [tx]
        p_eye[-1].start()
        if platform.system() == 'Linux':
            # We need to give the camera driver some time before requesting another camera.
            sleep(0.5)

    world(g_pool,world_src,world_size)


    # Exit / clean-up
    for p in p_eye:
        p.join()
Exemple #4
0
def main():

    # To assign camera by name: put string(s) in list
    world_src = ["Pupil Cam1 ID2","Logitech Camera","(046d:081d)","C510","B525", "C525","C615","C920","C930e"]
    eye0 = ["Pupil Cam1 ID0","HD-6000","Integrated Camera","HD USB Camera","USB 2.0 Camera"]
    eye1 = ["Pupil Cam1 ID1","HD-6000","Integrated Camera"]
    eye_src = eye0, eye1

    # to assign cameras directly, using integers as demonstrated below
    # eye_src =  1 , 1 #second arg will be ignored for monocular eye trackers
    # world_src = 0

    # to use a pre-recorded video.
    # Use a string to specify the path to your video file as demonstrated below
    # eye_src = '/Users/mkassner/Downloads/000/eye0.mkv' , '/Users/mkassner/Downloads/eye.avi'
    # world_src = "/Users/mkassner/Downloads/000/world.mkv"

    # Default camera video size in pixels (width,height)
    eye_size = (640,480)
    world_size = (1280,720)

    # on MacOS we will not use os.fork, elsewhere this does nothing.
    forking_enable(0)

    #g_pool holds variables. Only if added here they are shared across processes.
    g_pool = Global_Container()

    # Create and initialize IPC
    g_pool.pupil_queue = Queue()
    g_pool.quit = Value(c_bool,0)
    g_pool.timebase = Value(c_double,0)
    g_pool.eye_tx = []
    # make some constants avaiable
    g_pool.user_dir = user_dir
    g_pool.version = get_version(version_file)
    g_pool.app = 'capture'
    g_pool.binocular = binocular
    


    p_eye = []
    for eye_id in range(1+1*binocular):
        eye_end,world_end = Pipe(True)
        p_eye += [Process(target=eye, args=(g_pool,eye_src[eye_id],eye_size,eye_end,eye_id))]
        p_eye[-1].start()
        #wait for ready message from eye to sequentialize startup
        logger.debug(world_end.recv())
        g_pool.eye_tx += [world_end]


    world(g_pool,world_src,world_size)

    # Exit / clean-up
    for p in p_eye:
        p.join()
Exemple #5
0
def main():
    # To assign camera by name: put string(s) in list
    eye_src = ["Microsoft", "6000","Integrated Camera"]
    world_src = ["Logitech Camera","(046d:081d)","C510","B525", "C525","C615","C920","C930e"]

    # to assign cameras directly, using integers as demonstrated below
    # eye_src = 1
    # world_src = 0

    # to use a pre-recorded video.
    # Use a string to specify the path to your video file as demonstrated below
    # eye_src = '/Users/mkassner/Pupil/datasets/p1-left/frames/test.avi'
    # world_src = "/Users/mkassner/Desktop/2014_01_21/000/world.avi"

    # Camera video size in pixels (width,height)
    eye_size = (640,360)
    world_size = (1280,720)


    # on MacOS we will not use os.fork, elsewhere this does nothing.
    forking_enable(0)

    # Create and initialize IPC
    g_pool = Temp()
    g_pool.pupil_queue = Queue()
    g_pool.eye_rx, g_pool.eye_tx = Pipe(False)
    g_pool.quit = RawValue(c_bool,0)
    # this value will be substracted form the capture timestamp
    g_pool.timebase = RawValue(c_double,0)
    # make some constants avaiable
    g_pool.user_dir = user_dir
    g_pool.rec_dir = rec_dir
    g_pool.version = version
    g_pool.app = 'capture'
    # set up subprocesses
    p_eye = Process(target=eye, args=(g_pool,eye_src,eye_size))

    # Spawn subprocess:
    p_eye.start()
    if platform.system() == 'Linux':
        # We need to give the camera driver some time before requesting another camera.
        sleep(0.5)

    world(g_pool,world_src,world_size)



    # Exit / clean-up
    p_eye.join()
Exemple #6
0
def main():
    # To assign camera by name: put string(s) in list
    eye_src = ["Microsoft", "6000", "Integrated Camera"]
    world_src = [
        "Logitech Camera", "(046d:081d)", "C510", "B525", "C525", "C615",
        "C920", "C930e"
    ]

    # to assign cameras directly, using integers as demonstrated below
    # eye_src = 1
    # world_src = 0

    # to use a pre-recorded video.
    # Use a string to specify the path to your video file as demonstrated below
    # eye_src = '/Users/mkassner/Pupil/datasets/p1-left/frames/test.avi'
    # world_src = "/Users/mkassner/Desktop/2014_01_21/000/world.avi"

    # Camera video size in pixels (width,height)
    eye_size = (640, 360)
    world_size = (1280, 720)

    # on MacOS we will not use os.fork, elsewhere this does nothing.
    forking_enable(0)

    # Create and initialize IPC
    g_pool = Temp()
    g_pool.pupil_queue = Queue()
    g_pool.eye_rx, g_pool.eye_tx = Pipe(False)
    g_pool.quit = RawValue(c_bool, 0)
    # this value will be substracted form the capture timestamp
    g_pool.timebase = RawValue(c_double, 0)
    # make some constants avaiable
    g_pool.user_dir = user_dir
    g_pool.rec_dir = rec_dir
    g_pool.version = version
    g_pool.app = 'capture'
    # set up subprocesses
    p_eye = Process(target=eye, args=(g_pool, eye_src, eye_size))

    # Spawn subprocess:
    p_eye.start()
    if platform.system() == 'Linux':
        # We need to give the camera driver some time before requesting another camera.
        sleep(0.5)

    world(g_pool, world_src, world_size)

    # Exit / clean-up
    p_eye.join()
    def set_up_world_and_actions(self, world_params):
        self.my_world = world.world(**world_params)

        def increase_height():
            self.my_world.change_height(1)

        def decrease_height():
            self.my_world.change_height(-1)

        def increase_width():
            self.my_world.change_width(1)

        def decrease_width():
            self.my_world.change_width(-1)

        def increase_height2():
            self.my_world.change_height(1, ellipse=1)

        def decrease_height2():
            self.my_world.change_height(-1, ellipse=1)

        def increase_width2():
            self.my_world.change_width(1, ellipse=1)

        def decrease_width2():
            self.my_world.change_width(-1, ellipse=1)

        #List of actions to use for the network.
        self.actions = [increase_height,decrease_height,increase_width,decrease_width,\
                  increase_height2,decrease_height2,increase_width2,decrease_width2]
Exemple #8
0
 def __init__(self):
     ## Init panda
     ShowBase.__init__(self)
     ## Init client sql connection
     self.clientConn = clientConnection.clientConnection()
     ## Init world
     self.world = world.world()
 def __init__(self, world_dim, nagents, agent_xy):
     self.world = world(world_dim[1], world_dim[0])
     self.vis = visualize(self.world)
     self.list_agents = []
     for index in range(nagents):
         self.list_agents.append(
             self.world.new_agent(agent_xy[index][1], agent_xy[index][0]))
     self.init_vis()
Exemple #10
0
def main():

    w = world()
    r = robot()
    moves = [[45, 2], [-45, -1]]
    for i in range(2):
        r.move(w, moves[i][0], moves[i][1])
        pf = particleFilter(w, r)
        p = pf.initParticles(10)
        p = pf.localize(p, 10)
Exemple #11
0
def main():
    # To assign camera by name: put string(s) in list
    eye_src = ["Microsoft", "6000","Integrated Camera"]
    world_src = ["Logitech Camera","B525", "C525","C615","C920","C930e"]

    # to assign cameras directly, using integers as demonstrated below
    # eye_src = 1
    # world_src = 0

    # to use a pre-recorded video.
    # Use a string to specify the path to your video file as demonstrated below
    # eye_src = "/Users/mkassner/Pupil/datasets/eye2_fieldtest/eye 10.avi"
    # world_src = "/Users/mkassner/Downloads/2013_10_22_M25/000/world.avi"

    # Camera video size in pixels (width,height)
    eye_size = (640,360)
    world_size = (1280,720)


    # on MacOS we will not use os.fork, elsewhere this does nothing.
    forking_enable(0)

    # Create and initialize IPC
    g_pool = Temp()
    g_pool.pupil_queue = Queue()
    g_pool.eye_rx, g_pool.eye_tx = Pipe(False)
    g_pool.quit = RawValue(c_bool,0)
    # make some constants avaiable
    g_pool.user_dir = user_dir
    g_pool.rec_dir = rec_dir
    g_pool.version = version
    # set up subprocesses
    p_eye = Process(target=eye, args=(g_pool,eye_src,eye_size))

    # Spawn subprocess:
    p_eye.start()
    # On Linux, we need to give the camera driver some time before requesting another camera.
    sleep(0.5)
    # On MacOS cameras using MJPG compression (world camera) need to run in the main process.
    world(g_pool,world_src,world_size)

    # Exit / clean-up
    p_eye.join()
Exemple #12
0
 def __init__(self, app, socketio):
     self.app = app
     self.socketio = socketio
     self.max = 50
     self.players = {}
     self.world = world.world(self)
     with open('static/assets.json') as file:
         loaded = json.load(file)
         self.items = loaded['items']
         self.blocks = loaded['blocks']
         self.actors = loaded['actors']
Exemple #13
0
 def __init__(self, setup=0):
     self.w = world.world()
     if setup == 0:
         self.w.ground()
     elif setup == 1:
         self.setup_ball_wall_coll()
     else:
         try:
             exec "self.setup_" + str(setup) + "()"
         except NameError:
             print "Non-existant setup"
             print "Defaulting to basic setup"
             self.w.ground()
Exemple #14
0
 def __init__ (self,screen):
     width = 20
     length = 10
     self.tickrate = 10
     curses.curs_set(False)
     self.screen = screen
     self.World = world.world(width,length,self.tickrate)
     self.game_screen = 
     
     entity.player(0,0,self.World)
     entity.sheep(5,5,self.World)
     entity.zombie(7,7,self.World)
     a = entity.entity("D",3,3,25,self.World)
     a.name = "d"
     
     self.game_mode()
Exemple #15
0
class Player(Database):

    player_data = world("pt62").get_player()

    def __init__(self):
        super(Player, self).__init__()
    
    def update(self):
        self.connection.execute("CREATE TABLE IF NOT EXISTS Player (player_id INT, name TEXT, ally_id INT, num_vill INT, points INT, rank INT, datetime TEXT)")
        for key, item in Player.player_data.items():

            format = f"{item['player_id']}, '{item['name']}', {item['ally_id']}, {item['num_vill']}, {item['points']}, {item['rank']}, '{item['datetime']}'"

            self.cursor.execute(f"INSERT INTO Player VALUES({format})")

        self.connection.commit()
        self.cursor.close()
Exemple #16
0
    def __init__(self, width, height):
        #
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        # create pyglet window
        self.window = pyglet.window.Window()
        self.window.on_draw = self.on_draw
        self.window.on_key_press = self.on_key_press
        self.window.on_key_release = self.on_key_release
        self.window.width = width
        self.window.height = height
        self.key_pressed = []

        # create fps display 
        self.fps_display = pyglet.clock.ClockDisplay()

        # sync clock
        pyglet.clock.schedule_interval(self.tick, 1.0/60.0)   
        pyglet.clock.set_fps_limit(60)

        # create world
        world_width = 5000
        world_height = 5000
        self.world = world.world(world_width, world_height)

        # set background
        # self.background = pyglet.graphics.OrderedGroup(0)
        # self.background_image = pyglet.image.load('assets/space.png')
        # self.background_image.x_anchor = world_width / 2
        # self.background_image.y_anchor = world_height / 2
        #self.background_image.blit_into(img1,0,0,0)

        # create scene- match dimensions of the app window
        self.scene = scene.scene(self.world, offset_x=0, offset_y=0,width=width, height=height)

        # create physics engine
        self.engine = engine.engine()

        # throw some objects in there for now
        for _ in xrange(0, 100):
            theta = random() * 2 * math.pi
            pos = dict(x=random() * world_width, y=random() * world_height)
            s = square.square(position=pos, size=50)
            s.rotate(theta)
            self.world.add_entity(s)
def main():
	
	t01 = datetime.now()
	t1 = t01.strftime("%H:%M:%S.%f")
	ww = world.world()
	t02 = datetime.now()
	t2 = t02.strftime("%H:%M:%S.%f")
	print ("Start time: " + str(t1))
	print ("End time: " + str(t2))
	t03 = t02-t01
	#t3 = t03.strftime("%H:%M:%S.%f")
	print ("Elapsed time: " + str(t03))

	if(ww.RWSusage =="1"):
		print("Method used: RWS")
	else:
		print("Method used: Tournament")

	print("Number of generations: " + str(ww.nbGenerations))
Exemple #18
0
def init(data):
    # initialize and optimize the board
    data.weaponSet={100:glock(random.uniform(0.5,1.5),random.uniform(0.5,1.5)),
                    101:awp(random.randint(5,10),random.randint(3,4))}
    data.mode = 'start'
    data.size = BOARDSIZE
    maze = Maze(data.size, data.size)
    maze.initializeMap()
    for i in range(12):
        maze.optimizeMap()
    data.wallImg = imageRegister('wall.png')
    data.roadImg = imageRegister('road.png')
    data.healthImg = imageRegister('health.png')
    data.enemyImg = imageRegister('enemy.png')
    data.glockImg = imageRegister('glock.png')
    data.score = 0
    data.wallSize = WALLSIZE
    data.centerX = data.width / 2
    data.centerY = data.height / 2
    if BOARDSIZE%2!=0:
        data.scrollX = 0
        data.scrollY = 0
    else:
        data.scrollX = -WALLSIZE/2
        data.scrollY = -WALLSIZE/2
    data.gameWorld = world(copy.deepcopy(
        maze.board))  # The board of the world is to process all the events
    data.defaultWeapon = data.weaponSet[101]
    data.player = Player(data.gameWorld,[data.weaponSet[100],data.weaponSet[101]],PLAYER_HEALTH,None,data.wallSize/2,data.size//2,data.size//2)
    data.gameWorld.player = data.player
    data.timePassed = 0
    data.direction = ''
    data.road = []
    data.enemy = []
    data.gameOver = False
    data.gunX = 0
    data.gunY = 0
    data.bullet =[]
    data.health = []
    data.walls = []
    data.playerWeaponImg = None
    data.mouseX = 0
    data.mouseY = 0
Exemple #19
0
    def onLoadworld(self,event):
        openFileDialog = wx.FileDialog(self, "Open world file", "", "",
                                       "World files (*.world)|*.world", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

        openFileDialog.SetDirectory('./savebugs')
        if openFileDialog.ShowModal() == wx.ID_CANCEL:
            return     # the user changed idea...

        # proceed loading the file chosen by the user
        # this can be done with e.g. wxPython input streams:
        filename = openFileDialog.GetPath()

        X=world.world()
        file=open(filename,'rb')
        self.W=X.load(file)

        # Makes the map to use the recently loaded World
        self.map.W=self.W
        file.close()
        self.map.Refresh()
        self.refresh_labels()
Exemple #20
0
 def __init__(self, width=400, height=200):
     #Initialize the game
     pygame.init()
     self.fpsClock = pygame.time.Clock()
     #Set the window size
     self.width = width
     self.height = height
     #Change the screen
     self.screen = pygame.display.set_mode((self.width, self.height))
     pygame.display.set_caption('Nations')
     #Define RGB
     self.red = pygame.Color(255, 0, 0)
     self.green = pygame.Color(0, 255, 0)
     self.blue = pygame.Color(0, 0, 255)
     self.fontObj = pygame.font.Font('freesansbold.ttf', 24)
     msg = 'Nations Initialized'
     #Initialize Mouse position
     self.mousex, self.mousey = (0, 0)
     #Initialize Message
     self.msg = ''
     self.earth = world(width=self.width, height=self.height, viewMode=1)
Exemple #21
0
 def __init__(self, width=400, height=200):
     #Initialize the game
     pygame.init()
     self.fpsClock = pygame.time.Clock()
     #Set the window size
     self.width = width
     self.height = height
     #Change the screen
     self.screen = pygame.display.set_mode((self.width, self.height))
     pygame.display.set_caption('Nations')
     #Define RGB
     self.red = pygame.Color(255, 0, 0)
     self.green = pygame.Color(0, 255, 0)
     self.blue = pygame.Color(0, 0, 255)
     self.fontObj = pygame.font.Font('freesansbold.ttf', 24)
     msg = 'Nations Initialized'
     #Initialize Mouse position
     self.mousex, self.mousey = (0, 0)
     #Initialize Message
     self.msg = ''
     self.earth = world(width=self.width, height=self.height, viewMode = 1)
Exemple #22
0
class ODA(Database):

    oda_data = world("pt62").get_oda()

    def __init__(self):
        super(ODA, self).__init__()

    def update(self):
        self.connection.execute("CREATE TABLE IF NOT EXISTS ODA (player_id INT, points INT, rank INT, datetime TEXT)")
        for key, item in ODA.oda_data.items():

            try:
            
                format = f"{item['player_id']}, {item['points']}, {item['rank']}, '{item['datetime']}'"
                print(format)
                self.cursor.execute(f"INSERT INTO ODA VALUES({format})")

            except sqlite3.OperationalError:
                pass

        self.connection.commit()
        self.cursor.close()
Exemple #23
0
class Village(Database):

    village_data = world("pt62").get_village()

    def __init__(self):
        super(Village, self).__init__()

    def update(self):
        self.connection.execute("CREATE TABLE IF NOT EXISTS Village (village_id INT, name TEXT, x INT, y INT, continent INT, player_id INT, points INT, datetime TEXT)")
        for key, item in Village.village_data.items():

            try:
            
                format = f"{item['village_id']}, '{item['name']}', {item['x']}, {item['y']}, {item['continent']}, {item['player_id']}, {item['points']}, '{item['datetime']}'"
                print(format)
                self.cursor.execute(f"INSERT INTO Village VALUES({format})")

            except sqlite3.OperationalError:
                pass

        self.connection.commit()
        self.cursor.close()
Exemple #24
0
class Ally(Database):

    ally_data = world("pt62").get_ally()

    def __init__(self):
        super(Ally, self).__init__()

    def update(self):
        self.connection.execute("CREATE TABLE IF NOT EXISTS Ally (ally_id INT, name TEXT, tag TEXT, members INT, points INT, total_points INT, rank INT, datetime TEXT)")
        for key, item in Ally.ally_data.items():

            try:
            
                format = f"{item['ally_id']}, '{item['name']}', '{item['tag']}', {item['members']}, {item['points']}, {item['total_points']}, {item['rank']}, '{item['datetime']}'"
                print(format)
                self.cursor.execute(f"INSERT INTO Ally VALUES({format})")

            except sqlite3.OperationalError:
                pass

        self.connection.commit()
        self.cursor.close()
Exemple #25
0
def run(e, n_termites=1, n_woods=1, size=100, ticks=100000, command_line=True):
    w = world(density=0.3, size=size, n_woods=n_woods)
    for _ in range(n_termites):
        w.add_termite(termite(x=random.randint(0, size-1), y=random.randint(0, size-1)))

    if not command_line:
        disp = display(size=size, scale=4)

    running = True
    out = []
    while running:
        if not command_line:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
        w.tick()
        if w.ticks % e is 0:
            out.append((w.ticks, w.pile_count()))
            if not command_line:
                disp.redraw(w)
        if w.ticks > ticks:
            running = False
    return out
Exemple #26
0
def main():

    # To assign camera by name: put string(s) in list
    world_src = [
        "Pupil Cam1 ID2", "Logitech Camera", "(046d:081d)", "C510", "B525",
        "C525", "C615", "C920", "C930e"
    ]
    eye0 = [
        "Pupil Cam1 ID0", "HD-6000", "Integrated Camera", "HD USB Camera",
        "USB 2.0 Camera"
    ]
    eye1 = ["Pupil Cam1 ID1", "HD-6000", "Integrated Camera"]
    eye_src = eye0, eye1

    # to assign cameras directly, using integers as demonstrated below
    # eye_src =  1 , 1 #second arg will be ignored for monocular eye trackers
    # world_src = 0

    # to use a pre-recorded video.
    # Use a string to specify the path to your video file as demonstrated below
    # eye_src = '/Users/mkassner/Downloads/eye0.mkv' , '/Users/mkassner/Downloads/eye.avi'
    # world_src = "/Users/mkassner/Downloads/000/world.mkv"

    # Default camera video size in pixels (width,height)
    eye_size = (640, 480)
    world_size = (1280, 720)

    # on MacOS we will not use os.fork, elsewhere this does nothing.
    forking_enable(0)

    #g_pool holds variables. Only if added here they are shared across processes.
    g_pool = Global_Container()

    # Create and initialize IPC
    g_pool.pupil_queue = Queue()
    g_pool.quit = Value(c_bool, 0)
    g_pool.timebase = Value(c_double, 0)
    g_pool.eye_tx = []
    # make some constants avaiable
    g_pool.user_dir = user_dir
    g_pool.version = get_version(version_file)
    g_pool.app = 'capture'
    g_pool.binocular = binocular

    p_eye = []
    for eye_id in range(1 + 1 * binocular):
        eye_end, world_end = Pipe(True)
        p_eye += [
            Process(target=eye,
                    args=(g_pool, eye_src[eye_id], eye_size, eye_end, eye_id))
        ]
        p_eye[-1].start()
        #wait for ready message from eye to sequentialize startup
        logger.debug(world_end.recv())
        g_pool.eye_tx += [world_end]

    world(g_pool, world_src, world_size)

    # Exit / clean-up
    for p in p_eye:
        p.join()
import event_handler
import network
import world

server = False
for arg in sys.argv:
    
    if arg == '-s' or arg == '-server':
        server = True

try:
    if server:  net = network.server( constants.port )
    else:       net = network.client( "pymud.no-ip.org", constants.port )
except AttributeError, e:
    print "ERROR: in connection, %s" % e
    sys.exit(-1)

pygame.init()
rend = renderer.renderer( vector3( constants.width, constants.height ) )
hand = event_handler.handler()
scene = world.world( rend, hand, net )

while True:
    
    event = hand.process()
    if event and event.type == pygame.QUIT:
        break
    scene.update()
    
pygame.quit()
Exemple #28
0
def main():

	w = world.world()
	w.simulate()
Exemple #29
0
    def breed(self,other):
        childsBrain = []
        for selfLayer,otherLayer in zip(self.brain.layers,other.brain.layers):
            shape = selfLayer.shape
            mask = np.rint(np.random.random(shape))
            inverseMask = np.abs(mask-1)
            childLayer = selfLayer*mask+otherLayer*inverseMask
            if np.random.random()>.95:
                x = np.random.randint(childLayer.shape[0])
                y = np.random.randint(childLayer.shape[1])
                childLayer[x,y] = np.random.randn()
            childsBrain.append(selfLayer*mask+otherLayer*inverseMask)
        return(ant(self.world,brain = network([],layers = childsBrain)))


earth = world(.1)


population = [ant(earth) for i in range(50)]
print 'goin'

n = False
for g in range(100):

    if n:
        break

    for a in population:
        x = []
        y = []
        i = 0
Exemple #30
0
def worldChanged(w1, w2):

    for row in range(0, WORLD_ROWS + 2):
        for col in range(0, WORLD_COLS + 2):
            if w1.getCell(row, col) != w2.getCell(row, col):
                return True
    return False

pygame.init()
windowSize = (SCREEN_X, SCREEN_Y)
screen = pygame.display.set_mode(windowSize)
screen.fill(BLACK)
clock = pygame.time.Clock()


world1 = world()
world1.randomWorld()


while 1:

    clock.tick(40)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    world1.showWorld(screen)
    world1.updateWorld()

    pygame.display.update()
Exemple #31
0
middle.material.diffuse = 0.7
middle.material.specular = 0.3

right = sphere()
right.set_transform(translation(1.5, 0.5, -0.5) * scaling(0.5, 0.5, 0.5))
right.material.colour = color(0.5, 1, 0.1)
right.material.diffuse = 0.7
right.material.specular = 0.3

left = sphere()
left.set_transform(translation(-1.5, 0.33, -0.75) * scaling(0.33, 0.33, 0.33))
left.material.colour = color(1, 0.8, 0.1)
left.material.diffuse = 0.7
left.material.specular = 0.3

source = point_light(point(-10, 10, -10), color(1, 1, 1))

w = world(object=[middle, left, right, floor, left_wall, right_wall])
w.set_light(source)

c = camera(200, 100, pi / 3)

FROM = point(0, 1.5, -5)
TO = point(0, 1, 0)
UP = vector(0, 1, 0)
data = view_transform(FROM, TO, UP)
c.Set_Transform(data)

IMAGE = c.render(w)
IMAGE.to_ppm(filename='pls')
Exemple #32
0
def main():

	# To assign by name: put string(s) in list
	eye_src = ["Microsoft", "6000"]
	world_src = ["Logitech Camera","B525", "C525","C615","C920","C930e"]

	# to assign cameras directly, using integers as demonstrated below
	# eye_src = 1
	# world_src = 0

	# to use a pre-recorded video.
	# Use a string to specify the path to your video file as demonstrated below
	# eye_src = "/Users/mkassner/Pupil/pupil_google_code/wiki/videos/eye_simple_filter.avi"
	# world_src = 0

	# Camera video size in pixels (width,height)
	eye_size = (640,360)
	world_size = (1280,720)


	# Use the player - a seperate window for video playback and calibration animation
	use_player = True
	#startup size for the player window: this can be whatever you like
	player_size = (640,360)

	# Create and initialize shared globals
	g_pool = Temp()
	g_pool.gaze = Array('d',(0.0,0.0))
	g_pool.ref = Array('d',(0.0,0.0))
	g_pool.marker = Array('d',(0.0,0.0))
	g_pool.marker_state = Value('d',0.0)
	g_pool.calibrate = Value(c_bool, 0)
	g_pool.pos_record = Value(c_bool, 0)
	g_pool.eye_rx, g_pool.eye_tx = Pipe(False)
	g_pool.player_refresh = Event()
	g_pool.player_input = Value('i',0)
	g_pool.play = RawValue(c_bool,0)
	g_pool.quit = RawValue(c_bool,0)
	# shared constants
	g_pool.eye_src = eye_src
	g_pool.eye_size = eye_size
	g_pool.world_src = world_src
	g_pool.world_size = world_size

	# set up subprocesses
	p_eye = Process(target=eye, args=(g_pool,))
	if use_player: p_player = Process(target=player, args=(g_pool,player_size))

	# spawn subprocesses
	if use_player: p_player.start()
	p_eye.start()

	# On Linux, we need to give the camera driver some time before requesting another camera.
	sleep(1)

	# on MacOS, when using some cameras (like our current logitech worldcamera)
	# you can't run the world camera grabber in its own process
	# it must reside in the main process when you run on MacOS.
	world(g_pool)

	# Exit / clean-up
	p_eye.join()
	if use_player: p_player.join()
	print "main exit"
Exemple #33
0
capacity = 1000000
batchSize = 250

n_episode = 10000
episodes_before_train = 300

teamSpirit = 1 #0
teamSpirit_eps = 0 #1/n_episode

save_every_episodes = 2000

win = None
win2 = None
param = None

world = world(nSellers, totalTime, teamSpirit)

maddpg = MADDPG(nAgents, obsSize, nActions, batchSize, capacity,
                episodes_before_train)

rewardAveragers = [MovingAverager(100)] * nAgents
averageReward100 = [0] * nAgents

FloatTensor = th.cuda.FloatTensor if maddpg.use_cuda else th.FloatTensor
for i_episode in range(n_episode):
    obs = world.resetWorld()
    if isinstance(obs, np.ndarray):
        obs = th.from_numpy(obs).float()
    total_reward = 0.0
    rr = np.zeros((nAgents,))
    done = False
def init():
    global world, drawObjectsArray
    # Init OpenGL Utility Toolkit
    glutInit()
    # Init the Display Mode
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH)
    # and window size
    glutInitWindowSize(width, height)
    # and the Window Title (the b in front, is to give the name in bitwise - opengl needs that)
    glutCreateWindow(b"HS-RM 3D-Animation Avalanche")

    # clear the screen
    glClearColor(0, 0, 0, 0)

    # MatrixMode for setup
    glMatrixMode(GL_PROJECTION)

    # set up a perspective projection matrix
    # void gluPerspective(	GLdouble fovy,	GLdouble aspect, GLdouble zNear, GLdouble zFar);
    gluPerspective(40.0, float(width) / height, 1, 300.0)

    # define a viewing transformation - Camera on Z axis 10 away
    # void gluLookAt(GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX, GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ);

    # view far away
    '''gluLookAt(100, 100, 100,
              0, 0, 0,
              0, 1, 0)
    '''

    # view near
    gluLookAt(20, 40, 5, 0, 20, 0, 0, 1, 0)

    # set MatrixMode for render
    glMatrixMode(GL_MODELVIEW)

    # to have a callback function we need to add a display function
    glutDisplayFunc(display)

    # our world model
    world = world.world()

    # load my plane
    drawObjectsArray.append(
        object.object([0, -1, 0], 'resources/terrain.obj', world))

    # setup one particle position, velocity, mass, obj

    # whole map spawn
    for i in xrange(flakeCount):
        drawObjectsArray.append(
            particle.particle([
                uniform(-20.0, 20.0),
                uniform(40.0, 60.0),
                uniform(-20.0, 20.0)
            ], [0.0, 0.0, 0.0], uniform(.2, 1.0), 'resources/flake.obj', i,
                              world, drawObjectsArray))

    # near spawn
    '''for i in xrange(flakeCount):
        drawObjectsArray.append(particle.particle([uniform(-1.0, 1.0), uniform(2.0, 3.0), uniform(-1.0, 1.0)],
                              [0.0, 0.0, 0.0], uniform(.2, 1.0), 'resources/flake.obj', i, world, drawObjectsArray))'''

    # callback for keystroke
    glutKeyboardFunc(keyFunc)

    # callback for mousepress
    glutMouseFunc(mouseFunc)

    # Timer function for the 60 fps draw callback
    glutTimerFunc(1000 / 60, drawLoop, 1000 / 60)

    # glutMainLoop enters the GLUT event processing loop. This routine should be called at most once in a GLUT program.
    # Once called, this routine will never return. It will call as necessary any callbacks that have been registered.
    glutMainLoop()
 def createInitialWorld(self, _leftCardList, _rightCardList, _rule):
     self.retWorld = w.world(_leftCardList, _rightCardList, _rule)
     self.retWorld.dealCardsX(self.initialHand)
     self.retWorld.dealCardsToOpponentX(self.initialHand + 1)
     return self.retWorld
     pass
def fitness_func(solution):
    NN.set_weights(solution)
    score = world.world(50, artificial_player)
    return score
Exemple #37
0
 def loadworld(self,filename):
     X=world.world()
     file=open(filename,'rb')
     self.W=X.load(file)
     file.close()
Exemple #38
0
def main():
    print(hello.hello(), world.world())
Exemple #39
0
import sys
import math
import random
from world import world
from herbivore import herbivore
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
wrld = world(600,400,'spherical')
for i in range(50):
	wrld.agents.append(herbivore(wrld))
wrld.show()
sys.exit(app.exec_())
    def __init__(self):

        self.said_this_frame = []
        self.string_id = 0
        self.output = render2d.attach_new_node(TextNode("output text"))
        self.output.node().text = ""
        self.output.node().align = 2
        self.output.node().font = base.font
        self.output.set_scale(0.025, 0.025, 0.045)
        self.output.set_z(-0.75)
        self.to_output = []
        for i in range(5):
            self.say("")
        self.inventory = Inventory()
        self.money = self.inventory.add(Money(0, True))
        self.inventory.hide()
        self.say("press escape for menu")
        self.room, self.checkpoint, self.test = world()
        self.room.node.reparent_to(render)
        base.play_music(self.room.song)
        self.current = self.room

        self.location = render2d.attach_new_node(TextNode("location text"))
        self.location.node().text = self.room.node.name
        self.location.node().align = 2
        self.location.node().font = base.font
        self.location.set_scale(0.025, 0.025, 0.045)
        self.location.set_z(0.1)

        self.hp = 10
        self.max_hp = 10
        self.stats = {
            "offence": 0,
            "defence": 0,
            "endurance": 0,
        }
        self.equipment = {}
        self.creature_codex = []

        self.character = Inventory()
        self.character.hide()

        def get_health():
            base.interface.say("You have {}/{} hp.".format(
                self.hp, self.max_hp + self.stats["endurance"]))

        def get_stats():
            base.interface.say("Offence: {}.".format(self.stats["offence"]))
            base.interface.say("Defence: {}.".format(self.stats["defence"]))
            base.interface.say("Endurance: {}.".format(
                self.stats["endurance"]))

        manager = TextPropertiesManager.getGlobalPtr()
        tp = TextProperties()
        tp.setTextColor((0.2, 0.2, 0.2, 1))
        manager.setProperties("grey", tp)
        tp = TextProperties()
        tp.setTextColor((1, 1, 1, 1))
        manager.setProperties("white", tp)
        self.character.add(Option("inventory")).function = self.open_inventory
        self.character.add(Option("health")).function = get_health
        self.character.add(Option("stats")).function = get_stats
        quit = self.character.add(Menu("quit game"))
        quit.empty()
        quit.add(Return("yes, quit!", "")).function = sys.exit
        quit.add(Return("no, keep playing!", ""))
        self.dead = Rolodex("dead")
        self.dead.add(Option("You died."))
Exemple #41
0
    def __init__(self, width, height):
        # create pyglet window
        self.window = pyglet.window.Window()
        self.window.on_draw = self.on_draw
        self.window.on_key_press = self.on_key_press
        self.window.on_key_release = self.on_key_release
        self.window.width = width
        self.window.height = height
        self.key_pressed = []

        # create fps display 
        self.fps_display = pyglet.clock.ClockDisplay()
        self.clock = 0

        # sync clock
        pyglet.clock.schedule_interval(self.tick, 1.0/60.0)   
        pyglet.clock.set_fps_limit(60)

        # create world
        world_width = 3000
        world_height = 3000
        self.world = world.world(world_width, world_height)

        # create scene- match dimensions of the app window
        self.scene = scene.scene(self.world, offset_x=0, offset_y=0,width=width, height=height)

        # create physics engine
        self.engine = engine.engine()

        self.sun = []
        self.moon = []
        self.earth = []

        # throw some objects in there for now
        moon_pos = dict(x=world_width/2, y=world_height/2)
        moon = circle(position=moon_pos, color=(100, 100, 100, 255), radius=400, num_vertices=50, z_index=100)
        self.world.add_entity(moon)
        self.moon.append(moon)

        moon_pos = dict(x=world_width/2, y=world_height/2)
        moon = circle(position=moon_pos, color=(200, 200, 200, 255), radius=380, num_vertices=50, z_index=101)
        self.world.add_entity(moon)
        self.moon.append(moon)

        sun_pos = dict(x=world_width/4, y=world_height/4)
        sun = circle(position=sun_pos, color=(255, 255, 0, 200), radius=100, num_vertices=50, z_index=3)
        self.world.add_entity(sun)
        self.sun.append(sun)

        sun_pos = dict(x=world_width/4, y=world_height/4)
        sun = circle(position=sun_pos, color=(255, 215, 0, 200), radius=110, num_vertices=50, z_index=2)
        self.world.add_entity(sun)
        self.sun.append(sun)

        sun_pos = dict(x=world_width/4, y=world_height/4)
        sun = circle(position=sun_pos, color=(255, 150, 0, 200), radius=120, num_vertices=50, z_index=1)
        self.world.add_entity(sun)
        self.sun.append(sun)

        earth_pos = dict(x=world_width/8, y=world_height/8)
        earth = circle(position=earth_pos, color=(255, 255, 255, 100), radius=42, num_vertices=50, z_index=100)
        self.world.add_entity(earth)
        self.earth.append(earth)

        earth_pos = dict(x=world_width/8, y=world_height/8)
        earth = circle(position=earth_pos, color=(27, 92, 174, 255), radius=38, num_vertices=50, z_index=101)
        self.world.add_entity(earth)
        self.earth.append(earth)

        earth_pos = dict(x=world_width/8 + 5, y=world_height/8 + 5)

        land = [dict(x=-10, y=30), dict(x=0,y=0), dict(x=15, y=7.5), dict(x=20, y=15), dict(x=22, y=10), dict(x=20,y=-15)]
        earth = entity(position=earth_pos, color=(27, 98, 22, 225), z_index=102, vertices=land)
        self.world.add_entity(earth)
        self.earth.append(earth)
Exemple #42
0
# #f.write(data_stringB)
# pickle.dump(B,f)
#
l=preload('./carni')
C=bug.bug()
C.compile(l)
#
# #data_stringC=pickle.dumps(C)
# #f.write(data_stringC)
# pickle.dump(C,f)
# f.close()
# exit()



W=world.world()
W.add_hab(B,(10,20))
W.add_hab(C,(11,20))

while(GO and not TERMINATE):

    console.process_input()

    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()
        if event.type==MOUSEBUTTONDOWN:
            # Watchout swap rows,cols to match x,y
            # ToDo FIX offset
            y,x=event.pos
Exemple #43
0
        ourbot, ourdist = world.our_closest_robot_to_point(xpoint, ypoint)
        score += 100 * ourdist

        shoot_succes_reward = bot.shoot_from_pos(xpoint, ypoint)
        score += -shoot_succes_reward * 2
        score += field.distance_to_enemy_goal(field, xpoint, ypoint)
        return [score]


#################################################################################################

# some initial setup for the plot and the world
figure, ax = plt.subplots()
ax.set_xlim(field.leftx - 1, field.rightx + 1)
ax.set_ylim(field.boty - 1, field.topy + 1)
world = world()
world.create_their_bots(11)
world.create_our_bots(11)
world.plot_bots(ax)

# some constants for the field
N = 30
x = np.linspace(field.leftx, field.rightx, N, endpoint=False)
y = np.linspace(field.boty, field.topy, N, endpoint=False)
main_field = field()


# when the robots are dragged, the cost function needs to be recalculated
def redraw_cost_function():
    z = np.array([[a.cost_function(xpoint, ypoint)[0] for xpoint in x] for ypoint in y])
Exemple #44
0
def init():
    global world, drawObjectsArray
    # Init OpenGL Utility Toolkit
    glutInit()
    # Init the Display Mode
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH)
    # and window size
    glutInitWindowSize(width, height)
    # and the Window Title (the b in front, is to give the name in bitwise - opengl needs that)
    glutCreateWindow(b"HS-RM 3D-Animation Avalanche")

    # clear the screen
    glClearColor(0, 0, 0, 0)

    # MatrixMode for setup
    glMatrixMode(GL_PROJECTION)

    # set up a perspective projection matrix
    # void gluPerspective(	GLdouble fovy,	GLdouble aspect, GLdouble zNear, GLdouble zFar);
    gluPerspective(40.0, float(width) / height, 1, 300.0)

    # view far away
    gluLookAt(10, 45, -60, 0, 20, 0, 0, 1, 0)

    # set MatrixMode for render
    glMatrixMode(GL_MODELVIEW)

    # MatrixMode for setup
    glMatrixMode(GL_PROJECTION)

    # set ShadeModel
    glShadeModel(GL_SMOOTH)

    # enable if front and backface is rendered
    glEnable(GL_CULL_FACE)

    # enable depth Test
    glEnable(GL_DEPTH_TEST)

    # setup light - 2 lights for testing
    glLightfv(GL_LIGHT0, GL_POSITION, lightfv(-40, 200, 100, 0.0))
    glLightfv(GL_LIGHT0, GL_AMBIENT, lightfv(0.2, 0.2, 0.2, 1.0))
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightfv(0.5, 0.5, 0.5, 1.0))
    glEnable(GL_LIGHT0)

    # enable Lighting and Shadows
    glEnable(GL_LIGHTING)

    # enabling colored material
    glEnable(GL_COLOR_MATERIAL)

    # set MatrixMode for render
    glMatrixMode(GL_MODELVIEW)

    # our world model
    world = world.world()

    # load my plane
    drawObjectsArray.append(
        object.object([0, 0, 0], 'resources/terrain_smooth_flat.obj', world))

    # setup one particle position, velocity, mass, obj

    # collision Spawn Flakes
    for i in xrange(emitterCount):
        drawObjectsArray.append(
            particle.particle(
                [uniform(-5.0, 5.0),
                 uniform(50.0, 60.0),
                 uniform(0.0, 55.0)], [0.0, 0.0, 0.0], uniform(.2, 1.0),
                'resources/flake.obj', i, world, drawObjectsArray,
                flakesPerEmitter))

    # callback for mousepress
    glutMouseFunc(mouse)

    # Motion Func
    glutMotionFunc(motion)

    glutDisplayFunc(display)
    # Timer function for the 60 fps draw callback
    glutTimerFunc(1000 / fps, display, 1000 / fps)

    # glutMainLoop enters the GLUT event processing loop. This routine should be called at most once in a GLUT program.
    # Once called, this routine will never return. It will call as necessary any callbacks that have been registered.
    glutMainLoop()
Exemple #45
0
 def create_world(self):
     l=self.preload('./prog')
     B=bug.bug()
     B.compile(l)
     self.W=world.world()
     self.W.add_bug(B,pos.pos(2,1))
from macros import *
import numpy as np
import grid_agent as ga
from world import world
from visualize import visualize

if __name__ == "__main__":
    not_my_home = world(6, 6)
    not_my_home.new_agent(3, 4)
    my_agent = not_my_home.new_agent(4, 2)
    not_my_home.new_agent(2, 1)
    not_my_home.new_agent(3, 2)
    all_agents = not_my_home.list_all_agents()
    agents_in_range = not_my_home.agents_in_range(0, 3, 3, 0)
    for agent in agents_in_range:
        print agent
    my_agent.broadcast_msg(0x7)

    for agent in all_agents:
        print str(agent)

    # root = Tk()
    # canvas = Canvas(root, width=400, height=400)
    # canvas.grid()
    # root.mainloop()

    vis = visualize(not_my_home)
    vis.draw_world()
    vis.draw_agents()
    # vis.do_loop()
    vis.canvas.pack()
Exemple #47
0
import sys
import math
import random
from world import world
from herbivore import herbivore
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
wrld = world(800,600,'toroidal')
for i in range(20):
	wrld.agents.append(herbivore(wrld))
wrld.show()
sys.exit(app.exec_())
Exemple #48
0
----------------------------------------------- |
(iv)                                            |
Randomized Agent                                |
w/ Murphy                                       |
----------------------------------------------- |

"""

if __name__ == '__main__':

    for i in [1, 3, 5]:
        x = 0
        murphy = False
        random = False
        for _ in range(100):  # 100 Tests
            env = world.world(i, murphy)
            env.setup()

            v = world.vacuum(random, env)
            v.setup()
            x += v.act()
        x /= 100
        print("Dirt Spots: ", i, "M:", murphy, "R:", random, "Avg. Steps:", x)

    for i in [1, 3, 5]:
        x = 0
        murphy = False
        random = True
        for _ in range(100):  # 100 Tests
            env = world.world(i, murphy)
            env.setup()
Exemple #49
0
import sys
from world import world
from agent import agent
import random
from PyQt4 import QtGui, QtCore
from map import map

app = QtGui.QApplication(sys.argv)
inname = sys.argv[1]

mp = map(inname)

wrld = world(mp)
for i in range(mp.mwidth*mp.mheight/8):
	agent(wrld,i)
wrld.show()
sys.exit(app.exec_())
Exemple #50
0
from math import pi

from camera import camera, render
from canvas import canvas_to_ppm
from material import material
from matrix import scaling, translation, view_transform
from plane import plane
from sphere import sphere
from tuple import color, point, point_light, vector
from world import world

if __name__ == "__main__":
    start = time.time()
    print("Starting render...")

    w = world()
    w.light = point_light(point(-10, 10, -10), color(1, 1, 1))

    floor = plane()
    floor.transform = scaling(10, 0.01, 10)
    floor.material.color = color(1, 0.9, 0.9)
    floor.material.specular = 0
    w.objects.append(floor)

    # left_wall = sphere()
    # left_wall.transform = translation(0, 0, 5) * rotation_y(-pi/4) * rotation_x(pi/2) * scaling(10, 0.01, 10)
    # left_wall.material = floor.material
    # w.objects.append(left_wall)

    # right_wall = sphere()
    # right_wall.transform = translation(0, 0, 5) * rotation_y(pi/4) * rotation_x(pi/2) * scaling(10, 0.01, 10)
Exemple #51
0
    def __init__(self):
        # upper corner of the map shown in display
        self.coords=(0,0)
        # renderer
        self.re=None

        # Controls main loop
        self.GO=True
        self.TERMINATE=False

        self.RUNNING=False
        self.STEP=False
        # Shows the map
        self.SCREEN=True
        # Enables clicks on the map
        self.MAPENABLED=True
        # Selected bug
        self.SELECTEDBUG=None

        l=self.preload('./prog')
        B=bug.bug()
        B.compile(l)
        self.W=world.world()
        self.W.add_hab(B,(10,20))

        self.go_gui()
        self.draw_board()

        while self.GO and not self.TERMINATE:
            self.proc_events()
            if self.RUNNING or self.STEP:
                self.GO=self.W.cycle()
                if self.SCREEN:
                    self.draw_board()

            if self.STEP:
                self.STEP=False

            self.label_cycle.set_text("Cycle: "+str(self.W.cycles))
            self.label_bugs.set_text("Bugs: "+str(len(self.W.habs)))

            if self.SELECTEDBUG!=None and self.SELECTEDBUG in self.W.habs:
                hab=self.W.habs[self.SELECTEDBUG]
                bicho=hab.bug
                pos=hab.pos
                self.label_bugid.set_text("Bug Id: "+bicho.id)
                self.label_bugage.set_text("Age: "+str(bicho.age))
                self.label_bugenergy.set_text("Energy: "+str(bicho.energy()))
                self.label_bugpos.set_text("("+str(pos[0])+","+str(pos[1])+")")
                self.label_buginstr.set_text(bicho.last_executed)
            else:
                self.label_bugid.set_text("Bug Id: ")
                self.label_bugage.set_text("Age: ")
                self.label_bugenergy.set_text("Energy: ")
                self.label_bugpos.set_text("")
                self.label_buginstr.set_text("")

            self.screen.blit(self.re.screen,self.re.topleft)
            pygame.display.update()

        L=self.W.graveyard
        M=[x.bug for x in self.W.habs.values()]
        N=L+M
        totpop=len(N)
        print "The world ended at "+str(self.W.cycles)+" cycles."
        print "A total of "+str(totpop)+" bugs lived during this time."
        if totpop>0:
            oldest=max(L+M,key=attrgetter('age'))
            print "Oldest bug:"
            print "Id: "+oldest.id
            print "Age: "+str(oldest.age)
            print "Maxpop: "+str(self.W.maxpop)
            l=oldest.decompile()
            print l