def __init__(self, id, player_name, width, height, x, y, speed_x, speed_y, angle, angular_speed, type): Unit.__init__(self, id, width, height, x, y, speed_x, speed_y, angle, angular_speed) self.player_name = player_name self.type = type
def __init__(self, character_anims, attacksound, deathanim, x, unitType): rows_y = [0 * scale, 24 * scale, 48 * scale, 72 * scale] Unit.__init__(self, character_anims, attacksound, deathanim, rows_y[random.randint(0, 3)], unitType) self.velocity *= -1 self.storedvelocity *= -1 self.sprite.x = x
def handle_unit_action(unit: Unit): while True: options = unit.get_possible_action_targets() if len(options) == 0: print("No actions available") return print("\n".join( str(index) + ". " + str(x) for index, x in enumerate(options))) print("Enter a choice or q to cancel") input_value = input() if input_value == 'q': return else: if input_value.isdigit(): index = int(input_value) if index >= len(options): print("Out of range") continue options[index].select() unit.action_taken = True return else: print("Invalid entry")
def __init__(self): Unit.__init__(self,1200,0,'normal','fortified',5,0,0,0,0,'building',[]) self.upgrades_availbality_in_blacksmith = {'melee_attack_l1':[],'melee_attack_l2':['keep'], 'melee_attack_l3': ['castle']} self.last_name = 'blacksmith' self.name = self.last_name + self.name self.iron_forged_swords = False
def __init__(self, entity, properties, edges=[], inputEdges=[], outputEdges=[]): Unit.__init__(self, entity, properties)
def test_moving_wont_go_past_edge(self): footman = Unit(self.footman_card, self.p1) footman._ammo = 0 # so footman doesn't attempt to damage player self.b.grid[(TEST_FIELD_LENGTH - 2, 0)] = footman self.b.do_movements(self.p1, self.p2) self.assertEqual(self.b.grid.pop((TEST_FIELD_LENGTH - 2, 0)), footman) self.b.grid.clear()
def __init__(self,vg): config = Config(sample_buffers=1, samples=6, depth_size=16, double_buffer=True,) super(MapWindow,self).__init__(visible=False, resizable=True,config=config) self.vg=vg img = pyglet.image.load('./resources/ocean.jpg').get_texture(rectangle=True) self.background = pyglet.image.TileableTexture.create_for_image(img) self.texture = pyglet.image.load('./resources/test.jpg').get_texture() self.points_batch = pyglet.graphics.Batch() self.line_list = [] self.poly_list =[] self.refresh_draw_list() self.unit_batch = pyglet.graphics.Batch() self.unit_list=[] for i in range(15): x = random.randint(0,self.width) y = random.randint(0,self.height) unit = Unit('resources/test_sprite.png',x=x,y=y,batch=self.unit_batch) unit.sdx = random.randint(-5,5) unit.sdy = random.randint(-5,5) self.unit_list.append(unit) self.selected_unit = None self.width = img.width*3 self.height = img.height*3 self.set_visible() pyglet.clock.schedule_interval(self.update_pos,1/30.0)
def __init__(self): Unit.__init__(self, 290, 8.5, 'magic', max_mana=200, mana_regeneration_rate=0.667) self.last_name = 'priest' self.name = self.last_name +self.name self.heal_cooldown = 1 self.heal_cooldown_remaining = 0 self.time_ralated_functions.append(self.heal_tick)
def __init__(self, x, y, base): #if base, set health to 5 if (base): Unit.__init__(self, 0, 5, 0, 1, 0, x, y) #if camp, set health to 3 else: Unit.__init__(self, 1, 3, 0, 1, 0, x, y) self.isBase = base
def __init__( self, name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2): Unit.__init__(self, health, mana) self.name = name self.title = title self.mana_regeneration_rate = mana_regeneration_rate
def refresh(self, pie_charts, unit_list): self.units = [] self.unit_liststore = Gtk.ListStore(str, str, str, str) units = self.systemd.ListUnits( dbus_interface='org.freedesktop.systemd1.Manager') for unit in units: new_unit = Unit(unit[0]) for resource in ['mem', 'io', 'cpu']: res = self.get_resource(new_unit.name, resource) new_unit.resources[resource] = res self.units.append(new_unit) for chart in pie_charts: chart.set_sections(self.units)
def __init__(self, importFlag=False): # create units self.player = Unit(random.uniform(0, Common.boardWidth), random.uniform(0, Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight) self.predators = [ Unit(random.uniform(0, Common.boardWidth), random.uniform(0, Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight) for i in range(Common.numEnemies) ] self.prey = [ Unit(random.uniform(0, Common.boardWidth), random.uniform(0, Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight) for i in range(Common.numPrey) ] self.preyCoordTree = spatial.cKDTree( np.array([(p.x, p.y) for p in self.prey])) # create AI for e in self.predators: e.createBrain() if (importFlag): # import weights from file with open('weights.txt', 'r') as f: content = f.readlines() importWeights = [ast.literal_eval(lst) for lst in content] for p in self.predators: p.neuralNet.putWeights(random.choice(importWeights)) # wrapper class for GA functionality self.genAlg = GenAlg(Common.numEnemies, Common.mutRate, Common.crossRate, self.predators[0].neuralNet.getNumWeights()) # initialize tk, other fields and main loop self.initCanvas() self.ticker, self.epochs = 0, 0 self.animate = True self.avgFitness = [] self.maxFitness = [] self.gameLoop() self.root.mainloop()
def init(self): self.scrollablePosition = [0, 0] self.scrollableSize = [480, 240] self.map = Map(self.game, 'map.tmx') self.game.map = self.map self.scrollableLayer = ScrollableLayer(self.game, self.scrollablePosition, self.scrollableSize, [0, 0], self.map.size) self.game.scrollableLayer = self.scrollableLayer self.units = [] self.units.append(Unit(self.game, [96, 64])) self.units.append(Unit(self.game, [96, 96])) self.units.append(Unit(self.game, [96, 128])) self.units.append(Unit(self.game, [96, 160])) self.ui = UI(self.game)
def display(self, unit=Unit()): self.pic1 = unit.picture self.pic2 = unit.attack_picture self.display_name.configure(text=unit.name) self.display_img.configure(image=self.pic1) self.display_lbl.configure(text=unit.return_status())
def moveUnits(self): # advance player self.player.advance() # update enemy AI and advance for e in self.predators: output = e.neuralNet.update(self.getNNInput(e)) e.accX(output[0]) e.accY(output[1]) e.advance() # check if distance to nearest is small enough to clear (nearest, index) = self.getNearestPrey(e) if (self.getDist(e.x, e.y, nearest.x, nearest.y) < 10): # increment fitness e.fitness += 1 # remove prey self.prey.pop(index) # add new prey self.prey.append( Unit(random.uniform(0, Common.boardWidth), random.uniform(0, Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight)) # rebuild cKDTree self.preyCoordTree = spatial.cKDTree( np.array([(p.x, p.y) for p in self.prey])) # sort predators WRT fitness to keep track of most fit self.predators.sort()
def individual_generator(self): l = len(self.target) new = np.zeros((l), dtype=int) for i in range(l): new[i] = self.gene_generator() unit = Unit(new) self.fitness_function(unit) return unit
def individual_generator(self): l = 5 #Generalize for n box types new = np.zeros((l)) for i in range(l): new[i] = self.gene_generator() unit = Unit(new) self.fitness_function(unit) return unit
def __init__(self, length=100, width=100): self.temp_grad = Gradient(400) self.array = [] self.length = length self.width = width for i in range(length): self.array.append([]) for j in range(width): self.array[i].append(Unit(i=i, j=j))
def test_attacking_should_do_damage(self): footman = Unit(self.footman_card, self.p1) footman2 = Unit(self.footman_card, self.p2) starthp = footman.get_curr_hp() starthp2 = footman.get_curr_hp() self.b.grid[(1, 0)] = footman self.b.grid[(2, 0)] = footman2 self.b.do_all_attacks() self.assertEqual(footman.get_curr_hp() + footman2.get_damage(), starthp) self.assertEqual(footman2.get_curr_hp() + footman.get_damage(), starthp2) self.b.grid.clear()
def generate_from_string(s): clause = Clause() units_str = s.strip().split('|') clause.units = [] for unit_str in units_str: unit = Unit.generate_from_string(unit_str) clause.units.append(unit) return clause
def makeAlignment_pairwise2(self, seqa, seqb): if seqa == self.seqa and seqb == self.seqb: return self.range_a, self.range_b else: self.seqa = seqa self.seqb = seqb self.alns = pairwise2.align.globalds(seqa, seqb, matlist.blosum62, -10, -0.5) # aln_seqa, aln_seqb, score, begin, end = alns[0] indexRecord = IndexRecorder() a = list(map(indexRecord.check, self.alns[0][0])) indexRecord.reset() b = list(map(indexRecord.check, self.alns[0][1])) indexRecord.reset() mapped = list( filter(lambda x: x[0] != -1 and x[1] != -1, zip(a, b))) self.range_a = Unit.getInterval([i[0] for i in mapped]) self.range_b = Unit.getInterval([i[1] for i in mapped]) return self.range_a, self.range_b
def NOextract(f, options): try: if True: x = Unit(filename=f, options=options) del x except Exception, msg: print "UNIT EXCEPTION", f, msg import traceback, sys traceback.print_exc(file=sys.stderr) sys.stderr.flush()
def individual_generator(self): l = len(self.target) fill = ["a"] * l new = np.array(fill) for i in range(l): new[i] = self.gene_generator() unit = Unit(new) self.fitness_function(unit) return unit
def get_ante_cons(self): ante = Clause() cons = Unit() for unit in self.units: if unit.negated: u = unit.clone() u.negate() ante.add_unit(u) else: cons = unit.clone() return ante, cons
class UnitClassUnitTest(unittest.TestCase): ''' def setUp(self): self.unit = Unit() self.file = open("filedirect", "r") def tearDown(self): self.file.close() ''' def setUp(self): self.unit = Unit() def testA(self): self.unit.setCode('FIT1004') assert self.unit.code == 'FIT1004', "setCode not functioning correctly" def testB(self): self.unit.setTitle('Databases') assert self.unit.title == 'Databases', "setTitle not functioning correctly" def testC(self): self.unit.addCourse('2770') assert '2770' in self.unit.courses, "course code not being added correctly" def testD(self): self.unit.addStudent('10000000') assert '10000000' in self.unit.students, "student ID not being added correctly" def testE(self): self.unit.code = 'FIT1004' assert self.unit.getCode() == 'FIT1004', "correct unit code isn't being returned" def testF(self): self.unit.title = 'Databases' assert self.unit.getTitle() == 'Databases', "correct title not being returned"
def createUnit(self, university): print("\n \n \n") print("CREATING A NEW UNIT:") newUnit = Unit() code = input("New unit code: ") valid, code = validator.validateUnitCode(code) if valid: newUnit.setCode(code) title = input("New unit title: ") newUnit.setTitle(title) university.addUnit(newUnit) print("\nSUCCESS: UNIT RECORD CREATED: \n") newUnit.displayDetails() print("\n \n \n") else: print("ERROR: INVALID UNIT CODE FORMAT")
def confirm_unit(self): if self.first_unit.name == Unit().name: self.first_unit = copy.deepcopy(self.active_unit) self.first_unit.name = "Garret the " + self.first_unit.name self.left_unit.display(self.first_unit) else: self.second_unit = copy.deepcopy(self.active_unit) self.second_unit.name = "Rosa the " + self.second_unit.name self.right_unit.display(self.second_unit) self.confirm_button.configure(state="disabled") self.fight_button.configure(state="active") for b in self.unit_buttons: b.configure(state="disabled")
class UnitClassUnitTest(unittest.TestCase): ''' def setUp(self): self.unit = Unit() self.file = open("filedirect", "r") def tearDown(self): self.file.close() ''' def setUp(self): self.unit = Unit() def testA(self): self.unit.setCode('FIT1004') assert self.unit.code == 'FIT1004', "setCode not functioning correctly" def testB(self): self.unit.setTitle('Databases') assert self.unit.title == 'Databases', "setTitle not functioning correctly" def testC(self): self.unit.addCourse('2770') assert '2770' in self.unit.courses, "course code not being added correctly" def testD(self): self.unit.addStudent('10000000') assert '10000000' in self.unit.students, "student ID not being added correctly" def testE(self): self.unit.code = 'FIT1004' assert self.unit.getCode( ) == 'FIT1004', "correct unit code isn't being returned" def testF(self): self.unit.title = 'Databases' assert self.unit.getTitle( ) == 'Databases', "correct title not being returned"
def handle_unit_move(unit: Unit): while True: print("Enter position co-ordinates or q to cancel") input_value = input() if input_value == 'q': return else: if Vector2Int.is_coordinate(input_value): position = Vector2Int.from_battleship_coord(input_value) if not unit.move_to(position): print("Can't move there") else: return else: print("Invalid coordinate")
def editUnitDetails(self, university): print("\n \n \n") print("EDITING UNIT DETAILS:") code = input("Enter a Unit code: ") if university.unitExists(code): university.units.pop(code, None) newUnit = Unit() code = input("New unit code: ") code = validator.validateUnitCode(code) newUnit.setCode(code) title = input("New unit title: ") newUnit.setTitle(title) university.addUnit(newUnit) print("\nSUCCESS: UNIT RECORD CREATED") newUnit.displayDetails() else: print("ERROR: Unit code does not exist") print("\n \n \n")
def createUnit(self,university): print("\n \n \n") print("CREATING A NEW UNIT:") newUnit = Unit() code = input("New unit code: ") valid, code = validator.validateUnitCode(code) if valid: newUnit.setCode(code) title = input("New unit title: ") newUnit.setTitle(title) university.addUnit(newUnit) print("\nSUCCESS: UNIT RECORD CREATED: \n") newUnit.displayDetails() print("\n \n \n") else: print("ERROR: INVALID UNIT CODE FORMAT")
def __generateUnitInfo(self, mirror): result = [0] * 13 if mirror: result[0] = Unit(self.ball, True) for i in range(1, 13): if i <= 6: result[i] = Unit(self.playerOfTeamB[i - 1], True) else: result[i] = Unit(self.playerOfTeamA[i - 7], True) else: result[0] = Unit(self.ball) for i in range(1, 13): if i <= 6: result[i] = Unit(self.playerOfTeamA[i - 1]) else: result[i] = Unit(self.playerOfTeamB[i - 7]) return result
def __init__(self, importFlag=False): # create units self.player = Unit(random.uniform(0,Common.boardWidth), random.uniform(0,Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight) self.predators = [Unit(random.uniform(0,Common.boardWidth), random.uniform(0,Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight) for i in range(Common.numEnemies)] self.prey = [Unit(random.uniform(0,Common.boardWidth), random.uniform(0,Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight) for i in range(Common.numPrey)] self.preyCoordTree = spatial.cKDTree(np.array([(p.x,p.y) for p in self.prey])) # create AI for e in self.predators: e.createBrain() if (importFlag): # import weights from file with open('weights.txt','r') as f: content = f.readlines() importWeights = [ast.literal_eval(lst) for lst in content] for p in self.predators: p.neuralNet.putWeights(random.choice(importWeights)) # wrapper class for GA functionality self.genAlg = GenAlg(Common.numEnemies, Common.mutRate, Common.crossRate, self.predators[0].neuralNet.getNumWeights()) # initialize tk, other fields and main loop self.initCanvas() self.ticker, self.epochs = 0, 0 self.animate = True self.avgFitness = [] self.maxFitness = [] self.gameLoop() self.root.mainloop()
def handle_seqres_di(info_dict): # Deal with SEQRES_COL resides_col_li = DEFAULT_COLS['SEQRES_COL'][1:4] mtoTool = Unit.MultiToOne() for i in range(len(info_dict[resides_col_li[0]])): for resides_col in resides_col_li: info_dict[resides_col][i] = ''.join( mtoTool.multi_letter_convert_to_one_letter(j) for j in info_dict[resides_col][i]) pdbx_poly_key = DEFAULT_COLS['SEQRES_COL'][0] coordinates_model_key = DEFAULT_COLS['SEQRES_COL'][8] for i in range(len(info_dict[pdbx_poly_key])): strand_id_index = [0] li = info_dict[pdbx_poly_key][i] save_id = li[0] strand_id_li = [save_id] for j in range(len(li)): if li[j] != save_id: save_id = li[j] strand_id_index.append(j) strand_id_li.append(save_id) info_dict[pdbx_poly_key][i] = strand_id_li for col in DEFAULT_COLS['SEQRES_COL'][1:4]: info_dict[col][i] = [ MMCIF2Dfrm.get_index(strand_id_index, info_dict[col][i], j) for j in range(len(strand_id_index)) ] for col in DEFAULT_COLS['SEQRES_COL'][4:8]: info_dict[col][i] = [ ';'.join( MMCIF2Dfrm.get_index(strand_id_index, info_dict[col][i], j)) for j in range(len(strand_id_index)) ] new_comodel_li = [] for ele in info_dict[coordinates_model_key][i]: if ele not in new_comodel_li: new_comodel_li.append(ele) info_dict[coordinates_model_key][i] = new_comodel_li
def editUnitDetails(self,university): print("\n \n \n") print("EDITING UNIT DETAILS:") code = input("Enter a Unit code: ") if university.unitExists(code): university.units.pop(code, None) newUnit = Unit() code = input("New unit code: ") code = validator.validateUnitCode(code) newUnit.setCode(code) title = input("New unit title: ") newUnit.setTitle(title) university.addUnit(newUnit) print("\nSUCCESS: UNIT RECORD CREATED") newUnit.displayDetails() else: print("ERROR: Unit code does not exist") print("\n \n \n")
def on_mouse_press(x, y, button, modifiers): if button == mouse.LEFT: mouse_position['x'] = x mouse_position['y'] = y if commands["assigningUnit"] == True: for row in rows_y: if x > 22 * scale: if y > row and y < row + 24 * scale: commands["selectedRow"] = rows_y.index(row) commands["assigningUnit"] = False confirm_sound.play() if commands["selectedUnit"] == 0: sound = swordHit elif commands["selectedUnit"] == 1: sound = bowHit elif commands["selectedUnit"] == 2: sound = spellHit player_units.append( Unit(character_anims, sound, death_anim, row, commands["selectedUnit"])) for icon in unit_icons: if icon.onclick(mouse_position) == True: if commands['currency'] >= icon.type + 1: commands["assigningUnit"] = True commands["selectedUnit"] = icon.type commands['currency'] -= icon.type + 1 else: errorSound.play() if commands['currency'] > commands["currency_increase"]: if upgradeIcon.onclick(mouse_position): print "Upgraded mana" commands['currency'] -= commands['currency_increase'] commands['currency_increase'] *= 2 pyglet.clock.unschedule(increase_currency) commands["currency_gap"] *= 0.75 pyglet.clock.schedule_interval(increase_currency, commands["currency_gap"])
def __init__(self): Unit.__init__(self,450,25,'pierce','medium',0,1,2.31,) self.do_berserk = False self.berserk_cooldown = 30 self.berserk_cooldown_remaining = 0
class parse(HTMLParser): url = "" unit = None isUnit = False heading_tag_open = False body_tag_open = False title_tag_open = False script_tag_open = False temp_title = None http_regex = re.compile("^http://", re.IGNORECASE) slash_regex = re.compile("^/", re.IGNORECASE) double_slash_regex = re.compile("^//", re.IGNORECASE) heading_tag_regex = re.compile("^h\d$", re.IGNORECASE) unit_regex = re.compile("[a-z]{2,5}[0-9]{3,5}", re.IGNORECASE) def re_init(self, stack, visited, in_stack, db): self.stack = stack self.visited = visited self.in_stack = in_stack self.unit = Unit(self.url, db) def set_url(self, url): self.url = url self.unit.set_url(url) def setUnitTrue(self): self.isUnit = True def setUnitFalse(self): self.isUnit = False def count_words(self, data): words = data.split() return len(words) def get_domain(self): return self.url.split('/')[2] def handle_starttag(self, tag, attrs): if (tag == "a"): for name, value in attrs: if name == "href": if self.http_regex.match(value): if value not in self.visited and value not in self.in_stack: self.stack.push(value) self.in_stack.add(value) # print("pushing " + value) elif self.double_slash_regex.match(value): if ("http:" + value) not in self.visited and ("http:" + value) not in self.in_stack: self.stack.push("http:" + value) self.in_stack.add("http:" + value) elif self.slash_regex.match(value): if ("http://" + self.get_domain() + value) not in self.visited and ("http://" + self.get_domain() + value) not in self.in_stack: self.stack.push("http://" + self.get_domain() + value) self.in_stack.add("http://" + self.get_domain() + value) # else: # self.stack.push("http:" + value) # print("pushing " + "http:" + value) else: # print("tag is " + tag) if self.heading_tag_regex.match(tag): self.heading_tag_open = True elif tag == "body" or tag == "p": self.body_tag_open = True elif tag == "title": self.title_tag_open = True elif tag == "script": self.script_tag_open = True def handle_endtag(self, tag): if self.heading_tag_regex.match(tag): self.heading_tag_open = False elif tag == "body": self.body_tag_open = False elif tag == "title": self.title_tag_open = False elif tag == "script": self.script_tag_open = False def handle_data(self, data): if not self.isUnit: if self.heading_tag_open: result = self.unit_regex.search(data) if result: self.isUnit = True self.unit.add_unitcode(result.group(0)) self.unit.add_title(data) if self.body_tag_open and self.count_words(data) == 1 and self.unit_regex.search(data): self.isUnit = True if self.temp_title: self.unit.add_title(self.temp_title) self.unit.add_unitcode(self.unit_regex.search(data).group(0)) if self.body_tag_open and not self.script_tag_open: if self.count_words(data) > 10: self.unit.add_description(data) if self.title_tag_open: if self.isUnit: self.unit.add_title(data) else: self.temp_title = data if self.script_tag_open: res = re.finditer("href=.*$", data, re.MULTILINE) if res: for line in res: new_address = line.group() new_address = new_address.replace("&","&") new_address = re.search("\'.*\'", new_address, re.IGNORECASE).group(0) new_address = new_address[1:len(new_address)-1] # print(new_address) if self.http_regex.match(new_address): if new_address not in self.visited and new_address not in self.in_stack: self.stack.push(new_address) self.in_stack.add(new_address) # print("pushing " + value) elif self.double_slash_regex.match(new_address): if "http:" + new_address not in self.visited and "http:" + new_address not in self.in_stack: self.stack.push("http:" + new_address) self.in_stack.add("http:" + new_address) elif self.slash_regex.match(new_address): if "http://" + self.get_domain() + new_address not in self.visited and "http://" + self.get_domain() + new_address not in self.in_stack: self.stack.push("http://" + self.get_domain() + new_address) self.in_stack.add("http://" + self.get_domain() + new_address)
def __init__(self): Unit.__init__(self,1500,0,'normal','fortified',5,0,0,0,0,'building',None) self.unit_availbality_in_barracks = {'footman':[],'knight':['castle']} self.last_name = 'barracks' self.name = self.last_name+ self.name
def setUp(self): self.unit = Unit()
def __init__(self): Unit.__init__(self, 420, 12.5, armor_type='heavy', armor=2, hp_regeneration_rate=1, cooldown=1.35) self.last_name = 'footman' self.name = self.last_name + self.name self._defence = False
def __init__(self, id, x, y, type): Unit.__init__(self, id, x, y) self.type = type
def __init__(self): Unit.__init__(self, "Hydra", 80, 15, 12, (7, 14), 7, list([DmgBuff()]), None)
def __init__(self, id, width, height, x, y, type): Unit.__init__(self, id, width, height, x, y, 0.0, 0.0, 0.0, 0.0) self.type = type
def __init__(self, id, player_name, teammate_index, x, y, speed_x, speed_y, angle, angular_speed, turret_relative_angle, crew_health, hull_durability, reloading_time, remaining_reloading_time, premium_shell_count, teammate, type): Unit.__init__(self, id, get_width(type), get_height(type), x, y, speed_x, speed_y, angle, angular_speed) self.player_name = player_name self.teammate_index = teammate_index self.turret_relative_angle = turret_relative_angle self.crew_health = crew_health self.hull_durability = hull_durability self.reloading_time = reloading_time self.remaining_reloading_time = remaining_reloading_time self.premium_shell_count = premium_shell_count self.teammate = teammate self.type = type self.virtual_gun_length = { TankType.MEDIUM: 67.5, TankType.HEAVY: 82.5, TankType.TANK_DESTROYER: 97.5 }[type] self.mass = { TankType.MEDIUM: 10.0, TankType.HEAVY: 20.0, TankType.TANK_DESTROYER: 15.0 }[type] self.engine_power = { TankType.MEDIUM: 7500.0, TankType.HEAVY: 7500.0, TankType.TANK_DESTROYER: 5000.0 }[type] self.engine_rear_power_factor = { TankType.MEDIUM: 0.75, TankType.HEAVY: 0.5, TankType.TANK_DESTROYER: 0.35 }[type] self.turret_turn_speed = { TankType.MEDIUM: 1.0 * pi / 180.0, TankType.HEAVY: 0.5 * pi / 180.0, TankType.TANK_DESTROYER: 1.5 * pi / 180.0 }[type] self.turret_max_relative_angle = { TankType.MEDIUM: 0.0 * pi / 180.0, TankType.HEAVY: 0.0 * pi / 180.0, TankType.TANK_DESTROYER: 15.0 * pi / 180.0 }[type] self.crew_max_health = { TankType.MEDIUM: 100, TankType.HEAVY: 100, TankType.TANK_DESTROYER: 100 }[type] self.hull_max_durability = { TankType.MEDIUM: 200, TankType.HEAVY: 250, TankType.TANK_DESTROYER: 250 }[type] self.frontal_armor = { TankType.MEDIUM: 175, TankType.HEAVY: 200, TankType.TANK_DESTROYER: 250 }[type] self.side_armor = { TankType.MEDIUM: 150, TankType.HEAVY: 175, TankType.TANK_DESTROYER: 125 }[type] self.rear_armor = { TankType.MEDIUM: 100, TankType.HEAVY: 100, TankType.TANK_DESTROYER: 100 }[type]
def __init__(self): Unit.__init__(self, 250, 7.5, 'normal', 'light') NormalAttack.__init__(self)
def setUp(self): self.unit = Unit()
def underattacked(self, damage, underattack_type): if underattack_type == 'pierce' and self._defence: damage = damage * 0.5 Unit.underattacked(self, damage, underattack_type)
from Unit import Unit from Item import Item name = input("What do you want the player to be named?\n") name = "Darren" player = Unit(name, [5,5]) enemies = [ Unit("Orc", [4,4], 10, 2), Unit("Goblin", [6,6], 6, 3) ] items = [ Item("Treasure", [2,3]), Potion("Health Potion", [3,3]) ] menu = ["Move up", "Move Down", "Move Left", "Move Right"] def show_menu(): for i in range(len(menu)): print(f"{i+1}. {menu[i]}") i += 2 for item in player.inventory: print(f"{i}. Use {item.name}") i += 1 playing = True while playing:
def __init__(self): Unit.__init__(self,1500,0,'normal','fortified',5,0,0,0,0,'building',None) self.unit_availbality_in_townhall = {'peasant':[]} self.last_name = 'HumansTownhall' self.name = self.last_name + self.name
playing = True while playing: clear() print('Welcome to Crazy Kitchen!') name = input("What is your name?\n") print(f""" Hi Chef {name}! The kitchen is a mess. Ingredients have been left all over the place. Try to gather ingredients to make a pizza before you lose your patience! """) player = Player(name, [2, 2]) enemies = [ Unit("banana peel", [3, 3]), Unit("water spill", [4, 1]), Unit("gum", [2, 4]), Unit("broken glass", [3, 4]), Unit("trash", [0, 5]), Unit("Gordon Ramsey", [1, 4]) ] items = [ Item("mushrooms", [5, 5]), Item("pepperonis", [4, 5]), Item("crushed red pepper", [3, 5]), Item("extra cheese", [2, 5]), Item("oven", [4, 0]) ] playing = True
def __init__(self, id, width, height, x, y): Unit.__init__(self, id, width, height, x, y, 0.0, 0.0, 0.0, 0.0)
def __init__(self, id, player_name, teammate_index, x, y, speed_x, speed_y, angle, angular_speed, turret_relative_angle, crew_health, hull_durability, reloading_time, remaining_reloading_time, premium_shell_count, teammate, type): Unit.__init__(self, id, get_width(type), get_height(type), x, y, speed_x, speed_y, angle, angular_speed) self.player_name = player_name self.teammate_index = teammate_index self.turret_relative_angle = turret_relative_angle self.crew_health = crew_health self.hull_durability = hull_durability self.reloading_time = reloading_time self.remaining_reloading_time = remaining_reloading_time self.premium_shell_count = premium_shell_count self.teammate = teammate self.type = type self.virtual_gun_length = { TankType.MEDIUM: 67.5, TankType.HEAVY: 82.5, TankType.TANK_DESTROYER: 97.5 }[type] self.mass = { TankType.MEDIUM: 10.0, TankType.HEAVY: 30.0, TankType.TANK_DESTROYER: 20.0 }[type] self.engine_power = { TankType.MEDIUM: 7500.0, TankType.HEAVY: 13500.0, TankType.TANK_DESTROYER: 7500.0 }[type] self.engine_rear_power_factor = { TankType.MEDIUM: 0.75, TankType.HEAVY: 0.65, TankType.TANK_DESTROYER: 0.5 }[type] self.turret_turn_speed = { TankType.MEDIUM: 1.0 * pi / 180.0, TankType.HEAVY: 0.75 * pi / 180.0, TankType.TANK_DESTROYER: 1.5 * pi / 180.0 }[type] self.turret_max_relative_angle = { TankType.MEDIUM: 0.0 * pi / 180.0, TankType.HEAVY: 0.0 * pi / 180.0, TankType.TANK_DESTROYER: 20.0 * pi / 180.0 }[type] self.crew_max_health = { TankType.MEDIUM: 100, TankType.HEAVY: 100, TankType.TANK_DESTROYER: 100 }[type] self.hull_max_durability = { TankType.MEDIUM: 200, TankType.HEAVY: 250, TankType.TANK_DESTROYER: 250 }[type] self.frontal_armor = { TankType.MEDIUM: 175, TankType.HEAVY: 200, TankType.TANK_DESTROYER: 250 }[type] self.side_armor = { TankType.MEDIUM: 150, TankType.HEAVY: 175, TankType.TANK_DESTROYER: 125 }[type] self.rear_armor = { TankType.MEDIUM: 100, TankType.HEAVY: 100, TankType.TANK_DESTROYER: 100 }[type] self.shell_speed_bonus = { TankType.MEDIUM: 0.0 / 60.0, TankType.HEAVY: 25.0 / 60.0, TankType.TANK_DESTROYER: 50.0 / 60.0 }[type]
class Controller: # Input: # None # Output: # None # Description: # Initializes game state and starts app def __init__(self, importFlag=False): # create units self.player = Unit(random.uniform(0,Common.boardWidth), random.uniform(0,Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight) self.predators = [Unit(random.uniform(0,Common.boardWidth), random.uniform(0,Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight) for i in range(Common.numEnemies)] self.prey = [Unit(random.uniform(0,Common.boardWidth), random.uniform(0,Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight) for i in range(Common.numPrey)] self.preyCoordTree = spatial.cKDTree(np.array([(p.x,p.y) for p in self.prey])) # create AI for e in self.predators: e.createBrain() if (importFlag): # import weights from file with open('weights.txt','r') as f: content = f.readlines() importWeights = [ast.literal_eval(lst) for lst in content] for p in self.predators: p.neuralNet.putWeights(random.choice(importWeights)) # wrapper class for GA functionality self.genAlg = GenAlg(Common.numEnemies, Common.mutRate, Common.crossRate, self.predators[0].neuralNet.getNumWeights()) # initialize tk, other fields and main loop self.initCanvas() self.ticker, self.epochs = 0, 0 self.animate = True self.avgFitness = [] self.maxFitness = [] self.gameLoop() self.root.mainloop() # Input: # None # Output: # None # Description: # Initializes fields related to tkinter UI library def initCanvas(self): # create root and canvas self.root = Tk() self.canvas = Canvas(self.root, width=Common.boardWidth, height=Common.boardHeight) self.canvas.pack() self.root.canvas = self.canvas.canvas = self.canvas self.root.bind("<Key>", self.keyPressed) # Input: # event - tkinter keypress even to process # Output: # None # Description: # Accepts user arrow-key input and translates to unit acceleration def keyPressed(self, event): # move player unit if (event.keysym == "Up"): self.player.accY(-1) elif (event.keysym == "Down"): self.player.accY(1) elif (event.keysym == "Left"): self.player.accX(-1) elif (event.keysym == "Right"): self.player.accX(1) elif (event.keysym == "f"): # end animation and enter simulation self.animate = not self.animate # Input: # None # Output: # None # Description: # Timer function calls functions to advance game state def gameLoop(self): # advance state self.moveUnits() self.drawState() self.ticker += 1 if (self.ticker > Common.epochLen): # this epoch is over self.endEpoch() self.epochs += 1 self.canvas.after(Common.delay, self.gameLoop) elif (self.animate): # continue advancing state self.canvas.after(Common.delay, self.gameLoop) elif (self.epochs >= Common.numEpochs): # simulation over self.genPlot() self.root.destroy() sys.exit() else: # destroy game canvas and start pure simulation self.root.destroy() self.simLoop() # Input: # None # Output: # None # Description: # Timer function advances simulation state by whole epochs def simLoop(self): while (self.epochs < Common.numEpochs): # advance epoch while (self.ticker <= Common.epochLen): self.moveUnits() self.ticker += 1 self.endEpoch() self.epochs += 1 # generate fitness plot self.genPlot() # export data to text file f = open('weights.txt', 'w') for i in range(Common.numElite): netWeights = self.predators[i].neuralNet.getWeights() f.write(str(netWeights) + '\n') f.close() # exit app sys.exit() # Input: # None # Output: # None # Description: # Calls functions to advance unit state and positions def moveUnits(self): # advance player self.player.advance() # update enemy AI and advance for e in self.predators: output = e.neuralNet.update(self.getNNInput(e)) e.accX(output[0]) e.accY(output[1]) e.advance() # check if distance to nearest is small enough to clear (nearest, index) = self.getNearestPrey(e) if (self.getDist(e.x, e.y, nearest.x, nearest.y) < 10): # increment fitness e.fitness += 1 # remove prey self.prey.pop(index) # add new prey self.prey.append(Unit(random.uniform(0,Common.boardWidth), random.uniform(0,Common.boardHeight), 0, 0, Common.boardWidth, Common.boardHeight)) # rebuild cKDTree self.preyCoordTree = spatial.cKDTree(np.array([(p.x,p.y) for p in self.prey])) # sort predators WRT fitness to keep track of most fit self.predators.sort() # Input: # None # Output: # None # Description: # Clears old and draws new game state def drawState(self): # clear canvas self.canvas.delete(ALL) # draw player (l,r,t,b) = self.player.getDim() self.canvas.create_oval(l, t, r, b, fill="blue") # draw prey for p in self.prey: (l,r,t,b) = p.getPreyDim() self.canvas.create_rectangle(l, t, r, b, fill="green") # draw predators for i in range(len(self.predators)): e = self.predators[i] (l,r,t,b) =e.getDim() if (i < Common.numElite): # draw most fit preds in purple self.canvas.create_rectangle(l, t, r, b, fill="orange") else: self.canvas.create_rectangle(l, t, r, b, fill="red") (nearest, index) = self.getNearestPrey(e) self.canvas.create_line(e.x, e.y, nearest.x, nearest.y, fill="red", dash=(4,4)) # Input: # e - enemy unit for which to generate NN input # Output: # result - vector input for given unit's Neural Net # Description: # Returns input vector to given unit's Neural Net def getNNInput(self, e): # get vector towards nearest prey (nearest, index) = self.getNearestPrey(e) #nearest = self.player preyDir = [nearest.x - e.x, nearest.y - e.y] # and vector of this unit's current direction unitDir = [e.vx, e.vy] result = [preyDir[0], preyDir[1], unitDir[0], unitDir[1]] return result # Input: # unit - the unit for which to find the nearest prey # Output: # (prey, i) - where prey is the nearest prey and i is its index # Description: # Uses KDTree Nearest Neighbor search to find the prey nearest the given predator unit def getNearestPrey(self, unit): (dist, i) = self.preyCoordTree.query((unit.x, unit.y), k=1) return (self.prey[i], i) # Input: # None # Output: # None # Description: # Runs GA to evolve NN weights and restarts game def endEpoch(self): # store fitnesses fitness = [] for e in self.predators: fitness.append(e.fitness) self.avgFitness.append(sum(fitness)/len(fitness)) self.maxFitness.append(max(fitness)) print("Generation " + str(self.epochs)) print("Average fitness: " + str(self.avgFitness[-1])) print("Maximum fitness: " + str(self.maxFitness[-1])) print() # run GA on population of enemies population = [Chromosome(e.neuralNet.getWeights(), e.fitness) for e in self.predators] population = self.genAlg.evolve(population) # put weights into NNs for i in range(Common.numEnemies): self.predators[i].neuralNet.putWeights(population[i].weights) self.predators[i].fitness = 0 # start next epoch self.ticker = 0 # Input: # x1, y1 - coordinates of point 1 # x2, y2 - coordinates of point 2 # Output: # Distance # Description: # Returns euclidean distance between given points def getDist(self, x1, y1, x2, y2): return math.sqrt((x1 - x2)**2 + (y1 - y2)**2) # Input: # v - vector to normalize # Output: # result - normalized copy of given vector # Description: # Returns a normalized copy of the given vector (2-norm) def normalize(self, v): norm = math.sqrt(sum([x**2 for x in v])) if (norm != 0): result = [x/norm for x in v] else: result = v return result # Input: # None # Output: # None # Description: # Plots fitness of generations after simulation is complete def genPlot(self): pylab.plot(range(len(self.avgFitness)), self.avgFitness, 'b--', range(len(self.maxFitness)), self.maxFitness, 'r--') pylab.xlabel('epoch') pylab.ylabel('fitness') pylab.savefig('fitness.png')
def __init__(self, name): Unit.__init__(self, name) # Imprime alguns dados para debug, linha opcional. print ('UnloadingPoint object', '"'+self.get_name()+'"', 'created at', str(self)+'.\n')
def __init__(self): Unit.__init__(self, 570, 40, 'pierce', 'light', 0, 1,2, 0, 0, 'air', ['ground','building','air']) self.air_attack = 40 self.air_attack_cooldown = 2 self.air_attack_type = 'pierce'
def __init__(self, health=100, mana=100, damage=20): Unit.__init__(self, health, mana) self.attack_points = damage
def __init__(self, id, player_name, width, height, x, y, speed_x, speed_y, angle, angular_speed, type): Unit.__init__(self, id, width, height, x, y, speed_x, speed_y, angle, angular_speed) self.player_name = player_name self.type = type
def __init__(self): Unit.__init__(self, attack=0, armor_type='fortified')
def re_init(self, stack, visited, in_stack, db): self.stack = stack self.visited = visited self.in_stack = in_stack self.unit = Unit(self.url, db)