Exemplo n.º 1
0
def run(inputCount, outputCount, population, activationFunction, generationCount, windowSize = Fitness.windowSize):
    win = graphics.GraphWin("NEAT", width = windowSize[0], height = windowSize[1]) #The window that NEAT will draw the evaluation of each genome in
    currGeneration = Generation.generation(inputCount, outputCount, population, activationFunction) #Creates a first generation
    t = 0 #Keeps track of which generation we're on
    while t < generationCount:
        print("Beginning Generation " + str(t))
        currGeneration.assignSpecies() #Assigns a species to each member of the current generation
        currGeneration.countSpecies() #Counts up how many members are in each species
        activeSpecies = sum([x > 0 for x in currGeneration.counts])
        print("Active Species: " + str(activeSpecies)) #Prints how many species still have living members
        print("Extinct Species: " + str(len(currGeneration.counts) - activeSpecies)) #Prints how many species have lived and then gone extinct
        currGeneration.assignFitnesses(win) #Assigns each genome in the generation its fitness
        print("Max Fitness: " + str(max([x.FI * currGeneration.counts[int(x.SP[4:])] for x in currGeneration.genomes]))) #Prints the raw fitness of the best genome
        print("Average Fitness: " + str((sum([x.FI * currGeneration.counts[int(x.SP[4:])] for x in currGeneration.genomes])) / population)) #Prints the average raw fitness of the generation
        currGeneration.assignParents() #Creates the list of parents
        currGeneration.generateChildren() #Creates the genomes in the next generation
        nextGeneration = Generation.generation(inputCount, outputCount, population, activationFunction, currGeneration.IN) #Creates the next generation
        print("Current Innovation Number: " + str(currGeneration.IN)) #Prints the current innovation number
        nextGeneration.genomes = copy.deepcopy(currGeneration.children) #Loads the genomes into the new generation
        nextGeneration.holotypes = copy.deepcopy(currGeneration.holotypes) #Preserves the collection of holotypes
        currGeneration = copy.deepcopy(nextGeneration) #Loads the next generation
        del nextGeneration #Deletes the placeholder generation
        t += 1 #Moves the generation counter
        print(20 * "~*")
    win.close()
Exemplo n.º 2
0
def turn():
    Clear.clear()
    with open("UniData.txt", 'r') as f:
        variables = json.load(f)
        #variables["week"] += 1
        #f.close()
    variables["week"] += 1
    with open("UniData.txt", 'w') as f2:
        json.dump(variables, f2, indent=3)
        #f2.close()
    WordCore.word_core("A new week has come...", 0.01)
    print("\n")
    print("Week Number: " + str(variables["week"]))
    Generation.dna_weekly()
    Generation.dna_random()
    infecting_agent()
    check_cure_start()
    BURST_check()
    NECROSIS_check()
    ZOMBIFY_check()
    enforce_value_maximums()
    print("\n")
    Graph.graphical_analysis_mini()
    #time.sleep(3)
    player_menu()
Exemplo n.º 3
0
    def __init__(self,
                 OutputGeometryFile,
                 OutputXmlFile,
                 VoxelSizeMetres,
                 Axis,
                 LengthMetres,
                 RadiusMetres,
                 InletPressure=None,
                 OutletPressure=None):
        """Clip the STL and set attributes on the SWIG-proxied C++
        GeometryGenerator object.
        """
        GeometryGenerator.__init__(self)
        self.Axis = Axis
        self.LengthMetres = LengthMetres
        self.RadiusMetres = RadiusMetres
        self.InletPressure = InletPressure
        self.OutletPressure = OutletPressure

        self._profile = Profile()
        self._profile.StlFileUnitId = Profile._UnitChoices.index(metre)
        self._profile.VoxelSize = VoxelSizeMetres
        self._profile.OutputGeometryFile = OutputGeometryFile
        self._profile.OutputXmlFile = OutputXmlFile
        self._MakeIolets()

        self.generator = Generation.CylinderGenerator()
        self._SetCommonGeneratorProperties()

        self.generator.SetCylinderLength(LengthMetres / VoxelSizeMetres)
        self.generator.SetCylinderRadius(RadiusMetres / VoxelSizeMetres)
        self.generator.SetCylinderCentre(Generation.DoubleVector(0., 0., 0.))
        self.generator.SetCylinderAxis(Generation.DoubleVector(*self.Axis))
        return
Exemplo n.º 4
0
    def _MakeIolets(self):
        # Construct the Iolet structs
        inlet = Inlet()
        c = [0., 0., 0.]
        c[self.OpenAxis] = -0.5 * self.LengthVoxels * self._profile.VoxelSize
        inlet.Centre = Vector(*c)

        n = Generation.DoubleVector()
        n[self.OpenAxis] = 1.
        inlet.Normal = Vector(n.x, n.y, n.z)

        inlet.Radius = self.SideVoxels * self._profile.VoxelSizeMetres
        if self.InletPressure is not None:
            inlet.Pressure = self.InletPressure
        self._profile.Iolets.append(inlet)

        outlet = Outlet()
        c = [0., 0., 0.]
        c[self.OpenAxis] = 0.5 * self.LengthVoxels * self._profile.VoxelSize
        outlet.Centre = Vector(*c)

        n = Generation.DoubleVector()
        n[self.OpenAxis] = -1.
        outlet.Normal = Vector(n.x, n.y, n.z)

        outlet.Radius = self.SideVoxels * self._profile.VoxelSizeMetres
        if self.OutletPressure is not None:
            outlet.Pressure = self.OutletPressure
        self._profile.Iolets.append(outlet)

        return
Exemplo n.º 5
0
    def __init__(self, OutputGeometryFile, OutputXmlFile, VoxelSizeMetres,
                 OpenAxis, LengthVoxels, SideVoxels,
                 InletPressure=None, OutletPressure=None):
        """Clip the STL and set attributes on the SWIG-proxied C++
        GeometryGenerator object.
        """
        GeometryGenerator.__init__(self)
        assert OpenAxis in (0, 1, 2)
        self.OpenAxis = OpenAxis
        self.LengthVoxels = LengthVoxels
        self.SideVoxels = SideVoxels
        self.Sizes = Generation.DoubleVector(SideVoxels, SideVoxels, SideVoxels)
        self.Sizes[OpenAxis] = LengthVoxels
        
        self.InletPressure = InletPressure
        self.OutletPressure = OutletPressure

        self._profile = Profile()
        self._profile.StlFileUnitId = Profile._UnitChoices.index(metre)
        self._profile.VoxelSize = VoxelSizeMetres
        self._profile.OutputGeometryFile = OutputGeometryFile
        self._profile.OutputXmlFile = OutputXmlFile
        self._MakeIolets()

        self.generator = Generation.SquareDuctGenerator()
        self._SetCommonGeneratorProperties()

        self.generator.SetOpenAxis(self.OpenAxis)
        lb = self.Sizes * -0.5
        self.generator.SetLowerBound(lb)
        ub = self.Sizes * 0.5
        self.generator.SetUpperBound(ub)
        return
