예제 #1
0
    def loadDB(self):
        print("Initializing OpeningsLoader")

        file_data = self.preProcessGamesData()
        print("Current games folder data size:")
        print(len(file_data))

        # To do: remove truncation
        for gameMap in file_data[0:3]:
            game = Game(event=gameMap['Event'],
                        site=gameMap['Site'],
                        date=gameMap['Date'],
                        stage=gameMap['Round'],
                        white=gameMap['White'],
                        black=gameMap['Black'],
                        result=gameMap['Result'],
                        black_elo=gameMap['BlackElo'],
                        blackfide_id=gameMap['BlackFideId'],
                        black_title=gameMap['BlackTitle'],
                        eco=gameMap['ECO'],
                        event_date=gameMap['EventDate'],
                        opening=gameMap['Opening'],
                        variation=gameMap['Variation'],
                        white_elo=gameMap['WhiteElo'],
                        whitefide_id=gameMap['WhiteFideId'],
                        white_title=gameMap['WhiteTitle'],
                        moves=gameMap['Moves'])
            game.save()
        print("Database loaded successfully!")
예제 #2
0
def create_game(payload):
    body = request.get_json()
    # If the request doesn't contain the below keys return 400
    if not ('name' in body and
            'age_rating' in body and
            'category_id' in body and
            'developer_id' in body and
            'image_link' in body):
        abort(400)
    try:
        # Create a game instance
        game = Game(
            name=body.get('name'),
            age_rating=body.get('age_rating'),
            category_id=body.get('category_id'),
            developer_id=body.get('developer_id'),
            image_link=body.get('image_link')
        )
        # Create the record
        game.insert()

        return jsonify({
            "success": True,
            "game": game.format()
        })
    except BaseException:
        abort(422)
예제 #3
0
 def __perform_analysis(self):
     """
     Performs the analysis of all games of the specified players.
     """
     t1p1 = self.all_players[self.combo_t1_p1.currentIndex()] 
     t1p2 = self.all_players[self.combo_t1_p2.currentIndex()] 
     t2p1 = self.all_players[self.combo_t2_p1.currentIndex()] 
     t2p2 = self.all_players[self.combo_t2_p2.currentIndex()]
     date_from = self.start_date.date().toPyDate()
     date_to = self.end_date.date().toPyDate()
     date_to1 = datetime.datetime.combine(date_to, datetime.time(23,59,59))
     params = {'t1p1' : t1p1.id, 't1p2' : t1p2.id, 
         't2p1' : t2p1.id, 't2p2' : t2p2.id,
         'from' : date_from, 'to' : date_to1 }
     p = Game.getAnalysis(params)
     a1 = 0
     a2 = 0
     if p['num'] > 0:
         a1 = p['t1'] / p['num']
         a2 = p['t2'] / p['num']
     p['a1'] = a1
     p['a2'] = a2
     p['d1'] = p['t2'] - p['t1']
     p['d2'] = p['t1'] - p['t2']
     logging.info(u'analysis of ' + t1p1.info() + u' and ' + t1p2.info()
         + u' vs. ' + t2p1.info() + u' and ' + t2p2.info() + u'\n'
         + u'num games: ' + unicode(p['num']) + u', points: '
         + unicode(p['t1']) + u':' + unicode(p['t2']) )
     return p
예제 #4
0
def create_game_submission():
    try:
        # Query both category & developer based on name
        category = Category.query.filter_by(
            name=request.form["category"].lower()).first()
        developer = Developer.query.filter_by(
            name=request.form["developer"].lower()).first()
        # Create a game instance
        game = Game(name=request.form["name"].lower(),
                    age_rating=request.form["age_rating"],
                    category_id=category.id,
                    developer_id=developer.id,
                    image_link=request.form["image_link"])

        # Create the record
        game.insert()
        flash(request.form['name'] + ' game was successfully listed!')
        return redirect(url_for('web_app.get_games'))
    except BaseException:
        abort(422)
