Commit 94caf50c authored by Antoine Lima's avatar Antoine Lima

Real setting menu

To customize game's duration and score, language and league parameter.
Can read/write to JSON config file
parent 62d68f63
......@@ -56,6 +56,8 @@ class MainWin(QtWidgets.QMainWindow):
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
......@@ -84,10 +86,10 @@ class MainWin(QtWidgets.QMainWindow):
contentFolder = join(dirname(dirname(abspath(__file__))), 'content')
return join(contentFolder, path)
def _refreshAfterSettings(self):
def _loadSettings(self):
from settings import Settings
if Settings.ui['fullscreen']:
if Settings['ui.fullscreen']:
self.showFullScreen()
QApplication.setOverrideCursor(Qt.BlankCursor);
else:
......
......@@ -40,12 +40,11 @@ class Module(QtWidgets.QWidget):
self.mainwin.ui.panels.setCurrentIndex(newmod_idx)
self.mainwin.ui.panels.setFocusProxy(self.mainwin.modules[newmod_idx])
self.mainwin.modules[newmod_idx].setFocus()
self.mainwin.modules[newmod_idx].load()
# Select first element of the Module
self.mainwin.modules[newmod_idx].focusNextChild()
self.mainwin.modules[newmod_idx].focusPreviousChild()
self.mainwin.modules[newmod_idx].focusPreviousChild()
self.mainwin.modules[newmod_idx].load()
def send(self, to, **kwargs):
mod_idx = self.mainwin.findMod(to)
......
......@@ -69,7 +69,14 @@ class GameModule(Module):
self.showingReplay = False
if self.replayer:
self.replayer.start_recording()
self.gameoverChecker = GameOverChecker('score', 10)
gameover_type = Settings['gameover.type']
gameover_value = Settings['gameover.value']
if gameover_type=='time':
gameover_value *= 60
self.gameoverChecker = GameOverChecker(gameover_type, gameover_value)
if all([len(val)==0 for val in self.players.values()]):
self.players[Side.Left ].append(PlayerGuest)
......
......@@ -8,8 +8,8 @@ Created on Wed Apr 18 18:34:40 2018
import logging
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QTableWidgetItem, QComboBox, QApplication
from PyQt5.QtCore import Qt, QEvent
from PyQt5.QtWidgets import QRadioButton, QSlider
from settings import Settings
from module import Module
......@@ -19,39 +19,85 @@ from ui.options_ui import Ui_Form as OptionsWidget
class OptionsModule(Module):
def __init__(self, parent):
super().__init__(parent, OptionsWidget())
# Button connections
self.ui.btnSave.clicked.connect(self.handleSave)
self.ui.btnBack.clicked.connect(self.handleBack)
self.ui.sliderGameOverValue.valueChanged.connect(self.updateGameOverLabel)
self.ui.rbGameOver_Score.clicked.connect(self.updateGameOverLabel)
self.ui.rbGameOver_Time.clicked.connect(self.updateGameOverLabel)
self.ui.sliderGameOverValue.installEventFilter(self)
def load(self):
logging.debug('Loading OptionsModule')
cbb = QComboBox()
cbb.addItem('true')
cbb.addItem('false')
self.ui.options.insertRow(self.ui.options.rowCount())
self.ui.options.setItem(self.ui.options.rowCount()-1, 0, QTableWidgetItem('FullScreen'))
self.ui.options.setCellWidget(self.ui.options.rowCount()-1, 1, cbb)
# Set Gameover condition from settings
self.ui.rbGameOver_Score.setChecked(Settings['gameover.type']=='score')
self.ui.rbGameOver_Time.setChecked(Settings['gameover.type']=='time')
self.ui.sliderGameOverValue.setValue(Settings['gameover.value'])
# Set League players from settings
self.ui.rbNumPlayerLeague_1.setChecked(Settings['league.playerPerTeam']==1)
self.ui.rbNumPlayerLeague_2.setChecked(Settings['league.playerPerTeam']==2)
# Set Language from settings
self.ui.rbLanguage_English.setChecked(Settings['ui.language']=='en')
self.ui.rbLanguage_French.setChecked(Settings['ui.language']=='fr')
self.selectIndex = 0
self.updateSelection()
self.updateGameOverLabel(0)
def unload(self):
logging.debug('Unloading OptionsModule')
# Delete the table's content
self.ui.options.setRowCount(0)
def other(self, **kwargs):
logging.debug('Other OptionsModule')
def eventFilter(self, obj, event):
if obj==self.ui.sliderGameOverValue and event.type()==QEvent.KeyPress and (event.key()==Qt.Key_Up or event.key()==Qt.Key_Down):
self.keyPressEvent(event)
return True
return False
def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.handleBack()
elif e.key() == Qt.Key_Return:
self.handleSave()
elif e.key() == Qt.Key_Up:
#self.parent().focusPreviousChild()
self.selectIndex = self.selectIndex-1 if self.selectIndex!=0 else len(self.selectables)-1
self.updateSelection()
elif e.key() == Qt.Key_Down:
#self.parent().focusNextChild()
self.selectIndex = self.selectIndex+1 if self.selectIndex!=len(self.selectables)-1 else 0
self.updateSelection()
def updateSelection(self):
self.selectables = []
isSelectable = lambda widget: (isinstance(widget, QRadioButton) and widget.isChecked()) or isinstance(widget, QSlider)
for gb in [self.ui.gbGameOver, self.ui.gbLeaguePlayers, self.ui.gbLanguage]:
self.selectables.extend([child for child in gb.children() if isSelectable(child)])
self.selectables[self.selectIndex].setFocus()
def updateGameOverLabel(self, val):
sliderVal = self.ui.sliderGameOverValue.value()
strPoints = '{} point{}'.format(sliderVal, 's' if sliderVal>1 else '')
strTime = '{} minute{}'.format(sliderVal, 's' if sliderVal>1 else '')
self.ui.lblGameOverValue.setText(strPoints if self.ui.rbGameOver_Score.isChecked() else strTime)
def handleSave(self):
Settings['ui.fullscreen'] = self.ui.options.cellWidget(0, 1).currentText().lower() == 'true'
self.mainwin._refreshAfterSettings()
Settings['ui.language'] = 'en' if self.ui.rbLanguage_English.isChecked() else 'fr'
Settings['gameover.type'] = 'score' if self.ui.rbGameOver_Score.isChecked() else 'time'
Settings['gameover.value'] = self.ui.sliderGameOverValue.value()
Settings['league.playerPerTeam'] = 1 if self.ui.rbNumPlayerLeague_1.isChecked() else 2
Settings.saveSettingsToJSON()
self.mainwin._loadSettings()
self.switchModule(modules.MenuModule)
def handleBack(self):
# ToDo: Maybe add a warning
self.switchModule(modules.MenuModule)
......@@ -9,10 +9,20 @@ Created on Wed Apr 18 18:34:40 2018
import json
import main
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Setting):
return obj.__dict__
elif isinstance(obj, String) and obj=='settingsPath':
return None
else:
return json.JSONEncoder.default(self, obj)
class Setting(object):
TypeName = ''
def __init__(self, value):
self.type = type(self).TypeName
self.value = value
class SettingBoolean(Setting):
......@@ -36,10 +46,9 @@ class SettingRange(Setting):
def __init__(self, value, limits):
Setting.__init__(self, value)
self.lower_limit = min(limits)
self.upper_limit = max(limits)
self.range = [min(limits), max(limits)]
if self.value<self.lower_limit or self.value>self.upper_limit:
if self.value<self.range[0] or self.value>self.range[1]:
raise ValueError('Setting value {} not in range {}'.format(self.value, (self.lower_limit, self.upper_limit)))
class SettingsHolder(object):
......@@ -73,13 +82,8 @@ class SettingsHolder(object):
@staticmethod
def _parseKey(key):
return [k for k in key.split('.') if k]
def _init_ui(self):
self.ui.append(Setting())
def loadSettingsFromJSON(self):
settings = list()
with open(self.settingsPath, 'r') as f:
content = json.load(f)
......@@ -106,4 +110,14 @@ class SettingsHolder(object):
getattr(self, cat)[name] = setting
def saveSettingsToJSON(self):
# Deletes the settings path member to prevent it from being saved in the JSON
settingsPath = self.settingsPath
del self.settingsPath
with open(settingsPath, 'w') as f:
content = json.dump(self.__dict__, f, cls=MyEncoder, indent=4)
self.settingsPath = settingsPath
Settings = SettingsHolder(main.MainWin.getContent('settings.json'))
......@@ -141,7 +141,7 @@
color: rgb(229, 229, 229);
}
QPushButton {
QPushButton, QGroupBox {
background-color: rgba(44, 44, 63, 150);
border: 1px;
border-radius: 10px;
......
......@@ -31,12 +31,9 @@
<widget class="QLabel" name="label">
<property name="font">
<font>
<family>FreeSerif</family>
<family>Schoolbook Uralic [pyrs]</family>
<pointsize>72</pointsize>
<weight>50</weight>
<italic>true</italic>
<bold>false</bold>
<underline>false</underline>
</font>
</property>
<property name="styleSheet">
......
This diff is collapsed.
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