Exemplo n.º 6
0
def validate(load_data, feat_dict):
    clf = load_data['model']
    norm = load_data['norm']
    mean = load_data['mean']
    std = load_data['std']

    if (norm == "MeanStd"):
        g.normFeature(feat_dict, norm, mean, std)
    elif (norm == "MinMax"):
        g.normFeature(feat_dict, norm)
    else:
        assert (False)

    feat_array = g.convertDictToFeatArray(feat_dict)
    return clf.predict(feat_array)
Exemplo n.º 7
0
 def __init__(self):
     self.turtleWrapper = turtleWrap.TurtleWrapper()
     self.warehouse = warehouse.Warehouse()
     self.population = Generation.Generation()
     self.screen = turtle.Screen()
     self.current_position = Point.Point(round(self.warehouse.WIDTH/2), round(self.warehouse.HEIGHT/2))
     self.init_screen()
Exemplo n.º 8
0
class God:
    generation = None

    def initializeFirstGeneration(self):
        self.generation = Generation(0)

    def applyEvolution(self):
        empty = []
        empty2 = []  #number of stay puts
        for i in range(NUM_GENERATIONS):
            self.generation, normalizedScore, bestScore, number_of_stay_puts = self.generation.applyEvolution(
            )
            print(str(normalizedScore) + ',' + str(bestScore))
            empty.append(bestScore)
            empty2.append(number_of_stay_puts)

            with open('results.txt', 'a') as file:
                file.write(str(normalizedScore) + ',' + str(bestScore) + '\n')

        plt.plot(empty2, 'r-', label='Number of stay puts')
        plt.plot(empty, 'b-', label='Fitness in the population')
        plt.ylabel("Best Fitness in Population")
        plt.xlabel("Generation")
        plt.legend()
        plt.savefig('foo.png')
        plt.show()
def PrintGenerationMenu():
    Selection = input("\nGeneration Menu > ")
    try:
        if Selection == "exit":
            #print("Spacer")
            SelectMenu(GenerationMenu, MainMenu)
        elif Selection == "reload":
            Core.ClearScreen()
            os.execl(sys.executable, sys.executable, *sys.argv)
        else:
            Selection = (int(Selection))
            if Selection == 1:
                Generation.HTTPGen()
            elif Selection == 2:
                Generation.DHCPGen()
            elif Selection == 3:
                Generation.DNSGen()
    except:
        SelectMenu(GenerationMenu, GenerationMenu)
Exemplo n.º 10
0
def main():

    # Read yaml configuration file
    routing_config = Utilities.read_yml("routing_config.yml")
    routes = routing_config['routes']
    generations = routing_config['generations']
    generation_size = routing_config['generation_size']
    mutation_chance = routing_config['mutation_chance']
    origin = routing_config['origin']

    # Read in csv to a dictionary
    #nodes_dict = Utilities.read_input_nodes("Kiosk Coords.csv")
    nodes_dict = Utilities.read_json_states("state_capitals.json")

    #  Creates a Network object for the purpose of organizing the Nodes for use in the genetic algorithm
    node_network = Network.Network('StateCapitols', origin, nodes_dict)

    # Create the initial generation of solutions
    solution_generation = Generation.Generation(size=generation_size,
                                                routes=routes,
                                                origin=origin,
                                                network=node_network)

    # Begin iterating through generations
    best_solution = None
    for i in range(1, generations + 1):

        solution_generation.generation_step(mutation_chance)
        solution_generation.remove_weakest_half()

        # Log best solutions
        if best_solution is not None:
            current_best_solution = solution_generation.get_best_solution()
            if (best_solution.score > current_best_solution.score):
                best_solution = current_best_solution
        else:
            best_solution = solution_generation.get_best_solution()

        if i % 100 == 0:
            print("Generation:   ", i)
            print("Average distance: ",
                  solution_generation.generation_average_score())
            print("Min Distance: ", best_solution.score)
            print("")

    #print(best_solution.route_list)
    #print(best_solution.score)

    # If the best solution was found to be valid print output and generate a quick plot for validation
    if best_solution.valid_solution():
        node_network.process_solution(best_solution)
        node_network.display_routes()
        node_network.plot_routes()
    else:
        print("Error: Best solution is invalid")
Exemplo n.º 11
0
def turn_fast():
    Clear.clear()
    with open("UniData.txt", 'r') as f:
        variables = json.load(f)
    variables["week"] += 1
    with open("UniData.txt", 'w') as f2:
        json.dump(variables, f2, indent=3)
    print("A new week has come...")
    print("\n")
    print("Week Number: " + str(variables["week"]))
    Generation.dna_weekly()
    Generation.dna_random()
    infecting_agent()
    check_cure_start()
    BURST_check()
    NECROSIS_check()
    ZOMBIFY_check()
    enforce_value_maximums()
    Game_Over()
    print("\n")
Exemplo n.º 12
0
class God:
    generation = None

    def initialize_first_generation(self):
        self.generation = Generation(0)

    def apply_evolution(self):
        for i in range(NUM_GENERATIONS):
            self.generation, normalized_score, best_score = self.generation.apply_evolution()
            print(str(normalized_score) + ',' + str(best_score))
            with open('results.txt', 'a') as file:
                file.write(str(normalized_score) + ',' + str(best_score) + '\n')
Exemplo n.º 13
0
    def __init__(self, profile):
        """Clip the STL and set attributes on the SWIG-proxied C++
        GeometryGenerator object.
        """
        GeometryGenerator.__init__(self)
        self._profile = profile
        self.generator = Generation.PolyDataGenerator()
        self._SetCommonGeneratorProperties()
        self.generator.SetSeedPointWorking(
            profile.SeedPoint.x / profile.VoxelSize,
            profile.SeedPoint.y / profile.VoxelSize,
            profile.SeedPoint.z / profile.VoxelSize)

        # This will create the pipeline for the clipped surface
        clipper = Clipper(profile)

        # Scale by the voxel size
        trans = vtkTransform()
        scale = 1. / profile.VoxelSize
        trans.Scale(scale, scale, scale)

        transformer = vtkTransformFilter()
        transformer.SetTransform(trans)
        transformer.SetInputConnection(
            clipper.ClippedSurfaceSource.GetOutputPort())

        # Uncomment this an insert the output path to debug pipeline construction
        # write = StageWriter('/Users/rupert/working/compare/aneurysm').WriteOutput
        # i = 0
        # for alg in getpipeline(transformer):
        #     print i
        #     i += 1
        #     print alg
        #     write(alg)

        transformer.Update()
        self.ClippedSurface = transformer.GetOutput()
        self.generator.SetClippedSurface(self.ClippedSurface)

        originWorking, nSites = self._ComputeOriginWorking()
        self.generator.SetOriginWorking(*(float(x) for x in originWorking))
        self.generator.SetSiteCounts(*(int(x) for x in nSites))
        self.OriginMetres = Vector(originWorking * self.VoxelSizeMetres)
        return
