-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGUI_host.py
More file actions
1760 lines (1661 loc) · 95.2 KB
/
GUI_host.py
File metadata and controls
1760 lines (1661 loc) · 95.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import QCoreApplication, QTimer
from Main_Window_Host import Ui_MainWindow_Host
from dialog_newPlant import Ui_dialog_newPlant
from dialog_setDemand import Ui_dialog_setDemand
from Resources.optimization import Optimization
from Resources.classes import Plant
from Resources.AuxillaryMethods import endTime, endTime_to_seconds, number_to_string, create_plot_lists
from game_client import Game_client
import json
import time
from thread import ServerNetwork
from matplotlib.backends.qt_compat import is_pyqt5
if is_pyqt5():
from matplotlib.backends.backend_qt5agg import (
FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
else:
from matplotlib.backends.backend_qt4agg import (
FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
from matplotlib.figure import Figure
from matplotlib.lines import Line2D
import random
# for testing purposes
from Resources.classes import Player
import globals
# The functions of the window classes are implemented here (do not edit Main_Window_Player)
class startWindow_host(QtWidgets.QMainWindow, Ui_MainWindow_Host):
"""
This is the main class. It acts as a platform for the other game mechanics ie. main window and game components
All methods that change the GUI must be implemented here
"""
def __init__(self, *args, **kwargs):
super(startWindow_host, self).__init__(*args, **kwargs)
# Initialize the game object (containing all relevant data for the game
self.game_obj = Game_client("host")
# Initialize the optimization object running later
self.opt = Optimization(self.game_obj)
def setUpSlots(self):
self.create_button_next.clicked.connect(self.create_handle_button_next)
#self.settings_button_start.clicked.connect(self.settings_handle_button_start)
#test
self.settings_button_start.clicked.connect(self.settings_handle_button_create)
self.button_main.clicked.connect(self.handle_button_main)
self.button_players.clicked.connect(self.handle_button_players)
self.button_statistics.clicked.connect(self.handle_button_statistics)
self.host_main_quitButton.clicked.connect(QCoreApplication.instance().quit)
self.lobby_button_start.clicked.connect(self.lobby_handle_button_start)
self.main_button_add_plant.clicked.connect(self.main_handle_button_add_next_plant)
self.main_button_create_plant.clicked.connect(self.main_handle_button_newPlant)
self.main_button_set_demand.clicked.connect(self.main_handle_button_set_demand)
self.statistics_combobox_players.currentIndexChanged.connect(self.statistics_handle_comboBox)
self.statistics_performance_tabWidget.currentChanged.connect(self.plot_statistics_performance_graphs)
self.statistics_comboBox_round_results.currentIndexChanged.connect(self.statistics_round_results_handle_comboBox)
self.statistics_tabWidget_general_plots.currentChanged.connect(self.statistics_round_results_handle_general_plots)
self.transition_button_next.clicked.connect(self.transition_handle_button_next)
self.optimize_button_optimize.clicked.connect(self.initialize_optimization)
def setUpValidators(self):
"""
The validators are used to limit input data into certain fields
"""
# Create validator for IP-address
ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" # ipRange is: 0 to 199 and 200 to 249 and 250 to 255 ie. 0 to 255
ip_regex = QtCore.QRegExp(
"^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$") # Regular expression defined as xxx.xxx.xxx.xxx
ip_validator = QtGui.QRegExpValidator(ip_regex) # Creating a validator from the regular expression
self.create_lineEdit_hostIp.setValidator(ip_validator)
# integer regex (for settings)
int_regex = QtCore.QRegExp("[1234567890]+") # Integers only (might be a easier way to do this
int_validator = QtGui.QRegExpValidator(int_regex)
# float regex for numbers above zero (used in dialog windows)
float_positive_regex = QtCore.QRegExp("^[0-9]+(?:\.[0-9]+)?$")
self.float_positive_validator = QtGui.QRegExpValidator(float_positive_regex)
# float regex for percentages ie. between 0 and 100
float_positive_percentage_regex = QtCore.QRegExp("^([0-9](?:\.[0-9]+)?|[1-9][0-9](?:\.[0-9]+)?|100(?:\.[0]+)?)$") # Accepts only 0.0 to 99.99999.. and 100.0 or integers. No negative numbers.
self.float_positive_percentage_valdidator = QtGui.QRegExpValidator(float_positive_percentage_regex)
# Enable valikdators
self.settings_lineEdit_rounds.setValidator(int_validator)
self.settings_lineEdit_bidRounds.setValidator(int_validator)
self.settings_lineEdit_initialMoney.setValidator(int_validator)
def setUpMisc(self):
self.stackedWidget.setCurrentIndex(1)
self.stackedWidget_inner.setCurrentIndex(0)
self.statistics_tabWidget.setCurrentIndex(0)
self.statistics_performance_tabWidget.setCurrentIndex(0)
self.statistics_tabWidget_round_results.setCurrentIndex(0)
self.settings_lineEdit_rounds.setPlaceholderText(str(globals.default_years))
self.settings_lineEdit_bidRounds.setPlaceholderText(str(globals.default_rounds))
self.settings_lineEdit_initialMoney.setPlaceholderText(str(globals.default_money))
# Empty warning labels
self.create_label_warning.setText("")
self.lobby_label_warning.setText("")
self.main_label_warning.setText("")
self.players_label_warning.setText("")
# Repeaters
self.end_game_counter = 0 # quick fix getting rid of host sending a bunch of packages
# Define flags
self.countdown_stop_flag = False
self.player_removed = None
self.round_results_drawn = False
self.player_status_changed = False
# Create timer object
self.lobby_refresh_timer = QTimer(self)
self.player_refresh_timer = QTimer(self)
self.countdown = QTimer(self)
self.countdown.timeout.connect(self.update_countdown)
self.warnTimer = QTimer(self)
self.warnTimer.timeout.connect(self.warningCountdownFinished) # Trigger method when the timer times out
self.warnTimer.setSingleShot(True) # A single shot timer executes the timeout method only once
self.background_counter = QTimer(self)
self.background_counter.timeout.connect(self.background_flag_check)
self.background_counter.start(100) # connected method is run every 100 ms (input value given in ms)
# Set up alignments (this is done in designer but must be redone here to fix bug on MAC OSx)
self.formLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
self.formLayout.setFormAlignment((QtCore.Qt.AlignLeft))
self.formLayout_2.setLabelAlignment(QtCore.Qt.AlignLeft)
self.formLayout_2.setFormAlignment((QtCore.Qt.AlignLeft))
self.formLayout_3.setLabelAlignment(QtCore.Qt.AlignLeft)
self.formLayout_3.setFormAlignment((QtCore.Qt.AlignLeft))
self.formLayout_4.setLabelAlignment(QtCore.Qt.AlignLeft)
self.formLayout_4.setFormAlignment((QtCore.Qt.AlignLeft))
self.formLayout_5.setLabelAlignment(QtCore.Qt.AlignLeft)
self.formLayout_5.setFormAlignment((QtCore.Qt.AlignLeft))
self.formLayout_6.setLabelAlignment(QtCore.Qt.AlignLeft)
self.formLayout_6.setFormAlignment(QtCore.Qt.AlignLeft)
# Input data from excel
gas_cost_fixed, gas_cost_variable, coal_cost_fixed, coal_cost_variable, co2_tax = self.game_obj.host.input_data()
self.game_obj.gas_cost_fixed = gas_cost_fixed
self.game_obj.gas_cost_variable = gas_cost_variable
self.game_obj.coal_cost_fixed = coal_cost_fixed
self.game_obj.coal_cost_variable = coal_cost_variable
self.game_obj.co2_tax = co2_tax
self.statistics_comboBox_round_results.setEnabled(False)
self.statistics_tabWidget_general_plots.setEnabled(False)
self.statistics_tabWidget_round_results.setEnabled(False)
self.static_canvas_statistics_performance = None
self._static_ax_statistics_performance = None
self._static_ax = None
self._static_ax_statistics_round_results_players = None
self.static_canvas = None
self.static_canvas_statistics_round_results_players = None
self.statistics_tabWidget_general_plots_currentIndex = None
self.sec_remaining = 0
def background_flag_check(self):
"""
The method runs a timer which runs in the background and checks for flags and then runs events triggered by these flags
"""
if self.player_removed is not None:
if globals.DEBUGGING:
print(self.player_removed)
self.warningCountdown("kick", self.player_removed)
self.player_removed = None
if self.game_obj.host_status:
if self.game_obj.host_status == "update demand":
self.game_obj.host_status = ""
self.main_label_demand.setText(
number_to_string(self.game_obj.host.demand[0]) + "-" + number_to_string(
self.game_obj.host.demand[1]) + "Q")
elif self.game_obj.host_status == "valid ip":
self.game_obj.host_status = ""
data = self.createData("settings")
self.sendAll(data)
if self.stackedWidget.currentIndex() == 1:
self.stackedWidget.setCurrentIndex(2)
elif self.game_obj.host_status == "invalid ip":
self.game_obj.host_status = ""
self.warningCountdown("invalid ip")
def create_handle_button_next(self):
# Set up and start the network thread
self.serverThread = ServerNetwork(self)
self.serverThread.start()
ip = self.create_lineEdit_hostIp.text()
if (not ip.strip()) or ip.count(".") != 3: # Checks that field is nonempty (also for whitespaces) and that that IP-address has correct format (three dots)
# Show error message
print("Some error message")
else:
self.game_obj.setIp(ip)
#self.stackedWidget.setCurrentIndex(2)
# Set number of players to zero
self.num_players = 0
# Connect to slot method
self.lobby_refresh_timer.timeout.connect(self.automatic_lobby_refresh)
# Start the timer
self.lobby_refresh_timer.start(100) # argument is update frequency in ms
def settings_handle_button_create(self):
years = self.settings_lineEdit_rounds.text()
bidRounds = self.settings_lineEdit_bidRounds.text()
money = self.settings_lineEdit_initialMoney.text()
stratTime = self.strategy_timeEdit.text()
bidTime = self.bid_timeEdit.text()
self.initial_plants()
# Only use inputed values if they are edited. Else use default values defined in globals.py initialized in Game_client.py
if bool(years.strip()):
self.game_obj.years = int(years)
if bool(bidRounds.strip()):
self.game_obj.bidRounds = int(bidRounds)
if bool(money.strip()):
self.game_obj.initialMoney = int(money)*1000000
self.game_obj.setStrategyTime(stratTime)
self.game_obj.setBidTime(bidTime)
# Send settings to players
data = self.createData("settings")
self.sendAll(data)
self.label_time.setText(self.game_obj.getStrategyTime()) # initial time remaining in the game window
# Change page
#self.game_obj.host.setJoinable(True) # Should now be True
# Draw the lobby initially
self.drawLobby()
self.stackedWidget.setCurrentIndex(3)
def automatic_lobby_refresh(self):
"""
Lobby refreshes automatically in given intervalls. The refreshing is started when the host enters the setting page because players can be in the lobby at the same time
"""
if self.stackedWidget.currentIndex() == 3:
# Redraw the lobby
self.clearLobby()
self.drawLobby()
# A new player has joined since the last time the method was run
if self.num_players != len(self.game_obj.simple_players):
self.num_players = len(self.game_obj.simple_players)
# Share new information to all players
data = self.createData("players")
self.sendAll(data)
def lobby_handle_button_start(self):
if self.game_obj.host.allPlayersReady():
# Reset status of players to "not ready"
self.game_obj.host.setAllPlayersNotReady()
# Make the game not joinable
self.game_obj.host.setJoinable(False)
# Send playerNumbers to all players
for player in self.game_obj.host.players:
data = self.createData("playerNumber", player.playerNumber)
self.send(data, player.playerNumber)
# Calculate the time of the end of the round
self.game_obj.setEndTime(endTime(self.game_obj.getStrategyTime()))
# Send data about time of the end of the round
data = self.createData("endTime")
self.sendAll(data)
# Send initial plants
data = self.createData("plants")
self.sendAll(data)
for player in self.game_obj.host.players:
self.statistics_combobox_players.addItem(player.firm_name)
# Send expected demand
self.create_expected_demand()
data = self.createData("demand")
self.sendAll(data)
# Set correct labels
self.label_year.setText("Year: {}/{}".format(self.game_obj.year, self.game_obj.years))
self.main_label_number_new_plants.setText(str(len(self.game_obj.host.newPlants)))
self.main_label_next_plant_name.setText(self.game_obj.host.database.get_name_of_next_plant())
# Stop lobby refresh
self.lobby_refresh_timer.stop()
# Start the round countdown
if globals.DEBUGGING:
print(self.countdown_stop_flag)
self.startCountdown()
# Change window to main window
self.stackedWidget.setCurrentIndex(4)
else:
self.warningCountdown("notAllPlayersReady")
def create_expected_demand(self):
"""
The expected demand is somewhat different from the actual demand which means the players cannot really know
what happens in the market which is also true for realistic cases
"""
self.game_obj.expected_demand_fixed = random.uniform(0.75, 1.25) * self.game_obj.host.demand[0]
self.game_obj.expected_demand_variable = random.uniform(0.75, 1.25) * self.game_obj.host.demand[1]
def handle_button_main(self):
self.uncheck_buttons()
self.button_main.setChecked(True)
self.clear_page()
# Set correct labels
self.main_label_demand.setText("{}-{}Q".format(round(self.game_obj.host.demand[0],1), round(self.game_obj.host.demand[1],1)))
self.stackedWidget_inner.setCurrentIndex(0)
def handle_button_players(self):
try:
self.uncheck_buttons()
self.button_players.setChecked(True)
if self.stackedWidget_inner.currentIndex() == 1:
return
self.clear_page()
self.drawPlayers()
self.player_refresh_timer.timeout.connect(self.automatic_player_refresh)
# Start the timer
self.player_refresh_timer.start(100) # argument is update frequency in ms
self.stackedWidget_inner.setCurrentIndex(1)
except Exception as e:
print(e)
def handle_button_statistics(self):
self.uncheck_buttons()
self.button_statistics.setChecked(True)
self.clear_page()
self.draw_statistics_leaderboards()
# Force update player specific data
self.statistics_handle_comboBox()
# Make performance plot
self.plot_statistics_performance_graphs()
self.stackedWidget_inner.setCurrentIndex(2)
def main_handle_button_add_next_plant(self):
"""
Called when button "Add next plant in list" is clicked
The plant shown in label should be taken from the database and added to the hosts list of new plants to be added to players store
"""
next_plant = self.game_obj.host.database.get_next_plant_in_list(len(self.game_obj.storePlants) + len(self.game_obj.host.newPlants))
if next_plant:
self.game_obj.host.newPlants.append(next_plant)
self.warningCountdown("next_plant_added", next_plant.name)
self.main_label_next_plant_name.setText(self.game_obj.host.database.get_name_of_next_plant())
self.main_label_number_new_plants.setText(str(len(self.game_obj.host.newPlants)))
else:
self.warningCountdown("next_plant_failed")
def main_handle_button_newPlant(self):
# Initialize dialog window
self.dialog_new_plant = QtWidgets.QDialog()
# Set GUI wrapper
self.dialog_new_plant.ui = Ui_dialog_newPlant()
# Initialize the design onto the dialog using the wrapper
self.dialog_new_plant.ui.setupUi(self.dialog_new_plant)
# Set up slots for the input
self.dialog_new_plant.ui.dialog_addPlant_buttonBox.accepted.connect(self.addPlant_dialog_accepted)
self.dialog_new_plant.ui.dialog_addPlant_buttonBox.rejected.connect(self.close_dialog_new_plant_window)
# Set up validators
self.dialog_new_plant.ui.addPlant_lineEdit_capacity.setValidator(self.float_positive_validator)
self.dialog_new_plant.ui.addPlant_lineEdit_investmentCost.setValidator(self.float_positive_validator)
self.dialog_new_plant.ui.addPlant_lineEdit_annualCost.setValidator(self.float_positive_validator)
self.dialog_new_plant.ui.addPlant_lineEdit_variableCost.setValidator(self.float_positive_validator)
self.dialog_new_plant.ui.addPlant_lineEdit_emissions.setValidator(self.float_positive_validator)
self.dialog_new_plant.ui.addPlant_lineEdit_efficiency.setValidator(self.float_positive_percentage_valdidator)
# Make it so that only the dialog window can be used when it is open
self.dialog_new_plant.setModal(True)
# Show the dialog window
self.dialog_new_plant.show()
self.dialog_new_plant.exec_()
def addPlant_dialog_accepted(self):
"""
Method is called when the "OK" button is clicked in the addPlant dialog window as it is a standard acceptance button
"""
name = self.dialog_new_plant.ui.addPlant_lineEdit_name.text()
source = self.dialog_new_plant.ui.addPlant_comboBox_source.currentText()
try:
capacity = float(self.dialog_new_plant.ui.addPlant_lineEdit_capacity.text())
efficiency = float(self.dialog_new_plant.ui.addPlant_lineEdit_efficiency.text())/100 # division by 100 because efficiency uses decimal numbers for efficiency
investment_cost = float(self.dialog_new_plant.ui.addPlant_lineEdit_investmentCost.text()) * 10**6
annual_cost = float(self.dialog_new_plant.ui.addPlant_lineEdit_annualCost.text()) *10**6
variable_cost = float(self.dialog_new_plant.ui.addPlant_lineEdit_variableCost.text())
emissions = float(self.dialog_new_plant.ui.addPlant_lineEdit_emissions.text())
# Create plant from input values
new_plant = Plant(source, name, capacity, investment_cost, efficiency, annual_cost, variable_cost,
emissions)
# Add plant to vector of new plants to be added to the next round.
self.game_obj.host.newPlants.append(new_plant)
# Set label
self.main_label_number_new_plants.setText(str(len(self.game_obj.host.newPlants)))
self.warningCountdown("new_plant_success")
except:
self.warningCountdown("new_plant_failed")
# Close window
self.dialog_new_plant.close()
def close_dialog_new_plant_window(self):
"""
The method is called when "Cancel" is clicked as it is a standard rejection button
This method should simply close the dialog window without saving
"""
print("Closing dialog window")
self.dialog_new_plant.close()
def main_handle_button_set_demand(self):
"""
Set the event triggered by button click. Open dialog window showing demand setting.
"""
# Initialize dialog window
self.dialog_set_demand = QtWidgets.QDialog()
# Set GUI wrapper
self.dialog_set_demand.ui = Ui_dialog_setDemand()
# Initialize the design onto the dialog using the wrapper
self.dialog_set_demand.ui.setupUi(self.dialog_set_demand)
# Set up slots for the input
self.dialog_set_demand.ui.dialog_setDemand_plotButton.clicked.connect(self.dialog_set_demand_handle_button_plot)
self.dialog_set_demand.ui.dialog_setDemand_buttonBox.accepted.connect(self.set_demand_dialog_accepted)
self.dialog_set_demand.ui.dialog_setDemand_buttonBox.rejected.connect(self.close_dialog_set_demand_window)
# Enable validators for input fields
self.dialog_set_demand.ui.dialog_setDemand_fixed_lineEdit.setValidator(self.float_positive_validator)
self.dialog_set_demand.ui.dialog_setDemand_variable_lineEdit.setValidator(self.float_positive_validator)
# Make it so that only the dialog window can be used when it is open
self.dialog_set_demand.setModal(True)
# Plot the demand and previous bids if they exist
self.plot_inside_window(self.dialog_set_demand.ui.demand_dialog_verticalLayout)
# Show the dialog window
self.dialog_set_demand.show()
self.dialog_set_demand.exec_()
def dialog_set_demand_handle_button_plot(self):
# Clear the plot if it already exists
try:
self.dialog_set_demand.ui.demand_dialog_verticalLayout.removeWidget(self.static_canvas)
self.static_canvas.deleteLater()
self.static_canvas = None
except:
pass # plot does not exist so ignore the exception
try:
second_demand_fixed = float(self.dialog_set_demand.ui.dialog_setDemand_fixed_lineEdit.text())
second_demand_variable = float(self.dialog_set_demand.ui.dialog_setDemand_variable_lineEdit.text())
self.plot_inside_window(self.dialog_set_demand.ui.demand_dialog_verticalLayout, second_demand_fixed_optional=second_demand_fixed, second_demand_variable_optional=second_demand_variable)
except:
# Plot only the existing demand
self.plot_inside_window(self.dialog_set_demand.ui.demand_dialog_verticalLayout)
# Show some error message
pass
def set_demand_dialog_accepted(self):
# Save inputted values if valid
try:
self.game_obj.host.demand[0] = float(self.dialog_set_demand.ui.dialog_setDemand_fixed_lineEdit.text())
self.game_obj.host.demand[1] = float(self.dialog_set_demand.ui.dialog_setDemand_variable_lineEdit.text())
# Change label
self.main_label_demand.setText("{}-{}Q".format(round(self.game_obj.host.demand[0],1), round(self.game_obj.host.demand[1],1)))
# show sucess message
self.warningCountdown("set_demand_accepted")
except:
# show some error
self.warningCountdown("set_demand_rejected")
pass
# Clear plot
self.clear_set_demand_dialog_plot()
# Close window
self.dialog_set_demand.close()
def close_dialog_set_demand_window(self):
# Clear plot
self.clear_set_demand_dialog_plot()
# Close window
self.dialog_set_demand.close()
def uncheck_buttons(self):
if self.stackedWidget_inner.currentIndex()==0:
self.button_main.setChecked(False)
elif self.stackedWidget_inner.currentIndex()==1:
self.button_players.setChecked(False)
elif self.stackedWidget_inner.currentIndex()==2:
self.button_statistics.setChecked(False)
def transition_handle_button_next(self):
"""
Check current phase and make the correct transition
"""
self.countdown_stop_flag = False
self.game_obj.host.calculate_placements()
if self.game_obj.phase == "End game":
self.drawLeaderboard()
self.stackedWidget.setCurrentIndex(7)
return
elif self.game_obj.phase == "Strategy phase":
# Create endTime
self.game_obj.endTime = endTime(self.game_obj.strategyTime)
elif self.game_obj.phase == "Bidding phase":
self.game_obj.endTime = endTime(self.game_obj.bidTime)
self.clear_transition_results()
data = self.createData("endTime")
self.sendAll(data)
print(len(self.game_obj.host.host_statistics.host_round_results))
if len(self.game_obj.host.host_statistics.host_round_results) > 0:
print("Adding item to combobox")
self.statistics_comboBox_round_results.addItem(
"Year {} round {}".format(self.game_obj.host.host_statistics.host_round_results[-1]["year"],
self.game_obj.host.host_statistics.host_round_results[-1]["round"]))
self.startCountdown()
self.stackedWidget.setCurrentIndex(4)
self.handle_button_main()
self.statistics_tabWidget.setCurrentIndex(0)
if self.game_obj.host.host_statistics.host_round_results:
self.statistics_comboBox_round_results.setEnabled(True)
self.statistics_tabWidget_general_plots.setEnabled(True)
self.statistics_tabWidget_round_results.setEnabled(True)
def drawLobby(self):
try:
self.lobby_label_ip.setText(self.game_obj.getIp())
# Define font to be applied to new widgets
font = QtGui.QFont()
font.setPointSize(18)
# Get players from list
players = self.game_obj.host.players
# Go through every plant in list of plants and create a widget for every element
elements = len(players)
if elements == 0:
self.lobby_empty = QtWidgets.QLabel(self.page_lobby)
self.lobby_empty.setFont(font)
self.lobby_layout_emptyList.addWidget(self.lobby_empty)
self.lobby_empty.setText("Connected players will show up here..")
return
# Creating empty lists for every variable in the plant class.
self.lobby_widget_name = [None] * elements
self.lobby_widget_ready = [None] * elements
self.lobby_widget_kick = [None] * elements
for row, player in enumerate(players):
# Name
self.lobby_widget_name[row] = QtWidgets.QLabel(self.page_lobby)
self.lobby_widget_name[row].setFont(font)
self.lobby_gridLayout.addWidget(self.lobby_widget_name[row], row + 1, 0, 1, 1)
self.lobby_widget_name[row].setText(player.getName())
# motto?
# Status
self.lobby_widget_ready[row] = QtWidgets.QLabel(self.page_lobby)
self.lobby_widget_ready[row].setFont(font)
self.lobby_gridLayout.addWidget(self.lobby_widget_ready[row], row + 1, 1, 1, 1)
self.lobby_widget_ready[row].setText(player.status)
# Kick button
#self.lobby_widget_kick[row] = QtWidgets.QPushButton(self.page_lobby)
self.lobby_widget_kick[row] = QtWidgets.QPushButton("Kick", self)
self.lobby_widget_kick[row].setFont(font)
self.lobby_widget_kick[row].setObjectName("kickbutton_" + str(player.playerNumber))
self.lobby_gridLayout.addWidget(self.lobby_widget_kick[row], row+1, 2, 1, 1)
#self.lobby_widget_kick[row].setText("Kick")
#self.lobby_widget_kick[row].clicked.connect(self.handle_button_kick(player.playerNumber))
#self.lobby_widget_kick[row].clicked.connect(lambda: self.handle_button_kick(player.playerNumber))
self.lobby_widget_kick[row].clicked.connect(self.handle_button_kick)
except Exception as e:
print("Exception called in drawLobby():")
print(e)
#def handle_button_kick(self, playerNumber):
# # This method is used to allow input values in the connected event (the actual handler does not take input values)
# def handler():
# if globals.DEBUGGING:
# print("Kicking player")
# self.removePlayer(playerNumber, notify=True)
# return handler
#def handle_button_kick(self, playerNumber):
def handle_button_kick(self):
# The sender has information about the player associated with the button so extract that information
sender = self.sender()
playerNumber = int(sender.objectName().replace("kickbutton_", ""))
self.removePlayer(playerNumber, notify=True)
def statistics_handle_comboBox(self):
try:
n = self.statistics_combobox_players.currentIndex()
# Update labels for player
if n == -1: # this output means the player was not found
self.statistics_label_money.setText("-")
self.statistics_label_profits.setText("-")
self.statistics_label_emissions.setText("-")
self.statistics_label_co2tax.setText("-")
self.statistics_label_plants.setText("-")
else:
player = self.game_obj.host.getPlayer(n)
self.statistics_label_money.setText(number_to_string(player.money, "MNOK"))
self.statistics_label_profits.setText(number_to_string(player.statistics.profits, "MNOK"))
self.statistics_label_emissions.setText(
number_to_string(player.statistics.emissions, "TON CO<sub>2</sub>eq"))
self.statistics_label_co2tax.setText(number_to_string(player.statistics.taxes, "MNOK"))
self.statistics_label_plants.setText(str(len(player.getPlants())))
except Exception as e:
print("Exception in statistics_handle_comboBox")
print(e)
def clearLobby(self):
# Checks if the list exist and if it does, goes through it
try:
# Iterating through all rows and deleting contents
for row in range(0, len(self.lobby_widget_name)):
# Name
self.lobby_gridLayout.removeWidget(self.lobby_widget_name[row])
self.lobby_widget_name[row].deleteLater()
self.lobby_widget_name[row] = None
# Ready
self.lobby_gridLayout.removeWidget(self.lobby_widget_ready[row])
self.lobby_widget_ready[row].deleteLater()
self.lobby_widget_ready[row] = None
# Kick button
self.lobby_gridLayout.removeWidget(self.lobby_widget_kick[row])
self.lobby_widget_kick[row].deleteLater()
self.lobby_widget_kick[row] = None
except:
self.lobby_layout_emptyList.removeWidget(self.lobby_empty)
self.lobby_empty.deleteLater()
self.lobby_empty = None
def automatic_player_refresh(self):
"""
Player list refreshes automatically in given interval if a flag is set
"""
# A new player has joined since the last time the method was run
if self.player_status_changed:
self.player_status_changed = False
self.clearPlayers()
self.drawPlayers()
def drawPlayers(self):
"""
This method draws the players in the player tab of the main window.
It reads this from the players list in the host class
"""
# Define font to be applied to new widgets
font = QtGui.QFont()
font.setPointSize(18)
# Get player list
players = self.game_obj.host.players
# Go through every plant in list of plants and create a widget for every element
elements = len(players)
if elements == 0:
self.players_empty = QtWidgets.QLabel(self.page_players)
self.players_empty.setFont(font)
self.players_verticalLayout_emptyList.addWidget(self.players_empty)
self.players_empty.setText("There are no players in the game!")
return
# Creating empty lists for every variable in the plant class.
self.players_widget_name = [None] * elements
self.players_widget_motto = [None] * elements
self.players_widget_profits = [None] * elements
self.players_widget_emissions = [None] * elements
self.players_widget_status = [None] * elements
self.players_widget_kick = [None] * elements
# Looping through plants in order to draw information in window
try:
for row, player in enumerate(players):
# Name
self.players_widget_name[row] = QtWidgets.QLabel(self.page_players)
self.players_widget_name[row].setFont(font)
self.players_gridLayout.addWidget(self.players_widget_name[row], row + 1, 0, 1,
1) # Drawing at row+1 because information is drawn in row 0
self.players_widget_name[row].setText(player.firm_name)
# Motto
self.players_widget_motto[row] = QtWidgets.QLabel(self.page_players)
self.players_widget_motto[row].setFont(font)
self.players_gridLayout.addWidget(self.players_widget_motto[row], row + 1, 1, 1, 1)
self.players_widget_motto[row].setText(player.firm_motto)
# profits
self.players_widget_profits[row] = QtWidgets.QLabel(self.page_players)
self.players_widget_profits[row].setFont(font)
self.players_gridLayout.addWidget(self.players_widget_profits[row], row + 1, 2, 1, 1)
self.players_widget_profits[row].setText(number_to_string(player.statistics.profits, "MNOK"))
# emissions
self.players_widget_emissions[row] = QtWidgets.QLabel(self.page_players)
self.players_widget_emissions[row].setFont(font)
self.players_gridLayout.addWidget(self.players_widget_emissions[row], row + 1, 3, 1, 1)
self.players_widget_emissions[row].setText(number_to_string(player.statistics.emissions, "TON CO<sub>2</sub>eq" ))
# status
self.players_widget_status[row] = QtWidgets.QLabel(self.page_players)
self.players_widget_status[row].setFont(font)
self.players_gridLayout.addWidget(self.players_widget_status[row], row + 1, 4, 1, 1)
self.players_widget_status[row].setText(player.status)
# kick
self.players_widget_kick[row] = QtWidgets.QPushButton("Kick player", self)
self.lobby_widget_kick[row].setObjectName("kickbutton_" + str(player.playerNumber))
self.players_widget_kick[row].setFont(font)
self.players_gridLayout.addWidget(self.players_widget_kick[row], row + 1, 5, 1, 1)
#self.players_widget_kick[row].clicked.connect(lambda: self.handle_button_kick(player.playerNumber))
self.players_widget_kick[row].clicked.connect(self.handle_button_kick)
#self.players_widget_kick[row].clicked.connect(self.handle_button_kick(player.playerNumber))
except Exception as e:
print("Exception in drawPlayers(): ")
print(e)
def draw_transition_results(self):
"""
Creates labels for the transition window after bid rounds and shows results from this round.
"""
font = QtGui.QFont()
font.setPointSize(24)
try:
self.transition_formlayout.setLabelAlignment(QtCore.Qt.AlignLeft)
self.transition_formlayout.setFormAlignment(QtCore.Qt.AlignLeft)
# Bids
self.transition_label_bids = QtWidgets.QLabel(self.page_transition)
self.transition_label_bids.setFont(font)
self.transition_label_bids.setText("Bids accepted:")
self.transition_formlayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.transition_label_bids)
self.transition_widget_bids= QtWidgets.QLabel(self.page_transition)
self.transition_widget_bids.setFont(font)
try:
self.transition_widget_bids.setText(str(self.opt.accepted_bids_count) + "/" + str(len(self.opt.bids)))
except:
self.transition_widget_bids.setText("-/-")
self.transition_formlayout.setWidget(0, QtWidgets.QFormLayout.FieldRole,
self.transition_widget_bids)
# Hours
self.transition_label_hours= QtWidgets.QLabel(self.page_transition)
self.transition_label_hours.setFont(font)
self.transition_label_hours.setText("Hours for bid round:")
self.transition_formlayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.transition_label_hours)
self.transition_widget_hours = QtWidgets.QLabel(self.page_transition)
self.transition_widget_hours .setFont(font)
self.transition_widget_hours.setText(str(self.opt.hours_for_bidround) + " hours")
self.transition_formlayout.setWidget(1, QtWidgets.QFormLayout.FieldRole,
self.transition_widget_hours)
# System price
self.transition_label_system_price = QtWidgets.QLabel(self.page_transition)
self.transition_label_system_price.setFont(font)
self.transition_label_system_price.setText("System price:")
self.transition_formlayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.transition_label_system_price)
self.transition_widget_system_price = QtWidgets.QLabel(self.page_transition)
self.transition_widget_system_price.setFont(font)
self.transition_widget_system_price.setText(number_to_string(self.opt.system_price, "NOK/MWh"))
self.transition_formlayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.transition_widget_system_price)
# Demand
self.transition_label_demand = QtWidgets.QLabel(self.page_transition)
self.transition_label_demand.setFont(font)
self.transition_label_demand.setText("Demand:")
self.transition_formlayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.transition_label_demand)
self.transition_widget_demand= QtWidgets.QLabel(self.page_transition)
self.transition_widget_demand.setFont(font)
self.transition_widget_demand.setText(number_to_string(self.opt.demand*self.opt.hours_for_bidround,"GWh"))
self.transition_formlayout.setWidget(3, QtWidgets.QFormLayout.FieldRole,
self.transition_widget_demand)
# CO2 tax
self.transition_label_co2_tax = QtWidgets.QLabel(self.page_transition)
self.transition_label_co2_tax.setFont(font)
self.transition_label_co2_tax.setText("CO<sub>2</sub> tax:")
self.transition_formlayout.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.transition_label_co2_tax)
self.transition_widget_co2_tax= QtWidgets.QLabel(self.page_transition)
self.transition_widget_co2_tax.setFont(font)
self.transition_widget_co2_tax.setText(number_to_string(self.opt.co2_tax, "NOK/(kg CO<sub>2</sub>eq)"))
self.transition_formlayout.setWidget(4, QtWidgets.QFormLayout.FieldRole,
self.transition_widget_co2_tax)
# Gas price
self.transition_label_gas_price= QtWidgets.QLabel(self.page_transition)
self.transition_label_gas_price.setFont(font)
self.transition_label_gas_price.setText("Gas price:")
self.transition_formlayout.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.transition_label_gas_price)
self.transition_widget_gas_price = QtWidgets.QLabel(self.page_transition)
self.transition_widget_gas_price.setFont(font)
self.transition_widget_gas_price.setText(number_to_string(self.opt.gas_price, "NOK/MWh"))
self.transition_formlayout.setWidget(5, QtWidgets.QFormLayout.FieldRole,
self.transition_widget_gas_price)
# Coal price
self.transition_label_coal_price = QtWidgets.QLabel(self.page_transition)
self.transition_label_coal_price.setFont(font)
self.transition_label_coal_price.setText("Coal price:")
self.transition_formlayout.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.transition_label_coal_price)
self.transition_widget_coal_price = QtWidgets.QLabel(self.page_transition)
self.transition_widget_coal_price.setFont(font)
self.transition_widget_coal_price.setText(number_to_string(self.opt.coal_price, "NOK/MWh"))
self.transition_formlayout.setWidget(6, QtWidgets.QFormLayout.FieldRole,
self.transition_widget_coal_price)
# gas production
self.transition_label_gas_production = QtWidgets.QLabel(self.page_transition)
self.transition_label_gas_production.setFont(font)
self.transition_label_gas_production.setText("Gas production:")
self.transition_formlayout.setWidget(7, QtWidgets.QFormLayout.LabelRole, self.transition_label_gas_production)
self.transition_widget_gas_production = QtWidgets.QLabel(self.page_transition)
self.transition_widget_gas_production.setFont(font)
self.transition_widget_gas_production.setText(number_to_string(self.opt.total_gas_production, "GWh"))
self.transition_formlayout.setWidget(7, QtWidgets.QFormLayout.FieldRole,
self.transition_widget_gas_production)
# Coal production
self.transition_label_coal_production = QtWidgets.QLabel(self.page_transition)
self.transition_label_coal_production.setFont(font)
self.transition_label_coal_production.setText("Coal production:")
self.transition_formlayout.setWidget(8, QtWidgets.QFormLayout.LabelRole, self.transition_label_coal_production)
self.transition_widget_coal_production= QtWidgets.QLabel(self.page_transition)
self.transition_widget_coal_production.setFont(font)
self.transition_widget_coal_production.setText(number_to_string(self.opt.total_coal_production, "GWh"))
self.transition_formlayout.setWidget(8, QtWidgets.QFormLayout.FieldRole,
self.transition_widget_coal_production)
except Exception as e:
print("Exception in draw_transition_results:")
print(e)
def draw_statistics_leaderboards(self):
# Define font to be applied to new widgets
font = QtGui.QFont()
font.setPointSize(13)
# Get sorted player list and store it temporarily in case someone leaves game before the statistics tab is left
# Sliced list copy is used so that players_temp is not changed during operation
self.players_temp = self.game_obj.host.get_players_by_placement()[:]
elements = len(self.players_temp)
if elements == 0:
self.players_empty = QtWidgets.QLabel(self.page_statistics)
self.players_empty.setFont(font)
self.statistics_verticalLayout_leaderboards.addWidget(self.players_empty)
self.players_empty.setText("There are no players in the game!")
return
# Creating empty lists for every variable in the plant class.
self.players_widget_placement = [None] * elements
self.players_widget_name = [None] * elements
self.players_widget_profits = [None] * elements
# Looping through plants in order to draw information in window
try:
for row, player in enumerate(self.players_temp):
# Placement
self.players_widget_placement[row] = QtWidgets.QLabel(self.page_statistics)
self.players_widget_placement[row].setFont(font)
self.statistics_gridLayout.addWidget(self.players_widget_placement[row], row + 1, 0, 1,
1) # Drawing at row+1 because information is drawn in row 0
self.players_widget_placement[row].setText(str(player.statistics.placement))
# Name
self.players_widget_name[row] = QtWidgets.QLabel(self.page_statistics)
self.players_widget_name[row].setFont(font)
self.statistics_gridLayout.addWidget(self.players_widget_name[row], row + 1, 1, 1,
1) # Drawing at row+1 because information is drawn in row 0
self.players_widget_name[row].setText(player.firm_name)
# Profits
self.players_widget_profits[row] = QtWidgets.QLabel(self.page_statistics)
self.players_widget_profits[row].setFont(font)
self.statistics_gridLayout.addWidget(self.players_widget_profits[row], row + 1, 2, 1,
1) # Drawing at row+1 because information is drawn in row 0
self.players_widget_profits[row].setText(number_to_string(player.statistics.profits, "MNOK"))
except Exception as e:
print("Exception in draw_statistics_leaderboard")
print(e)
def clear_statistics_leaderboards(self):
# Checks if the list exist and if it does, goes through it
try:
# If the empty widget exists remove it
self.statistics_verticalLayout_leaderboards.removeWidget(self.players_empty)
self.players_empty.deleteLater()
self.players_empty = None
except:
# If it does not it means there are players so remove them instead
for row in range(len(self.players_temp)):
# Placement
self.statistics_gridLayout.removeWidget(self.players_widget_placement[row])
self.players_widget_placement[row].deleteLater()
self.players_widget_placement[row] = None
# Name
self.statistics_gridLayout.removeWidget(self.players_widget_name[row])
self.players_widget_name[row].deleteLater()
self.players_widget_name[row] = None
# Profits
self.statistics_gridLayout.removeWidget(self.players_widget_profits[row])
self.players_widget_profits[row].deleteLater()
self.players_widget_profits[row] = None
def clear_transition_results(self):
try:
#bids
self.transition_widget_bids.deleteLater()
self.transition_widget_bids = None
self.transition_label_bids.deleteLater()
self.transition_label_bids = None
# hours
self.transition_widget_hours.deleteLater()
self.transition_widget_hours = None
self.transition_label_hours.deleteLater()
self.transition_label_hours = None
# Systemprice
self.transition_widget_system_price.deleteLater()
self.transition_widget_system_price = None
self.transition_label_system_price.deleteLater()
self.transition_label_system_price = None
# demand
self.transition_widget_demand.deleteLater()
self.transition_widget_demand= None
self.transition_label_demand.deleteLater()
self.transition_label_demand= None
# co2 tax
self.transition_widget_co2_tax.deleteLater()
self.transition_widget_co2_tax= None
self.transition_label_co2_tax.deleteLater()
self.transition_label_co2_tax= None
# gas price
self.transition_widget_gas_price.deleteLater()
self.transition_widget_gas_price= None
self.transition_label_gas_price.deleteLater()
self.transition_label_gas_price= None
# coal price
self.transition_widget_coal_price.deleteLater()
self.transition_widget_coal_price= None
self.transition_label_coal_price.deleteLater()
self.transition_label_coal_price= None
# gas production
self.transition_widget_gas_production.deleteLater()
self.transition_widget_gas_production= None
self.transition_label_gas_production.deleteLater()
self.transition_label_gas_production = None
# coal production
self.transition_widget_coal_production.deleteLater()
self.transition_widget_coal_production= None
self.transition_label_coal_production.deleteLater()
self.transition_label_coal_production= None
except:
pass # Results were not drawn so ignore the clearing
def statistics_round_results_handle_comboBox(self):
"""
Triggered by a change in the current index of the combobox for the bid results
Triggers: player enters another item in the combobox
player enters info tab
"""
try:
# Clear the current round results but only if some round result has been written
if self.round_results_drawn:
self.clear_statistics_round_results()
self.round_results_drawn = False
# Draw the round results
self.draw_statistics_round_results() # round_results_drawn flag set if drawing is successful
except Exception as e:
print("Exception in statistics_round_results_handle_comboBox()")
print(e)
def draw_statistics_round_results(self):
# bids accepted
# hours for bid round
# system price
# demand
# production
# co2 tax
# gas price
# gas production
# coal price
# coal production
# demand/player plot
# pv production
# pv market share
# gas production
# gas market share
# coal production
# coal market share
font = QtGui.QFont()
font.setPointSize(12)
try:
n = self.statistics_comboBox_round_results.currentIndex()
result = self.game_obj.host.host_statistics.host_round_results[n]
# Set labels
# for general
self.statistics_round_results_label_bids_accepted.setText(str(result["bids_accepted"]) + "/" + str(result["number_of_bids"]))
self.statistics_round_results_label_hours_for_bid_round.setText(number_to_string(result["hours_for_bid_round"], "hours"))
self.statistics_round_results_label_system_price.setText(number_to_string(result["system_price"], "NOK/MW"))
self.statistics_round_results_label_demand.setText(number_to_string(result["demand"], "MW"))
self.statistics_round_results_label_production.setText(number_to_string(result["production"], "GWh"))
self.statistics_label_co2tax.setText(number_to_string(result["co2_tax"], "NOK/(CO<sub>2</sub>eq)"))
self.statistics_round_results_label_pv_production.setText(number_to_string(result["pv_production"], "GWh"))
self.statistics_round_results_label_gas_price.setText(number_to_string(result["gas_price"], "NOK/MWh"))
self.statistics_round_results_label_gas_production.setText(number_to_string(result["gas_production"], "GWh"))
self.statistics_round_results_label_coal_price.setText(number_to_string(result["coal_price"], "NOK/MWh"))
self.statistics_round_results_label_coal_production.setText(number_to_string(result["coal_production"], "GWh"))
# labels for sources
# Calculate the source market shares
if result["production"] == 0:
self.pv_market_share = 0
self.gas_market_share = 0
self.coal_market_share = 0
else:
if result["pv_production"] == 0:
self.pv_market_share = 0
else:
self.pv_market_share = result["pv_production"] / result["production"]
if result["gas_production"] == 0:
self.gas_market_share = 0
else:
self.gas_market_share = result["gas_production"] / result["production"]
if result["coal_production"] == 0:
self.coal_market_share = 0
else:
self.coal_market_share = result["coal_production"] / result["production"]
# Set production labels
self.statistics_round_results__sources_label_pv_production.setText(number_to_string(result["pv_production"], "GWh"))
self.statistics_round_results_sources_label_gas_production.setText(
number_to_string(result["gas_production"], "GWh"))
self.statistics_round_results_sources_label_coal_production.setText(