Exemplo n.º 1
0
 def __init__(self):
     super(OptionsScreen, self).__init__()
 
     self.font = utils.getFont('VolterGoldfish', 44)
     self.infofont = utils.getFont('VolterGoldfish', 18)
     self.keyfont = utils.getFont('VolterGoldfish', 24)
     self.background = pygame.image.load("../img/backgrounds/options.png").convert()
     self.soundBar = pygame.image.load("../img/backgrounds/soundBar.png").convert_alpha()
     self.musicBar = pygame.image.load("../img/backgrounds/soundBar.png").convert_alpha()
     self.keyImg = pygame.image.load("../img/backgrounds/key.png").convert_alpha()
     self.volumeTest = pygame.mixer.Sound("../sounds/volumeTest.wav")
     self.menuEntries = ["Music","Sound","Controls","Back"]
     self.menuPositions = [(200,100),(200,200),(200,300),(200,500)]
     self.menuChoice = 0
     self.activeColor = THECOLORS["black"]
     self.inactiveColor = THECOLORS["grey64"]
     self.soundLevel = 0
     if exist('soundLevel'):
         self.soundLevel = load('soundLevel')
     self.musicLevel = 0
     if exist('musicLevel'):
        self.musicLevel = load('musicLevel')
     self.actionKeys = ['slow time','shield','trap','left','jump','right']
     self.keys = ['w','x','c','<','^','>']
     self.actionKeysPos = [(200,450),(330,450),(430,450),(530,450),(630,450),(730,450)]
Exemplo n.º 2
0
def imwrite(path, data, data_format="byxc"):
    if not exist(parent(path)):
        mkdir(parent(path))
    if data.ndim != 4:
        raise ValueError("iomanager.imwrite: image's dimension is not 4d")

    if data_format.lower() == "byxc":
        pass
    elif data_format.lower() == "bcyx":
        data = np.transpose(data, (0, 3, 1, 2))
    else:
        raise ValueError(
            'iomanager.imwrite: this data format is not supported. format:({})'
            .format(data_format))

    b, y, x, c = data.shape

    if b != 1 or (c != 1 and c != 3 and c != 4):
        raise ValueError(
            "iomanager.imwrite: not appropriate b,y,x,c ({},{},{},{})".format(
                b, y, x, c))

    if c == 3 or c == 4:
        img = np.clip((data[0] * 255), 0, 255).astype(np.uint8)
    elif c == 1:
        img = np.clip((data[0, :, :, 0] * 255), 0, 255).astype(np.uint8)
    imageio.imsave(path, img)
Exemplo n.º 3
0
 def __init__(self, levelInd):
     super(GameScreen, self).__init__()
     self.fadeScreen    = pygame.image.load("../img/backgrounds/blackscreen.png").convert()
     self.font          = getFont("VolterGoldfish", 20)
     self.nextColorIcon = pygame.image.load("../img/hud/nextColor23.png").convert_alpha()
     self.progressIcon  = pygame.image.load("../img/hud/progress.png").convert_alpha()
     self.timebar       = pygame.image.load("../img/hud/timebar.png").convert_alpha()
     self.shieldbar     = pygame.image.load("../img/hud/shieldbar.png").convert_alpha()
     self.lifebar_      = pygame.image.load("../img/hud/lifebar_.png").convert()
     
     self.level         = Level(levelInd)
     self.camera        = Camera(640, 800, 3200)
     # running          = True
     self.retry         = False
     self.frame_number  = 0
     self.anims         = []
     
     self.stopDelay     = 0
     self.stopped       = False
     
     self.killFragments = []
     self.dust          = []
     
     self.starting      = True
     self.ending        = False
     self.alpha         = 255
     
     
     # Music load
     # pygame.mixer.music.load("../sounds/piano.wav")
     # pygame.mixer.music.play(-1)
     pygame.mixer.music.set_volume(0.5)
     
     # Player
     self.player        = Player()
     self.fire          = Rect((0,3200),(800,5))
     self.playerDown    = False
     
     
     self.answerPos     = [(100,300),(100,400),(100,500)]
     self.answerChoice  = 0
     self.activecolor   = THECOLORS['white']
     self.inactivecolor = THECOLORS['grey21']
     
     if exist('powers'):
         self.player.timePower, self.player.mines, self.player.shields = load('powers')
