Commit 67ecafce authored by Antoine Lima's avatar Antoine Lima

Cleanup

Removed unnecessary headers and split main into a window and a program
parent 93163434
#!/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
from settings import Settings
class DatabaseError(Exception):
pass
......@@ -19,8 +14,8 @@ class Database():
def __init__(self):
if not Database.__db:
from main import MainWin
db_path = MainWin.getContent('babyfut.sqlite')
from main import getContent
db_path = getContent('babyfut.sqlite')
self._connection = sqlite3.connect(db_path)
@staticmethod
......@@ -61,6 +56,7 @@ class Database():
self._connection.commit()
def select_all_rfid(self, debug=False):
from settings import Settings
if Settings['app.mode']=='prod':
return self._cursor.execute('SELECT rfid FROM Players WHERE rfid>0').fetchall()
else:
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
......@@ -11,91 +9,19 @@ OnRasp = os.uname()[1] == 'raspberrypi'
import sys
import logging
import threading
from os.path import dirname, abspath, join
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QGraphicsBlurEffect, QApplication
from PyQt5.QtCore import QTime, Qt
from ui.main_ui import Ui_MainWindow
from modules import *
from player import Side
class MainWin(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
#Background blur
bgBlur = QGraphicsBlurEffect()
bgBlur.setBlurHints(QGraphicsBlurEffect.QualityHint)
#bgBlur.setBlurRadius(5)
#self.ui.panels.setGraphicsEffect(bgBlur)
# Module loading
self.modules = [
MenuModule(self),
AuthQuickModule(self),
AuthLeagueModule(self),
GameModule(self),
EndGameModule(self),
LeaderboardModule(self),
OptionsModule(self)
]
for mod in self.modules:
self.ui.panels.addWidget(mod)
self.ui.panels.setCurrentIndex(0)
self.ui.panels.currentWidget().setFocus()
self.ui.panels.setFocusProxy(self.ui.panels.currentWidget())
self.ui.panels.currentWidget().load()
self.displaySystemTime()
self.startTimer(1000)
self._loadSettings()
def getContent(path):
contentFolder = join(dirname(dirname(abspath(__file__))), 'content')
return join(contentFolder, path)
#def eventFilter(target, event):
# return event.type()==QEvent.KeyPress and event.key() not in acceptedKeys
def timerEvent(self, e):
self.displaySystemTime()
def displaySystemTime(self):
self.ui.lcdTime.display(QTime.currentTime().toString("hh:mm:ss"))
def findMod(self, type):
mod_idx = [i for i, x in enumerate(self.modules) if isinstance(x, type)]
return -1 if len(mod_idx)==0 else mod_idx[0]
def dispatchMessage(self, msg, toType=None, toAll=False):
if toType!=None:
modulesIdx = [self.findMod(toType)]
else:
modulesIdx = self.modules if toAll else [self.findMod(type(self.ui.panels.currentWidget()))]
for modIdx in modulesIdx:
self.modules[modIdx].other(**msg)
@staticmethod
def getContent(path):
contentFolder = join(dirname(dirname(abspath(__file__))), 'content')
return join(contentFolder, path)
def _loadSettings(self):
from settings import Settings
if Settings['ui.fullscreen']:
self.showFullScreen()
QApplication.setOverrideCursor(Qt.BlankCursor);
else:
self.showNormal()
QApplication.setOverrideCursor(Qt.ArrowCursor);
if __name__=='__main__':
from settings import Settings
from ui.mainwin import MainWin
from modules import GameModule
from player import Side
from input import GPIOThread
from database import Database
from replay import Replay as ReplayThread
......
#!/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
from PyQt5 import QtWidgets
from PyQt5.QtCore import QTime, QTimer, Qt
from PyQt5.QtWidgets import QTableWidgetItem, QComboBox, QApplication
from PyQt5.QtWidgets import QApplication, QWidget
class Module(QtWidgets.QWidget):
class Module(QWidget):
def __init__(self, parent, widget):
# UI Setup
QtWidgets.QWidget.__init__(self, parent)
QWidget.__init__(self, parent)
self.mainwin = parent
self.ui = widget
self.ui.setupUi(self)
......@@ -29,11 +25,11 @@ class Module(QtWidgets.QWidget):
elif newmod_idx<0:
logging.error('Unknown panel {}'.format(new_type))
else:
# Unfocus the current module
# Unfocus the current module
if QApplication.focusWidget() != None:
QApplication.focusWidget().clearFocus()
# Swap modules by unloading, changing the ui then loading
# Swap modules by unloading, changing the ui then loading
self.mainwin.modules[curmod_idx].unload()
self.mainwin.ui.panels.setCurrentIndex(newmod_idx)
self.mainwin.ui.panels.setFocusProxy(self.mainwin.modules[newmod_idx])
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
......@@ -12,7 +10,7 @@ from PyQt5.QtCore import Qt
import modules
from module import Module
from player import Side, Player, PlayerGuest
from player import Side, Player
class AuthModuleBase(Module):
def __init__(self, parent, widget):
......
#!/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
from PyQt5.QtWidgets import QAbstractItemView
from module import Module
from modules.auth import AuthModuleBase
from ui.authleague_ui import Ui_Form as AuthLeagueWidget
......@@ -53,7 +50,7 @@ class AuthLeagueModule(AuthModuleBase):
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
# Update the right side list, making sure that the added player is showed
self.ui.playersList.addItem('{}. {}'.format(len(self.players[side]), player.name))
widgetItem = self.ui.playersList.item(self.ui.playersList.count()-1)
self.ui.playersList.scrollToItem(widgetItem, QAbstractItemView.PositionAtBottom)
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
......@@ -10,10 +8,8 @@ import logging
from PyQt5.QtWidgets import QSizePolicy
import modules
from module import Module
from modules.auth import AuthModuleBase
from player import Side, Player, PlayerGuest
from player import Side, PlayerGuest
from ui.authquick_ui import Ui_Form as AuthQuickWidget
class AuthQuickModule(AuthModuleBase):
......@@ -44,7 +40,7 @@ class AuthQuickModule(AuthModuleBase):
self.players = {Side.Left: list(), Side.Right: list()}
def addPlayer(self, side, player):
# If there is a placeholder Guest, clear it from the list, we don't need it anymore
# If there is a placeholder Guest, clear it from the list, we don't need it anymore
if len(self.players[side])>0 and self.players[side][0]==PlayerGuest:
self.players[side].clear()
......
#!/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
from PyQt5 import QtWidgets
from PyQt5.QtGui import QRegion
from PyQt5.QtCore import QTime, QTimer, QRect, Qt
from PyQt5.QtCore import QTimer, Qt
from database import Database, DatabaseError
from database import Database
from player import Side, PlayerGuest
from module import Module
import modules
......@@ -51,7 +48,7 @@ class EndGameModule(Module):
self.screenTimeout.stop()
del self.players
del self.gameType
del self.gameType
del self.winSide
del self.scores
del self.start_time
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
......@@ -12,7 +10,7 @@ import logging
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtGui import QRegion
from PyQt5.QtCore import QDateTime, QDate, QTime, QTimer, QRect, Qt, QUrl, QEvent
from PyQt5.QtCore import QDateTime, QDate, QTime, QTimer, QRect, Qt, QUrl
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
......@@ -87,7 +85,7 @@ class GameModule(Module):
self.ui.btnScore2.clicked.connect(lambda: self.goal(Side.Right))
self.camera = None
self.player = None
self.video_player = None
def load(self):
logging.debug('Loading GameModule')
......@@ -96,7 +94,7 @@ class GameModule(Module):
self.timerUpdateChrono.start(1000)
self.ui.lcdChrono.display(QTime(0,0).toString("hh:mm:ss"))
self.player = None
self.video_player = None
if self.camera:
self.camera.start_recording()
......@@ -118,8 +116,8 @@ class GameModule(Module):
def unload(self):
logging.debug('Unloading GameModule')
del self.gameStartTime
self.timerUpdateChrono.stop()
self.gameStartTime = None
if self.camera:
self.camera.stop_recording()
......@@ -165,7 +163,7 @@ class GameModule(Module):
self.ui.lcdChrono.display(QTime(0,0).addSecs(self.getGameTime()).toString("hh:mm:ss"))
# Don't check scores while showing a replay to avoid closing the engame screen too soon
if not self.player:
if not self.video_player:
self.checkEndGame()
def getGameTime(self):
......@@ -192,14 +190,16 @@ class GameModule(Module):
replayFile = ''
if replayFile and os.path.exists(replayFile):
self.player = ReplayPlayer(self)
self.player.start_replay(replayFile)
self.video_player = ReplayPlayer(self)
self.video_player.start_replay(replayFile)
else:
self.updateScores()
def endOfReplay(self):
self.player = None
self.updateScores()
self.video_player = None
if self.gameStartTime:
self.updateScores()
if self.camera:
self.camera.start_recording()
......@@ -214,5 +214,5 @@ class GameModule(Module):
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.send(modules.EndGameModule, start_time=start_timestamp, duration=self.getGameTime(), gameType=self)
self.switchModule(modules.EndGameModule)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
......@@ -10,7 +8,7 @@ import logging
from operator import attrgetter
from PyQt5.QtWidgets import QWidget, QDialog, QListWidgetItem
from PyQt5.QtCore import QTime, Qt, QSize, QItemSelectionModel
from PyQt5.QtCore import Qt, QItemSelectionModel
import modules
from module import Module
......@@ -89,7 +87,7 @@ class LeaderboardModule(Module):
if key=='rfid' and self.deleteDialog and self.deleteDialog.check(val):
Database.instance().delete_player(self.deleteDialog.player.id)
# Reset the dialog and the player list
# Reset the dialog and the player list
self.deleteDialog.close()
del self.deleteDialog
self.deleteDialog = None
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
......@@ -10,7 +8,6 @@ import logging
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
import modules
from module import Module
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
......
......@@ -7,7 +7,6 @@ Created on Wed Apr 18 18:34:40 2018
"""
import logging
import sqlite3
from enum import Enum
......@@ -48,7 +47,7 @@ class Player():
# Retrieve generic informations
id, fname, lname, pic = db.select_one(Player.__query_infos, rfid)
# Retrieve stats
# 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)
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
from threading import Thread, Event
from main import MainWin, OnRasp
from main import getContent, OnRasp
from settings import Settings
if OnRasp:
......@@ -17,7 +15,7 @@ if OnRasp:
class Replay(Thread):
def __init__(self, side):
Thread.__init__(self)
self.replayPath = MainWin.getContent('Replay {}.mp4'.format(side.name))
self.replayPath = getContent('Replay {}.mp4'.format(side.name))
self.shutdown = False
self.start_flag = Event()
......@@ -68,7 +66,7 @@ class Replay(Thread):
self.stream.copy_to(self.replayPath)
self.stream.clear()
# Set this flag to tell the calling thread that replay is saved
# Set this flag to tell the calling thread that replay is saved
self.stopped_flag.set()
self.cam.close()
......@@ -76,7 +74,7 @@ class Replay(Thread):
@classmethod
def Dummy(cls):
return MainWin.getContent('Replay Left.mp4')
return getContent('Replay Left.mp4')
@staticmethod
def isCamAvailable():
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
......@@ -115,9 +113,9 @@ class SettingsHolder(object):
del self.settingsPath
with open(settingsPath, 'w') as f:
content = json.dump(self.__dict__, f, cls=MyEncoder, indent=4)
json.dump(self.__dict__, f, cls=MyEncoder, indent=4)
self.settingsPath = settingsPath
import main
Settings = SettingsHolder(main.MainWin.getContent('settings.json'))
from main import getContent
Settings = SettingsHolder(getContent('settings.json'))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
import os
OnRasp = os.uname()[1] == 'raspberrypi'
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QGraphicsBlurEffect, QApplication
from PyQt5.QtCore import QTime, Qt
from ui.main_ui import Ui_MainWindow
import modules
class MainWin(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
#Background blur
bgBlur = QGraphicsBlurEffect()
bgBlur.setBlurHints(QGraphicsBlurEffect.QualityHint)
#bgBlur.setBlurRadius(5)
#self.ui.panels.setGraphicsEffect(bgBlur)
# Module loading
self.modules = [
modules.MenuModule(self),
modules.AuthQuickModule(self),
modules.AuthLeagueModule(self),
modules.GameModule(self),
modules.EndGameModule(self),
modules.LeaderboardModule(self),
modules.OptionsModule(self)
]
for mod in self.modules:
self.ui.panels.addWidget(mod)
self.ui.panels.setCurrentIndex(0)
self.ui.panels.currentWidget().setFocus()
self.ui.panels.setFocusProxy(self.ui.panels.currentWidget())
self.ui.panels.currentWidget().load()
self.displaySystemTime()
self.startTimer(1000)
self._loadSettings()
#def eventFilter(target, event):
# return event.type()==QEvent.KeyPress and event.key() not in acceptedKeys
def timerEvent(self, e):
self.displaySystemTime()
def displaySystemTime(self):
self.ui.lcdTime.display(QTime.currentTime().toString("hh:mm:ss"))
def findMod(self, type):
mod_idx = [i for i, x in enumerate(self.modules) if isinstance(x, type)]
return -1 if len(mod_idx)==0 else mod_idx[0]
def dispatchMessage(self, msg, toType=None, toAll=False):
if toType!=None:
modulesIdx = [self.findMod(toType)]
else:
modulesIdx = self.modules if toAll else [self.findMod(type(self.ui.panels.currentWidget()))]
for modIdx in modulesIdx:
self.modules[modIdx].other(**msg)
def _loadSettings(self):
from settings import Settings
if Settings['ui.fullscreen']:
self.showFullScreen()
QApplication.setOverrideCursor(Qt.BlankCursor);
else:
self.showNormal()
QApplication.setOverrideCursor(Qt.ArrowCursor);
\ No newline at end of file
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