Exemplo n.º 14
0
    def __init__(self, size, maze_type, algorithm, auto_generation=True):
        self.size = size
        self.maze_type = maze_type
        self.type_value = getattr(self.Type, maze_type)
        self.position = None
        self.cell_size = None
        self.graph_cell_size = None
        self.algorithm = algorithm

        if auto_generation:
            self.cell_list = CellList.generate(self.type_value, self.size)
            self.edge_list = EdgeList.generate(self.type_value, self.size)

            self.maze_list, self.maze_order, self.maze_cell_borders = Generation.generate(
                algorithm, self.type_value, self.cell_list, self.edge_list)

        else:
            self.cell_list = None
            self.edge_list = None

            self.maze_list, self.maze_order, self.maze_cell_borders = None, None, None

        # solution lists
        self.solution_path = []
        self.visited = []

        self.graph_bool = False
        self.step_bool = False
        self.delay = False

        (start,
         end) = MazeFunctions.cell_endpoints_calculate(self.type_value,
                                                       self.size)

        self.start = self.cell_list[start]
        self.end = self.cell_list[end]

        # maze colors
        self.color_background = Color.white
        self.color_line = Color.black
        self.color_start = Color.green_light
        self.color_end = Color.salmon
        self.color_frame = Color.black
Exemplo n.º 15
0
    def __init__(self, ce_id):
        # check if there is "Simulations" folder is already created or not
        self.simulationsPath = os.path.dirname(
            os.path.realpath(__file__)) + "/Simulations/"
        if os.path.isdir(self.simulationsPath):
            pass
        else:
            os.makedirs(self.simulationsPath)

        # Collection of all CultEvo runs
        # something of the form : ..cwd..\Simulations_2016-03-04_[13_23_06]\
        self.simulationPath = self.simulationsPath + "Sim_{}/".format(ce_id)
        if os.path.isdir(self.simulationPath):
            pass
        else:
            # create folders with specific simulation detail as their name
            os.makedirs(self.simulationPath)

        # individual simulation run paths(holding all its generation folders):
        self.simRunPath = self.simulationPath + "SimRun_000/"

        if os.listdir(self.simulationPath).__len__() == 0:
            os.makedirs(self.simRunPath)

        else:
            # get the highest index of the already existing folders.

            self.simRunPath = self.simulationPath + "SimRun_{:03}/".format(
                int(sorted(os.listdir(self.simulationPath))[-1].split("_")[1])
                + 1)
            os.makedirs(self.simRunPath)

        # for Generation folders check in Generation.py

        # Variable determining how many generations we wan t toallow
        generations = P.generations

        generation_run = Generation.Generation(P.numberAgents, generations,
                                               self.simRunPath)

        self.numOfGenerations = generation_run.countGenUp
Exemplo n.º 16
0
def init(floor, wall, render_layer):
    lvl, enemies = Generation.generate()

    for xx in range(size_x):
        for yy in range(size_y):
            f = None
            if lvl[(xx, yy)] == 1:
                f = wall(xx, yy)
            else:
                f = floor(xx, yy)

            actors[(xx, yy)] = None
            terrain[(xx, yy)] = f

            render_layer.add(f)

    for k, v in enemies.items():
        enemy = v(k[0], k[1])
        actors[k] = enemy

        render_layer.add(enemy)

        State.spawn(enemy)
Exemplo n.º 17
0
    def _MakeIoletProxies(self):
        # Construct the Iolet structs
        nIn = 0
        nOut = 0
        ioletProxies = []
        for io in self._profile.Iolets:
            proxy = Generation.Iolet()

            proxy.Centre = DVfromV(io.Centre) / self._profile.VoxelSize
            proxy.Normal = DVfromV(io.Normal)
            proxy.Radius = io.Radius / self._profile.VoxelSize

            if isinstance(io, Inlet):
                io.Id = proxy.Id = nIn
                proxy.IsInlet = True
                nIn += 1
            elif isinstance(io, Outlet):
                io.Id = proxy.Id = nOut
                proxy.IsInlet = False
                nOut += 1
                pass
            ioletProxies.append(proxy)
            continue
        return ioletProxies
Exemplo n.º 18
0
def DVfromV(v):
    """Translate a Model.Vector.Vector to a Generation.DoubleVector.
    """
    return Generation.DoubleVector(v.x, v.y, v.z)