Exemplo n.º 4
0
def get_dtd(file):
    if file in files:
        # static files
        f = files[file]
    else:
        # dynamic generate files
        f = {'lang': {'java': False, 'php': False}}
        url = ''
        # protocol
        if exist(request.args.get('f')):
            url += 'file'
        elif exist(request.args.get('j')):
            url += 'jar'
            f['lang']['java'] = True
        elif exist(request.args.get('p')):
            url += 'php'
            f['lang']['php'] = True
        elif exist(request.args.get('ft')):
            url += 'ftp'
        else:
            return "No url scheme specified."
        url += '://'
        if valid(request.args.get('fu')):
            url += request.args.get('fu')
        else:
            return "No url content specified."
        f['url'] = url

        # language
        if not f['lang']['java'] and not f['lang']['php']:
            if exist(request.args.get('lj')):
                f['lang']['java'] = True
            elif exist(request.args.get('lp')):
                f['lang']['php'] = True
            elif exist(request.args.get('lpb')):
                f['lang']['php'] = True
                f['base64'] = True
            else:
                return "No language specified."
        f['domain'] = host
        f['port'] = port

    return render_template('dtd.html', file=f)
Exemplo n.º 5
0
def latest_idx(fdir, fname, fext="pth", pattern=None):
	"""
	:param fdir:		모델이 저장된 폴더
	:param fname:		iteration 번호를 제외한 model 이름
	:param fext:		확장자
	:param pattern:	model 이름 패턴. 기본적으로는 ".*{}-(\d+).{}$".format(join(fdir, fname, fext)) 형태
	:return:			해당 파일이 있으면 iteration 인덱스를 줌, 없으면 None
	"""

	# 경로 없으면 None
	if not exist(fdir):
		return None

	# 폴더인지 여부
	if not is_dir(fdir):
		raise ValueError("pc6.util_pt.saver.latest_idx: path ({}) not dir".format(fdir))

	# 인덱스 찾아서 리턴
	files, idxs = ls_model(fdir, fname, fext, pattern=pattern)
	if len(idxs) == 0:
		return None
	else:
		return idxs[-1]
