class Server(): def __init__(self): logging.basicConfig(filename='server.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%m-%d-%Y %H:%M:%S') self._keep_running = True self._games = Games() self._listener = Sock_listener(Settings.SERVER_HOST, Settings.PORT, Connection) logging.info('listening on ' + str(Settings.SERVER_HOST) + ':' + str(Settings.PORT)) def run(self): while self._keep_running: start_time = time.time() self._games.tick() # max number of clients might be around 1/5 of MAX_MESSAGES_PER_TICK , this does not scale well # can not use another thread because of asyncore threading issues self._listener.poll(0, Settings.MAX_MESSAGES_PER_TICK) sleep_time = Settings.TICK - (time.time() - start_time) if sleep_time > 0.001: time.sleep(sleep_time) else: logging.debug('sleep time: ' + str(sleep_time)) def stop(self): self._keep_running = False
def __init__(self): logging.basicConfig(filename='server.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%m-%d-%Y %H:%M:%S') self._keep_running = True self._games = Games() self._listener = Sock_listener(Settings.SERVER_HOST, Settings.PORT, Connection) logging.info('listening on ' + str(Settings.SERVER_HOST) + ':' + str(Settings.PORT))
def index(): if request.method == 'POST': print('if') elo_range = request.form['service'] opening_original = request.form['name'] opening = "['" + opening_original.replace(",", "', '") + "']" g = Games('/data/lichess.db', elo=elo_range, opening=opening) x = g.df.date.tolist() x = [datetime.strptime(d, '%Y.%m.%d') for d in x] y = g.df.opening_percentage_played.tolist() chart_title = "Popularity of " + opening_original + " by " + elo_range + " ELOs" p = figure(title=chart_title, x_axis_type="datetime") p.xaxis.formatter = DatetimeTickFormatter(days="%d-%b") p.line(x, y, color="darkorange", line_width=3) p.yaxis.axis_label = "% of games beginning with " + opening_original p.yaxis.axis_label_text_color = "#662900" p.xaxis.axis_label = "Date" p.xaxis.axis_label_text_color = "#662900" script1, div1 = components(p) cdn_js = CDN.js_files cdn_css = CDN.css_files return render_template('index.html', script1=script1, div1=div1, cdn_css=cdn_css, cnd_js=cdn_js) else: print('else') g = Games('/data/lichess.db', elo='ALL', opening="['d4', 'd5', 'c4']") x = g.df.date.tolist() x = [datetime.strptime(d, '%Y.%m.%d') for d in x] y = g.df.opening_percentage_played.tolist() chart_title = "Popularity of 1. d4 d5 2. c4 by All ELOs" p = figure(title=chart_title, x_axis_type="datetime") p.xaxis.formatter = DatetimeTickFormatter(days="%d-%b") p.line(x, y, color="darkorange", line_width=3) p.yaxis.axis_label = "% of games beginning with 1. d4 d5 2. c4 " p.yaxis.axis_label_text_color = "#662900" p.xaxis.axis_label = "Date" p.xaxis.axis_label_text_color = "#662900" script1, div1 = components(p) cdn_js = CDN.js_files cdn_css = CDN.css_files return render_template('index.html', script1=script1, div1=div1, cdn_css=cdn_css, cnd_js=cdn_js)
def selectScoringGame(self): """show all games, select an existing game or create a new game""" Players.load() if len(Players.humanNames) < 4: logWarning(m18n('Please define four players in <interface>Settings|Players</interface>')) return False gameSelector = Games(self) if gameSelector.exec_(): selected = gameSelector.selectedGame if selected is not None: ScoringGame.loadFromDB(selected) else: self.newGame() if self.game: self.game.throwDices() gameSelector.close() self.updateGUI() return bool(self.game)
def scoreGame(): """show all games, select an existing game or create a new game""" Players.load() if len(Players.humanNames) < 4: logWarning( m18n('Please define four players in <interface>Settings|Players</interface>')) return gameSelector = Games(Internal.mainWindow) selected = None if not gameSelector.exec_(): return selected = gameSelector.selectedGame gameSelector.close() if selected is not None: return ScoringGame.loadFromDB(selected) else: selectDialog = SelectPlayers() if not selectDialog.exec_(): return return ScoringGame(list(zip(Wind.all4, selectDialog.names)), selectDialog.cbRuleset.current)
def selectScoringGame(self): """show all games, select an existing game or create a new game""" Players.load() if len(Players.humanNames) < 4: logWarning( m18n( 'Please define four players in <interface>Settings|Players</interface>' )) return False gameSelector = Games(self) if gameSelector.exec_(): selected = gameSelector.selectedGame if selected is not None: ScoringGame.loadFromDB(selected) else: self.newGame() if self.game: self.game.throwDices() gameSelector.close() self.updateGUI() return bool(self.game)
def main(): """Maps the popularity of an opening against the lichess.org database. Outputs the findings to a line graph. """ cfg = get_configs() elo_range = '800-1000' opening_name = 'Queen\'s Gambit' opening = "['d4', 'd5', 'c4']" g = Games('/data/lichess.db', elo=elo_range, opening=opening) plot_popularity(g.df, opening_name, elo=elo_range)
def main(): steam_dir, remote_dir = parse_cmdline() games = Games(steam_dir, remote_dir) # parse the command line games.validate_paths() games.update_games() choice = '' while choice != 'q': display_menu(games.game_list) choice = get_choice(games.game_list) if choice == 'q': print('\nExiting...') sys.exit() elif choice == 'r': continue # start at the top of the loop and display the menu again else: games.move_game(choice) games.update_games()
def scoreGame(): """show all games, select an existing game or create a new game""" Players.load() if len(Players.humanNames) < 4: logWarning( i18n( 'Please define four players in <interface>Settings|Players</interface>' )) return gameSelector = Games(Internal.mainWindow) selected = None if not gameSelector.exec_(): return selected = gameSelector.selectedGame gameSelector.close() if selected is not None: return ScoringGame.loadFromDB(selected) else: selectDialog = SelectPlayers() if not selectDialog.exec_(): return return ScoringGame(list(zip(Wind.all4, selectDialog.names)), selectDialog.cbRuleset.current)
def main(): try: serverInfo = MCLIENT.server_info() logger.info("Connected to Mongo Server: %s." % serverInfo) except: logger.error("Could not connect to the Mongo Server.") raise updater = Updater(AUTHTOKEN) logger.info("Passed Auth") dp = updater.dispatcher game_state = Games(dp, MDB, logger=logger) user_state = Users(dp, MDB, logger=logger) updater.start_polling() logger.info("Starting polling") updater.idle()
def __init__(self, game, gamma, agentProportions): self.game = Games.get_game(game, gamma) self.agentProportions = agentProportions
from memshark_config import MemsharkConfig from games import Games from gui import gui from background import background, memshark, server config = MemsharkConfig('config.json') games = Games('games') memshark = memshark.Memshark(config) exploit_server = server.ExploitServer() background.schedule(memshark) background.schedule(exploit_server) app = gui.MainApp(config, games, memshark, exploit_server) app.start()
# The executable was compiled with pyinstaller import os import sys import argparse from pathlib import Path from const import Const from forms import Forms from games import Games from updater import Updater from settings import Settings updater = Updater(Const.updateurl, Const.version) games = Games(Const.gamesjsonpath) settings = Settings(Const.settingsjsonpath) forms = Forms(updater=updater, games=games, settings=settings) parser = argparse.ArgumentParser() parser.add_argument('--noui', action='store_true') parser.add_argument('--name') parser.add_argument('--path') parser.add_argument('--host', action='store_true') args = parser.parse_args() if __name__ == "__main__": if args.name is not None and args.path is not None: if args.host is not None: games.addgame(args.name, args.path, args.host) else:
if player.checkWin(self.lotto.history): return True return False def endSequence(self): Game.endSequence(self) for player in self.players: if player.checkWin(self.lotto.history): print("Winner: %s" % player) if __name__ == "__main__": from time import sleep from random import randint from player import Player from games import Games from lobby import Lobby lobby = Lobby() games = Games(lobby) G = [] for _ in range(5): players = [Player(name=None, sock=randint(3, 100)) for _ in range(3)] g = Bingo(players) g.games = games G.append(g) for g in G: print(g) games.addGame(g)
import threading from argparse import ArgumentParser from socket import socket, AF_INET, SOCK_STREAM import pickle import sys import logging from games import Games from players import Players __PLAYERS = Players() __GAMES = Games() FORMAT = '%(asctime)-15s %(levelname)s %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) LOG = logging.getLogger() LOG.setLevel(logging.INFO) from common import __MSG_FIELD_SEP, __REQ_REG_USER, __REQ_GET_GAMES, \ __REQ_CREATE_GAME, __REQ_ADD_PLAYER_TO_GAMEROOM, __REQ_MAKE_MOVE, \ __REQ_INIT_GAME, __RSP_OK, __REQ_CONNECT_SERVER_PORT, __RSP_GAME_FULL_ERROR, __REQ_GET_STATE, __REQ_REMOVE_PLAYER, \ __REQ_REMOVE_PLAYER_LOBBY def parse_msg(message, client_sock): """ Method for parsing message and sending response to client :param message: message received by server :param client_sock: Client socket :return: None
from fplplayers import Data from games import Games d = Data('data.json') g = Games('E0.csv') #all_teams = list(d.all_teams()) all_teams = ['Arsenal', 'Chelsea', 'Liverpool', 'Man City']#, 'Man Utd', 'Everton', 'Tottenham',] temp_points_progressions = [g.of_team(t).points_progression_for(t) for t in all_teams] points_progressions = [] for p in temp_points_progressions: points_progressions.append([0,] + p) import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.set_ylabel('Points') ax.set_xlabel('Gameweek') ax.set_title('Points progression') ax.set_xticks(np.arange(38)+1) ax.set_yticks(np.arange(0,114,3)) #ax.legend TODO lines = [] for team, points in zip(all_teams, points_progressions): lines.append(ax.plot(np.arange(len(points)), points)) ax.legend( tuple([line[0] for line in lines]), tuple(all_teams), loc=4)
from flask import Flask, escape, request, render_template from word_dictionaries import WordDictionaries from config.config import Config from games import Games import json app = Flask(__name__) WordDictionaries.initialize() Config.initialize() games = Games() @app.route('/') def main_path(): name = request.args.get("name", "World") return "hello" @app.route('/game_state', methods=['GET']) def game_state(): game_key = request.args.get("game_key") return json.dumps(games.get_game_state_dict(game_key)) @app.route('/create_game', methods=['POST']) def create_game(): data = request.form.to_dict()
from discord.ext import commands # Custom Cogs from eco import Eco from games import Games from blackjack import Blackjack from coinflip import CoinFlip # Load Settings COMMAND_PREFIX = "." TOKEN = os.environ.get("DISCORD_BOT_SECRET") # Enable Logging logging.basicConfig(level=logging.INFO) # Load Cogs bot = commands.Bot(command_prefix=COMMAND_PREFIX) bot.add_cog(Eco(bot)) bot.add_cog(Games(bot)) bot.add_cog(Blackjack(bot)) bot.add_cog(CoinFlip(bot)) # Runs on bot ready, overrides default listener @bot.event async def on_ready(): print("logged in as {0.user}".format(bot)) bot.run(TOKEN)
class Parameters: # environment settings GAMES = Games() GAME = "SpaceInvaders-v0" DISPLAY = False USE_DDQN = True USE_PRIORITIZATION = False LOADED_FILE = None TO_UPDATE = None CURRENT_STEP = 0 @staticmethod def add_attr(name, value): """ Statically adds a parameter as an attribute to class Parameters. All new Parameters attributes are in capital letters. :param name: str Name of the new attribute :param value: object Value of the corresponding hyper-parameter """ name = name.upper() setattr(Parameters, name, value) @staticmethod def get_attr(name): return getattr(Parameters, name.upper()) @staticmethod def load(filepath): """ Statically loads the hyper-parameters from a json file :param filepath: str Path to the json parameter file """ Parameters.LOADED_FILE = filepath Parameters.TO_UPDATE = list() with open(filepath, "r") as f: data = json.load(f) for key in sorted(data.keys()): if isinstance(data[key], dict): if key in ("SESSION_SAVE_FILENAME", "SESSION_SAVE_DIRECTORY"): # make session path specific to the game being played data[key]["value"] = data[key]["value"] + \ Parameters.GAME elif key == "GAME": data[key]["value"] = eval('Parameters.GAMES.' + data[key]["value"]) Parameters.add_attr(key, data[key]["value"]) if "update" in data[key] and data[key]["update"]: Parameters.TO_UPDATE.append(key) @staticmethod def update(): if Parameters.LOADED_FILE is None: print( '[Warning] Trying to save parameters but none have been loaded.' ) return with open(Parameters.LOADED_FILE, "r") as f: data = json.load(f) for key in data: if not isinstance(data[key], dict) or key not in Parameters.TO_UPDATE: continue if data[key]['value'] != Parameters.get_attr(key): data[key]["value"] = Parameters.get_attr(key) with open(Parameters.LOADED_FILE, "w") as f: pretty_str = json.dumps(data, indent=4, sort_keys=True) f.write(pretty_str)
from gameutils import points from fplplayers import Data d = Data("data.json") from games import Games g = Games("E0.csv") predictedpoints = {} finalpoints = [] currentpoints = [] for team, fixtures in d.fixturestoplay().items(): predictedpoints[team] = 0 for f in fixtures: if f.playedat == "A": for gm in g.of_team_at_home(team): if f.opponent == gm.awayteam: predictedpoints[team] += gm.homepoints # print team+ ' scored '+str(gm.homepoints)+' against '+gm.awayteam.name break else: for gm in g.of_team_at_away(team): if f.opponent == gm.hometeam: predictedpoints[team] += gm.awaypoints # print team+ ' scored '+str(gm.awaypoints)+' against '+gm.hometeam.name break finalpoints.append((team, predictedpoints[team] + points(g.of_team(team), team), points(g.of_team(team), team))) finalpoints.sort(key=lambda x: x[1], reverse=True)