Exemplo n.º 19
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--Start', '-s', type=int, default=11)
    parser.add_argument('--End', '-e', type=int, default=15)
    parser.add_argument('--Plot', '-p', type=str, default="False")

    # Append additional data to results.pkg
    parser.add_argument('--Append', '-a', type=str, default="True")

    # Using C values instead
    parser.add_argument('--C', '-c', type=str, default="False")

    args = parser.parse_args()

    meas_obj = mm.Measurement("Study_005_channel1.pkg", args.Start, args.End)
    meas_obj.downsample(2)

    feat_obj = fe.Feature(meas_obj)

    feat_label_dict = g.getFeaturesAndLabel(meas_obj, feat_obj)
    feat_dict = dict(
        (k, feat_label_dict[k]) for k in feat_key if k in feat_label_dict)
    data_downsampled = feat_label_dict['data']
    label_downsampled = feat_label_dict['label']

    # Good practice to check that the correct keys are generated for their value
    if (g.checkDictForFeat(feat_dict) == False):
        assert (False)

    # MIGHT GET RID OF APPEND AND REPLACE IT WITH ANOTHER FUNCTION THAT SIMPLY DELETES EXTRANEOUS INFORMATION?
    list_of_files = os.listdir('.')
    trained_files = []
    if (str2bool(args.Append) == True and str2bool(args.C) == False):
        start_gamma = input("Enter the first gamma: ")
        end_gamma = input("Enter the last gamma: ")
        inc = 1
        for i in np.arange(start_gamma, end_gamma + inc, inc):
            pattern = "trained_SVM_rbf_gamma_" + str(i) + "_*"
            for entry in list_of_files:
                if fnmatch.fnmatch(entry, pattern) and entry.find('C') == -1:
                    x = input(entry)
                    trained_files.append(entry)
                    break
        load_results = loadFile("results.pkg")
        results = load_results['results']
        gamma_data = load_results['gamma_data']
        for i in trained_files:
            load_svm = loadFile(i)
            if (load_svm['gamma'] not in gamma_data):
                temp_feat_dict = copy.deepcopy(feat_dict)
                result = validate(load_svm, temp_feat_dict)
                results.append(result)
                gamma_data.append(load_svm['gamma'])
            else:
                print("Skipping")
        save_data = {
            'feat_obj': feat_obj,
            'results': results,
            'gamma_data': gamma_data
        }
        pickle.dump(save_data, open("results.pkg", 'wb'))

    elif (str2bool(args.Append) == False and str2bool(args.C) == False):
        pattern = "trained_SVM_rbf_gamma_*"
        for entry in list_of_files:
            if fnmatch.fnmatch(entry, pattern) and entry.find('C') == -1:
                trained_files.append(entry)
        # Going through all the trained files and analyzing its performance
        results = []
        gamma_data = []
        for i in trained_files:
            load_svm = loadFile(i)
            temp_feat_dict = copy.deepcopy(feat_dict)
            result = validate(load_svm, temp_feat_dict)
            results.append(result)
            gamma_data.append(load_svm['gamma'])
            #if (str2bool(args.Plot) == True):
            #    plotResults(data_downsampled, result, label_downsampled, load_data['gamma'], load_data['method'])
        save_data = {
            'feat_obj': feat_obj,
            'results': results,
            'gamma_data': gamma_data
        }
        pickle.dump(save_data, open("results.pkg", 'wb'))

    else:
        print("Calculating C")
        pattern = "trained_SVM_rbf_gamma_*"
        for entry in list_of_files:
            if fnmatch.fnmatch(entry, pattern) and entry.find('C') != -1:
                trained_files.append(entry)
        x = input(trained_files)
        results = []
        C_data = []
        gamma_data = []
        for i in trained_files:
            load_svm = loadFile(i)
            print(load_svm['gamma'])
            temp_feat_dict = copy.deepcopy(feat_dict)
            result = validate(load_svm, temp_feat_dict)
            results.append(result)
            C_data.append(load_svm['C'])
            gamma_data.append(load_svm['gamma'])
            #if (str2bool(args.Plot) == True):
            #    plotResults(data_downsampled, result, label_downsampled, load_data['gamma'], load_data['method'])
        save_data = {
            'feat_obj': feat_obj,
            'results': results,
            'gamma_data': gamma_data,
            'C_data': C_data
        }
        pickle.dump(save_data, open("results_C.pkg", 'wb'))
Exemplo n.º 20
0
import Generation as G

gen = G.Generation()
Exemplo n.º 21
0
    def __init__(self, island, pos):
        self.entities = []
        self.island = island
        self.pos = pos
        self.discovered = False
        self.visited = False
        self.type = RoomType.NORMAL

        # Get background textures
        self.map = Parser.main(pos, self.island.width, self.island.length)
        self.tileLib = Parser.tileDict()
        self.tiles = []
        self.drawX = 0
        self.drawY = 0

        # Get room contents
        self.layout = Parser.getLayout(self.type)
        self.layoutLib = Parser.getLayoutLib()

        # Data from generation
        self.neighbors = dict()
        self.gen_Object = Generation.Generation().Room()

        # Apply background textures
        self.bg = pygame.Surface(
            pygame.math.Vector2(Constants.ROOM_SIZE * Constants.TILE_SIZE,
                                Constants.ROOM_SIZE * Constants.TILE_SIZE))
        for element in self.map:
            self.tilesRow = []
            for unit in element:
                tilename = self.tileLib[unit].replace('"', '')
                tilename = random.choice(tilename.split('&'))
                self.image = Drawing.Sprite(
                    pygame.image.load(tilename).convert_alpha())
                self.image.scale = pygame.math.Vector2(
                    64 / self.image.tex.get_width(),
                    64 / self.image.tex.get_height())
                self.tilesRow.append(self.image)
            self.tiles.append(self.tilesRow)

        for element in self.tiles:
            for unit in element:
                unit.pos = pygame.math.Vector2(self.drawX, self.drawY)
                unit.draw(self.bg)
                self.drawX += 64
            self.drawY += 64
            self.drawX = 0

        # Apply room contents
        self.drawX = 0
        self.drawY = 0
        for row in self.layout:
            for element in row:
                if element in self.layoutLib:
                    obj = 0
                    if element is "h":
                        obj = Characters.HornetEnemy(self)
                    elif element is "s":
                        obj = Characters.SnakeEnemy(self)
                    obj.pos = pygame.math.Vector2(self.drawX, self.drawY)
                    self.entities.append(obj)
                self.drawX += 64
            self.drawY += 64
            self.drawX = 0
Exemplo n.º 22
0
 def initialize_first_generation(self):
     self.generation = Generation(0)
Exemplo n.º 23
0
def generate_sudoku(difficulty):
    return remove_numbers(Generation.make_full_grid(3), difficulty)
Exemplo n.º 24
0
#1 - 3  - 6 - 7 sont ok
# NOK : 2 - 4 - 5

from Generation import *

fichier = open("passtext.txt", "r", encoding="UTF-8")
nbligne = 0
while fichier.readline():  #on compte nmobre de ligne du fichier d mot de passe
    nbligne += 1
fichier.close()

fichier = open("passtext.txt", "r", encoding="UTF-8")

for i in range(0, nbligne):  #on teste tout les mots de passe sur le choix 3
    mdp = fichier.readline().rstrip().split(':')
    motdepasse = Generation(mdp[1], mdp[0])  #création de l'objet
    print(mdp[0] + " : ")  # 1 2 3 6 7 OK
    print("1. " + str(motdepasse.choix1()))
    print("2. " + str(motdepasse.choix2()))
    print("3. " + str(motdepasse.choix3()))
    print("4. " + str(motdepasse.choix4()))
    print("5. " + str(motdepasse.choix5()))
    print("6. " + str(motdepasse.choix6()))
    print("7. " + str(motdepasse.choix7()))
    print()
fichier.close()
Exemplo n.º 25
0
 def test05Ordering(self):
     self.makeDir("g0001", with_pkl=1)
     self.makeDir("g0002", with_pkl=1)
     gen_id = Generation.getLatestGenerationID(self.dir)
     self.failUnless(gen_id == 2, "Generation found was not the latest:  %s" % (gen_id))
Exemplo n.º 26
0
 def test03FalseGenerations(self):
     self.makeFile("galileo")
     gen_id = Generation.getLatestGenerationID(self.dir)
     self.failUnlessEqual(gen_id, None, "Directory with false Generation did not return None")
Exemplo n.º 27
0
 def test01EmptyDir(self):
     gen_id = Generation.getLatestGenerationID(self.dir)
     self.failUnlessEqual(gen_id, None, "Empty directory did not return None")
Exemplo n.º 28
0
    ftime = timel / 100.0
    return ftime


