def get_peoples_id(URL): time.sleep(2) print('dentro-get_peoples_id') print(URL) try: r = requests.get(URL) if r.ok: print("okey!") d = r.json() print(d['total_pages']) for actores in d['results']: try: val = int(actores['name']) print("val: " + val) pass except: lista_peliculas = [] for x in actores['known_for']: lista_peliculas.append(x['title']) print(actores['name']) lista_actores.append( actor( actores['name'], "http://image.tmdb.org/t/p/w500/" + actores['profile_path'], lista_peliculas, actores['id'])) # return render_template('index.html', output=listita) except: pass
def __init__(self, id, type='basic'): self.token = None self.cookie_redirect = None self.cookie = None self.type = type self.oauth = None self.trust = None # Proposed response code after checkAuthentication() or authorise() have been called self.response = { 'code': 403, # Result code (http) 'text': "Forbidden", # Proposed response text 'headers': [], # Headers to add to response after authentication has been done } # Whether authentication is complete or not (depends on flow) self.authn_done = False # acl stores the actual verified credentials and access rights after # authentication and authorisation have been done self.acl = { "authenticated": False, # Has authentication been verified and passed? "authorised": False, # Has authorisation been done and appropriate acls set? "rights": '', # "a", "r" (approve or reject) "relationship": None, # E.g. creator, friend, admin, etc "peerid": '', # Peerid if there is a relationship "approved": False, # True if the peer is approved } Config = config.config() self.config = Config self.actor = actor.actor(id) if not self.actor.id: self.actor = None self.oauth = oauth.oauth(token=None) self.token = None self.expiry = None self.refresh_expiry = None self.refresh_token = None return # We need to initialise oauth for use towards the external oauth service self.property = 'oauth_token' # Property name used to set self.token self.token = self.actor.getProperty(self.property).value self.oauth = oauth.oauth(token=self.token) self.expiry = self.actor.getProperty('oauth_token_expiry').value self.refresh_expiry = self.actor.getProperty('oauth_refresh_token_expiry').value self.refresh_token = self.actor.getProperty('oauth_refresh_token').value if self.type == 'basic': self.realm = Config.auth_realm elif self.type == 'oauth': if self.oauth.enabled(): self.cookie = 'oauth_token' if self.actor.getProperty('cookie_redirect').value: self.cookie_redirect = Config.root + \ self.actor.getProperty('cookie_redirect').value else: self.cookie_redirect = None self.redirect = Config.root + self.actor.id + '/oauth' else: self.type = 'none'
def parseActor(self): doc = xml.dom.minidom.parse(self.filename) actors = doc.getElementsByTagName("actor") for Actor in actors: id = Actor.getAttribute("id") firstName = Actor.getAttribute("firstName") lastName = Actor.getAttribute("lastName") fatherName = Actor.getAttribute("fatherName") rank = Actor.getAttribute("rank") expirience = Actor.getAttribute("expirience") newActor = actor(firstName, lastName, fatherName, rank, expirience) self.actorsList[id] = newActor print(self.actorsList)
def readDb(self,inp): a = actor("Gleb","Nazemnov","Andreevich","glavnui","15") p = performances("12 стульев","2015","322") lab = labor(a,p,"Остап Бендер","20000000") conn = db.connect(inp) curs = conn.cursor() curs.execute('select * from actor') data=curs.fetchall() for r in data:print(r) curs.execute('select * from performance') data=curs.fetchall() for r in data:print(r) curs.execute('select * from labor') data=curs.fetchall() for r in data:print(r) conn.close()
def get_actors(self,film_id): r=proxy.gethtml(url='https://movie.douban.com/subject/'+str(film_id)+'/celebrities',headers=util.headers,params={}) if r is None: return soup=BeautifulSoup(r.content.decode(),'html.parser') if soup is None: return lis=soup.find_all('li',{'class':'celebrity'}) if lis is None: return for li in lis: act=actor.actor() sf=li.find('span',{'class':'name'}) if sf: sfa=sf.find('a') if sfa: act.actor_name=sfa.get_text() ar=re.search(r'(\d+)\/?$',sfa.get('href')) if ar: act.actor_id=ar.group(1) if act.actor_id=="": continue sf=li.find('span',{'class':'role'}) if sf: act.actor_role=sf.get_text() sf=li.find('span',{'class':'works'}) if sf: sfa=sf.find_all('a') if sfa: act.main_works=util.listtostr(sfa,'/') dbacts=sql.get_actor_byid(act.actor_id) try: if len(dbacts)==0: self.get_actor_info(act) sql.save_actor(act) dbactfs=sql.get_actor_film_byid(act.actor_id,film_id) if len(dbactfs)==0: sql.save_actor_film(act.actor_id,film_id,act.actor_role) except Exception as e: log.logger.info(str(e)) print(act)
upper_quartile_alpha = scoreatpercentile(alpha,75) at_risk = [agent for agent in graph.nodes() if alpha[agent]>=upper_quartile_alpha and fraction_of_influencers(influence_kernel[agent],upper_quartile_influence_kernel)>upper_quartile_receiving_influence] return at_risk G = nx.MultiDiGraph() tmp = nx.barabasi_albert_graph(params['n']['nodes'],params['n']['edges']) G.add_edges_from(tmp.edges()) G.add_nodes_from(tmp) G.add_edges_from(nx.MultiDiGraph(nx.barabasi_albert_graph(params['n']['nodes'],params['n']['edges'])).reverse().edges()) max_degree = max(nx.degree(G).values()) #Link an agent with each node actors = [actor() for _ in xrange(params['n']['nodes'])] for node_idx,actor in zip(G.nodes(),actors): G.node[node_idx]['actor'] = actor alpha=np.random.random_sample(size=(params['n']['nodes'],)) #alpha = np.zeros((params['n']['nodes'],)) influence = {node:len(G.predecessors(node))/float(len(G.successors(node))) for node in G.nodes_iter()} influence_kernel = {node:normalize(np.array([influence[predecessor] for predecessor in G.predecessors(node)]).astype(float)) for node in G.nodes_iter()} fraction = int(options.fraction)*.01 timesteps = directory['timesteps'] total_duration = 3*timesteps attitudes = np.zeros((params['n']['nodes'],total_duration))
def newActor(self, id, firsName, lastName, fatherName, rank, expirience): a = actor(firsName, lastName, fatherName, rank, expirience) actor.setId(id) self.setactor(a)
def main(incomeTax = True, toTax = [True, True, True], initITP = [0, 0.25, 0.9], incomeTaxThresholds = [0.33, 0.66], long = False, name = "", actorNum = 95, nobleNum = 5, moneyPerActor = 1000, rounds = 100000, taxMod = 0.3): actors = []; for i in range(actorNum): actors.append(actor.actor(moneyPerActor)); for i in range(nobleNum): actors.append(actor.actor(moneyPerActor, 3)); totGold = 0; totPop = 0; for a in actors: totGold += a.gold; totPop += 1; # Init variables lastPrices = [1,2,3]; curPrices = [1,2,3]; allPrices = [[],[],[]] allPops = [[],[],[],[]] allSold = [[],[],[]] allProduced = [[],[],[]] allWanted = [[],[],[]] movements = [[],[],[],[],[]] taxRevs = [] nobleSpending = [] totGoldarray = [[],[],[],[],[]] gdp = []; conSpend = []; govSpend = []; investSpend = []; ppp = []; # gdp/(# actors * price of food). Guess it's kinda an adjusted gdp for 'inflation' (mostly adusts for actors eating money supply) cci = []; # consumer confidence index. Measures proportion of actors willing to bid for luxury goods. tax = [0,0,0]; jewelersCanBuyLux = False; # If incomeTax is true, then income taxes are used. If false, then VAT tax is used. #incomeTax = True; # VAT tax variables #toTax = [False, False, True]; taxes = [[],[],[]] # Income tax proportions (Income Tax Prop. - ITP) #initITP = [0, 0.25, 0.5]; curITP = initITP.copy(); #incomeTaxThresholds = [0.33, 0.66]; actualTaxThresholds = []; for i in range(len(incomeTaxThresholds)): actualTaxThresholds.append([]); # Run loops (with fancy progress display) for i in tqdm(range(rounds)): for a in actors: a.beforeTrades(i); # Run auctions for food, tools and luxury goods, in that order prodCosts = []; buyerValues = []; taxRevs.append(0); nobleSpending.append(0); gdp.append(0); conSpend.append(0); govSpend.append(0); investSpend.append(0); cci.append(0); for j in range(3): prodCosts.clear(); buyerValues.clear(); # Determine production costs and buyer values for a in actors: # food auction if (j == 0): if (a.type == 0 and a.inv[0] > 0): # base food cost roughly on last round's food cost, plus some random variation # (farmers should never starve) numSelling = max(a.inv[0], 0); prodCost = max((lastPrices[0] + r.randint(-2,2) / numSelling * (1 + tax[0])), 1) if (a.lastUsedTool): prodCost = max(int(lastPrices[1] / numSelling * (1 + tax[0])), 1); prodCosts.extend([[prodCost, a]] * numSelling); else: buyPrice = a.getValue(j, lastPrices, incomeTax); buyPriceRatio = int(buyPrice / lastPrices[0]); if (buyPriceRatio > 4): buyerValues.append([buyPrice / 2, a]); buyerValues.append([buyPrice / 4, a] * 2); else: buyerValues.append([buyPrice / 2, a]); # tool auction elif (j == 1): if (a.type == 1): # Set tool production cost to be based on last round food price, plus # some random markup/down based on previous sell price numToSell = max(a.inv[1] - 1, 1); if (numToSell != 0): prodCost = int(max((lastPrices[0] + r.randint(-2,2)) / numToSell * (1 + tax[1]), 1)); prodCosts.extend([[randint(prodCost, lastPrices[1] + 5), a]] * numToSell); else: buyerValues.append([a.getValue(j, lastPrices, incomeTax), a]); # luxury auction else: # j == 2 if (a.type == 2): # Set luxury production cost to be based on last round food and tool price, # plus some random markup/down based on last sell price numToSell = max(a.inv[2], 0); if (numToSell != 0): prodCost = int(max((lastPrices[0] + lastPrices[1] + r.randint(-2,2)) / numToSell * (1 + tax[2]), 1)); prodCosts.extend([[randint(prodCost, lastPrices[2] + 5), a]] * numToSell); elif (a.type != 2 or jewelersCanBuyLux): numToBuy = 1; if (a.type == 3): numToBuy = int(max(1, (a.gold - lastPrices[0] * 3)/lastPrices[2] - 1)); buyerValues.extend([[a.getValue(j, lastPrices, incomeTax)/(numToBuy * r.randint(1, 2)), a]] * numToBuy); cci[-1] += 1; else: luxVal = a.getValue(j, lastPrices, incomeTax); if (luxVal > 0): buyerValues.append([luxVal, a]); cci[-1] += 1; cci[-1] = cci[-1]/totPop; allProduced[j].append(len(prodCosts)); allWanted[j].append(len(buyerValues)); if (len(buyerValues) == 0 or len(prodCosts) == 0): if (len(prodCosts) > len(buyerValues)): allPrices[j].append(curPrices[j] - 1); curPrices[j] -= 1; else: allPrices[j].append(curPrices[j] + 1) curPrices[j] += 1; allSold[j].append(0); else: # Arrange production costs from low to high bubble_sort(prodCosts); bubble_sort(buyerValues); # equate costs & values list lengths by removing lowest buyer bids # or highest seller bids if (len(prodCosts) < len(buyerValues)): buyerValues = buyerValues[len(buyerValues) - len(prodCosts):]; elif (len(prodCosts) > len(buyerValues)): prodCosts = prodCosts[:len(buyerValues)]; # Arrange buyer bids from high to low buyerValues.reverse(); # Get price for good j (use buyervalues to set price for both buyers # and sellers, to prevent incentives from adding/removing gold from economy) k = 0; for k in range(len(prodCosts) - 1): if (prodCosts[k][0] <= buyerValues[k][0] and prodCosts[k + 1][0] > buyerValues[k + 1][0]): break; curPrices[j] = prodCosts[k][0]; allPrices[j].append(curPrices[j]); # Complete trades totSold = 0; for b in range(len(buyerValues)): if (buyerValues[b][0] >= curPrices[j] and prodCosts[b][0] <= curPrices[j]): buyerValues[b][1].gold -= curPrices[j]; # Add transaction to gdp gdp[-1] += curPrices[j]; if (j != 1 and buyerValues[b][1].type != 3): conSpend[-1] += curPrices[j]; elif (j == 1): investSpend[-1] += curPrices[j]; elif (buyerValues[b][1].type == 3): govSpend[-1] += curPrices[j]; nobleSpending[-1] += curPrices[j]; buyerValues[b][1].inv[j] += 1; assert(buyerValues[b][1].gold >= 0); prodCosts[b][1].pay(curPrices[j] / (1 + tax[j])); taxRevs[-1] += curPrices[j] - curPrices[j] / (1 + tax[j]); prodCosts[b][1].inv[j] -= 1; assert(prodCosts[b][1].inv[j] >= 0); totSold += 1; #if (buyerValues[b][1].type != 3 and j == 2): # print(buyerValues[b][1].type) allSold[j].append(totSold); #assert(conSpend[-1] + investSpend[-1] + govSpend[-1] == gdp[-1]); for n in range(5): movements[n].append(0); # Adjust tax rate to support noble spending if (not incomeTax): mod = taxMod; if (len(totGoldarray[0]) > 0 and totGoldarray[4][-1]/totGoldarray[0][-1] > 0.5): mod = 1.25; for taxType in range(len(tax)): if (taxRevs[-1] == 0 and toTax[taxType]): tax[taxType] = 0.1; else: tax[taxType] *= nobleSpending[-1]/max(mod * taxRevs[-1],1); tax[taxType] = min(tax[taxType], 2); taxes[taxType].append(tax[taxType]); else: # Calculate income thresholds incTax = []; for act in actors: incTax.append(act.lastIncome); incTax.sort(); thresh = [incTax[int(len(incTax) * kek)] for kek in incomeTaxThresholds]; for kekek in range(len(actualTaxThresholds)): actualTaxThresholds[kekek].append(thresh[kekek]); # Collect income tax for act in actors: taxBracket = 0; for th in thresh: if (act.lastIncome > thresh[taxBracket]): taxBracket += 1; else: break; newTax = min(int(act.lastIncome * curITP[taxBracket]), act.gold); taxRevs[-1] += newTax; act.gold -= newTax; act.lastTax = newTax act.lastIncome = 0; mod = taxMod; # as mod increases, nobles get less money from taxes if (len(totGoldarray[0]) > 0 and totGoldarray[4][-1]/totGoldarray[0][-1] > 0.5): mod = 1.25; #print("oh no") for taxType in range(len(curITP)): if (taxRevs[-1] < 1 and initITP[taxType] > 0): # and nobleSpending[-1] != 0): curITP[taxType] = initITP[taxType]; else: curITP[taxType] *= nobleSpending[-1]/max(mod * taxRevs[-1],1); #1.013 good for sales tax curITP[taxType] = min(curITP[taxType], 4) if (taxType != 0): taxes[taxType-1].append(curITP[taxType]); # Distribute tax revenue (split equally among economy if no nobles) noblecount = 0; for a in actors: if (a.type == 3): noblecount += 1; if (noblecount == 0): for a in actors: a.gold += taxRevs[-1]/totPop; else: for a in actors: if (a.type == 3): a.gold += taxRevs[-1]/noblecount; for a in actors: a.afterTrades(lastPrices, movements, totGold, totPop); if (a.dead): actors.remove(a); print("d"); del a; lastPrices = curPrices; tGold = 0; fGold = 0; sGold = 0; jGold = 0; nGold = 0; pop = [0,0,0,0] for kek in actors: tGold += kek.gold; pop[kek.type] += 1; if (kek.type == 0): fGold += kek.gold; elif (kek.type == 1): sGold += kek.gold; elif (kek.type == 2): jGold += kek.gold; elif (kek.type == 3): nGold += kek.gold; totGoldarray[0].append(tGold); totGoldarray[1].append(fGold); totGoldarray[2].append(sGold); totGoldarray[3].append(jGold); totGoldarray[4].append(nGold); for n in range(4): allPops[n].append(pop[n]) ppp.append(gdp[-1]/(totPop * max(1, lastPrices[0]))) if (not long): plt.figure(1); lbs = ["Food", "Tools", "Luxury"]; for i in range(3): plt.plot(ma(allPrices[i]), label = ("Price of " + lbs[i])); plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(2); lbs = ["Food", "Tools", "Luxury"]; for i in range(3): plt.plot(ma(allSold[i]), label = ("Units sold: " + lbs[i])); plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(3); lbs = ["Farmers", "Smiths", "Jewelers", "Nobles"]; for i in range(4): plt.plot(allPops[i],label = lbs[i]); plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(4); plt.plot(ma(allProduced[0]), label = "Food Supply") plt.plot(ma(allWanted[0]), label = "Food Demand") plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(5); plt.plot(ma(allProduced[1]), label = "Tool Supply") plt.plot(ma(allWanted[1]), label = "Tool Demand") plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(6); plt.plot(allProduced[2], label = "Luxury Supply") plt.plot(allWanted[2], label = "Luxury Demand") plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(8); plt.plot(ma(taxRevs), label = "Tax Revenue") plt.plot(ma(nobleSpending), label = "Noble Spending"); plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(9); lbs = ["Total Gold", "Farmer Gold", "Smith Gold", "Jeweler Gold", "Noble Gold"]; for i in range(5): plt.plot(totGoldarray[i],label = lbs[i]); plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(10); lbs = ["Avg. Farmer Gold", "Avg. Smith Gold", "Avg. Jeweler Gold", "Avg. Noble Gold"]; for i in range(4): plt.plot(ma([totGoldarray[i+1][j]/max(1, allPops[i][j]) for j in range(len(allPops[i]))]),label = lbs[i]); plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(13); if (not incomeTax): lbs = ["Food Tax", "Tool Tax", "Luxury Tax"]; for i in range(3): plt.plot(ma(taxes[i]),label = lbs[i]); else: lbs = [str(kek) + "+ Tax" for kek in incomeTaxThresholds]; for i in range(len(incomeTaxThresholds)): plt.plot(ma(taxes[i]),label = lbs[i]); plt.legend(); plt.ylim(ymin=0); plt.show(); if (incomeTax): plt.figure(14); lbs = [str(kek) + "+ Tax Threshold" for kek in incomeTaxThresholds]; for i in range(len(actualTaxThresholds)): plt.plot(ma(actualTaxThresholds[i]),label = lbs[i]); plt.legend(); plt.ylim(ymin=0); plt.show(); plt.figure(11); smoothing = 250; if (not long): plt.plot(ma(gdp), label = "GDP US"); plt.plot(ma(investSpend), label = "Investment Spending"); plt.plot(ma(conSpend), label = "Consumer Spending"); plt.plot(ma(govSpend), label = "Government Spending"); plt.title("Nominal GDP Over Time"); plt.xlabel("Round"); plt.ylabel("Nominal GDP ($)"); plt.plot(ma(gdp, smoothing), label = (name + " GDP")) plt.legend(); plt.ylim(ymin=0, ymax = 3000); plt.grid(True); plt.show(); plt.figure(12); if (not long): plt.plot(ma(ppp), label = "rGDP US") plt.plot(ma(ppp, smoothing), label = (name + " rGDP")) plt.legend(); plt.title("rGDP Over Time"); plt.xlabel("Round"); plt.ylabel("Real Per-Capita GDP (Units of Food)"); plt.ylim(ymin=0.75, ymax = 3.25); plt.grid(True); plt.show(); plt.figure(16); if (not long): plt.plot(ma(cci), label = "CCI US") plt.plot(ma(cci, smoothing), label = (name + " CCI")); plt.title("CCI Over Time"); plt.xlabel("Round"); plt.ylabel("Consumer Confidence Index"); plt.legend(); plt.ylim(ymin=0, ymax = 1); plt.grid(True); plt.show(); plt.figure(7); #lbs = ["Starved", "NEL", "F->S", "S->J", "J->N"]; #for i in range(5): # plt.plot(ma(movements[i]),label = lbs[i]); plt.plot(ma([movements[0][i] / (totPop - allPops[0][i]) for kek in range(len(movements[0]))], 100),label = (name + " Starvation Index")); plt.legend(); plt.ylim(ymin=0, ymax=0.5); plt.title("Starvation Index Over Time"); plt.xlabel("Round"); plt.ylabel("Starvation Index"); plt.grid(True); plt.show(); plt.figure(15); jqi=[(allPops[1][i] + allPops[2][i] * 2) / totPop for i in range(len(allPops[1]))] plt.plot(ma(jqi, smoothing), label = (name + " Job Quality Index")) plt.legend(); plt.ylim(ymin=0, ymax = 1); plt.title("Job Quality Index Over Time"); plt.xlabel("Round"); plt.ylabel("Job Quality Index"); plt.grid(True); plt.show(); print(name + " avg gdp: " + str(sum(gdp)/len(gdp))) print(name + " avg rgdp: " + str(sum(ppp)/len(ppp))) print(name + " avg jqi: " + str(sum(jqi)/len(jqi)))
with open(custom) as f: custom_args = yaml.load(f.read()) args.update(custom_args) args['cuda'] = args['cuda'] and torch.cuda.is_available() log_dir = f'results/{datetime.now().strftime("%Y-%m-%d-%H:%M:%S")}-{args["env"]}-{args["prefix"]}' log_dir = MPI.COMM_WORLD.bcast(log_dir, root=0) args['log_dir'] = log_dir if MPI.COMM_WORLD.Get_rank() == 0: os.makedirs(log_dir) with open(log_dir + '/configuration.yaml', 'w') as f: f.write(yaml.dump(args)) args['device'] = torch.device('cuda' if args['cuda'] else 'cpu') return args if __name__ == '__main__': torch.set_num_threads(1) args = parse() set_context(args['num_units'], args['num_actors']) if global_dict['unit_idx'] == args['num_units']: evaluator(args) else: rank = global_dict['rank_local'] if rank == global_dict['rank_learner']: learner(args) elif rank == global_dict['rank_replay']: replay(args) else: actor_id = rank actor(args, actor_id)
def __init__(self, distance, neighbour): self.e = en.env(distance, neighbour) self.ac = ac.actor() self.cr = ac.critic() self.aco = self.ac.optimizer() self.cro = self.cr.optimizer()
#plt.switch_backend('Agg') from numpy.linalg import norm from actor import actor from optparse import OptionParser from scipy.stats import percentileofscore, scoreatpercentile,kruskal from progressbar import Bar, Percentage, ProgressBar from termcolor import cprint from awesome_print import ap #(1/100) n = 100 start = 1 stop = 20 actors = [actor() for _ in xrange(10)] gain = .01 EFFECT_SIZE = -gain * n normalize = lambda data: data/np.linalg.norm(data) effect = np.zeros((stop,)) intent = np.zeros_like(effect) INITIAL_ATTITUDES = 2*np.random.random_sample(size=(n,))-1 attitudes = np.tile(INITIAL_ATTITUDES,(stop,1)).T G = nx.MultiDiGraph() tmp = nx.barabasi_albert_graph(n,3) G.add_edges_from(tmp.edges()) G.add_nodes_from(tmp) G.add_edges_from(nx.MultiDiGraph(nx.barabasi_albert_graph(n,3)).reverse().edges()) max_degree = max(nx.degree(G).values())
from actor import actor from performances import performances from labor import labor a = actor("Gleb","Nazemnov","Andreevich","glavnui","15") p = performances("12 стульев","2015","322") cr = labor(a,p,"Остап Бендер","20000000") print(a) print(p) print(cr)
def networkthread(clientid): global predict global messages global msgtimeout global kicked global player1 #print("yes") while True: try: data, addr2 = sock.recvfrom(4096) except: break data = data.decode('UTF-8') split = data.split("\n") for p in split: split2 = p.split(";") if split2[0] == "spawn": if split2[1] is not clientid: multiplays.append( actor.actor(int(split2[2]), int(split2[3]), 25, 50, 0, hitbox, split2[1], split2[4])) if split2[0] == "join": if split2[1] is not clientid: multiplays.append( actor.actor(int(split2[2]), int(split2[3]), 25, 50, 0, hitbox, split2[1])) if split2[0] == "pos": for x in multiplays: if x.index == split2[1]: x.setPos(int(split2[2]), int(split2[3])) x.setRoom(split2[4]) if split2[0] == "leave": print("x") if split2[1] == clientid: os._exit(1) for x in multiplays: if x.index == split2[1]: multiplays.remove(x) if split2[0] == "msg": messages.append(split2[1] + ": " + split2[2]) msgtimeout = 0 if split2[0] == "bspawn": newbul = bullet.bullet( pygame.math.Vector2(int(float(split2[1])), int(float(split2[2]))), pygame.math.Vector2(int(float(split2[3])), int(float(split2[4])))) newbul.idd = split2[5] newbul.room = split2[6] newbul.size = split2[7] player1.all_bullets.append(newbul) if split2[0] == "die": messages.append(split2[1] + " has died") msgtimeout = 0 if split2[0] == "killed": names = None print(split2) for p in multiplays: print(p.index) if str(p.index) == str(split2[2]): names = p.name messages.append(names + " has killed " + split2[1]) msgtimeout = 0 os._exit(1)
state.state = "start" pygame.display.flip() print("hello?") sock.settimeout(None) initdata, addr = sock.recvfrom(4096) initdata = initdata.decode('UTF-8') split = initdata.split("\n") for p in split: split2 = p.split(";") if split2[0] == "init": clientid = split2[1] multiplays.append( actor.actor(int(split2[2]), int(split2[3]), 25, 50, 0, hitbox, split2[1], split2[4])) player1 = actor.actor(int(split2[2]), int(split2[3]), 25, 50, 0, hitbox, split2[1], split2[4]) clock = pygame.time.Clock() FPS = 60 fps = clock.tick(FPS) def networkthread(clientid): global predict global messages global msgtimeout global kicked global player1 #print("yes")
def __init__(self,params,env,state_size,action_size): self.params=params self.critic_object=critic.critic(params,env,state_size,action_size) self.actor_object=actor.actor(params,env,state_size,action_size,self.critic_object.target_network) self.buffer_object=buffer_class.buffer_class(max_length=self.params['max_buffer_size'])