Beispiel #1
0
    def flushToDB(self):
        super(GenericRoundMatch, self).flushToDB()

#         db.execute("BEGIN")
        db.execute("DELETE FROM Round where idMatch={};".format(self.idMatch))
        db.execute("DELETE FROM RoundStatistics "
                   "where idMatch={};".format(self.idMatch))

        db.execute("INSERT OR REPLACE INTO MatchExtras (idMatch,key,value) "
                   "VALUES ({},'Dealer','{}');".format(
                        self.idMatch, self.getDealer()))
        db.execute("INSERT OR REPLACE INTO MatchExtras (idMatch,key,value) "
                   "VALUES ({},'DealingPolicy','{}');".format(
                        self.idMatch, self.getDealingPolicy()))

        for rnd in self.rounds:
            for player, score in rnd.getScore().items():
                winner = 0
                if rnd.getWinner() == player:
                    winner = 1
                db.execute("INSERT OR REPLACE INTO Round (idMatch, nick, "
                           "idRound, winner,score) "
                           "VALUES ({},'{}',{},{},{});".format(
                                self.idMatch, str(player),
                                rnd.getNumRound(), winner, score))
Beispiel #2
0
    def resumeMatch(self, idMatch):
        if self.start is not None:
            return False
        if not isinstance(idMatch, int):
            return False
        cur = db.execute(
            "SELECT Game_name,state,started,elapsed "
            "FROM Match WHERE idMatch ={};".format(idMatch))
        row = cur.fetchone()
        if not row:
            return False
        if row['Game_name'] != self.game or row['state'] != self.SAVED:
            return False
        self.elapsed = int(row['elapsed'])
        self.start = datetime.datetime.strptime(
            row['started'], "%Y-%m-%d %H:%M:%S.%f")
        self.resumed = datetime.datetime.now()
        # Retrieve players
        self.players = []
        cur = db.execute(
            "SELECT rowid,nick,totalScore FROM MatchPlayer "
            "WHERE idMatch ={} ORDER BY rowid;".format(idMatch))
        for row in cur:
            player = str(row['nick'])
            self.players.append(player)
            self.totalScores[player] = int(row['totalScore'])

        self.state = self.RUNNING
        self.idMatch = idMatch
        return True
Beispiel #3
0
 def flushToDB(self):
     super(CarcassonneMatch, self).flushToDB()
     for entry in self.rounds:
         db.execute("INSERT OR REPLACE INTO RoundStatistics "
                    "(idMatch,nick,idRound,key,value) "
                    "VALUES ({},'{}',{},'kind','{}');".format(
                         self.idMatch, entry.getPlayer(),
                         entry.getNumEntry(), entry.getKind()))
Beispiel #4
0
 def flushToDB(self):
     super(RemigioMatch, self).flushToDB()
     db.execute("INSERT OR REPLACE INTO MatchExtras (idMatch,key,value) "
                "VALUES ({},'Top','{}');".format(self.idMatch, self.top))
     for rnd in self.rounds:
         db.execute("INSERT OR REPLACE INTO RoundStatistics "
                    "(idMatch,nick,idRound,key,value) "
                    "VALUES ({},'{}',{},'closeType','{}');".format(
                         self.idMatch, rnd.getWinner(),
                         rnd.getNumRound(), rnd.closeType))
Beispiel #5
0
 def flushToDB(self):
     if self.idMatch < 0:
         cur = db.execute("INSERT INTO Match (Game_name,state,started,finished,elapsed) VALUES ('{}',{},'{}','{}',{});".format(self.game,self.state,str(self.start),str(self.finish),self.elapsed))
         self.idMatch = cur.lastrowid
     else:
         cur = db.execute("INSERT OR REPLACE INTO Match (idMatch,Game_name,state,started,finished,elapsed) VALUES ({},'{}',{},'{}','{}',{});".format(self.idMatch,self.game,self.state,str(self.start),str(self.finish),self.elapsed))
     for p in self.players:
         winner = 0
         if str(p)==self.getWinner(): winner = 1
         db.execute("INSERT OR REPLACE INTO MatchPlayer (idMatch,nick,totalScore,winner) VALUES ({},'{}',{},{});".format(str(self.idMatch),str(p),self.getScoreFromPlayer(str(p)),winner))
Beispiel #6
0
 def __init__(self,game):
     self.game = game
     self.candidates = {}
     cur = db.execute("SELECT idMatch,started,finished,elapsed FROM Match WHERE state=4 and Game_name='{}'".format(self.game))
     for row in cur:
         self.candidates[row['idMatch']] = {}
         self.candidates[row['idMatch']]['started'] = row['started']
         self.candidates[row['idMatch']]['finished'] = row['finished']
         self.candidates[row['idMatch']]['elapsed'] = row['elapsed']
         self.candidates[row['idMatch']]['players'] = []
         
     for idMatch,match in self.candidates.items():
         cur = db.execute("SELECT nick FROM MatchPlayer WHERE idMatch={}".format(idMatch))
         for row in cur:
             match['players'].append(str(row['nick']))
Beispiel #7
0
    def resumeMatch(self,idMatch):
        if not super(GenericRoundMatch,self).resumeMatch(idMatch): return False
        cur = db.execute("SELECT idRound,nick,winner,score FROM Round WHERE idMatch ={} ORDER BY idRound;".format(idMatch))
        current = 0
        rnd = None
        for row in cur:
            if row['idRound'] != current:
                current += 1
                if rnd is not None: self.rounds.append(rnd)
                rnd = self.createRound(current)
            if row['winner'] == 1: rnd.setWinner(str(row['nick']))
            rnd.addInfo(str(row['nick']), int(row['score']))
        if rnd is not None: self.rounds.append(rnd) 
        
        cur = db.execute("SELECT value FROM MatchExtras WHERE idMatch ={} and key='Dealer';".format(idMatch))
        row = cur.fetchone()
        if row: self.dealer = str(row['value'])

        cur = db.execute("SELECT value FROM MatchExtras WHERE idMatch ={} and key='DealingPolicy';".format(idMatch))
        row = cur.fetchone()
        if row: self.dealingp = int(row['value'])
        
        cur = db.execute("SELECT idRound,nick,key,value FROM RoundStatistics WHERE idMatch ={} ORDER BY idRound,nick,key,value;".format(idMatch))
        
        currentr = 0
        currentp = ""
        extras = {}
        for row in cur:
            if row['idRound'] != currentr:
                if len(extras):
                    for player,extra in extras.items(): 
                        self.rounds[currentr-1].addExtraInfo(player,extra)
                extras = {}
                currentp = ""
                currentr += 1
                
            if str(row['nick']) != currentp:
                currentp = str(row['nick'])
                extras[currentp] = {}
            
            extras[currentp].update(self.resumeExtraInfo(currentp,str(row['key']),str(row['value'])))
                
        if len(extras):
            for player,extra in extras.items(): 
                self.rounds[currentr-1].addExtraInfo(player,extra)
        
        return True
Beispiel #8
0
 def __init__(self,players=[]):
     super(CarcassonneMatch,self).__init__(players)
     self.game = 'Carcassonne'
     cur = db.execute("SELECT value FROM GameExtras WHERE Game_name = '{}' and key='Kinds';".format(self.game))
     row = cur.fetchone()
     self.entry_kinds = [ str(kind) for kind in row['value'].split(',') ]
     self.dealingp = 3
     self.updatewinnereveryround = False
Beispiel #9
0
 def addPlayer(self, nick, fullName=""):
     if (fullName == ""):
         fullName = nick
     self.porder.append(nick)
     self.players[nick] = Player()
     self.players[nick].nick = nick
     cur = db.execute("Select * from Player where nick='{}';".format(nick))
     # Exists in db?
     user = cur.fetchone()
     if (user):
         self.players[nick].fullName = user['fullName']
     else:
         self.players[nick].fullName = fullName
         self.players[nick].dateCreation = datetime.datetime.now()
         qd = str(self.players[nick].dateCreation)
         q = """INSERT INTO Player (nick, fullName, dateCreation)
              VALUES ('{}','{}','{}');""".format(nick, fullname, qd)
         db.execute()
Beispiel #10
0
 def resumeMatch(self,idMatch):
     if not super(RemigioMatch,self).resumeMatch(idMatch): return False
                    
     cur = db.execute("SELECT value FROM MatchExtras WHERE idMatch ={} and key='Top';".format(idMatch))
     row = cur.fetchone()
     if row: self.top = int(row['value'])
     
     for player in self.getPlayers(): self.playerStart(player)
     
     return True
Beispiel #11
0
 def resumeMatch(self,idMatch):
     if not super(Phase10Match,self).resumeMatch(idMatch): return False
     
     cur = db.execute("SELECT value FROM MatchExtras WHERE idMatch ={} and key='PhasesInOrder';".format(idMatch))
     row = cur.fetchone()
     if row: 
         self.phasesinorder = bool(int(row['value']))
         
     for player in self.getPlayers():
         if player not in self.phasesCleared: self.phasesCleared[player] = []
 
     return True