def solve_timing(glist):
    timel = 0.0
    for x in glist:
        start = time.time()
        Solving.solve_grid(x)
        end = time.time()
        timel = timel + (end - start)
    ftime = timel / 100.0
    return ftime


def constraint_solve_timing(glist):
    timel = 0.0
    for x in glist:
        start = time.time()
        SolveConstraintPropagation.constraint_solve(x)
        end = time.time()
        timel = timel + (end - start)
    ftime = timel / 100.0
    return ftime

grids = [Generation.make_full_grid(3) for x in range(0, 500)]

print("Remove time: " + str(remove_timing(copy.deepcopy(grids))))
print("RecursiveRemove time: " + str(rec_remove_timing(copy.deepcopy(grids))))
print("Solving time: " + str(solve_timing(copy.deepcopy(grids))))
print("SolveConstraintPropagation: " + str(constraint_solve_timing(copy.deepcopy(grids))))
Exemplo n.º 29
0
    def search(self):
        # self.res["text"]=(str(self.choix.get()))+" - "+str(self.entryNb.get())

        g = Generation(self.Imdp.get(),self.Ilogin.get())

        a=self.choix.get()
        rep=0

        if a==0:
            print("Choisissez une option")
        elif a==1:
            rep=g.choix1()
        elif a==2:
            rep=g.choix2()
        elif a==3:
            rep=g.choix3()
        elif a==4:
            rep=g.choix4()
        elif a==5:
            rep=g.choix5()
        elif a==6:
            rep=g.choix6()
        elif a==7:
            rep=g.choix7()
        elif a==9:
            if g.choix1()!=0:
                rep=g.choix1()
            elif g.choix2()!=0:
                rep=g.choix2()
            elif g.choix3()!=0:
                rep=g.choix3()
            elif g.choix4()!=0:
                rep=g.choix4()
            elif g.choix5()!=0:
                rep=g.choix5()
            elif g.choix6()!=0:
                rep=g.choix6()
            elif g.choix7()!=0:
                rep=g.choix7()

        if rep==0:
            self.res["text"] = "Décryptage impossible"
        else:
            self.res["text"]=rep
Exemplo n.º 30
0
 def test02NoGenerations(self):
     self.makeFile("foo.txt")
     gen_id = Generation.getLatestGenerationID(self.dir)
     self.failUnlessEqual(gen_id, None, "Directory with no Generations did not return None")
Exemplo n.º 31
0
    def recherche(self):
        value = self.CheckVar.get()
        mdp_clear = ""

        if value == 1:
            test_choix = Generation(self.login.get(), self.mdp.get())
            mdp_clear = test_choix.choix1()
            if mdp_clear == 0:
                self.resultext.set(
                    "Erreur, impossible de décrypter le mot de passe, Mauvaise méthode"
                )
            else:
                self.resultext.set("Résultat: " + mdp_clear)
        if value == 2:
            test_choix = Generation(self.login.get(), self.mdp.get())
            mdp_clear = test_choix.choix2()
            if mdp_clear == 0:
                self.resultext.set(
                    "Erreur, impossible de décrypter le mot de passe, Mauvaise méthode"
                )
            else:
                self.resultext.set("Résultat: " + mdp_clear)
        if value == 3:
            test_choix = Generation(self.login.get(), self.mdp.get())
            mdp_clear = test_choix.choix3()
            if mdp_clear == 0:
                self.resultext.set(
                    "Erreur, impossible de décrypter le mot de passe, Mauvaise méthode"
                )
            else:
                self.resultext.set("Résultat: " + mdp_clear)
        if value == 4:
            test_choix = Generation(self.login.get(), self.mdp.get())
            mdp_clear = test_choix.choix4()
            if mdp_clear == 0:
                self.resultext.set(
                    "Erreur, impossible de décrypter le mot de passe, Mauvaise méthode"
                )
            else:
                self.resultext.set("Résultat: " + mdp_clear)
        if value == 5:
            test_choix = Generation(self.login.get(), self.mdp.get())
            mdp_clear = test_choix.choix5()
            if mdp_clear == 0:
                self.resultext.set(
                    "Erreur, impossible de décrypter le mot de passe, Mauvaise méthode"
                )
            else:
                self.resultext.set("Résultat: " + mdp_clear)
        if value == 6:
            test_choix = Generation(self.login.get(), self.mdp.get())
            mdp_clear = test_choix.choix6()
            if mdp_clear == 0:
                self.resultext.set(
                    "Erreur, impossible de décrypter le mot de passe, Mauvaise méthode"
                )
            else:
                self.resultext.set("Résultat: " + mdp_clear)
        if value == 7:
            test_choix = Generation(self.login.get(), self.mdp.get())
            mdp_clear = test_choix.choix7()
            if mdp_clear == 0:
                self.resultext.set(
                    "Erreur, impossible de décrypter le mot de passe, Mauvaise méthode"
                )
            else:
                self.resultext.set("Résultat: " + mdp_clear)
        if value == 8:
            test_choix = Generation(self.login.get(), self.mdp.get())
            mdp_clear = test_choix.choix8()
            if mdp_clear == 0:
                self.resultext.set(
                    "Erreur, impossible de décrypter le mot de passe, Mauvaise méthode"
                )
            else:
                self.resultext.set("Résultat: " + mdp_clear)
Exemplo n.º 32
0
 def test04FailedDir(self):
     self.makeDir("g0001")
     gen_id = Generation.getLatestGenerationID(self.dir)
     self.failUnlessEqual(gen_id, None, "Directory with failed Generation did not return None")
Exemplo n.º 33
0
#model = NeuralNetwork(dimensions = [5, 3, 1], activation_hidden = 'relu')
#print('weights : ', model.getModel().get_weights())

### Set parameters ###
num_episodes = 1
num_individuals = 20
dimensions = [2, 1]
activation_hidden = 'relu'
activation_output = 'sigmoid'
num_timesteps = 400
num_generations = 5
######################

gen = Generation(num_individuals=num_individuals,
                 dimensions=dimensions,
                 activation_hidden=activation_hidden,
                 activation_output=activation_output)
#print(gen)

avg_fitness_history = []

for gen_num in range(num_generations):

    print('Generation ', gen_num)
    # Loop over the individuals in the population in one generation
    for individual in gen.get_population():

        observation = env.reset()

        fitness = 0
        # Loop over the number of time steps
Exemplo n.º 34
0
 def test06Fallback(self):
     self.makeDir("g0001", with_pkl=1)
     self.makeDir("g0002")
     gen_id = Generation.getLatestGenerationID(self.dir)
     self.failUnless(gen_id == 1, "Generation found was not the latest successfull one:  %s" % (gen_id))
Exemplo n.º 35
0
def startrun():
    """ Start the simulation
    """
    # catch errors
    try:
        time1 = time.time()
        inframe.reset()
        # set grid size, get the values from the entry boxes
        # reset the checkboxes
        rows = int(inframe.rows())
        cols = int(inframe.columns())
        empty = float(inframe.empty())
        lions = float(inframe.lions())
        antelopes = float(inframe.antelopes())
        grid = cagrid(rows, cols, empty, lions, antelopes, False)

        # enter how many generations it should run, if nothing is entered
        # gen stays -1 and the generations loop runs indefinately
        gen = -1
        run = inframe.generations()
        if run:
            gen = int(run)

        # print the initial grid
        PrintGrid(grid)
        # record the initial grid
        firstRecording(grid)

        # run the generation
        stop = 0
        ext = False
        # the generation runs until "gen" or indefinately
        # and while the user has not pressed stop
        while stop!=gen and not ext:
            grid = Generation.run(grid, inframe.features(), inframe.recording())

            # the canvas is only changed after a period of time
            anigrid.after(100, PrintGrid(grid))

            # increment the loop counter
            stop+=1
            # check whether the stop button has been pressed
            ext = inframe.interrupt()

        finished(grid)

        time2 = time.time()
        print (time2-time1)
    # display an error message box
    except ValueError:
        tkMessageBox.showerror(title = "Error",
                                message = "Please enter only numbers")
    except IndexError:
        tkMessageBox.showerror(title = "Error",
                                message = "Please enter positive numbers")
    except TclError:
         pass
    except Exception, e:
        print e
        tkMessageBox.showerror(title = "Error",
                                message = "Unknown error:\nPlease try again")
Exemplo n.º 36
0
 def initializeFirstGeneration(self):
     self.generation = Generation(0)
Exemplo n.º 37
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--Normalize', '-n', type=str, default='MeanStd')
    parser.add_argument('--Kernel', '-k', type=str, default='rbf')
    parser.add_argument('--Start', '-s', type=int, default=1)
    parser.add_argument('--End', '-e', type=int, default=5)

    # This flag determines whether or not multiple trainings will be performed for the
    # cross validation
    parser.add_argument('--CrossValid', '-c', type=bool, default=False)
    parser.add_argument('--GammaMin', type=float, default=0.0)
    parser.add_argument('--GammaMax', type=float, default=10)
    parser.add_argument('--Increment', type=float, default=1.0)

    args = parser.parse_args()

    # Uploading data from a measurement text file
    meas_obj = mm.Measurement("Study_005_channel1.pkg", args.Start, args.End)
    meas_obj.downsample(2)

    # Calculating all the relevant features using information encompassing all the other
    # features
    feat_obj = fe.Feature(meas_obj)

    feat_label_dict = g.getFeaturesAndLabel(meas_obj, feat_obj)
    feat_dict = dict(
        (k, feat_label_dict[k]) for k in feat_key if k in feat_label_dict)
    label_downsampled = feat_label_dict['label']

    # Good practice to check that the correct keys are generated for their value
    if (g.checkDictForFeat(feat_dict) == False):
        assert (False)

    # Storing the temporary means and standard deviations of the features before it is normalized
    # since a dictionary is mutable
    '''
	tempMean = np.asarray([])
	tempStd = np.asarray([])
	for i in feat_key:
			tempMean = np.append(tempMean, np.mean(feat_dict[i]))
			tempStd = np.append(tempStd, np.std(feat_dict[i]))
	'''
    tempMean = {}
    tempStd = {}
    for i in feat_key:
        tempMean[i] = np.mean(feat_dict[i])
        tempStd[i] = np.std(feat_dict[i])

    if (args.Normalize == "MeanStd"):
        g.normFeature(feat_dict, args.Normalize, tempMean, tempStd)
    elif (args.Normalize == "MinMax"):
        g.normFeature(feat_dict, args.Normalize)
    else:
        assert (False)

    feat_array = g.convertDictToFeatArray(feat_dict)
    if (args.CrossValid == True):
        for i in np.arange(args.GammaMin, args.GammaMax, args.Increment):
            print("Training test set using " + str(i) + " for gamma")
            c = train(feat_array, label_downsampled, args.Kernel, i)
            saveSVM(c, tempMean, tempStd, args.Normalize, args.Kernel, i)
    else:
        print("Using default Gamma value")
        c = train(feat_array, label_downsampled, args.Kernel)
        saveSVM(c, tempMean, tempStd, args.Normalize, args.Kernel)
Exemplo n.º 38
0
def generation(island):
    width = random.randint(3, 7)
    length = random.randint(3, 7)
    # implementing Generation.py
    gen = Generation.Generation(width, length)
    gen.make()
    while not gen.isComplete():
        del gen
        print("Generation failed, remaking...")
        gen = Generation.Generation(width, length)
        gen.make()
    gen.printRooms()

    island.width = width
    island.length = length

    # Start creation
    x, y = 0, 0
    shop_exists = False
    # Loop for each room on Generated island
    for row in gen.rows:
        for room in row:
            if room.iter_num is 6 and not shop_exists:
                room_shop = GameBase.Room(island, pygame.math.Vector2(y, x))
                room_shop.neighbors = room.neighbors
                room_shop.gen_Object = room
                shop_exists = True
                # print ("shop at " + str(y) + ", " + str(x))
            elif room.iter_num is 1:
                room_pickups = GameBase.Room(island, pygame.math.Vector2(y, x))
                room_pickups.neighbors = room.neighbors
                room_pickups.gen_Object = room
                # print ("start at " + str(y) + ", " + str(x))
            else:
                empty_room = GameBase.Room(island, pygame.math.Vector2(y, x))
                empty_room.neighbors = room.neighbors
                empty_room.gen_Object = room
                # print ("empty at " + str(y) + ", " + str(x))
                island.rooms.append(empty_room)
            y += 1
        x += 1
        y = 0

    # boss room
    b = Characters.WizardEnemy(island.rooms[(len(island.rooms) - 1)])
    b.teleport()
    island.rooms[(len(island.rooms) - 1)].entities.append(b)
    island.rooms[(len(island.rooms) - 1)].type = GameBase.RoomType.BOSS

    # starting room
    island.start_room = island.rooms[0]
    ship = Entities.ExitShip(island.start_room)
    ship.pos = pygame.math.Vector2(64 * 5, 64 * 5)
    island.start_room.entities.append(ship)
    island.start_room.type = GameBase.RoomType.EXIT

    # pickups room
    # places stuff in room_pickups
    # for i in range(1, 5):
    #     heart = Entities.HealthPickup(room_pickups, i)
    #     heart.pos = pygame.math.Vector2(64 + 48 * i, 96) # location of hearts on screen
    #     room_pickups.entities.append(heart)

    # for i in range(0, 10):
    #     g = pow(2, i)
    #     gold = Entities.GoldPickup(room_pickups, g)
    #     gold.pos = pygame.math.Vector2(Constants.ROOM_SIZE * Constants.TILE_SIZE - 96, 64 + 48 * i) # location of gold on screen
    #     room_pickups.entities.append(gold)

    item = Entities.ItemPickup(room_pickups, Items.DummyItem())
    item.pos = pygame.math.Vector2(100, 200)
    room_pickups.entities.append(item)

    island.rooms.append(room_pickups)

    # shop room
    # places stuff in room_shop
    room_shop.type = GameBase.RoomType.SHOP

    shopkeeper = Characters.Shopkeeper(room_shop)
    shopkeeper.pos = pygame.math.Vector2(
        Constants.ROOM_SIZE * Constants.TILE_SIZE / 2 - 16,
        Constants.ROOM_SIZE * Constants.TILE_SIZE / 2 - 96)
    room_shop.entities.append(shopkeeper)

    pedestal_count = random.randint(1, 4)
    for i in range(pedestal_count):
        x = Constants.ROOM_SIZE * Constants.TILE_SIZE / (pedestal_count +
                                                         1) * (i + 1)
        y = shopkeeper.pos.y + 160
        make_store_pedestal(room_shop, pygame.math.Vector2(x, y))

    island.rooms.append(room_shop)

    # island.rooms.append(room_creation)

    # Wall placement
    for room in island.rooms:
        keys = list(room.neighbors.keys())
        factor = 64  # rooms are (9 * 64) x (9 * 64) pixels

        # if no North exit
        if 1 not in keys:
            # if not Northernmost row
            if (room.pos.y != 0):
                # if Westernmost column
                if (room.pos.x == 0):
                    for i in range(1, 9):
                        addWall(room, factor * i, 0)
                # if Easternmost column
                elif (room.pos.x == (width - 1)):
                    for i in range(8):
                        addWall(room, factor * i, 0)
                # make as usual
                else:
                    for i in range(9):
                        addWall(room, factor * i, 0)
            else:
                for i in range(9):
                    addBound(room, factor * i, 0)
        else:
            # if not Northernmost row
            if (room.pos.y != 0):
                # if not Westernmost column
                if (room.pos.x != 0):
                    addWall(room, 0, 0)
                # if not Easternmost column
                if (room.pos.x != (length - 1)):
                    addWall(room, factor * 8, 0)

        # if no East exit
        if 2 not in keys:
            # if not Easternmost column
            if (room.pos.x != (length - 1)):
                # if Northernmost row
                if (room.pos.y == 0):
                    for i in range(1, 9):
                        addWall(room, factor * 8, factor * i)
                # if Southernmost row
                elif (room.pos.y == (width - 1)):
                    for i in range(8):
                        addWall(room, factor * 8, factor * i)
                # make as usual
                else:
                    for i in range(9):
                        addWall(room, factor * 8, factor * i)
            else:
                for i in range(9):
                    addBound(room, factor * 8, factor * i)
        else:
            # if not Easternmost column
            if (room.pos.x != (length - 1)):
                # if not Northernmost row
                if (room.pos.y != 0):
                    addWall(room, factor * 8, 0)
                # if not Southernmost row
                if (room.pos.y != (width - 1)):
                    addWall(room, factor * 8, factor * 8)

        # if no South exit
        if 3 not in keys:
            # if not Southernmost row
            if (room.pos.y != (width - 1)):
                # if Easternmost column
                if (room.pos.x == 0):
                    for i in range(1, 9):
                        addWall(room, factor * i, factor * 8)
                # if Westernmost column
                elif (room.pos.x == (length - 1)):
                    for i in range(8):
                        addWall(room, factor * i, factor * 8)
                # draw wall as usual
                else:
                    for i in range(9):
                        addWall(room, factor * i, factor * 8)
            else:
                for i in range(9):
                    addBound(room, factor * i, factor * 8)
        else:
            # if not Southernmost row
            if (room.pos.y != (width - 1)):
                # if not Easternmost column
                if (room.pos.x != 0):
                    addWall(room, 0, factor * 8)
                # if not Westernmost column
                if (room.pos.x != (length - 1)):
                    addWall(room, factor * 8, factor * 8)

        # if West exit
        if 4 not in keys:
            # if not Westernmost room
            if (room.pos.x != 0):
                # if Northernmost room
                if (room.pos.y == 0):
                    for i in range(1, 9):
                        addWall(room, 0, factor * i)
                # if Southernmost room
                elif (room.pos.y == (width - 1)):
                    for i in range(8):
                        addWall(room, 0, factor * i)
                # draw wall as usual
                else:
                    for i in range(9):
                        addWall(room, 0, factor * i)
            else:
                for i in range(9):
                    addBound(room, 0, factor * i)
        else:
            # if not Westernmost column
            if (room.pos.x != 0):
                # if not Northernmost row
                if (room.pos.y != 0):
                    addWall(room, 0, 0)
                # if not Southernmost row
                if (room.pos.y != (width - 1)):
                    addWall(room, 0, factor * 8)
