def retrieveLot(lotID): lot = lotID.get() container = LOTContainer() container.lot = lot container.games = list(Game.query(Game.lotID == lotID.id())) #Load all players that are referenced by the LOT. First, get their player IDs and remove dupes pids = set(flatten([g.players for g in container.games])) | set(lot.playersParticipating) | set(lot.playerRanks) #logging.info("Loading lot " + str(lotID) + " got " + str(len(pids)) + " pids") #Turn the player IDs into Player instances players = list(ndb.get_multi([ndb.Key(Player, p) for p in pids])) #Store them as a dictionary so we can easily look them up by id later container.players = dict([(p.key.id(), p) for p in players if p is not None]) return container
class gameThread(threading.Thread): def __init__(self, audio_ready, gui_event): threading.Thread.__init__(self) self.game = Game(audio_ready, gui_event) self.audio_ready = audio_ready self.gui_event = gui_event self.start() def run(self): self.gui_event.wait() self.setGame(self.gui_event.game) self.game.quit = False self.gui_event.clear() while not self.game.quit: self.game.playRound() # change game if needed if self.gui_event.change_game: self.run() def setGame(self, game_field): if game_field == "pan": self.game.processAudio = audio_process_functions.pan elif game_field == "eq": self.game.processAudio = audio_process_functions.eq print("Game is now EQ! :)))))")
def createAndStartGame(user): """ Create a game and start playing """ game = Game(humanUser=user, initialFoodCount=20, initialSmartAiCount=1, initialRandomAiCount=5) game.start()
def number_up_star(self, items): debug('number_up_star', items) if len(items) > 2: return Game.NumberUpStar(int(items[0][0]), int(items[0][1]), int(items[1]), int(items[2])) else: return Game.NumberUpStar(int(items[0][0]), int(items[0][1]), int(items[1]), 0)
def main(): # Define the envy constants of the utility function in relation to the other players envy_constants_player1 = (0, .4, .3) envy_constants_player2 = (.4, 0, .2) envy_constants_player3 = (.5, .3, 0) # Define the guilt constants of the utility function in relation to the other players guilt_constants_player1 = (0, .2, .1) guilt_constants_player2 = (.3, 0, .1) guilt_constants_player3 = (.7, .4, 0) # Define the utility functions for each of the players utility1 = lambda x, p: envy__guilt_utility_function_player( x, p, envy_constants_player1, guilt_constants_player1) utility2 = lambda x, p: envy__guilt_utility_function_player( x, p, envy_constants_player2, guilt_constants_player2) utility3 = lambda x, p: envy__guilt_utility_function_player( x, p, envy_constants_player3, guilt_constants_player3) # Store these utility functions in a list utility_functions = [utility1, utility2, utility3] #Create an instance of the bargaining game with the required utility functions game = Game(utility_functions) game.simulate_game() #Exctract the value functions of every time step and the state transition probabilites at every time step value_functions = game.value_functions probability_matrices = game.probability_matrices x_data_v, y_data_v, x_label_v, y_label_v, legend_labels_v, plot_title_v = \ get_value_data(value_functions) x_data_p, y_data_p, x_label_p, y_label_p, legend_labels_p, plot_title_p = \ get_probability_data(probability_matrices) # Plot value functions of state "(A,A,A)" plt.figure(1) plt.plot(x_data_v, y_data_v) plt.xlabel(x_label_v) plt.ylabel(y_label_v) plt.legend(legend_labels_v) plt.title(plot_title_v) # Plot probability of consensus for begin state "(A,A,A)" plt.figure(2) plt.plot(x_data_p, y_data_p) plt.xlabel(x_label_p) plt.ylabel(y_label_p) plt.legend(legend_labels_p) plt.title(plot_title_p)
def post(self, lotID): if not TestMode: return self.response.write( "api.TestMode is not enabled. This page should only be used while testing." ) container = lot.getLot(lotID) if 'ClearData' in self.request.POST: #User clicked Clear Data, delete all games and players ndb.delete_multi([ o.key for o in Game.query(Game.lotID == container.lot.key.id()) ]) container.lot.playerRanks = [] container.lot.playerRating = {} container.lot.playerMean = {} container.lot.playerStandardDeviation = {} container.lot.put() container.changed() memcache.flush_all() TestPage.renderPage(self, lotID, 'Deleted all games') elif 'RunCron' in self.request.POST: #Just execute the same thing that we'd do if we hit /cron, but also time it start = datetime.now() cron.execute(self.request, container) TestPage.renderPage( self, lotID, 'Cron finished in ' + unicode(datetime.now() - start)) elif 'AddPlayers' in self.request.POST: #Add some dummy player data. It won't work on warlight.net of course, but if TestMode is enabled it won't ever be passed there. Just be sure and delete it before disabling TestMode. numPlayers = long(self.request.POST["NumPlayers"]) for z in range(numPlayers): name = ''.join( random.choice(string.ascii_uppercase + string.digits) for x in range(5)) p = Player(name=name, inviteToken=name, color="#0000FF", customProperties={}, numberOfGamesAtOnce=2) p.put() container.lot.playersParticipating.append(p.key.id()) container.lot.put() container.changed() TestPage.renderPage(self, lotID, 'Added ' + str(numPlayers) + ' fake players') elif 'FlushCache' in self.request.POST: if memcache.flush_all(): TestPage.renderPage(self, lotID, 'Deleted everything from cache') else: TestPage.renderPage(self, lotID, 'Error while trying to flush cache') elif 'Test' in self.request.POST: #Just a blank space for testing random stuff TestPage.renderPage(self, lotID, 'Ran test code') else: self.response.write("No handler")
async def post(self, request, session=None): data = await validate(LobbyJoinSerializer, request) if session.state != STATE_NOT_IN_GAME: raise HTTPException(401, "Already in game") session.state = STATE_IN_LOBBY game = Game.get_or_create_game(data["game_name"], session) game.add_player(session) return JSONResponse({"status": "ok"})
def __init__(self, frames_used): Game.__init__(self, 5, 5, frames_used) # initialize the snake's direction self.snake_dir = random.randint(1, 4) # initialize head and fruit (so that get_free_cell() works) self.head_pos = [-1, -1] self.fruit_pos = [-1, -1] # move them to random cells self.head_pos = self.get_free_cell() self.fruit_pos = self.get_free_cell() # paint them self.set_tile(self.head_pos, 1) # paint the head self.set_tile(self.fruit_pos, 1) # paint the fruit self.lose_r = -5 self.survive_r = -1 self.win_r = 15
def __init__(self, frames_used): Game.__init__(self, 10, 10, frames_used) self.player_width = 3 # self.player_pos = self.grid_width // 2 - self.player_width // 2 self.player_pos = random.randint(0, self.grid_width - self.player_width) self.fruit_pos = [0, self.grid_width // 2 ] #random.randint(0, self.grid_width-1)] self.draw_player() self.grid[tuple(self.fruit_pos)] = 1 self.extra_info = 0 self.lose_r = -10 self.survive_r = 0 self.win_r = 10
def get(self, playerID): playerID = long(playerID) p = Player.get_by_id(playerID) games = Game.query(Game.players == playerID) self.response.write( get_template('viewplayer.html').render({ 'player': p, 'games': games }))
def __init__(self, game: str, data_file: str = DATA): """Init""" # Set command prefix super().__init__(command_prefix='.') # Get all games for name, obj in inspect.getmembers(games, inspect.ismodule): if name != 'base': for n, o in inspect.getmembers(inspect.getmodule(obj), inspect.isclass): if n not in ('Move', 'Game', 'Playbook'): self.GAMES[n.lower()] = o # Bot properties self.game = self.GAMES[game](self) if game else Game(self) self.private_clocks = False self.mc = None # Add commands self.add_cog(ClockCommands(self)) self.add_cog(ContactCommands(self)) self.add_cog(FunctionalCommands(self)) self.add_cog(MiscCommands(self)) self.add_cog(HiddenCommands(self)) self.add_cog(self.game) # Extract data from file self.memories = [] self.dead_characters = {} self.clocks = [] self.contacts = [] self.data_file = data_file try: with open(f'{self.data_file}/clocks.json', 'rb') as file: clocks = jsons.loadb(file.read()) self.clocks = [ Clock(clock['name'], time=clock['time']) for clock in clocks ] with open(f'{self.data_file}/contacts.json', 'rb') as file: contacts = jsons.loadb(file.read()) self.contacts = [ Contact(contact['name'], contact['description']) for contact in contacts ] with open(f'{self.data_file}/memories.json', 'rb') as file: self.memories = jsons.loadb(file.read()) with open(f'{self.data_file}/dead_characters.json', 'rb') as file: self.dead_characters = jsons.loadb(file.read()) print('Data extracted') except EOFError: print('No data in file.') except FileNotFoundError: print('No data file found.') except KeyError as ke: print(f'KeyError while loading data: {ke}')
def get(self, playerID, lotID): playerID = long(playerID) p = Player.get_by_id(playerID) games = Game.query(Game.players == playerID) container = lot.getLot(lotID) currentPlayer = None if 'authenticatedtoken' in self.session: inviteToken = self.session['authenticatedtoken'] currentPlayer = Player.query(Player.inviteToken == inviteToken).get() self.response.write(get_template('viewplayer.html').render({'player': p, 'games': games, 'currentPlayer': currentPlayer, 'container':container}))
def post(self, lotID): if not TestMode: return self.response.write("api.TestMode is not enabled. This page should only be used while testing.") container = lot.getLot(lotID) if 'ClearData' in self.request.POST: #User clicked Clear Data, delete all games and players ndb.delete_multi([o.key for o in Game.query(Game.lotID == container.lot.key.id())]) container.lot.playersParticipating = [] container.lot.playerRanks = [] container.lot.put() container.changed() memcache.flush_all() TestPage.renderPage(self, lotID, 'Deleted all games and players') elif 'RunCron' in self.request.POST: #Just execute the same thing that we'd do if we hit /cron, but also time it start = datetime.now() cron.execute(self.request, container) TestPage.renderPage(self, lotID, 'Cron finished in ' + unicode(datetime.now() - start)) elif 'AddPlayers' in self.request.POST: #Add some dummy player data. It won't work on warlight.net of course, but if TestMode is enabled it won't ever be passed there. Just be sure and delete it before disabling TestMode. numPlayers = long(self.request.POST["NumPlayers"]) for z in range(numPlayers): name = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(5)) p = Player(name=name, inviteToken=name, color="#0000FF") p.put() container.lot.playersParticipating.append(p.key.id()) container.lot.put() container.changed() TestPage.renderPage(self, lotID, 'Added ' + str(numPlayers) + ' fake players') elif 'FlushCache' in self.request.POST: if memcache.flush_all(): TestPage.renderPage(self, lotID, 'Deleted everything from cache') else: TestPage.renderPage(self, lotID, 'Error while trying to flush cache') elif 'Test' in self.request.POST: #Just a blank space for testing random stuff TestPage.renderPage(self, lotID, 'Ran test code') else: self.response.write("No handler")
def get(self): templateVars = {'title':'Error 404'} games = Game.gql('').fetch(8) shuffle(games) template = JINJA_ENVIRONMENT.get_template('head.html') self.response.write(template.render(templateVars)) template = JINJA_ENVIRONMENT.get_template('404.html') self.response.write(template.render({'game':games[0]})) template = JINJA_ENVIRONMENT.get_template('footer.html') self.response.write(template.render({})) self.response.set_status(404)
def get(self, playerID, lotID): playerID = long(playerID) p = Player.get_by_id(playerID) games = Game.query(Game.players == playerID) container = lot.getLot(lotID) currentPlayer = None if 'authenticatedtoken' in self.session: inviteToken = self.session['authenticatedtoken'] currentPlayer = Player.query( Player.inviteToken == inviteToken).get() self.response.write( get_template('viewplayer.html').render({ 'player': p, 'games': games, 'currentPlayer': currentPlayer, 'container': container }))
#importation baniere accueil banner = pygame.image.load('assets/banner.png') banner = pygame.transform.scale(banner,(500, 500)) banner_rect = banner.get_rect() banner_rect.x = math.ceil(screen.get_width() / 4) #import bouton de lancement de jeux play_button = pygame.image.load('assets/button.png') play_button = pygame.transform.scale(play_button,(400, 150)) play_button_rect = play_button.get_rect() play_button_rect.x = math.ceil(screen.get_width() / 3.33 + 10) play_button_rect.y = math.ceil(screen.get_height() / 2) #chargement du jeu game = Game() running = True #boucle tant que cette condition est vrai while running: #appliquer la fenetre du jeu screen.blit(background, (0,-200)) #verifier si le jeu à commencé ou non if game.is_playing: #declancher les instructions de la partie game.update(screen) #verifier si le jeu n'a pas commencé else:
def __init__(self, game: Game, visualize=False): super().__init__(game, visualize) self.previous_action = None # In case one wants to reach it after execution. self.action_space = game.get_potentially_legal_actions()
def general_game(self, items): left, right = items return Game.GeneralGame(left, right)
def ups(self, items, ud, star): """Helper method for up multiples""" if items: return Game.UpMultiple(ud * int(items[0]), star) else: return Game.UpMultiple(ud, star)
def nimber(self, items): debug('nimber', items) if items: return Game.Nimber(int(items[0])) else: return Game.Nimber(1)
def dyadic_rational(self, items): num, *rest = items if rest: return Game.DyadicRational(int(num), int(rest[0])) else: return Game.DyadicRational(int(num), 1)
def integer_game(self, items): return Game.Integer(int(items[0]))
import datetime as dt from games import Game from players import Player game = Game("NFL", dt.datetime.now()) print(game) player = Player("Veena", 0) print(player)
def __init__(self, server, *players): Game.__init__(self, server, *players) self.commands = {"PLACE": self.place, "STATUS": self.status}
def __init__(self, server, *players): Game.__init__(self, server, *players) self.commands = {"M": self.send, "MSG": self.send}
def __init__(self, game: Game, visualize=False): super().__init__(game, visualize) self.action_space = game.get_potentially_legal_actions()
def __init__(self, audio_ready, gui_event): threading.Thread.__init__(self) self.game = Game(audio_ready, gui_event) self.audio_ready = audio_ready self.gui_event = gui_event self.start()
def up_star(self, items): debug('up_star', items) if len(items) == 2: return Game.UpMultiple(int(items[0]), int(items[1])) else: return Game.UpMultiple(int(items[0]), 0)
def __init__(self, server, *players): Game.__init__(self, server, *players) self.commands = { "M" : self.send, "MSG" : self.send }
for url in game_urls: resp = requests.get(base + url) if (resp.status_code != 200): print("bad status code bye ", resp.status_code) print("url: ", base + url) quit() soup = BeautifulSoup(resp.content, 'html.parser') over_under = GO.get_over_under(soup) if (over_under == -1): print('skipping this game') continue spread = GO.get_spread(soup) game = Game(over_under, spread) #find past 5 games past_games = soup.find( 'div', attrs={'class': 'tab-content sub-module__parallel'}) teams = past_games.find_all('article') for t in teams: squad = Team(GO.get_team_name(t), GO.get_last_five_scores(t)) if (squad.is_favorite(GO.get_favorite(soup))): game.favorite = squad else: game.underdog = squad game.display_game() game.check_over_under()
def number_star(self, items): debug('number_star', items) return Game.NumberStar(int(items[0][0]), int(items[0][1]), int(items[1]))
def get(self, playerID): playerID = long(playerID) p = Player.get_by_id(playerID) games = Game.query(Game.players == playerID) self.response.write(get_template('viewplayer.html').render({'player': p, 'games': games}))