Beispiel #12
0
 def addPlayer(self, nick, fullName=""):
     if fullName == "":
         fullName = nick
     self.porder.append(nick)
     self.players[nick] = Player()
     self.players[nick].nick = nick
     cur = db.execute("Select * from Player where nick='{}';".format(nick))
     ## Exists in db?
     user = cur.fetchone()
     if user:
         self.players[nick].fullName = user["fullName"]
     else:
         self.players[nick].fullName = fullName
         self.players[nick].dateCreation = datetime.datetime.now()
         db.execute(
             "INSERT INTO Player (nick, fullName, dateCreation) values ('"
             + nick
             + "','"
             + fullName
             + "','"
             + str(self.players[nick].dateCreation)
             + "');"
         )
Beispiel #13
0
 def flushToDB(self):
     super(Phase10Match,self).flushToDB()
     if self.phasesinorder: inorderflag = 1
     else: inorderflag = 0
     db.execute("INSERT OR REPLACE INTO MatchExtras (idMatch,key,value) VALUES ({},'PhasesInOrder','{}');".format(self.idMatch,inorderflag))
     for rnd in self.rounds:
         for player in rnd.score.keys():
             db.execute("INSERT OR REPLACE INTO RoundStatistics (idMatch,nick,idRound,key,value) VALUES ({},'{}',{},'PhaseAimed','{}');".format(self.idMatch,player,rnd.getNumRound(),rnd.aimedPhase[player]))
             db.execute("INSERT OR REPLACE INTO RoundStatistics (idMatch,nick,idRound,key,value) VALUES ({},'{}',{},'PhaseCompleted','{}');".format(self.idMatch,player,rnd.getNumRound(),rnd.completedPhase[player]))  
Beispiel #14
0
 def getPhases(self):
     cur = db.execute("Select key,value from GameExtras where Game_name='{}' and key like 'Phase %' order by key asc".format(self.game))
     return [row['value'] for row in cur ]
Beispiel #15
0
    db = GameLogDB()
    db.connectDB("../db/gamelog.db")

    currentMatch = 0
    currentRound = 0
    aimed = {}
    result = []

    for row in db.queryDict(_mainquery):
        #        print(row)
        if int(row["idMatch"]) != currentMatch:
            currentMatch = int(row["idMatch"])
            currentRound = 0
            aimed = {}

        if int(row["idRound"]) != currentRound:
            currentRound += 1

        if currentRound == 1:
            aimed[row["nick"]] = 1

        result.append([row["idMatch"], row["idRound"], row["nick"], "PhaseAimed", aimed[row["nick"]]])
        if row["completed"] != "0":
            aimed[row["nick"]] += 1

    insert = "INSERT INTO RoundStatistics (idMatch,idRound,nick,key,value) VALUES ({0[0]},{0[1]},'{0[2]}','{0[3]}','{0[4]}');"
    for row in result:
        stmt = insert.format(row)
        db.execute(stmt)
#        print(stmt)
Beispiel #16
0
 def getGameMaxPlayers(self):
     cur = db.execute("Select maxPlayers from Game where name='{}'".format(self.game))
     r = cur.fetchone()
     return int(r["maxPlayers"])
Beispiel #17
0
 def flushToDB(self):
     super(RatukiMatch,self).flushToDB()
     db.execute("INSERT OR REPLACE INTO MatchExtras (idMatch,key,value) VALUES ({},'Top','{}');".format(self.idMatch,self.top))
Beispiel #18
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from controllers.db import GameLogDB, db

_mainquery = """UPDATE GameExtras SET value='{2}' WHERE Game_name='{0}' AND key='{1}';"""

if __name__ == "__main__":
    db = GameLogDB()
    db.connectDB("../db/gamelog.db")      
    
    phases = {
    'Phase10' : ['2s3','1s3 1r4','1s4 1r4','1r7','1r8','1r9','2s4','1c7','1s5 1s2','1s5 1s3'],
    'Phase10Master' : ['4s2','1c6','1s4 1r4','1r8','1c7','1r9','2s4','1cr4 1s3','1s5 1s3','1s5 1cr3']
    }

    for game,phases in phases.items():
        for i, phase in enumerate(phases,start=1):
            key = "Phase {0:02}".format(i)
            query = _mainquery.format(game,key,phase)
            print (query)
            db.execute(query)
            
    db.disconnectDB()