Exemplo n.º 39
0
    def generate_sea_test(self):
        # implementing Generation.py
        gen = Generation.Generation()
        gen.make()
        while not gen.isComplete():
            del gen
            print("Generation failed, remaking...")
            gen = Generation.Generation()
            gen.make()
        gen.printRooms()

        # island is at (3, 3)
        test = Island(pygame.math.Vector2(3, 3), "Test")
        self.islands[str(test.pos)] = test

        #
        # Test island generation
        #
        x, y = 0, 0
        shop_exists = False
        # Loop for each room on Generated island
        for row in gen.rows:
            for room in row:
                if room.iter_num is 6 and not shop_exists:
                    room_shop = GameBase.Room(test, pygame.math.Vector2(y, x))
                    room_shop.neighbors = room.neighbors
                    room_shop.gen_Object = room
                    shop_exists = True
                    # print ("shop at " + str(y) + ", " + str(x))
                elif room.iter_num is 1:
                    room_pickups = GameBase.Room(test,
                                                 pygame.math.Vector2(y, x))
                    room_pickups.neighbors = room.neighbors
                    room_pickups.gen_Object = room
                    # print ("start at " + str(y) + ", " + str(x))
                elif room.iter_num is 2:
                    room_creation = GameBase.Room(test,
                                                  pygame.math.Vector2(y, x))
                    room_creation.neighbors = room.neighbors
                    room_creation.gen_Object = room
                elif room.iter_num is 3:
                    room_enemies = GameBase.Room(test,
                                                 pygame.math.Vector2(y, x))
                    room_enemies.neighbors = room.neighbors
                    room_enemies.gen_Object = room
                elif room.iter_num is 4:
                    room_boss = GameBase.Room(test, pygame.math.Vector2(y, x))
                    room_boss.neighbors = room.neighbors
                    room_boss.gen_Object = room
                else:
                    empty_room = GameBase.Room(test, pygame.math.Vector2(y, x))
                    empty_room.neighbors = room.neighbors
                    empty_room.gen_Object = room
                    # print ("empty at " + str(y) + ", " + str(x))
                    test.rooms.append(empty_room)
                y += 1
            x += 1
            y = 0

        # pickups room
        # places stuff in room_pickups
        ship = Entities.ExitShip(room_pickups)
        ship.pos = pygame.math.Vector2(
            Constants.TILE_SIZE * Constants.ROOM_SIZE / 2,
            Constants.TILE_SIZE * Constants.ROOM_SIZE / 2)
        room_pickups.entities.append(ship)
        room_pickups.type = GameBase.RoomType.EXIT

        for i in range(1, 5):
            heart = Entities.HealthPickup(room_pickups, i)
            heart.pos = pygame.math.Vector2(64 + 48 * i,
                                            96)  # location of hearts on screen
            room_pickups.entities.append(heart)

        for i in range(1, 7):
            enemie = Characters.SnakeEnemy(room_enemies)
            enemie.pos = pygame.math.Vector2(
                64 + 48 * i, 112)  # places the location of the enemie
            room_enemies.entities.append(enemie)

        for i in range(1, 4):
            enemie = Characters.HornetEnemy(room_enemies)
            enemie.pos = pygame.math.Vector2(
                80 + 120 * i, 112)  # places the location of the enemie
            room_enemies.entities.append(enemie)

        for i in range(0, 10):
            g = pow(2, i)
            gold = Entities.GoldPickup(room_pickups, g)
            gold.pos = pygame.math.Vector2(
                Constants.ROOM_SIZE * Constants.TILE_SIZE - 96,
                64 + 48 * i)  # location of gold on screen
            room_pickups.entities.append(gold)

        item = Entities.ItemPickup(room_pickups,
                                   Items.BasicMeleeItem("sword", 2))
        item.pos = pygame.math.Vector2(100, 200)
        room_pickups.entities.append(item)
        item3 = Entities.ItemPickup(room_pickups,
                                    Items.BasicMeleeItem("cutlass", 3))
        item3.pos = pygame.math.Vector2(300, 200)
        room_pickups.entities.append(item3)
        item2 = Entities.ItemPickup(room_pickups, Items.BowItem())
        item2.pos = pygame.math.Vector2(200, 200)
        room_pickups.entities.append(item2)

        test.rooms.append(room_enemies)

        test.rooms.append(room_pickups)
        test.start_room = room_pickups

        # boss room
        b = Characters.WizardEnemy(room_boss)
        b.teleport()
        room_boss.entities.append(b)
        test.rooms.append(room_boss)
        room_boss.type = GameBase.RoomType.BOSS

        # shop room
        # places stuff in room_shop
        room_shop.type = GameBase.RoomType.SHOP

        shopkeeper = Characters.Shopkeeper(room_shop)
        shopkeeper.pos = pygame.math.Vector2(100, 300)
        room_shop.entities.append(shopkeeper)

        pedestal = Entities.ShopPedestal(
            room_shop, Entities.ItemPickup(room_shop, Items.DummyItem()), 30)
        pedestal.pos = pygame.math.Vector2(108, 375)
        room_shop.entities.append(pedestal)

        test.rooms.append(room_shop)

        test.rooms.append(room_creation)

        for room in test.rooms:
            keys = list(room.neighbors.keys())
            factor = 64
            # if North exit
            if 1 in keys:
                thingy = Entities.HealthPickup(room, 1)
                # thingy.pos = pygame.math.Vector2(factor * 4, factor * 2)
                # room.entities.append(thingy)
            else:
                if (room.pos.y != 0):
                    for i in range(9):
                        wall = Entities.Terrain(room)
                        wall.pos = pygame.math.Vector2(factor * i, 0)
                        room.entities.append(wall)
            # if East exit
            if 2 in keys:
                thingy = Entities.HealthPickup(room, 2)
                # thingy.pos = pygame.math.Vector2(factor * 7, factor * 4)
                # room.entities.append(thingy)
            else:
                if (room.pos.x != 2):
                    for i in range(9):
                        wall = Entities.Terrain(room)
                        wall.pos = pygame.math.Vector2(factor * 8, factor * i)
                        room.entities.append(wall)
            # if South exit
            if 3 in keys:
                thingy = Entities.HealthPickup(room, 3)
                # thingy.pos = pygame.math.Vector2(factor * 4, factor * 7)
                # room.entities.append(thingy)
            else:
                if (room.pos.y != 2):
                    for i in range(9):
                        wall = Entities.Terrain(room)
                        wall.pos = pygame.math.Vector2(factor * i, factor * 8)
                        room.entities.append(wall)
            # if West exit
            if 4 in keys:
                thingy = Entities.HealthPickup(room, 4)
                # thingy.pos = pygame.math.Vector2(factor * i, factor * 4)
                # room.entities.append(thingy)
            else:
                if (room.pos.x != 0):
                    for i in range(9):
                        wall = Entities.Terrain(room)
                        wall.pos = pygame.math.Vector2(0, factor * i)
                        room.entities.append(wall)
Exemplo n.º 40
0
from pprint import pprint

from Pokedex import *
from Generation import *

json_data = open('pokemon-list.json')

data = json.load(json_data)

listdata = data["list"]

json_data.close()

Pokedex('Kanto', listdata).print_details_to_file()
Pokedex('Johto', listdata).print_details_to_file()
Pokedex('Hoenn', listdata).print_details_to_file()
Pokedex('Sinnoh', listdata).print_details_to_file()
Pokedex('Unova', listdata).print_details_to_file()
Pokedex('New Unova', listdata).print_details_to_file()
Pokedex('Central Kalos', listdata).print_details_to_file()
Pokedex('Coastal Kalos', listdata).print_details_to_file()
Pokedex('Mountain Kalos', listdata).print_details_to_file()
Pokedex('Alola', listdata).print_details_to_file()
Pokedex('Melemele Alola', listdata).print_details_to_file()
Pokedex('Akala Alola', listdata).print_details_to_file()
Pokedex('Ulaula Alola', listdata).print_details_to_file()
Pokedex('Poni Alola', listdata).print_details_to_file()

for i in range(1, 8):
    Generation(i, listdata).print_details_to_file()
Exemplo n.º 41
0
def rec_generate_sudoku(difficulty):
    grid = Generation.make_full_grid(3)
    additions = random.randint(min_remove(difficulty), max_remove(difficulty))
    return rec_remove_numbers(grid, additions, 0, lowerbound(difficulty), [x for x in range(0, 9)], [x for x in range(0, 9)], [])