Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
825 lines (673 loc) · 27.1 KB
/
Copy pathmain.py
File metadata and controls
825 lines (673 loc) · 27.1 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
#!/usr/bin/env python3
# coding: utf-8
#
# $Id: main.py 1571.develop.14 $
# SPDX-License-Identifier: BSD-2-Clause
"""
même GUI que tk_mockup02, mais avec SimpleGUI
python3 >= 3.7
"""
import FreeSimpleGUI as sg
import constants
import core
import sgui
from itertools import groupby
from pprint import pprint
# because of '.db' between p3.7 and newer:
from platform import python_version
from packaging.version import Version
# Globals
MAXW = constants.MAXWIDTH
MAXH = constants.MAXHEIGHT
MAXP = constants.MAXPARSEC
COLORS = constants.COLORS
fname = constants.FILENAME # needed for blind save
overview = ' '.join(constants.OVERVIEW)
msg_overview = '\n'.join(['pySpaceTrader', constants.VERSION, overview])
univers = [] # global container for game objects
target = [] # items composing the 'target'
limite = [] # item composing the limit circle
# define GUI, using sgui.py layout
# create window
window = sg.Window('pySpaceTrader',
sgui.final_layout,
auto_size_buttons=False,
resizable=True)
# simplify call for map objects
graph = window['-GRAPH-']
def buy_cargo(facture):
""" load into cargo pods whats in the incoming invoice """
# unpack incoming invoice
good_type = facture.good_type
good_price = facture.good_value
qty = facture.quantity
cargo_value = facture.total_value
# TODO if cargo_value is > captain.account.cash, propose a loan
# and start computing interests (bank account)
empty_pod = [x for x in captain.ship.cargo.keys() if captain.ship.cargo[x]['type'] is None]
available_cargo = len(empty_pod)
# print(f'pod(s): {empty_pod}')
# print(f'avail: {available_cargo}')
if qty > available_cargo:
sg.popup_error("Cannot buy, not enought cargo space!")
else:
for index in range(empty_pod[0], empty_pod[0] + qty):
captain.ship.cargo[index]['type'] = good_type
captain.ship.cargo[index]['value'] = good_price
available_cargo -= 1
captain.location.price_slip[good_type][2] -= 1
captain.account.log.append(facture)
# print(f'{captain.account.log}')
captain.account.cash -= cargo_value
update_trading(window['-LOC-TABLE-'], captain.location)
update_cargo_board()
update_docks_board(captain.location)
update_bank()
def buy_ship(idx):
""" FIXME replace current ship by new one """
new_ship = captain.location.shipyard[idx]
old_ship = captain.ship
# transfert fuel (only if new.reservoir >= old.reservoir)
if old_ship.reservoir <= new_ship.reservoir:
new_ship.reservoir = old_ship.reservoir
# transfert cargo
for index in range(old_ship.model['cargo']):
if old_ship.cargo[index]['type'] is not None:
new_ship.cargo[index]['type'] = old_ship.cargo[index]['type']
new_ship.cargo[index]['value'] = old_ship.cargo[index]['value']
# transfert gadgets properly (vice-versa)
new_ship.gadgets = old_ship.gadgets
# TODO transfert crew(s)
invoice = core.Transaction('-', new_ship.model['model'], new_ship.model['price'], 1)
captain.ship = new_ship
captain.location.shipyard[idx] = old_ship
captain.account.cash -= invoice.total_value
# TODO/FIXME old ship should be selled at a second hand price
captain.account.log.append(invoice)
update_cargo_board()
update_docks_board(captain.location)
update_bank()
update_captain_ship()
update_shipyard(captain.location)
def draw_limite(point, rayon=None):
""" erase and redraw the parsec limit
point: Point object or position attribute
rayon: int (or None)
"""
if rayon is None:
rayon = int(captain.ship.model['fuel'] * MAXP)
for item in limite:
# erase previous circle (if any)
graph.delete_figure(item)
limite.clear()
limite.append(graph.draw_circle(point.position, rayon, line_color=COLORS['limit']))
def draw_map(rayon=None):
""" draw the Galactic Map
rayon: int (or None)
"""
graph.erase()
for planete in planetes:
x, y = planete.position
if planete.homeworld:
graph.draw_circle((x, y),
2,
fill_color=COLORS['homeworld'],
line_color=COLORS['homeworld'])
if planete.ships is not None:
graph.draw_circle((x+3, y+3),
1,
line_color=COLORS['shipyard'])
if planete.moon is not False:
graph.draw_circle((x-3, y+3),
1,
line_color=COLORS['moon'])
elif planete.visited:
graph.draw_circle((x, y),
2,
fill_color=COLORS['visited'],
line_color=COLORS['visited'])
if planete.ships is not None:
graph.draw_circle((x+3, y+3),
1,
line_color=COLORS['shipyard'])
if planete.moon is not False:
graph.draw_circle((x-3, y+3),
1,
line_color=COLORS['moon'])
else:
graph.draw_circle((x, y),
2,
fill_color=COLORS['default'],
line_color=COLORS['default'])
# draw and update Captain location
location = captain.location
# trace fuel limit
draw_limite(location, rayon=captain.ship.reservoir)
if captain.destination:
location = captain.destination
draw_target(location)
def draw_target(pos):
""" erase and redraw the target
pos: Planet or Point object (with x, y attributes)
"""
for item in target:
graph.delete_figure(item)
target.clear()
target.append(graph.draw_line((pos.x, 0),
(pos.x, MAXH),
color=COLORS['target']))
target.append(graph.draw_line((0, pos.y),
(MAXW, pos.y),
color=COLORS['target']))
def load_game():
""" load saved game """
global univers, planetes, captain, fname
# TODO: use try/except
# replace -> AttributeError
# empty -> error? OSError?
# if ".db" TypeError?
if Version(python_version()) >= Version('3.9'):
try:
fname = sg.popup_get_file('Saved game to open',
default_extension='.db',
file_types=(('saved game(s)', '*.db'),
('all files', '*.*')),
) # .replace('.db', '')
except AttributeError:
pass
else:
try:
fname = sg.popup_get_file('Saved game to open',
default_extension='.db',
file_types=(('saved game(s)', '*.db'),
('all files', '*.*')),
).replace('.db', '')
except AttributeError:
pass
if fname == "":
print("empty filename!")
load_game()
if Version(python_version()) >= Version('3.9'):
if ".db" not in fname:
fname = fname + ".db"
univers = core.load_file(fname=fname)
planetes = [x for x in univers if isinstance(x, core.Planet)]
_toto = [x for x in univers if isinstance(x, core.Captain)]
captain = _toto[0]
draw_map()
update_gui()
def new_game():
""" new game """
global univers, planetes, captain, fname
# create universe
univers = core.create_universe()
# set planets apart
planetes = [x for x in univers if isinstance(x, core.Planet)]
# pprint(planetes)
# set Captain apart too
_toto = [x for x in univers if isinstance(x, core.Captain)]
captain = _toto[0]
fname = captain.homeworld.name
# pprint(captain.__dict__)
draw_map()
update_gui()
def next_turn():
""" compute next turn """
try:
# distance = core.get_distance(captain.location.position, captain.destination.position)
distance = captain.location.distance(captain.destination)
if captain.ship.reservoir > 0:
# calculate rayon loss
rayon = captain.ship.reservoir - distance
if rayon <= 0:
captain.ship.reservoir = 0
rayon = 0
else:
captain.ship.reservoir = rayon
# update planete.visited to True
captain.destination.visited = True
# switch captain position
captain.location = captain.destination
captain.destination = None
# pprint(captain.ship.cargo)
# update gui
draw_map(rayon=rayon)
update_gui()
# if there is no destination set ->AttributeError
except AttributeError:
sg.popup("'Set a destination first.")
def on_click(position):
""" redraw graph with new clicked Point or selected Planet"""
clicked_position = position
for planete in planetes:
if planete.distance(position) <= 5:
position = core.Point(planete.x, planete.y)
clicked_position = planete
if clicked_position.distance(captain.location) <= captain.ship.reservoir:
set_destination(clicked_position)
else:
window['-NEXT-TURN-'].update(disabled=True)
update_affiche(planete)
draw_target(position)
window['-IN-CLIC-'].update(value=f'Detected clic in X={position.x}, Y={position.y}')
def refuel():
""" refuel the captain.ship according to captain.account.cash,
captain.ship.reservoir and planete.fuel_price
"""
capacity = int(captain.ship.model['efficiency'] * MAXP)
quantity = captain.location.price_slip['fuel'][2]
fuel_price = captain.location.price_slip['fuel'][1]
reserve = captain.ship.reservoir
if reserve < capacity:
fuel_deficit = capacity - reserve
if fuel_deficit > quantity:
fuel_deficit = quantity
fuel_invoice = core.Transaction('-', 'fuel', fuel_price, fuel_deficit)
if fuel_invoice.total_value <= captain.account.cash:
captain.account.cash -= fuel_invoice.total_value
captain.ship.reservoir = reserve + fuel_deficit
captain.account.log.append(fuel_invoice)
captain.location.price_slip['fuel'][2] -= fuel_deficit
draw_limite(captain.location, captain.ship.reservoir)
update_trading(window['-LOC-TABLE-'], captain.location)
update_affiche(captain)
update_cargo_board()
update_planet_selector()
update_bank()
update_shipyard(captain.location)
window['-REFUEL-'].update(disabled=True)
else:
# FIXME/TODO: how much can I buy?
# and buy only that much or else 'not enought Cr'
sg.popup("Cannot buy fuel: not enought credit")
else:
sg.popup("Cannot buy fuel: full capacity")
def save():
""" save into the previously open/selected file: fname """
global univers, fname
# print(f"{fname}")
if Version(python_version()) >= Version('3.9'):
if ".db" not in fname:
fname = fname + ".db"
else:
if ".db" in fname:
fname = fname.rstrip('.db')
core.save_file(univers, fname=fname)
def save_as():
""" save to a new file """
global univers, captain, fname
# print(f"{fname}")
try:
fname = sg.popup_get_file('Save game to file',
save_as=True,
default_extension='',
file_types=(('saved game(s)', '*.db'),
('all files', '*.*')),
).replace('.db', '')
except AttributeError:
pass
if not fname:
fname = captain.homeworld.name
core.save_file(univers, fname=fname)
def sell_cargo(pods, dump=False):
""" sell (or dump) good from list of pods """
# pprint(pods)
ordlist = sorted(pods, key=lambda x: x[1]) # sort on good_type
for key, value in groupby(ordlist, lambda x: [x[1], x[2]]): # sort on [good_type, good_value]
idx = []
valeurs = list(value)
for items in valeurs:
idx.append(items[0])
good_type = key[0]
good_price = captain.location.price_slip[good_type][0]
qty = len(idx)
facture = core.Transaction('+', good_type, good_price, qty)
if not dump:
captain.account.log.append(facture)
captain.account.cash += facture.total_value
captain.location.price_slip[good_type][2] += qty
for index in idx:
captain.ship.unload_cargo(index)
update_gui()
def set_destination(pos):
""" save clicked/selected position into captain.destination """
global captain
try:
distance = captain.location.distance(pos)
if distance == 0:
sg.popup("Cannot set destination: Same as current location.")
elif distance < captain.ship.reservoir:
captain.destination = pos
# update Trading tab
window['-IN-PLNT-SELECTOR-'].update(value=captain.destination.name)
window['-DEST-TITLE-'].update(value=f'Destination: {captain.destination.name}')
update_trading(window['-DEST-TABLE-'], captain.destination)
update_profit(captain.destination)
# allow next_turn()
window['-NEXT-TURN-'].update(disabled=False)
elif distance > int(captain.ship.model['fuel'] * MAXP):
sg.popup("Cannot set destination: Too far.")
else:
sg.popup("Cannot set destination: Not enought fuel.")
except AttributeError:
sg.popup("Cannot set destination: Same as current location.")
def show_destination():
""" set/draw target on destination """
if captain.destination:
planete = captain.destination
draw_target(planete)
update_affiche(planete)
# update_gui()
else:
sg.popup("Cannot show destination: None set.")
def show_homeworld():
""" set target on homeworld """
for planete in planetes:
if planete.homeworld:
draw_target(planete)
update_affiche(planete)
# update_gui()
def show_location():
""" set target on actual captain.location """
planete = captain.location
draw_target(planete)
update_affiche(planete)
# update_gui()
def update_affiche(objet):
""" update text in labels
objet: Planet() or Captain()
"""
if isinstance(objet, core.Planet):
_description = ''.join([objet.name,
': ',
str(objet.position),
'\n',
'\n'.join(objet.gov)])
window['-IN-PLANET-'].update(_description)
window['-IN-DSTCE-'].update(value=f'Distance: {captain.location.distance(objet):.2f}')
elif isinstance(objet, core.Captain):
_description = ''.join([objet.name,
' from ',
objet.homeworld.name,
])
window['-IN-CAPTAIN-'].update(_description)
_balance = objet.balance
window['-IN-BALANCE-'].update(value=f'{_balance:.2f}')
_reserve = objet.ship.reservoir
window['-IN-RESERVE-'].update(value=f'{_reserve:.2f}')
def update_bank():
""" update bank table with account.log """
window['-BANK-TABLE-'].update(values=captain.account.display())
def update_buy_goods(planet):
""" update values in combo's goods Cargo frame """
_key_list = []
for key, value in planet.price_slip.items():
# if no stock, don't bother adding to picklist
if value[2] != 0:
_key_list.append(key)
window['-IN-GOODS-'].update(values=_key_list)
def update_buy_qty(good=None):
""" update picklist in combo's quantity Cargo frame """
# FIXME: clear=False, instead of good=None
# redo this algo
_none_cargo = [x for x in captain.ship.cargo.keys() if captain.ship.cargo[x]['type'] is None]
avail_pods = len(_none_cargo)
if good is not None:
_qty_max = captain.location.price_slip[good][2]
# _value_list = []
if _qty_max < avail_pods:
_value_list = list(range(1, _qty_max + 1))
else:
_value_list = list(range(1, avail_pods + 1))
else:
if avail_pods != 0:
_value_list = list(range(1, avail_pods + 1))
else:
_value_list = ''
window['-IN-QTY-'].update(values=_value_list)
def update_captain_ship():
""" display ship characteristics """
window['-CPTN-SHIP-MODEL-'].update(value=f"Ship: {captain.ship.model['model']} ")
window['-CPTN-SHIP-PODS-'].update(value=f"{captain.ship.model['cargo']}")
window['-CPTN-SHIP-WPNS-'].update(value=f"{captain.ship.model['weapon']}")
window['-CPTN-SHIP-SHLDS-'].update(value=f"{captain.ship.model['shield']}")
window['-CPTN-SHIP-GDGT-'].update(value=f"{captain.ship.model['gadget']}")
window['-CPTN-SHIP-CREW-'].update(value=f"{captain.ship.model['crew']}")
window['-CPTN-SHIP-HULL-'].update(value=f"{captain.ship.model['hull']}")
def update_cargo_board():
""" update Cargo board informations GUI element """
pods = 0
tbl_pod = []
total_pods = len(captain.ship.cargo)
total_value = 0
for key in captain.ship.cargo.keys():
if captain.ship.cargo[key]['type']:
pods += 1
total_value += captain.ship.cargo[key]['value']
tbl_pod.append([key,
captain.ship.cargo[key]['type'],
captain.ship.cargo[key]['value']])
window['-IN-BD-CASH-'].update(value=f'{captain.account.cash:.2f}')
window['-IN-BD-CARGO-'].update('/'.join([str(pods),
str(total_pods)]))
window['-IN-BD-VALUE-'].update(value=f'{total_value:.2f}')
window['-MANIFEST-'].update(values=tbl_pod)
if pods == total_pods:
window['-BUY-CARGO-'].update(disabled=True)
def update_docks_board(planet):
""" update values in Docks frame's elements """
update_buy_goods(planet)
update_buy_qty(good=None)
window['-IN-INVOICE-'].update(value='')
def update_gui():
""" update all GUI elements """
update_affiche(captain)
update_affiche(captain.location)
capacity = int(captain.ship.model['efficiency'] * MAXP)
if (captain.ship.reservoir < capacity) and (captain.location.price_slip['fuel'][2] != 0):
window['-REFUEL-'].update(disabled=False)
else:
window['-REFUEL-'].update(disabled=True)
update_planet_selector()
if captain.destination:
# window['-SETDEST-'].update(disabled=True)
window['-NEXT-TURN-'].update(disabled=False)
window['-DEST-TITLE-'].update(value=f'Destination: {captain.destination.name}')
update_trading(window['-DEST-TABLE-'], captain.destination)
else:
# window['-SETDEST-'].update(disabled=False)
window['-NEXT-TURN-'].update(disabled=True)
# clear trading tab -DEST-TABLE-
window['-DEST-TITLE-'].update(value='Destination:')
update_trading(window['-DEST-TABLE-'])
update_profit()
update_profit_row_color(None)
window['-LOC-TITLE-'].update(value=f'Current location: {captain.location.name}')
update_trading(window['-LOC-TABLE-'], captain.location)
update_buy_goods(captain.location)
update_cargo_board()
# pprint(captain.account.log)
update_bank()
update_captain_ship()
update_shipyard(captain.location)
def update_invoice(good_type, qty):
""" calculate the invoice, update the relevant GUI elements
return a core.Transaction() object
"""
good_price = captain.location.price_slip[good_type][1]
invoice = core.Transaction('-', good_type, good_price, qty)
cargo_value = invoice.total_value
if cargo_value > captain.account.cash:
window['-IN-INVOICE-'].update(value=f'{cargo_value:.2f}', text_color='red')
window['-BUY-CARGO-'].update(disabled=True)
else:
window['-IN-INVOICE-'].update(value=f'{cargo_value:.2f}', text_color='black')
window['-BUY-CARGO-'].update(disabled=False)
# print(f'{invoice}')
return invoice
def update_planet_selector():
""" update the planet combo selector """
# do NOT add captain.location.position to the list
lst_selectable_names = []
lst_nearest_planets = []
for planete in planetes:
if planete.distance(captain.location) <= captain.ship.reservoir:
if planete is not captain.location:
lst_nearest_planets.append(planete)
for item in lst_nearest_planets:
lst_selectable_names.append(item.name)
window['-IN-PLNT-SELECTOR-'].update(values=lst_selectable_names)
def update_profit(planet=None):
""" update profit GUI element """
if planet is None:
window['-PROFIT-TABLE-'].update(values=[[0]])
else:
valeurs = core.calculate_profit_pod(captain.location, planet)
window['-PROFIT-TABLE-'].update(values=valeurs)
def update_profit_row_color(selected=None):
""" show 'selected' colors on all 3 row of trading layout
-LOC-TABLE-, -PROFIT-TABLE-, -DEST-TABLE-
"""
if selected is None:
window['-LOC-TABLE-'].update(select_rows=None)
window['-PROFIT-TABLE-'].update(select_rows=None)
window['-DEST-TABLE-'].update(select_rows=None)
else:
window['-LOC-TABLE-'].update(select_rows=selected)
window['-PROFIT-TABLE-'].update(select_rows=selected)
window['-DEST-TABLE-'].update(select_rows=selected)
def update_shipyard(planete):
""" update shipyard tab: if there is any ship in planete.shipyard,
show them, else 'None'
"""
window['-AVAIL-FUEL-'].update(f"{planete.price_slip['fuel'][2]:.2f}")
if planete.tech_level < 5:
window['-SHIP-TABLE-'].update(values=[['None', 0, 0, 0, 0, 0, 0, 0, 0, None, 0]])
else:
if planete.shipyard:
ships_list = []
for item in planete.shipyard:
ships_list.append(item.display())
window['-SHIP-TABLE-'].update(values=ships_list)
window['-PLNT-SHIPYD-LOC-'].update(planete.name)
else:
# no shipyard
window['-SHIP-TABLE-'].update(values=[['None', 0, 0, 0, 0, 0, 0, 0, 0, None, 0]])
window['-PLNT-SHIPYD-LOC-'].update(planete.name)
def update_trading(element, planet=None):
""" update price slip in the Trading tab tables """
if planet is None:
element.update(values=[['None', 0, 0, 0]])
else:
price_list = core.slip_list(planet.price_slip)
element.update(values=price_list)
if __name__ == '__main__':
# Event Loop
while True:
event, values = window.read()
# debug:
print(event, values)
if event == sg.WIN_CLOSED or event == 'Exit':
break
elif event == 'New':
new_game()
elif event == 'Load':
load_game()
elif event == 'Save':
save()
elif event == 'Save_as':
save_as()
elif event == '-GRAPH-':
if not univers:
sg.popup_error("No game loaded!")
else:
x, y = values['-GRAPH-']
position = core.Point(x, y)
on_click(position)
elif event == '-HOMEWORLD-':
if not univers:
sg.popup_error("No game loaded!")
else:
show_homeworld()
elif event == '-LOCATION-':
if not univers:
sg.popup_error("No game loaded!")
else:
show_location()
elif event == '-DESTINATION-':
if not univers:
sg.popup_error("No game loaded!")
else:
show_destination()
elif event == '-IN-PLNT-SELECTOR-':
name_planet = values['-IN-PLNT-SELECTOR-']
for planete in planetes:
if name_planet == planete.name:
on_click(planete)
elif event == '-REFUEL-' or event == '-REFILL-':
if not univers:
sg.popup_error("No game loaded!")
else:
refuel()
elif event == '-NEXT-TURN-':
if not univers:
sg.popup_error("No game loaded!")
else:
next_turn()
elif event == '-IN-GOODS-':
update_buy_qty(values['-IN-GOODS-'])
window['-IN-INVOICE-'].update(value='', text_color='black')
elif event == '-IN-QTY-':
if values['-IN-QTY-'] is None:
window['-BUY-CARGO-'].update(disabled=True)
else:
invoice = update_invoice(values['-IN-GOODS-'], values['-IN-QTY-'])
elif event == '-BUY-CARGO-':
buy_cargo(invoice)
elif event == '-SELL-':
sell_cargo(values['-MANIFEST-'])
elif event == '-SELL-ALL-':
sell_cargo(window['-MANIFEST-'].get_list_values())
elif event == '-DUMP-':
sell_cargo(values['-MANIFEST-'], dump=True)
elif event == '-SHIP-TABLE-':
# event cleared after or in update_shipyard()
try:
idx = int(values['-SHIP-TABLE-'][0])
except IndexError:
idx = 0
if captain.location.shipyard:
ship_price = captain.location.shipyard[idx].model['price']
if ship_price <= captain.account.cash:
window['-BUY-SHIP-'].update(disabled=False)
else:
window['-BUY-SHIP-'].update(disabled=True)
elif event == '-BUY-SHIP-':
buy_ship(int(values['-SHIP-TABLE-'][0]))
# composed events (clicked ones)
elif isinstance(event, tuple):
# update color of selected row on all 3 trading tables
if event[0] == '-LOC-TABLE-' and event[1] == '+CLICKED+':
idx = values['-LOC-TABLE-']
update_profit_row_color(idx)
elif event[0] == '-PROFIT-TABLE-' and event[1] == '+CLICKED+':
idx = values['-PROFIT-TABLE-']
update_profit_row_color(idx)
elif event[0] == '-DEST-TABLE-' and event[1] == '+CLICKED+':
idx = values['-DEST-TABLE-']
update_profit_row_color(idx)
elif event[0] == '-SHIP-TABLE-' and event[1] == '+CLICKED+':
# event cleared after or in update_shipyard()
try:
idx = int(values['-SHIP-TABLE-'][0])
except IndexError:
idx = 0
if captain.location.shipyard:
ship_price = captain.location.shipyard[idx].model['price']
if ship_price <= captain.account.cash:
window['-BUY-SHIP-'].update(disabled=False)
else:
window['-BUY-SHIP-'].update(disabled=True)
elif event == 'About':
sg.popup(f'{msg_overview}')
window.close()