def mainloop(self): if (GlobalData.displayInitialized==0): self.initDisplay() self.initPlayer() pygame.key.set_repeat(75, 75) TextBox.loadTextImages(3, 3, -1) Battle.loadBattleTextures() Creature.loadCreatureImages() Map.loadTileSet("Exterior_Town1.png", 30, 16) Map.loadTileSet("Interior_Town1.png", 30, 16) Map.loadTileSet("Interior_Cave1.png", 30, 16) self.map = Map.Map("Exterior_Town1", "Exterior_Town1-6", 30, 30) self.maps["Exterior_Town1"] = [self.map] #timer = pygame.time.get_ticks() #timeOffset = 0.00 while not GlobalData.quitFlag: for e in pygame.event.get(): if e.type == QUIT: GlobalData.quitFlag = 1 return self.playerInput(e) pygame.event.pump() self.drawWorld() self.printFPS() self.flipScreenBuffer() self.timer.tick(12)
def generate_grid(self, surf): """ Generates a new grid with randomized terrain covering the map. :param surf: surface images are displayed to :return: stored data """ row_len = 0 for row in range(self.width // self.block_size): col_len = 0 self.grid.append([]) for col in range(self.height // self.block_size): grass_or_clover = random.randint(0, 5) spot = [ [row_len, col_len, self.block_size, self.block_size], Creature.Creature(""), Terrain.Terrain(""), ] spot[1] = Empty.Empty() if grass_or_clover > 1: spot[2] = Grass.Grass() else: spot[2] = Clover.Clover() spot[2].set_color("alive") spot.append( pygame.draw.rect(surf, spot[2].get_color(), spot[0])) self.grid[row].append(spot) col_len += self.block_size row_len += self.block_size return self.grid
def test_creature_create(): attributes = {} senses = {} action_set = [] #Create Attributes attributes.__setitem__('STR', 16) attributes.__setitem__('DEX', 15) attributes.__setitem__('CON', 18) attributes.__setitem__('INT', 22) attributes.__setitem__('WIS', 17) attributes.__setitem__('CHA', 13) #Create Senses senses.__setitem__('DarkVision', 'DarkVision 60ft.') senses.__setitem__('TremorSense', '') senses.__setitem__('BlindSense', '') myAction = Action.Action('Test_Action', 'Melee 5ft slash', '+5 to hit', '2d12 + 3 damage') action_set.append(myAction) #created_creature = Creat (name, size, specification, alignment, ac, hp, speed, attributes, senses, # languages, challenge_rating, action_set) myCreature = Creature.Creature('Test', 'Small', 'Dragon', 'LG', 16, '100', '35 ft.', attributes, senses, 'Draconic Common', '4', action_set) myCreature.save(True)
def __init__(self, parent, width, height): """ Initializes the application Args: parent: An object for the parent of the application width: An integer for the width of the application height: An integer for the height of the application """ Frame.__init__(self, parent) # Create the frame self.parent = parent self.width = width self.height = height center_window(self) self.parent.title("Evolution Simulator") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self) self.create_tiles() Utils.creatures = Creature.create_creatures(Utils.init_creature_num, self.canvas) self.canvas.pack(fill=BOTH, expand=1) self.update_app()
def __init__(self, data): """""" try: self.Race = data["Race"] self.Class = data["Class"] self.creature = Creature(data) self.Creature_Id = self.creature.Id except ValueError: print(data["Name"]) raise
def __init__(self, data): """""" try: self.creature = Creature(data) self.Creature_Id = self.creature.Id self.Environment = data ["Environment"] self.Source = data["Source"] self.Description = data["Description_Visual"] except ValueError: print(data["Name"]) raise
def game_loop(): creatures = [ Creature('Bat', 5), Creature('Toad', 1), Creature('Tiger', 12), Dragon('Black Dragon', 50, scaliness=2, breathes_fire=False), Wizard('Evil Wizard', 1000), ] hero = Wizard('Gandolf', 75) while True: active_creature = random.choice(creatures) print('A {} of level {} has appeared from a dark and foggy forest...' .format(active_creature.name, active_creature.value)) #ask user for action if win or exit: break print("Goodbye")
class Room: x = 0 y = 0 monster_list = [] treasure_list = [] monster_list.append(Creature.giant_spider_rarity()) monster_list.append(Creature.skeleton_rarity()) monster_list.append(Creature.orc_rarity()) monster_list.append(Creature.troll_rarity()) treasure_list.append(Treasure.gemstone_rarity()) treasure_list.append(Treasure.gold_jewelry_rarity()) treasure_list.append(Treasure.loose_coins_rarity()) treasure_list.append(Treasure.small_treasure_chest_rarity()) def __init__(self, x, y): self.x = x self.y = y def getx(self): return self.x def gety(self): return self.y
def _create_starting_creatures(self): creatures = [] for i in range(1): senseg = Gene(10, 0, (lambda x: x + randint(-1, 1))) speedg = Gene(PolarVector(BASE_TURN_SPEED, BASE_MOVE_SPEED), 10, (lambda x: PolarVector( (x.angle + radians(randint(-2, 2)) % (2 * pi)), x.magnitude + randint(-2, 2)))) sizeg = Gene(1, 20, (lambda x: x + randint(-5, 5))) start_pos, start_heading = self._get_start_pos() creatures.append( Creature(start_pos, 10000, senseg, sizeg, speedg, start_heading)) return creatures
class main: #Colors in RGB format BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) Origin = Point.Point(0, 0) if __name__ == "__main__": pygame.init() ## Spawn player, floors, and wall gameWorld = World.World(500, 500) gameWorld.initialize_world() player = Creature.Creature(Point.Point(250, 400), Point.Point(275, 425), 5) # xloc, yloc, size gameWorld.spawnCreature(player) floor = Wall.Wall(Point.Point(0, gameWorld.yPixels - 30), Point.Point(gameWorld.xPixels, gameWorld.yPixels)) leftWall = Wall.Wall(Origin, Point.Point(30, gameWorld.yPixels)) rightWall = Wall.Wall( Point.Point(gameWorld.xPixels - 30, 0), Point.Point(gameWorld.yPixels, gameWorld.yPixels)) ceiling = Wall.Wall(Origin, Point.Point(gameWorld.xPixels, 30)) gameWorld.spawnWall(floor) gameWorld.spawnWall(leftWall) gameWorld.spawnWall(rightWall) gameWorld.spawnWall(ceiling) gameWorld.update_world() ## end world initialization while True: # main game loop for event in pygame.event.get(): if event.type == pygame.locals.QUIT: pygame.quit() sys.exit() elif event.type == pygame.locals.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() player.handleMouseClick(pos, gameWorld) keys = pygame.key.get_pressed() # checking pressed keys player.handleInput(keys, gameWorld) gameWorld.screen.fill(BLACK) gameWorld.update_world() # update all locations gameWorld.renderworld() # redraw the world on screen
def spawn_creature(self, *args, **kwargs): """ Method to spawn new creature in current environment. :param creature_lifetime: time after which creature dies (used for GA) Used for self.alive parameter. :param sensor_cells: cells treated as sensory - stimulated from simulation :param trackL_cells: cells treated as motor - drive body's left track in simulation :param trackR_cells: cells treated as motor - drive body's right track in simulation :param motors_min_spikes: minimum numer of spikes of sensory cell, none if not using smooth_track_control :param motors_max_spikes: maximum numer of spikes of sensory cell, none if not using smooth_track_control :param smooth_track_control: set it if engine force should be dependend on number of motory cells :param logging: decides whether to log creature's activity from within this classs """ creature = Creature.Creature(*args, **kwargs) self.creatures.append(creature)
def __init__(self): pygame.init() self.clk = pygame.time.Clock() self.fps = 0 self.size = Params.window_size self.screen = pygame.display.set_mode(self.size) self.caption = "Pygame Window" self.toFullscreen = 0 self.tileset = None self.map_surface = None self.curr_map_surface = None self.curr_creature = Creature() pygame.display.set_caption(self.caption) self.map_surface = pygame.Surface(Params.map_size) self.curr_map_surface = pygame.Surface(Params.map_size) self.buffer_surface = pygame.Surface((1, 1)) self.buffer_surface.set_colorkey(Params.buffer_color_key) self.buffer_aa_surface = self.buffer_surface.copy() pygame.display.set_caption("PyGame Window") pygame.mouse.set_cursor(*Window.get_cursor_data('std')) pygame.mouse.set_visible(1) pygame.key.set_repeat(200, 10)
def __init__(self, pos=[0, 0, 0], rot=[0.0, 0.0, 0.0]): # give player a creature to control self.creature = Creature.Creature(self) # let Creature class know what creature is the player creature Creature.Creature.PlayerCreature = self.creature # give the player a ship - for testing self.ship = Ship.Ship(self) # Give the player an OP weapon - for testing self.ship.weapon.setFireRate(20) self.ship.weapon.setCoolrate(20) # Player is not really in ship yet self.inship = False # set the position of the player. this should not be used. # var to tell if player is in the atmosphere of some planet self.inatmosphere = False # var to tell if player is in a dungeon self.in_dungeon = False # give the player a camera self.cam = Camera(self) # let the Player class know the player instance Player.setPlayer(self) # give the player stats self.stats = RPGStats() # the player will be level 1 self.stats.lvlUP() # player enters ship, set vars to make this happen - for testing self.enterShip(self.ship)
def __init__(self, cam): pi = 3.141 maxDist = 100 minDist = maxDist - 50 self.ang = random.uniform(-pi*2,pi ) dis = random.randint(minDist, maxDist) self.pos = cam.pos.add( Vex(math.sin(self.ang)*dis, math.cos(self.ang)*dis, 0)) self.pos.setZ(0) self.speed = -.1 self.ship = Ship.Ship(self) self.inship = False self.inatmosphere = False self.state = 0 self.mindDur = 0 self.mindCho = 0 self.mindTim = 0 self.shotspd = 2 self.shotms = 0 self.statement = "" self.creature = Creature.Creature(self) self.target = [] self.enterShip(self.ship) Mind.Minds.extend([self])
def eval_genome(genome, config): net = neat.ctrnn.CTRNN.create(genome, config, time_const) fitnesses = [] for runs in range(runs_per_net): sim = Creature.Creature(simulation_field) net.reset() # Run the given simulation for up to num_steps time steps. fitness = 0.0 while sim.total_time < simulation_seconds: inputs = sim.return_inputs() action = net.advance(inputs, time_const, time_const) sim.move_AI(action) fitness = sim.fitness fitnesses.append(fitness) #print("{0} fitness {1}".format(net, fitness)) # The genome's fitness is its worst performance across all runs. return min(fitnesses)
from Creature import * import time from rayMarcher import * pygame.init() pygame.font.init() clock = pygame.time.Clock() background = [1,22,39] myfont = pygame.font.SysFont('timesnewromanttf', 15) screen = pygame.display.set_mode((500, 500))#, pygame.FULLSCREEN) #screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) pygame.display.set_caption("EvoSim") lsit = [] firstCreature = Creature(screen, (50, 50)) food = [food(screen, (100, 100))] runFlag = True generation = 0 # Main game loop secondCounter = 0 testPolygon = [(200,140),(250, 195), (280, 144)] testBodies = [[(200,140),(250, 195), (280, 144)],[(290,240),(340, 295), (370, 244)]] testFoods = [(100,100)] rayStart = (250, 250) rayDirection = 3
from sklearn.neural_network import MLPRegressor as mlp import Environment as E import Creature as C import Hunter as H import Operations as Op brain = mlp(hidden_layer_sizes=(100, ), max_iter=200, shuffle=True, activation='relu', learning_rate='adaptive') creature = C.Creature('trained_creature.sav', -1) hunter = H.Hunter('Problems', -1000) environment = E.Environment('The Matrix', 15, creature, hunter) Op.train_to_win(environment, 10000, 100, .95, 10000) Op.interactive_trial(environment) Op.save_creature(environment.creature, 'trained_creature.sav')
import os import pickle import Creature import neat from neat.math_util import mean import visualize runs_per_net = 5 simulation_seconds = 60.0 time_const = Creature.EPOCH_DELAY simulation_field = Creature.Field(30, 30, nibbles=100) def eval_genome(genome, config): net = neat.ctrnn.CTRNN.create(genome, config, time_const) fitnesses = [] for runs in range(runs_per_net): sim = Creature.Creature(simulation_field) net.reset() # Run the given simulation for up to num_steps time steps. fitness = 0.0 while sim.total_time < simulation_seconds: inputs = sim.return_inputs() action = net.advance(inputs, time_const, time_const) sim.move_AI(action)
def __init__(self, x, y): super().__init__(x, y, Creature.blue_dragon())
def main(story): # Load game data try: with open(story) as f: game_data = json.load(f) print("Story Loaded...ready to begin.") except Exception as e: print("File problem: {}".format(e)) print("Exiting.") # Import our challenges try: import challenges except ImportError as e: print("Error loading challenges.") print("Exiting.") # Begin the Game ut.slow_print("Welcome to the Adventure Game in Text") print("The Rules are Simple: Get through the rooms and stay alive.") print("To get started, let's hear a little about you: ") # Initialize Player player = Player.Player() print("You start off with an empty knapsack:") for i in player.knapsack: print(i) print("You have {} hitpoints".format(player.hitpoints)) ut.slow_print(game_data['introduction']) # While loop for multiple episodes. # Initialize Episode episode_data = game_data["episodes"][0] episode = Episode.Episode(episode_data) episode.print_narrative() ut.slow_print("You enter the room.") episode.describe_room() reply = input("Do you want to look for treasure? (Y/n) ") if reply.lower() != "n": result = episode.get_treasure() player.hitpoints += result[0] player.add_item(result[1]) # Initialize Creature creature_data = game_data["creatures"][0] creature = Creature.Creature(creature_data) print("There's a creature in the room.") creature.describe() reply = input("Do you want to greet {}? (Y/n)".format(creature.name)) if reply.lower() != "n": creature.greet() creature.tell_story() print("{} wants to offer you a challenge to get out of the room.".format( creature.name)) reply = input("Do you accept? (Y/n)") if reply.lower() != "n": success = False chal = challenges.Episode1() # chal = challenges.Episode2() while not creature.is_hostile and not success: success = creature.offer_challenge(chal) if success: print("YOU WIN!") else: print("YOU NEED TO TRY THIS ROOM AGAIN. THE MONSTER'S PISSED.")
import Episode import Creature import Utils as ut import Player import Game import random def challenge_1(num): guess = None guess = input("Give me a number between 1 and 10") try: guess = int(guess) if guess == num: return True elif guess < num: print("Try higher") elif guess > num: print("Try lower") except: print("That was not a number. Try again") return False c = Creature.Creature("Billy", "Hi there", "No greeting", "no story") n = random.randint(1, 10) success = False while not c.is_hostile and not success: success = c.offer_challenge(challenge_1(n))
from sklearn.neural_network import MLPRegressor as mlp import Environment as E import Creature as C import Hunter as H import Operations as Op creature = C.Creature('Extraordinary Algorithm', -1) hunter = H.Hunter('Problems', -1000) environment = E.Environment('The Matrix', 15, creature, hunter) Op.train_to_win(environment, 10000, 100, .95, 10000) Op.interactive_trial(environment)
def addCreature(self, pos): self.creatures.append(Creature(self.anType, self.name, pos))
interpreter = ga.GAinterpreter() interpreter.id_len = 10 # So now we have max of 1024 cells architecture, dop, dopdr = interpreter.decode(DNA_str) conf = dict([("dopamine-r%d" % i, False) for i in xrange(num_of_regions)]) conf["random_stim"] = False conf["random_stim_cells"] = 50. conf["sensor_stim"] = False # im = ControlGUI.ControlPanel(conf) # Initailize our creature! creature = Creature.Creature(display_sim=display_sim, clock=0, creature_sim_dt=creature_sim_dt, sensor_cells=sensor_cells, trackL_cells=trackL_cells, trackR_cells=trackR_cells, creature_lifetime=creature_lifetime, num_of_targets=0, logging=True) creature.create_from_architecture(architecture, dop, dopdr) while True: print "stepping" creature.step() # Loop for all regions for i in xrange(num_of_regions): if im.conf['dopamine-r%d' % i] is True: print "Feel the pleasure" # Stimulate and reset button
print('(4) Update an Existing Creature - BETA') print('(5) Delete an Existing Creature') selection = input("\nPlease Select your option:") if selection == '0': print('\nGoodbye!') exit() # Creates a Creature Object through Prompts, saves the completed Creature into the database elif selection == '1': Database.Database.print_all_creatures(False) elif selection == '2': user_input = input('Name of Creature: ') menu_creature = Database.Database.read(user_input, False) menu_creature.export(menu_creature.to_dict(), False) elif selection == '3': CreateCreature.prompt_create().save(False) # Update functionality is in Beta, not guaranteed to work. elif selection == '4': u_creature = Creature.Creature('','','','','','','','','','','','',) u_creature.update(False) elif selection == '5': user_input = input('Name of Creature: ') Database.Database.delete(user_input, False) else: print('Unknown option selected. Please try again.')
def create(A,race,pop,breed,tech): A = Creature.__init__(race,pop,breed,tech)
def generateCreature(): CR.new_creature(main, nameEntry.get(), int(sizeEntry.get()), int(soakEntry.get()), int(initEntry.get()))
def prompt_create(): selection = '' attributes = {} senses = {} action_set = [] #Create Attributes dictionary attributes.__setitem__('STR', 16) attributes.__setitem__('DEX', 15) attributes.__setitem__('CON', 18) attributes.__setitem__('INT', 22) attributes.__setitem__('WIS', 17) attributes.__setitem__('CHA', 13) #Create Senses senses.__setitem__('DarkVision', 'DarkVision 60ft.') senses.__setitem__('TremorSense', '') senses.__setitem__('BlindSense', '') my_action = Action.Action('Test_Action', 'Melee 5ft slash', '+5 to hit', '2d12 + 3 damage') action_set.append(my_action) created_creature = Creature.Creature('Test', 'Small', 'Dragon', 'LG', 16, '100', '35 ft,', attributes, senses, 'Draconic Common', '4', action_set) print('You will be prompted for values representing a creature. Press X to exit at any time') # allows quitting early while selection != 'x': selection = input('Name:') name = selection selection = input('Size:') size = selection selection = input('Specification:') specification = selection selection = input('Alignment:') alignment = selection selection = input('Armor Class (int):') ac = selection selection = input('Hit Points:') hp = selection selection = input('Speed (feet):') speed = selection selection = input('Strength (Int)') attributes.__setitem__('STR', selection) selection = input('Dexterity (Int)') attributes.__setitem__('DEX', selection) selection = input('Constitution (Int)') attributes.__setitem__('CON', selection) selection = input('Intelligence (Int)') attributes.__setitem__('INT', selection) selection = input('Wisdom (Wis)') attributes.__setitem__('WIS', selection) selection = input('Charisma (Int)') attributes.__setitem__('CHA', selection) selection = input('Senses: DarkVision?') senses.__setitem__('DarkVision', selection) selection = input('Senses: TremorSense?') senses.__setitem__('TremorSense', selection) selection = input('Senses: BlindSense?') senses.__setitem__('BlindSense', selection) selection = input('Languages:') languages = selection selection = input('Challenge Rating:') challenge_rating = selection # Build an Action selection = input('Action Name:') action_name = selection selection = input('Action Descriptor:') action_desc = selection selection = input('Attack Modifier to Hit:') action_attack = selection selection = input('Attack Damage:') action_hit = selection creature_action = Action.Action(action_name, action_desc, action_attack, action_hit) assert isinstance(creature_action, Action.Action) # Assign Creature Action action_set.append(creature_action) # Create the Creature created_creature = Creature.Creature(name, size, specification, alignment, ac, hp, speed, attributes, senses, languages, challenge_rating, action_set) assert isinstance(created_creature, Creature.Creature) selection = 'x' try: return created_creature except Exception as e: print('Creature Creation stopped before completion.') print(e)
def read(creature_name, is_test): try: if is_test: db = sqlite3.connect('..\src\db\cst8333.db') else: db = sqlite3.connect('db\cst8333.db') print("Opened database successfully.") cursor = db.cursor() print('*** Cursor set') cursor.execute('SELECT * FROM CREATURE WHERE name = ?', (creature_name, )) print('***Execute SELECT') # from the Creature Table, *** Might throw an error if more than 1 creature_name is selected... for row in cursor: print(row) name = row[1] size = row[2] specification = row[3] alignment = row[4] ac = row[5] hp = row[6] speed = row[7] attribute_ref = row[8] senses_ref = row[9] languages = row[10] challenge_rating = row[11] action_collection_ref = row[12] # from the Attributes Table cursor.execute('SELECT * FROM ATTRIBUTES WHERE ATTRIBUTES.ID = ?', (attribute_ref, )) attributes = {} for row in cursor: print(row) attributes.__setitem__('STR', str(row[1])) attributes.__setitem__('DEX', str(row[2])) attributes.__setitem__('CON', str(row[3])) attributes.__setitem__('INT', str(row[4])) attributes.__setitem__('WIS', str(row[5])) attributes.__setitem__('CHA', str(row[6])) # from the Senses Table cursor.execute('SELECT * FROM SENSES WHERE SENSES.ID = ?', (senses_ref, )) senses = {} for row in cursor: print(row) senses.__setitem__('DarkVision', row[1]) senses.__setitem__('TremorSense', row[2]) senses.__setitem__('BlindSense', row[3]) print(senses.get('TremorSense')) # from the Action Collection Table cursor.execute( 'SELECT * FROM ACTION_COLLECTION WHERE ACTION_COLLECTION.ID = ?', (action_collection_ref, )) action_collection = [] for row in cursor: print(row) action_collection.append(row[1]) # Retrieving the actions action_set = [] for fk in action_collection: cursor.execute('SELECT * FROM ACTIONS WHERE ACTIONS.ID = ?', (str(fk), )) action = {} for row in cursor: print(row) action.__setitem__('Name', row[1]) action.__setitem__('Description', row[2]) action.__setitem__('Attack', row[3]) action.__setitem__('Hit', row[4]) # Add the Dictionary to the List ¯\_(ツ)_/¯ action_set.append(action) this_creature = Creature.Creature(name, size, specification, alignment, ac, hp, speed, attributes, senses, languages, challenge_rating, action_set) except Exception as e: print('*** The Following Exception Occurred:') print(e) db.rollback() finally: db.close() return this_creature