예제 #5
0
 def __handle_save(self):
     """
     Saves the new game to db.
     """
     try:
         date = self.calendar.selectedDate().toPyDate()
         time = self.time.time().toPyTime()
         played_at = datetime.datetime.combine(date, time)
         pt1 = int(self.points_t1.text())
         pt2 = int(self.points_t2.text())
         t1p1 = self.all_players[self.combo_t1_p1.currentIndex()] 
         t1p2 = self.all_players[self.combo_t1_p2.currentIndex()] 
         t2p1 = self.all_players[self.combo_t2_p1.currentIndex()] 
         t2p2 = self.all_players[self.combo_t2_p2.currentIndex()] 
         g = Game(played_at, pt1, pt2, t1p1, t1p2, t2p1, t2p2)
         g.save()
         logging.info('game saved - ' + g.info())
         QMessageBox.information(self, self.tr('Game saved'),
                               self.tr('The game was saved succesfully.'))
         self.parent.go_home()
     
     except ValueError as detail:
         QMessageBox.warning(self, self.tr('Game not saved'),
                               self.tr('An error ocured while saving: ')+ detail.args[0] )
 def get(self):
     games = Game.objects().to_json()
     return Response(games, mimetype="application/json", status=200)
 def get(self, name):
     games = Game.objects(opening=name).to_json()
     print(games)
     return Response(games, mimetype="application/json", status=200)
 def post(self):
     body = request.get_json()
     game = Game(**body).save()
     id = game.id
     return {'id': str(id)}, 200
예제 #9
0
def update():
    logger = getLogger("cronjob.pastats")
    logger.info("Updating PAStats Winners database...")

    # calculate duration, at most seconds since start
    with shelfopen(environ["PASTATS_SHELF"], "c") as shelf:
        last = shelf.get("last", 0)
    reset = int(environ["PASTATS_RESET"])
    start = max(last, reset)

    reference = datetime(1970, 1, 1) + timedelta(seconds=start)
    dur_delta = datetime.utcnow() - reference
    duration = int(dur_delta.total_seconds())

    # create url we need for the query
    params = {"start": start, "duration": duration}
    winners_url = "http://pastats.com/report/winners"
    url = "{0}?{1}".format(winners_url, urlencode(params))
    logger.debug("PAStats URL: %s", url)

    # update start for next query
    start += duration
    # set it back again three hours so we can be sure to get all matches
    start -= (60 * 60 * 3)
    # save it for the next run
    with shelfopen(environ["PASTATS_SHELF"], "c") as shelf:
        shelf["last"] = start

    request = Request(url, headers={"Accept-Encoding": "gzip"})
    with urlopen(request) as response:
        data = response.read()
        if response.info().get("Content-Encoding") == "gzip":
            data = decompress(data)
            data = str(data, "utf-8")

    logger.info("Updating game database...")
    games = loads(data)
    session = Session()
    known_games = list(chain(*session.query(Game.gid).all()))

    for game in games:
        game_id = game["gameId"]
        # check only games we haven't seen yet
        if game_id in known_games:
            continue

        # for now only add games with exactly 2 teams and 1 player per team
        teams = game["teams"]
        if (len(teams) != 2 or len(teams[0]["players"]) != 1
                or len(teams[1]["players"]) != 1):
            continue

        # start time is stored in ms
        game_start = game["startTime"] // 1000
        game_time = datetime(1970, 1, 1) + timedelta(seconds=game_start)

        p1 = teams[0]["players"][0]
        p2 = teams[1]["players"][0]

        p1_id, p1_name = p1["playerId"], p1["playerName"]
        p2_id, p2_name = p2["playerId"], p2["playerName"]

        del p1, p2

        # ignore matches vs anonymous players for now
        if p1_id == -1 or p2_id == -1:
            continue

        try:
            p1 = session.query(Player).filter(Player.pid == p1_id).one()
        except NoResultFound:
            p1 = Player(p1_id, p1_name, trueskill.Rating(), game_time)
            session.add(p1)
            logger.debug("Created new player: {0}".format(p1))

        if p1.name != p1_name:
            p1.name = p1_name
            session.add(p1)

        if p1.updated < game_time:
            p1.updated = game_time
            session.add(p1)

        try:
            p2 = session.query(Player).filter(Player.pid == p2_id).one()
        except NoResultFound:
            p2 = Player(p2_id, p2_name, trueskill.Rating(), game_time)
            session.add(p2)
            logger.debug("Created new player: {0}".format(p2))

        if p2.name != p2_name:
            p2.name = p2_name
            session.add(p2)

        if p2.updated < game_time:
            p2.updated = game_time
            session.add(p2)

        # check for winner or draw and update ratings
        if game["winner"] == -1:
            winner = None
            p1.skill, p2.skill = trueskill.rate_1vs1(p1.skill,
                                                     p2.skill,
                                                     drawn=True)
        elif teams[0]["teamId"] == game["winner"]:
            winner = p1
            p1.skill, p2.skill = trueskill.rate_1vs1(p1.skill, p2.skill)
        else:
            winner = p2
            p2.skill, p1.skill = trueskill.rate_1vs1(p2.skill, p1.skill)

        # add match
        session.add(Game(game_id, winner, p1, p2))

        # for the unlikely case we receive the same match twice:
        known_games.append(game_id)

    session.commit()
    session.close()

    logger.info("Received and parsed all new data, "
                "seen {0} matches".format(len(known_games)))
예제 #10
0
 def __init__(self, parent = None):
     """
     Constructor: inits all elements of the widget. It offers an 
     analysis of games by specifying the players.
     It creates the actions and connects them to their methods.
     
     Keyword arguments:
     parent -- parent widget
     """
     QWidget.__init__(self, parent)
     self.parent = parent
     self.game = None
     self.all_players = Player.get()
     if len(self.all_players) < 4:
         error = QLabel(self.tr('Error!\nThere are not enough Players.'), self)
         error.move(30, 30)
         return
         
     greet = QLabel(self.tr('Analysis'), self)
     greet.setStyleSheet("""
         QLabel { 
             font-size: 12pt;
         }""")
      
     ok = QPushButton(self.tr('Print Analysis'), self)
     self.connect(ok, SIGNAL('clicked()'), 
         self.__handle_print)
      
     lbl_num = QLabel(self.tr('Games played:'), self)
     self.num = QLabel(' ', self)
     hbox_num = QHBoxLayout()
     hbox_num.addWidget(lbl_num)
     hbox_num.addWidget(self.num)
     
     mind = Game.getMinDate()
     d_from = QDate(1900, 1, 1)
     if mind is not None and len(mind) > 9:
         d_from = QDate.fromString(mind[0:10], 'yyyy-MM-dd')
     lbl_start_date = QLabel(self.tr('From:'), self)
     self.start_date = QDateEdit(d_from, self)
     self.start_date.setDisplayFormat('dd.MM.yyyy')
     self.start_date.setMinimumDate(QDate(1900, 1, 1))
     self.start_date.setMaximumDate(QDate(3000, 1, 1))
     lbl_end_date = QLabel(self.tr('To:'), self)
     self.end_date = QDateEdit(QDate.currentDate (), self)
     self.end_date.setDisplayFormat('dd.MM.yyyy')
     self.end_date.setMinimumDate(QDate(1900, 1, 1))
     self.end_date.setMaximumDate(QDate(3000, 1, 1))
     hbox_start_date = QHBoxLayout()
     hbox_start_date.addStretch(1)
     hbox_start_date.addWidget(lbl_start_date)
     hbox_start_date.addWidget(self.start_date)
     hbox_start_date.addSpacing(11)
     hbox_start_date.addWidget(lbl_end_date)
     hbox_start_date.addWidget(self.end_date)
     hbox_start_date.addStretch(1)
     
     vbox_game = QVBoxLayout()
     vbox_game.addWidget(greet)
     vbox_game.addStretch(2)
     vbox_game.addLayout(hbox_start_date)
     vbox_game.addStretch(2)
     vbox_game.addLayout(hbox_num)
     vbox_game.addStretch(1)
     
     lbl_t1 = QLabel(self.tr('Team 1:'), self)
     vbox_game.addWidget(lbl_t1)
     self.combo_t1_p1 = self.__fill_combo()
     vbox_game.addWidget(self.combo_t1_p1)
     self.combo_t1_p2 = self.__fill_combo(1)
     vbox_game.addWidget(self.combo_t1_p2)
     self.points_t1 = QLabel(' ', self)
     hbox_pt1 = QHBoxLayout()
     lbl_p1 = QLabel(self.tr('Points:'), self)
     hbox_pt1.addWidget(lbl_p1)
     hbox_pt1.addWidget(self.points_t1)
     vbox_game.addLayout(hbox_pt1)
     self.diff_t1 = QLabel(' ', self)
     hbox_diff_t1 = QHBoxLayout()
     lbl_diff_t1 = QLabel(self.tr('Difference:'), self)
     hbox_diff_t1.addWidget(lbl_diff_t1)
     hbox_diff_t1.addWidget(self.diff_t1)
     vbox_game.addLayout(hbox_diff_t1)
     self.avg_t1 = QLabel(' ', self)
     lbl_a1 = QLabel(self.tr('AVG Points per Game:'), self)
     hbox_avg1 = QHBoxLayout()
     hbox_avg1.addWidget(lbl_a1)
     hbox_avg1.addWidget(self.avg_t1)
     vbox_game.addLayout(hbox_avg1)
     vbox_game.addStretch(1)
     lbl_t2 = QLabel(self.tr('Team 2:'), self)
     vbox_game.addWidget(lbl_t2)
     self.combo_t2_p1 = self.__fill_combo(2)
     vbox_game.addWidget(self.combo_t2_p1)
     self.combo_t2_p2 = self.__fill_combo(3)
     vbox_game.addWidget(self.combo_t2_p2)
     self.points_t2 = QLabel(' ', self)
     lbl_p2 = QLabel(self.tr('Points:'), self)
     hbox_pt2 = QHBoxLayout()
     hbox_pt2.addWidget(lbl_p2)
     hbox_pt2.addWidget(self.points_t2)
     vbox_game.addLayout(hbox_pt2)
     self.diff_t2 = QLabel(' ', self)
     hbox_diff_t2 = QHBoxLayout()
     lbl_diff_t2 = QLabel(self.tr('Difference:'), self)
     hbox_diff_t2.addWidget(lbl_diff_t2)
     hbox_diff_t2.addWidget(self.diff_t2)
     vbox_game.addLayout(hbox_diff_t2)
     self.avg_t2 = QLabel(' ', self)
     lbl_a2 = QLabel(self.tr('AVG Points per Game:'), self)
     hbox_avg2 = QHBoxLayout()
     hbox_avg2.addWidget(lbl_a2)
     hbox_avg2.addWidget(self.avg_t2)
     vbox_game.addLayout(hbox_avg2)
     vbox_game.addStretch(2)
     
     vbox_game.addWidget(ok)
     
     self.setLayout(vbox_game)
     
     self.preview = QPrintPreviewDialog()
     self.connect(self.preview,
         SIGNAL("paintRequested (QPrinter *)"),self.__print)
     self.connect(self.combo_t1_p1,
         SIGNAL("currentIndexChanged (int)"),self.__handle_ok)
     self.connect(self.combo_t1_p2,
         SIGNAL("currentIndexChanged (int)"),self.__handle_ok)
     self.connect(self.combo_t2_p1,
         SIGNAL("currentIndexChanged (int)"),self.__handle_ok)
     self.connect(self.combo_t2_p2,
         SIGNAL("currentIndexChanged (int)"),self.__handle_ok)
     self.connect(self.start_date,
         SIGNAL("dateChanged (const QDate&)"),self.__handle_ok)
     self.connect(self.end_date,
         SIGNAL("dateChanged (const QDate&)"),self.__handle_ok)
     self.__handle_ok()