Exemplo n.º 6
0
def gaVRPTW(instName,
            unitCost,
            initCost,
            waitCost,
            delayCost,
            indSize,
            popSize,
            cxPb,
            mutPb,
            NGen,
            exportCSV=False,
            customizeData=False):
    if customizeData:
        jsonDataDir = os.path.join(BASE_DIR, 'data', 'json_customize')
    else:
        jsonDataDir = os.path.join(BASE_DIR, 'data', 'json')
    jsonFile = os.path.join(jsonDataDir, '%s.json' % instName)
    with open(jsonFile) as f:
        instance = load(f)
    creator.create('FitnessMax', base.Fitness, weights=(1.0, ))
    creator.create('Individual', list, fitness=creator.FitnessMax)
    toolbox = base.Toolbox()
    # Attribute generator
    toolbox.register('indexes', random.sample, range(1, indSize + 1), indSize)
    # Structure initializers
    toolbox.register('individual', tools.initIterate, creator.Individual,
                     toolbox.indexes)
    toolbox.register('population', tools.initRepeat, list, toolbox.individual)
    # Operator registering
    toolbox.register('evaluate',
                     evalVRPTW,
                     instance=instance,
                     unitCost=unitCost,
                     initCost=initCost,
                     waitCost=waitCost,
                     delayCost=delayCost)
    toolbox.register('select', tools.selRoulette)
    toolbox.register('mate', cxPartialyMatched)
    toolbox.register('mutate', mutInverseIndexes)
    pop = toolbox.population(n=popSize)
    # Results holders for exporting results to CSV file
    csvData = []
    print 'Start of evolution'
    # Evaluate the entire population
    fitnesses = list(map(toolbox.evaluate, pop))
    for ind, fit in zip(pop, fitnesses):
        ind.fitness.values = fit
    print '  Evaluated %d individuals' % len(pop)
    # Begin the evolution
    for g in range(NGen):
        print '-- Generation %d --' % g
        # Select the next generation individuals
        offspring = toolbox.select(pop, len(pop))
        # Clone the selected individuals
        offspring = list(map(toolbox.clone, offspring))
        # Apply crossover and mutation on the offspring
        for child1, child2 in zip(offspring[::2], offspring[1::2]):
            if random.random() < cxPb:
                toolbox.mate(child1, child2)
                del child1.fitness.values
                del child2.fitness.values
        for mutant in offspring:
            if random.random() < mutPb:
                toolbox.mutate(mutant)
                del mutant.fitness.values
        # Evaluate the individuals with an invalid fitness
        invalidInd = [ind for ind in offspring if not ind.fitness.valid]
        fitnesses = map(toolbox.evaluate, invalidInd)
        for ind, fit in zip(invalidInd, fitnesses):
            ind.fitness.values = fit
        print '  Evaluated %d individuals' % len(invalidInd)
        # The population is entirely replaced by the offspring
        pop[:] = offspring
        # Gather all the fitnesses in one list and print the stats
        fits = [ind.fitness.values[0] for ind in pop]
        length = len(pop)
        mean = sum(fits) / length
        sum2 = sum(x * x for x in fits)
        std = abs(sum2 / length - mean**2)**0.5
        print '  Min %s' % min(fits)
        print '  Max %s' % max(fits)
        print '  Avg %s' % mean
        print '  Std %s' % std
        # Write data to holders for exporting results to CSV file
        if exportCSV:
            csvRow = {
                'generation': g,
                'evaluated_individuals': len(invalidInd),
                'min_fitness': min(fits),
                'max_fitness': max(fits),
                'avg_fitness': mean,
                'std_fitness': std,
            }
            csvData.append(csvRow)
    print '-- End of (successful) evolution --'
    bestInd = tools.selBest(pop, 1)[0]
    #print 'Best individual: %s' % bestInd
    #print 'Fitness: %s' % bestInd.fitness.values[0]
    #printRoute(ind2route(bestInd, instance))
    #print 'Total cost: %s' % (1 / bestInd.fitness.values[0])

    # We need returning json, not print on console and/or writing csv
    return_json = {}
    our_order = bestInd[:]
    return_json['order'] = order_map(our_order)
    return_json['route'] = route_map(ind2route(bestInd, instance))
    return_json['Fitness'] = bestInd.fitness.values[0]
    return_json['cost'] = 1 / bestInd.fitness.values[0]
    return return_json
    if exportCSV:
        csvFilename = '%s_uC%s_iC%s_wC%s_dC%s_iS%s_pS%s_cP%s_mP%s_nG%s.csv' % (
            instName, unitCost, initCost, waitCost, delayCost, indSize,
            popSize, cxPb, mutPb, NGen)
        csvPathname = os.path.join(BASE_DIR, 'results', csvFilename)
        print 'Write to file: %s' % csvPathname
        makeDirsForFile(pathname=csvPathname)
        if not exist(pathname=csvPathname, overwrite=True):
            with open(csvPathname, 'w') as f:
                fieldnames = [
                    'generation', 'evaluated_individuals', 'min_fitness',
                    'max_fitness', 'avg_fitness', 'std_fitness'
                ]
                writer = DictWriter(f, fieldnames=fieldnames, dialect='excel')
                writer.writeheader()
                for csvRow in csvData:
                    writer.writerow(csvRow)