def parseGameList(xmlString): """Parses a string representing a list of games. Args: xmlString: The string to parse. Returns: .game.GameList: an object containing all the information on the list. Raises: .exceptions.InvalidXmlStructure: If there is an error while parsing. .exceptions.NoResultFound: If the list is empty. """ root = _getRoot(xmlString) gameList = GameList() for elem in root.iter("item"): if "boardgame" == elem.get("type"): try: game = Game(id_=elem.get("id")) nameElem = elem.find("name") if nameElem is None: raise exceptions.InvalidXmlStructure() game.setName(nameElem.get("value")) yearElem = elem.find("yearpublished") if yearElem is not None: game.setYear(yearElem.get("value")) game.setLink(constants.BOARDGAMEGEEK_BASE_ADDRESS + game.id_) gameList.addGame(game) except ET.ParseError as err: logger.exception("Parse exception") raise exceptions.InvalidXmlStructure() if gameList.isEmpty(): raise exceptions.NoResultFound() return gameList
def solve(fptr): # Start the game g = Game(fptr) # Print a representation of the board print(g) # Solve the board, and time how long it took. t0 = time.time() g.run() t1 = time.time() print("\n\n\tTime = %.2f" % (t1 - t0))
def createGame(data): """Socket for creating (Private) game""" # username = data['player']['username'] # email = data['player']['email'] # userid = data['player']['userid'] # player = Player(userid, username, email) cards = data['cards'] maxplayers = data['players'] game = Game(False, cards, maxplayers) gameLst[game.gameid] = game data['gameid'] = game.gameid joinGame(data) send(game.gameid, room=game.gameid) return game.gameid
def create_game(self, pid): """ Creates a game for the PID given @param pid: PID of player wanting to join a game @type pid: int @return: if successful @rtype: bool """ gid = RandomNumGen(int(round(time.time() * 1000))).randint(0, 65535) self.notify.debug(f"[create_game] Create game {gid} for player {pid}") # create game game = Game(gid, self) self.games[gid] = game self.add_player_to_game(pid, game.gid) return True
def getCompletedGame(self, matchID): game = None try: db = self.sqlHelper.getConnection() with closing(db.cursor()) as cur: cur.execute( """SELECT * FROM `complete_matches` WHERE `match_id` = %s""", (matchID, )) result = cur.fetchone() if not result is None: game = Game(result[2], result[0], "Recent", result[1], result[3], result[4], result[5], result[6]) game.setScore(result[7]) except Exception as e: print(traceback.format_exc()) finally: db.close() return game
def checkGames(data): """Socket for checking games""" # username = data['player']['username'] # email = data['player']['email'] # userid = data['player']['userid'] # player = Player(userid, username, email) # game is running for gameid, game in gameLst.items(): if (game.gameStatus()): data['gameid'] = gameid joinGame(data) send(gameid, room=gameid) return game.gameid # no games running, make new game game = Game(True, 5, 0) gameLst[game.gameid] = game data['gameid'] = game.gameid joinGame(data) send(game.gameid, room=game.gameid) return game.gameid
import eventlet from eventlet import wsgi import socketio from objects.responses import Response from objects.game import Game server = socketio.Server() app = socketio.WSGIApp(server) game = Game() # SERVER EVENTS @server.event def connect(sid, environ): print(f'[CLIENT] {sid} connected') @server.event def disconnect(sid): leave_room(sid) print(f'[CLIENT] {sid} disconnected') @server.event def register(sid, name): game.register_user(sid, name) print(f'[NEW PLAYER] {name} registered') return Response.SUCCESS.value
def parseGame(xmlString): """Parses a string representing a game. Args: xmlString: The string to parse. Returns: .game.Game: an object containing all the information on the game. Raises: .exceptions.InvalidXmlStructure: If there is an error while parsing. .exceptions.NoResultFound: If the result is not a board game or an expansion. """ root = _getRoot(xmlString) item = root.find("item") if item is None: raise exceptions.NoResultFound() game = None type_ = item.get("type") if "boardgame" == type_ or "boardgameexpansion" == type_: try: game = Game(id_=item.get("id")) for nameElem in item.findall("name"): if "primary" == nameElem.get("type"): game.setName(nameElem.get("value")) break; yearElem = item.find("yearpublished") if yearElem is not None: game.setYear(yearElem.get("value")) playingTimeElem = item.find("playingtime") if playingTimeElem is not None: game.setPlayingTime(playingTimeElem.get("value")) minPlayersElem = item.find("minplayers") if minPlayersElem is not None: game.setMinPlayers(minPlayersElem.get("value")) maxPlayersElem = item.find("maxplayers") if maxPlayersElem is not None: game.setMaxPlayers(maxPlayersElem.get("value")) for elem in item.findall("link"): if "boardgamecategory" == elem.get("type"): game.addCategory(elem.get("value")) elif "boardgamemechanic" == elem.get("type"): game.addMechanic(elem.get("value")) elif "boardgamedesigner" == elem.get("type"): game.addDesigner(elem.get("value")) elif "boardgameartist" == elem.get("type"): game.addArtist(elem.get("value")) descrElem = item.find("description") if descrElem is None or not descrElem.text: descr = "No description available." else: descr = descrElem.text game.setDescription(descr) thumbElem = item.find("thumbnail") if thumbElem is not None: game.setThumbnail(_parseThumbnail(thumbElem.text)) game.setLink(constants.BOARDGAMEGEEK_BASE_ADDRESS + game.id_) # STATS statistics = item.find("statistics") if statistics is not None: ratings = statistics.find("ratings") if ratings is not None: avg = ratings.find("average") if avg is not None: game.setAverage(avg.get("value")) ranks = ratings.find("ranks") if ranks is not None: for rank in ranks.findall("rank"): if "1" == rank.get("id"): game.setRank(rank.get("value")) except ET.ParseError as err: logger.exception("Parse exception") raise exceptions.InvalidXmlStructure() if game is None: raise exceptions.NoResultFound() return game
def updateMatches(self): threading.Timer(60 * 60, self.updateMatches).start() gamesToUpdate = ["csgo", "lol", "dota2", "hearth", "hots"] csgoMatchLink = "http://www.gosugamers.net/counterstrike/gosubet" dotaMatchLink = "http://www.gosugamers.net/dota2/gosubet" lolMatchLink = "http://www.gosugamers.net/lol/gosubet" hearthMatchLink = "http://www.gosugamers.net/hearthstone/gosubet" hotsMatchLink = "http://www.gosugamers.net/heroesofthestorm/gosubet" self.clearLists() for gameType in gamesToUpdate: try: link = "" if gameType == "csgo": link = csgoMatchLink elif gameType == "lol": link = lolMatchLink elif gameType == "dota2": link = dotaMatchLink elif gameType == "hearth": link = hearthMatchLink elif gameType == "hots": link = hotsMatchLink req = urllib2.Request( link, headers={ 'User-Agent': "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" }) web_page = urllib2.urlopen(req).read() bs = BeautifulSoup(web_page) match_columns = bs.findAll("div", attrs={"id": "col1"}) boxes = match_columns[0].findAll("div", attrs={"class": "box"}) for box in boxes: header = "" h1 = box.find("h1") if h1 is None: h2 = box.find("h2") header = h2.text.strip() else: header = h1.text.strip() if header.find("Live") != -1: header = "Live" elif header.find("Recent") != -1: header = "Recent" elif header.find("Upcoming") != -1: header = "Upcoming" table = box.find("table", attrs={"class": "simple"}) if not table is None: matches = table.find("tbody") rows = matches.findAll("tr") for row in rows: cols = row.findAll("td") match_info = cols[0].find("a", attrs={"class": "match"}) link = match_info['href'] id = match_info['href'].split("/")[-1].split( "-")[0] opponent1 = match_info.find("span", attrs={ "class": "opp1" }).text.strip() bet1 = match_info.find("span", attrs={ "class": "bet1" }).text.strip() opponent2 = match_info.find("span", attrs={ "class": "opp2" }).text.strip() bet2 = match_info.find("span", attrs={ "class": "bet2" }).text.strip() # Add game to list game = Game(gameType, id, header, link, opponent1, opponent2, bet1, bet2) if header == "Upcoming": timeCol = cols[1].find( "span", attrs={"class": "live-in"}) timeUntil = timeCol.text.strip() game.setTime(timeUntil) elif header == "Recent": winnerScore = cols[1].find("span", attrs={ "class": "hidden" }).text.strip() game.setScore(winnerScore) self.queryHelper.insertComplete(game) if gameType == "csgo": if header == "Live": self.csgoLiveList.append(game) elif header == "Upcoming": self.csgoUpcomingList.append(game) elif header == "Recent": self.csgoRecentList.append(game) else: raise Exception("Parsed invalid header") elif gameType == "lol": if header == "Live": self.lolLiveList.append(game) elif header == "Upcoming": self.lolUpcomingList.append(game) elif header == "Recent": self.lolRecentList.append(game) else: raise Exception("Parsed invalid header") elif gameType == "dota2": if header == "Live": self.dotaLiveList.append(game) elif header == "Upcoming": self.dotaUpcomingList.append(game) elif header == "Recent": self.dotaRecentList.append(game) else: raise Exception("Parsed invalid header") elif gameType == "hearth": if header == "Live": self.hearthLiveList.append(game) elif header == "Upcoming": self.hearthUpcomingList.append(game) elif header == "Recent": self.hearthRecentList.append(game) else: raise Exception("Parsed invalid header") elif gameType == "hots": if header == "Live": self.hotsLiveList.append(game) elif header == "Upcoming": self.hotsUpcomingList.append(game) elif header == "Recent": self.hotsRecentList.append(game) else: raise Exception("Parsed invalid header") except Exception as e: print("Error retrieving game data") print(traceback.format_exc())