Commit b731184c authored by Antoine Lima's avatar Antoine Lima

SQLite db migration

Load/save players and stats from sqlite database
Spyproject cleanup
parent d1f058e6
/__pycache__/
*/__pycache__/
/.spyproject/
*/*.log
*/*_ui.py
*/*_rc.py
[codestyle]
indentation = True
[main]
version = 0.1.0
[encoding]
text_encoding = utf-8
[main]
version = 0.1.0
[vcs]
use_version_control = False
version_control_system =
[main]
version = 0.1.0
[workspace]
restore_data_on_startup = True
save_data_on_exit = True
save_history = True
save_non_project_files = False
[main]
version = 0.1.0
recent_files = ['/home/antoine/prog/PR/source-rasp/main.py', '/home/antoine/prog/PR/source-rasp/modules/game.py', '/home/antoine/prog/PR/content/settings.json', '/home/antoine/prog/PR/source-rasp/replay.py', '/home/antoine/prog/PR/source-rasp/com.py']
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
import logging
import sqlite3
class DatabaseError(Exception):
pass
class Database():
__db = None
def __init__(self):
if not Database.__db:
from main import MainWin
db_path = MainWin.getContent('babyfut.sqlite')
self._connection = sqlite3.connect(db_path)
@staticmethod
def instance():
'''
Singleton
'''
if not Database.__db:
Database.__db = Database()
return Database.__db
@property
def _cursor(self):
return self._connection.cursor()
def select_one(self, query, *args):
res = self._cursor.execute(query, args).fetchone()
if not res:
raise DatabaseError('Query \"{}\" returned nothing with args {}'.format(query, args))
return res
def select_guest_team(self):
return self.select_one('SELECT id FROM players WHERE fname LIKE "guest"')[0]
def insert_team(self, players, goals):
if len(players)<2:
players.append(None)
logging.debug('DB Inserting {} to table Teams'.format((goals, players[0], players[1],)))
self._cursor.execute('INSERT INTO Teams (nGoals, player1, player2) VALUES (?, ?, ?)', (goals, players[0], players[1],))
self._connection.commit()
return self._cursor.execute('SELECT seq FROM sqlite_sequence WHERE name="Teams"').fetchone()[0]
def insert_match(self, start_time, duration, team1, team2):
logging.debug('DB Inserting {} to table Matchs'.format((start_time, duration, team1, team2,)))
self._cursor.execute('INSERT INTO Matchs (timestamp, duration, winningTeam, losingTeam) VALUES (?, ?, ?, ?)', (start_time, duration, team1, team2,))
self._connection.commit()
def close(self):
self._connection.close()
......@@ -19,6 +19,7 @@ from ui.main_ui import Ui_MainWindow
from modules import *
from player import Side
from input import GPIOThread
from database import Database
class MainWin(QtWidgets.QMainWindow):
def __init__(self, parent=None):
......@@ -122,3 +123,4 @@ if __name__=='__main__':
finally:
GPIOThread.clean()
Database.instance().close()
......@@ -48,9 +48,9 @@ class AuthLeagueModule(AuthModuleBase):
# Update the left side description
player.displayImg(self.ui.img)
self.ui.lblName.setText(player.name)
self.ui.lblStat1.setText('{} Victories'.format(player.stats.victories))
self.ui.lblStat2.setText('{} Games Played'.format(player.stats.games_played))
self.ui.lblStat3.setText('{} Goals Scored'.format(player.stats.goals_scored))
self.ui.lblStat1.setText('{} Victories'.format(player.stats['victories']))
self.ui.lblStat2.setText('{} Games Played'.format(player.stats['games_played']))
self.ui.lblStat3.setText('{} Goals Scored'.format(player.stats['goals_scored']))
if player!=PlayerEmpty:
# Update the right side list, making sure that the added player is showed
......
......@@ -12,7 +12,8 @@ from PyQt5 import QtWidgets
from PyQt5.QtGui import QRegion
from PyQt5.QtCore import QTime, QTimer, QRect, Qt
from player import Side
from database import Database, DatabaseError
from player import Side, PlayerGuest
from module import Module
import modules
from ui.endgame_ui import Ui_Form as EndGameWidget
......@@ -31,13 +32,16 @@ class EndGameModule(Module):
self.setActiveP2(len(self.players[self.winSide])>1)
self.displayPlayers()
db = Database.instance()
idTeams = {}
for side in [Side.Left, Side.Right]:
for player in self.players[side]:
player.stats.victories += 1 if side==self.winSide else 0
player.stats.goals_scored += self.scores[side]
player.stats.time_played += self.time
player.stats.games_played += 1
player.save()
if PlayerGuest in self.players[side]:
idTeams[side] = db.select_guest_team()
else:
idTeams[side] = db.insert_team([player.id for player in self.players[side]], self.scores[side])
db.insert_match(int(self.start_time), int(self.duration), idTeams[self.winSide], idTeams[self.winSide.opposite])
# Quit the screen after 5 seconds if the user doesn't do it before
#self.screenTimeout.start(5000)
......@@ -58,8 +62,12 @@ class EndGameModule(Module):
self.winSide = val
elif key=='scores':
self.scores = val
elif key=='time':
self.time = val
elif key=='start_time':
self.start_time = val
print('start_time {}'.format(val))
elif key=='duration':
self.duration = val
print('duration {}'.format(val))
#else:
# raise ValueError('Unknown message identifier {}'.format(kwargs)
......
......@@ -11,7 +11,7 @@ import logging
from PyQt5 import QtWidgets
from PyQt5.QtGui import QRegion
from PyQt5.QtCore import QTime, QTimer, QRect, Qt, QUrl
from PyQt5.QtCore import QDateTime, QDate, QTime, QTimer, QRect, Qt, QUrl
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
......@@ -40,7 +40,7 @@ class GameOverChecker():
if self.conditionType=='score' and scores[bestPlayer]>=self.limit:
return bestPlayer
elif self.conditionType=='time' and time>self.limit:
elif self.conditionType=='time' and time>=self.limit:
return bestPlayer
else:
return Side.Undef
......@@ -174,5 +174,8 @@ class GameModule(Module):
winSide = self.gameoverChecker.check(self.getGameTime(), self.scores)
if winSide!=Side.Undef:
self.send(modules.EndGameModule, players=self.players, winSide=winSide, scores=self.scores, time=self.getGameTime())
start_timestamp = int(QDateTime(QDate.currentDate(), self.gameStartTime).toMSecsSinceEpoch()/1000)
self.send(modules.EndGameModule, players=self.players, winSide=winSide, scores=self.scores)
self.send(modules.EndGameModule, start_time=start_timestamp, duration=self.getGameTime())
self.switchModule(modules.EndGameModule)
......@@ -28,10 +28,10 @@ class LeaderboardItemWidget(QtWidgets.QWidget):
self.ui.lblFName.setText(player.fname)
self.ui.lblLName.setText(player.lname)
self.ui.lblVictories.setText (self.ui.lblVictories.text().replace('####', str(player.stats.victories)))
self.ui.lblGamesPlayed.setText (self.ui.lblGamesPlayed.text().replace('####', str(player.stats.games_played)))
self.ui.lblGoalsScored.setText (self.ui.lblGoalsScored.text().replace('####', str(player.stats.goals_scored)))
self.ui.lblMinutesPlayed.setText(self.ui.lblMinutesPlayed.text().replace('####', str(player.stats.time_played)))
self.ui.lblVictories.setText (self.ui.lblVictories.text().replace('####', str(player.stats['victories'])))
self.ui.lblGamesPlayed.setText (self.ui.lblGamesPlayed.text().replace('####', str(player.stats['games_played'])))
self.ui.lblGoalsScored.setText (self.ui.lblGoalsScored.text().replace('####', str(player.stats['goals_scored'])))
self.ui.lblMinutesPlayed.setText(self.ui.lblMinutesPlayed.text().replace('####', str(player.stats['time_played'])))
self.ui.pushButton.clicked.connect(lambda: logging.debug('clicked'))
......@@ -48,13 +48,14 @@ class LeaderboardModule(Module):
self.selectedSort = 0
self.sortMethodRB = [self.ui.rbName, self.ui.rbVictories, self.ui.rbScore, self.ui.rbGamesPlayed, self.ui.rbTimePlayed]
self.sortMethodAttr = ['lname', 'stats.victories', 'stats.goals_scored', 'stats.games_played', 'stats.time_played']
self.sortMethodAttr = ['lname', 'stats_property.victories', 'stats_property.goals_scored', 'stats_property.games_played', 'stats_property.time_played']
self.sortMethodRB[self.selectedSort].setChecked(True)
def load(self):
logging.debug('Loading LeaderboardModule')
self.loadList()
self.setFocus()
def unload(self):
logging.debug('Unloading LeaderboardModule')
......
......@@ -56,7 +56,7 @@ class MenuModule(Module):
self.send(modules.MenuModule, rfid=-2, source=Side.Left)
elif e.key() == Qt.Key_Right:
self.send(modules.MenuModule, rfid=-4, source=Side.Right)
self.send(modules.MenuModule, rfid=-3, source=Side.Right)
elif e.key() == Qt.Key_Return:
if QApplication.focusWidget()==None:
......
......@@ -7,7 +7,10 @@ Created on Wed Apr 18 18:34:40 2018
"""
import logging
import sqlite3
from enum import Enum
from database import Database, DatabaseError
class Side(Enum):
'''
......@@ -16,52 +19,43 @@ class Side(Enum):
Undef = -1
Left = 0
Right = 1
@property
def opposite(self):
return Side.Right if self==Side.Left else Side.Left
class Player():
def __init__(self, id, fname='', lname='', pic_path=':ui/img/placeholder_head.jpg'):
__query_infos = 'SELECT id, fname, lname, pic FROM Players WHERE rfid==?'
__query_time_goals_games = 'SELECT SUM(Matchs.duration) AS timePlayed, SUM(Teams.nGoals) AS goalsScored, COUNT(*) AS gamesPlayed FROM Teams INNER JOIN Matchs ON (Teams.id==Matchs.winningTeam OR Teams.id==Matchs.losingTeam) WHERE (Teams.player1==? OR player2==?)'
__query_victories = 'SELECT COUNT(*) AS victories FROM Players INNER JOIN Teams ON (Players.id==Teams.player1 OR Players.id==Teams.player2) INNER JOIN Matchs ON (Teams.id==Matchs.winningTeam) WHERE Players.id==?'
_placeholder_pic_path = ':ui/img/placeholder_head.jpg'
def __init__(self, id, fname, lname, pic_path, stats):
self.id = id
self.fname = fname
self.lname = lname
self.pic_path = pic_path
self.stats = Stat(id)
self.pic_path = pic_path if pic_path else Player._placeholder_pic_path # Default pic if None
self.stats = stats
@staticmethod
def fromRFID(id):
fname, lname, pic_url = '','','' # Replace with DB calls
if id==-1:
player = Player(id, 'Guest')
elif id==-2:
player = Player(id, 'Alfredo', 'Enrique')
elif id==-3:
player = Player(id, 'Bastien', 'Dali')
player.stats.victories = 1
elif id==-4:
player = Player(id, 'Carim', 'Cuebache')
player.stats.time_played = 1
elif id==-5:
player = Player(id, 'Dorian', 'Boulet')
player.stats.games_played = 1
elif id==-6:
player = Player(id, 'Enzo', 'Arobaz')
player.stats.goals_scored = 1
def fromRFID(rfid):
db = Database.instance()
try:
# Retrieve generic informations
id, fname, lname, pic = db.select_one(Player.__query_infos, rfid)
elif id==-10:
player = Player(id, 'Name', '')
player.stats.victories = ''
player.stats.time_played = ''
player.stats.games_played = ''
player.stats.goals_scored = ''
# Retrieve stats
stats = {}
stats['time_played'], stats['goals_scored'], stats['games_played'] = db.select_one(Player.__query_time_goals_games, id, id)
stats['victories'], = db.select_one(Player.__query_victories, id)
else:
player = Player(id, fname, lname, pic_url)
return Player(id, fname, lname, pic, stats)
return player
except DatabaseError as e:
logging.warn('DB Error: {}'.format(e))
return PlayerGuest
def displayImg(self, containerWidget):
containerWidget.setStyleSheet('border-image: url({});'.format(self.pic_path))
......@@ -70,29 +64,21 @@ class Player():
'''
Update or create the player in database
'''
# TODO
pass
@property
def name(self):
return '{} {}'.format(self.fname, self.lname.upper())
@property
def pic(self):
return QPixmap(self.pic_path)
class Stat():
def __init__(self, player_id):
self.victories = 0
self.time_played = 0
self.games_played = 0
self.goals_scored = 0
def stats_property(self):
class Stat:
def __init__(self, stats):
self.victories = stats['victories']
self.time_played = stats['time_played']
self.goals_scored = stats['goals_scored']
self.games_played = stats['games_played']
if player_id >= 0:
self.victories = 0
self.time_played = 0
self.games_played = 0
self.goals_scored = 0
return Stat(self.stats)
PlayerGuest = Player.fromRFID(-1)
PlayerEmpty = Player.fromRFID(-10)
PlayerEmpty = Player(-1, '', '', Player._placeholder_pic_path, {'time_played':'', 'goals_scored':'', 'games_played':'', 'victories': ''})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment