-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameBoard.py
1180 lines (1056 loc) · 50.1 KB
/
GameBoard.py
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
""" Main class for the client """
import pyglet
import os
from Deck import Deck
from PodSixNet.Connection import connection, ConnectionListener
import cPickle as pickle
from pyglet.sprite import Sprite
from pyglet import window
from pyglet import clock
from pyglet import font
from Token import Token
from TokenList import TokenList
from camera import Camera
from constants import *
from vec2 import Vec2
from pyglet.gl import *
from act import Act
from MessageList import MessageList
from MovableStat import MovableStat
from MovableStatList import MovableStatList
from random import randint
import kytten
from DeckList import DeckList
from pprint import pprint
VERSION = 0.4
pyglet.options['debug_gl'] = False
class GameBoard(window.Window, ConnectionListener):
""" GameBoard is the main client / class for the game
and will maintain the game state """
is_event_handler = True #: enable pyglet's events
def __init__(self, *args, **kwargs):
""" init """
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_default_screen()
template = pyglet.gl.Config(double_buffer=True)
config = screen.get_best_config(template)
context = config.create_context(None)
window.Window.__init__(self, resizable=True, width=WINWIDTH, height=WINHEIGHT, caption="REZD:" + str(VERSION), context=context)
self.camera = Camera(self)
#host = "localhost"
self.host = "localhost"
#self.host = "192.168.0.101"
#self.host = "24.138.79.5"
self.port = 1234
self.connected = False
self.players = {}
self.cards = {} #cards from the network
self.tokens = {}
self.acts = {}
self.mss = {}
self.statusLabel = "Not Connected"
self.playersLabel = "0 players"
self.baseDeck = Deck() # used to lookup cards basically a reference instead of using a database. Basically don't remove / add cards
self.baseDeck.populate('assets/cardlist.xml')
self.playerDeck = Deck() # the actual decks we can remove cards from this one
self.localCardList = Deck()
self.hand = Deck()
self.opponentsHandSize = 0
self.tokenList = TokenList()
self.HQuuid = None
self.RNDuuid = None
self.ARCHIVEuuid = None
self.movableStatList = MovableStatList()
self.mouseposx = 0
self.mouseposy = 0
self.selected = None
self.selectedToken = None
self.selectedMS = None
self.zoomedCard = None
self.drawing = False
self.nickname = None
self.deckBrowserCard = None
self.ML = MessageList()
self.decoded = pyglet.text.decode_text(self.ML.getMessages())
self.scroll_area = pyglet.text.layout.ScrollableTextLayout(self.decoded, 500, 210, multiline=True)
self.scroll_area.x = 50
self.scroll_area.y = 200
# kytten stuff
self.theme = kytten.Theme(os.path.join(os.getcwd(), 'theme'), override={
"gui_color": [64, 128, 255, 255],
"font_size": 14
})
self.theme2 = kytten.Theme(self.theme, override={
"gui_color": [61, 111, 255, 255],
"font_size": 12
})
self.decklist = DeckList()
self.menu_showing = False
self.action_menu = False
self.chat_menu = False
self.archives = None
#___________________________________MAIN______________________________________________________#
def main_loop(self):
""" Where the action happens """
self.batch = pyglet.graphics.Batch()
self.batch2 = pyglet.graphics.Batch()
self.batch3 = pyglet.graphics.Batch()
self.register_event_type('on_update')
pyglet.clock.schedule(self.update_kytten)
self.menu = self.generateMenu() #part of batch3 rendering
self.create_network_dialog()
self.fps = pyglet.clock.ClockDisplay()
pyglet.font.add_file('assets/myfont.ttf')
while not self.has_exit: # main loop
self.push_handlers(self.on_mouse_release)
if self.connected:
self.Pump() # send stuffs to the network
connection.Pump() # recieve stuffs from the network
self.clear()
clock.tick()
self.dispatch_events()
# Camera transformed stuff
glPushMatrix()
self.camera.transform()
self.processNetworkedVars()
#gameboard cards
self.drawLocalCards()
self.batch.draw()
self.drawSelectedCard()
# rectangles
self.drawRects()
#hand
self.drawTokens()
self.drawUnderlay()
glPopMatrix()
# End camera transformed stuff
# Draw the Hud stuff over top
self.drawHandCards()
self.batch2.draw()
self.drawHandRects()
self.batch3.draw()
self.drawZoomedCard()
self.drawDeckBrowserCard()
self.scroll_area.draw()
self.fps.draw()
self.flip() #flip to the other opengl buffer
def drawDeckBrowserCard(self):
""" used for when players want to browse through the deck for a card """
if self.deckBrowserCard != None:
if self.deckBrowserCard.sprite == None:
self.deckBrowserCard.sprite = self.setupCard(self.deckBrowserCard)
self.deckBrowserCard.scale = 2
self.deckBrowserCard.sprite.image.anchor_x = self.deckBrowserCard.sprite.image.width/2
self.deckBrowserCard.sprite.image.anchor_y = self.deckBrowserCard.sprite.image.height/2
self.deckBrowserCard.sprite.position = (self.width/4, self.height/2)
self.deckBrowserCard.sprite.draw()
def drawZoomedCard(self):
""" zooms in on a card so you can read the details """
if self.zoomedCard:
self.zoomedCard.scale = 2
self.zoomedCard.image.anchor_x = self.zoomedCard.image.width/2
self.zoomedCard.image.anchor_y = self.zoomedCard.image.height/2
self.zoomedCard.position = (self.width/2, self.height/2)
self.zoomedCard.draw()
def drawSelectedCard(self):
""" draw the selected card """
if self.selected != None:
if self.selected.sprite == None or self.selected.image == None:
self.selected.image = pyglet.image.load(self.selected.imageloc)
self.selected.sprite = Sprite(self.selected.image) #, batch=self.batch2)
self.selected.loadImg()
self.selected.sprite.draw()
#process network actions
def ConnectToServer(self):
""" establish a network connection to the server """
self.Connect((self.host, self.port))
self.SetNickname(self.nickname)
connection.Send({"action": "message", "message": pickle.dumps("Has Connected")})
self.createHQMS()
self.createRNDMS()
self.createArchivesMS()
self.connected = True
def processNetworkedVars(self):
""" read in the stuff from the network for each the the players """
for p in self.players:
color = self.players[p]['color']
#if DEBUG: print "COLOR: OMG", str(color)
pyglet.gl.glColor4f(color[0],color[1],color[2],1.0)
while self.cards[p]['cards']:
cardn = self.cards[p]['cards'].pop()
self.MakeLocalCard(cardn)
while self.tokens[p]['tokens']:
tokenn = self.tokens[p]['tokens'].pop()
self.MakeLocalToken(tokenn)
while self.mss[p]['mss']:
msn = self.mss[p]['mss'].pop()
self.MakeLocalMovableStat(msn, color)
while self.acts[p]['acts']:
actn = self.acts[p]['acts'].pop()
self.MakeLocalAct(actn)
#gui functions
def update_chat(self, message):
""" update the chat messages with the new message """
self.ML.addMessage(message)
self.decoded = pyglet.text.decode_text(self.ML.getMessages())
self.decoded.set_style(0, len(self.decoded.text), dict(color=(255,255,255,255)))
self.scroll_area._set_document(self.decoded)
# Kytten stuff
def on_escape(self, dialog):
""" Handle pressing esc """
self.deckBrowserCard = None
dialog.teardown()
def on_escape_menu(self, dialog):
""" handle esc on menu """
dialog.teardown()
def on_escape_action(self, dialog):
""" handle esc on action """
dialog.teardown()
self.action_menu = False
def on_escape_chat(self, dialog):
""" handle esc on chat """
dialog.teardown()
self.chat_menu = False
def update_kytten(self,dt):
""" update kytten """
self.dispatch_event('on_update', dt)
def on_select(self, choice):
""" handle selections """
if choice == 'Deck Loader':
self.create_deckloader_dialog()
elif choice == "Actions":
if self.action_menu == False:
self.create_actions_dialog()
self.action_menu = True
elif choice == "Runner Actions":
self.create_runner_actions_dialog()
elif choice == "Corp Actions":
self.create_corp_actions_dialog()
elif choice == "Controls":
self.create_controls_dialog()
elif choice == "Chat":
self.create_chat_dialog()
elif choice == "Quit":
self.quitGame()
else:
if DEBUG: print "Unexpected menu selection: %s" % choice
def loadDeck(self, deck):
""" load the specified deck from xml """
self.playerDeck.populate("decks/" + deck)
self.playerDeck.shuffle()
act = Act(self.RNDuuid, "update", "ms", payload=len(self.playerDeck.deck))
self.Send({"action": "addact", "act": pickle.dumps(act)})
connection.Send({"action": "message", "message": pickle.dumps("Has loaded a deck:" + deck)})
def generateMenu(self):
""" Create the menu """
dialog = kytten.Dialog(
kytten.TitleFrame("Main Menu",
kytten.VerticalLayout([
kytten.Label("Select dialog to show"),
kytten.Menu(options=["Deck Loader","Actions","Runner Actions", "Corp Actions","Controls","Chat","Quit" ],
on_select=self.on_select),
]),
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_TOP_LEFT, on_escape=self.on_escape,
theme=self.theme)
return dialog
def create_deckloader_dialog(self):
""" create the deckloader dialog """
def on_select(choice):
if DEBUG: print "Selected: %s" % choice
self.loadDeck(choice)
self.on_escape(dialog)
self.create_actions_dialog()
dialog = kytten.Dialog(
kytten.Frame(
kytten.VerticalLayout([
kytten.Label("Select a Deck:"),
kytten.Dropdown(self.decklist.decklist,
on_select=on_select),
]),
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_CENTER,
theme=self.theme2, on_escape=self.on_escape)
return dialog
def create_deckbrowser_dialog(self):
""" create the deckbrowser dialog """
def on_select(choice):
if DEBUG: print "Selected: %s" % choice
self.deckBrowserCard = None
self.deckBrowserCard = self.playerDeck.findCardByName(choice)
def on_submit():
if self.deckBrowserCard != None:
card = self.playerDeck.findCardByUUID(self.deckBrowserCard.uuid)
mouse_STW = self.camera.screen_to_world(self.width/2, self.height/2)
card.position = (mouse_STW[0], mouse_STW[1])
if DEBUG: print "Dropping"
card.dirty = True
card.faceUp = False
self.Send({"action": "movecard", "card": pickle.dumps(card.getCardN())})
connection.Send({"action": "message", "message": pickle.dumps("Has picked a card from his deck")})
act = Act(self.RNDuuid, "update", "ms", payload=len(self.playerDeck.deck))
self.Send({"action": "addact", "act": pickle.dumps(act)})
self.deckBrowserCard = None
self.on_escape(dialog)
list = []
for card in self.playerDeck.deck:
list.append(card.name)
dialog = kytten.Dialog(
kytten.Frame(
kytten.VerticalLayout([
kytten.Label("Select a Deck:"),
kytten.Dropdown(list, on_select=on_select),
kytten.Button("Place Card on Gameboard", on_click=on_submit)
]),
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_CENTER,
theme=self.theme2, on_escape=self.on_escape)
return dialog
def create_stats_dialog(self):
""" create the stats dialog """
dialog = kytten.Dialog(
kytten.Frame(
kytten.VerticalLayout([
kytten.Label('FPS'),
kytten.Label('Connection'),
kytten.Label('Players'),
kytten.Label(str(len(self.hand.deck))),
kytten.Label('Cards in Play'),
kytten.Label('Tokens')
])
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_CENTER,
theme=self.theme2, on_escape=self.on_escape
)
return dialog
def create_chat_dialog(self):
""" create the chat dialog """
dialog = None
def on_enter(dialog):
if DEBUG: print "Form submitted!"
for key, value in dialog.get_values().iteritems():
if key == "chat_text":
if value != "":
self.SendMessage(value)
else:
if DEBUG: print "not sending blank message"
self.on_escape_chat(dialog)
def on_submit():
on_enter(dialog)
def on_cancel():
if DEBUG: print "Form canceled."
self.on_escape_chat(dialog)
dialog = kytten.Dialog(
kytten.Frame(
kytten.VerticalLayout([
kytten.Label("Text:"), kytten.Input("chat_text", "", max_length=80),
kytten.HorizontalLayout([
kytten.Button("Submit", on_click=on_submit),
kytten.Button("Cancel", on_click=on_cancel)
])
]),
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_CENTER,
theme=self.theme2,on_enter=on_enter, on_escape=self.on_escape)
return dialog
def create_network_dialog(self):
""" create the network dialog """
dialog = None
def on_enter(dialog):
if DEBUG: print "Form submitted!"
for key, value in dialog.get_values().iteritems():
if key == "name":
if value != "":
self.nickname=value
else:
if DEBUG: print "no name sent"
if key == "host":
if value != "":
self.host=value
else:
if DEBUG: print "No host specified"
if key == "port":
if value != "":
self.port = int(value)
else:
if DEBUG: print "not sending blank message"
if self.host != "" and self.port != "":
self.ConnectToServer()
self.on_escape(dialog)
self.create_deckloader_dialog()
def on_submit():
on_enter(dialog)
def on_cancel():
if DEBUG: print "Form canceled."
self.on_escape_chat(dialog)
if self.nickname == None:
dialog = kytten.Dialog(
kytten.Frame(
kytten.VerticalLayout([
kytten.Label("Name: "), kytten.Input("name", "TypeYourNameHere", max_length=20),
kytten.Label("Host: "), kytten.Input("host", self.host, max_length=20),
kytten.Label("Port:"), kytten.Input("port", str(self.port), max_length=10),
kytten.Button("Connect", on_click=on_submit),
kytten.Button("Cancel", on_click=on_cancel)
]),
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_CENTER,
theme=self.theme2,on_enter=on_enter, on_escape=self.on_escape_chat)
return dialog
def create_actions_dialog(self):
""" create the actions dialog """
dialog = kytten.Dialog(
kytten.Frame(
kytten.VerticalLayout([
kytten.Button("Draw Card", on_click=self.draw_a_card),
kytten.Button("Put top card on the table", on_click=self.play_top_card),
kytten.Button("Create bit", on_click=self.createBit),
kytten.Button("Create 5 bit", on_click=self.create5Bit),
kytten.Button("Roll D6", on_click=self.rollD6),
kytten.Button("Shuffle Deck", on_click=self.shuffleDeck),
kytten.Button("Browse Deck for a card", on_click=self.create_deckbrowser_dialog),
kytten.Button("Pass Turn", on_click=self.passTurn)
]),
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_CENTER,
theme=self.theme2, on_escape=self.on_escape_action)
return dialog
def create_runner_actions_dialog(self):
""" create the runner actions dialog """
dialog = kytten.Dialog(
kytten.Frame(
kytten.VerticalLayout([
kytten.Button("Run the Archives", on_click=self.run_archives),
kytten.Button("Run R&D", on_click=self.run_rnd),
kytten.Button("Run HQ", on_click=self.run_hq),
kytten.Button("Run Aux Datafort", on_click=self.run_datafort),
kytten.Button("Remove Tag", on_click=self.remove_tag),
kytten.Button("Create Brain Damage", on_click=self.createBD),
kytten.Button("Create Virus Token", on_click=self.createVirus),
kytten.Button("Create Bad Publicity Token", on_click=self.createBadPublicity),
]),
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_CENTER,
theme=self.theme2, on_escape=self.on_escape_action)
return dialog
def create_corp_actions_dialog(self):
""" create the corp actions dialog """
dialog = kytten.Dialog(
kytten.Frame(
kytten.VerticalLayout([
kytten.Button("Trace", on_click=self.trace),
kytten.Button("Tag", on_click=self.create_tag),
kytten.Button("Destroy Runner Resource", on_click=self.destroy_resource)
]),
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_CENTER,
theme=self.theme2, on_escape=self.on_escape_action)
return dialog
def remove_tag(self):
""" send the network message to remove a tag """
connection.Send({"action": "message", "message": pickle.dumps("2Bits and an action to remove a Tag")})
def destroy_resource(self):
""" send the network message to destroy a resource """
connection.Send({"action": "message", "message": pickle.dumps("2Bits and an action to destroy a resource of Tagged runner.")})
def run_archives(self):
""" send a network message about running on the archives """
connection.Send({"action": "message", "message": pickle.dumps("Starting a run on the Archives")})
def run_rnd(self):
""" send a network message about running on rnd"""
connection.Send({"action": "message", "message": pickle.dumps("Starting a run on the R&D")})
def run_hq(self):
""" send a network message about running on HQ """
connection.Send({"action": "message", "message": pickle.dumps("Starting a run on the HQ")})
def run_datafort(self):
""" send a network message about running a particular datafort """
connection.Send({"action": "message", "message": pickle.dumps("Starting a run on the Aux Datafort")})
def trace(self):
""" send a network message about doing a trace """
connection.Send({"action": "message", "message": pickle.dumps("Is executing a Trace")})
def shuffleDeck(self):
""" shuffle the deck, and send the network message to notify the clients """
self.playerDeck.shuffle()
connection.Send({"action": "message", "message": pickle.dumps("Has Shuffled his deck")})
def create_controls_dialog(self):
""" create the controls dialog, used kytten markup """
document = pyglet.text.decode_attributed('''
{bold True}----MOUSE----{bold False}
{bold True}LEFT{bold False} click / drag to move a card\n
{bold True}RIGHT{bold False} click to Tap a card or Delete a Token\n
{bold True}MIDDLE{bold False} click to Flip a Card\n
{bold True}SCROLL{bold False} the mouse wheel to Zoom In or Out\n
{bold True}----KEYBOARD----{bold False}
{bold True}F1{bold False} Toggles Zoom in on a card\n
{bold True}ENTER{bold False} to open up the Chat window\n
{bold True}ESCAPE{bold False} will close out menu's or bring up the Main Menu\n
{bold True}L-ALT + Mouse over{bold False} will put a card back in your hand\n
{bold True}L-CTRL + mouse over{bold False} will put a card back on top of your deck\n
{bold True}SPACEBAR{bold False} will clear your drawings on the screen\n
{bold True}UP, DOWN, LEFT and RIGHT{bold False} will move the Camera\n
''')
dialog = kytten.Dialog(
kytten.Frame(
kytten.Document(document, width=500, height=500)
),
window=self, batch=self.batch3,
anchor=kytten.ANCHOR_CENTER,
theme=self.theme2, on_escape=self.on_escape)
return dialog
# schedule a update function to be called less often
# Turn Network Data into local Data
def MakeLocalAct(self, actn):
""" Turn a network action into a local action, this gets called on actions
that come in from the network """
tempact = pickle.loads(actn)
if tempact.target == "ms":
if tempact.action == "remove":
ms = self.movableStatList.findMSByUUID(tempact.uuid)
elif tempact.action == "update":
ms = self.movableStatList.findMSByUUID(tempact.uuid)
if ms:
ms.count = tempact.payload
self.movableStatList.statlist.append(ms)
elif tempact.target == "token":
if tempact.action == "remove":
token = self.tokenList.findTokenByUUID(tempact.uuid)
elif tempact.target == "card":
if tempact.action == "remove":
card = self.localCardList.findCardByUUID(tempact.uuid)
else:
if DEBUG: print "Could not process action"
def MakeLocalCard(self, cardn):
"""Turn the networked card into a local card managed by self.localCardList """
tempcard = pickle.loads(cardn)
if tempcard.dirty:
newcard = self.localCardList.findCardByUUID(tempcard.uuid)
if newcard == None:
newcard = self.baseDeck.findCardByCID(tempcard.cid)
newcard.position = tempcard.position
newcard.uuid = tempcard.uuid
newcard.isTapped = tempcard.isTapped
newcard.faceUp = tempcard.faceUp
newcard.inHand = tempcard.inHand
if DEBUG: print "Loading: ", newcard.name + "From the network"
newcard.dirty = True
self.localCardList.addCard(newcard)
def MakeLocalToken(self, tokenn):
""" build a local copy of the network token """
temptoken = pickle.loads(tokenn)
newtoken = self.tokenList.findTokenByUUID(temptoken.uuid)
if newtoken == None:
newtoken = Token(temptoken.type)
newtoken.uuid = temptoken.uuid
newtoken.position = temptoken.position
self.tokenList.tokens.append(newtoken)
def MakeLocalMovableStat(self, msn, color):
""" Create the movable stats """
tempms = pickle.loads(msn)
if DEBUG: print "new position", str(tempms.position)
newms = self.movableStatList.findMSByUUID(tempms.uuid)
if newms == None:
if DEBUG: print "NO MS FOUND, CREATING NEW ONE"
newms = MovableStat(tempms.label, tempms.count)
if DEBUG: print "old position: ", str(newms.position)
else:
if DEBUG: print "Already there, updating"
newms.color = color
newms.uuid = tempms.uuid
newms.position = tempms.position
self.movableStatList.statlist.append(newms)
def drawUnderlay(self):
""" Draw the text for the particular movable stat """
for ms in self.movableStatList.statlist:
ms.loadImg()
pyglet.text.Label(ms.label + str(ms.count), font_name="Computerfont", font_size=78,x=ms.sprite.x+35,y=ms.sprite.y-15, color=(ms.color[0], ms.color[1], ms.color[2], ms.color[3])).draw()
ms.sprite.draw()
if self.selectedMS:
self.selectedMS.sprite.draw()
def drawTokens(self):
""" draw all the local tokens """
for token in self.tokenList.tokens:
token.loadImg()
token.sprite.draw()
if self.selectedToken:
self.selectedToken.sprite.draw()
def drawHandCards(self):
""" draw all the cards in your hand """
for card in self.hand.deck:
if card.sprite == None or card.image == None:
card.image = pyglet.image.load(card.imageloc)
card.sprite = Sprite(card.image, batch=self.batch2)
card.loadImg()
card.position = (100 + self.hand.deck.index(card)*170,130)
card.set_sprite_pos()
def setupCard(self, card):
""" setup / init a card / refresh its image if its loaded from the network """
if card.sprite == None:
card.image = pyglet.image.load(card.imageloc)
if card.faceUp:
card.sprite = Sprite(card.image, batch=self.batch)
else:
if card.playertype == "Runner":
card.sprite = Sprite(RUNNERBACK, batch=self.batch)
else:
card.sprite = Sprite(CORPBACK, batch=self.batch)
else:
if card.faceUp:
card.sprite = Sprite(card.image, batch=self.batch)
else:
if card.playertype == "Runner":
card.sprite = Sprite(RUNNERBACK, batch=self.batch)
else:
card.sprite = Sprite(CORPBACK, batch=self.batch)
return card.sprite
def drawLocalCards(self):
""" draw all the local cards """
if self.localCardList.deck:
for card in self.localCardList.deck:
card.sprite = self.setupCard(card)
card.loadImg()
card.set_sprite_pos()
def drawRects(self):
""" Draw rectangles around the local cards """
pyglet.gl.glColor4f(1.0,0,0,1.0)
for card in self.localCardList.deck:
if card.isTapped:
ax,ay,bx,by,cx,cy,dx,dy = card.rotateRect(90)
else:
ax,ay,bx,by,cx,cy,dx,dy = card.rotateRect(0)
pyglet.graphics.draw(5, pyglet.gl.GL_LINE_STRIP,('v2i', (ax,ay,bx,by,cx,cy,dx,dy,ax,ay)))
def drawHandRects(self):
""" Draw outlines around the cards in the hand """
pyglet.gl.glColor4f(1.0,0,1,1.0)
for card in self.hand.deck:
ax,ay,bx,by,cx,cy,dx,dy = card.rotateRect(0)
pyglet.graphics.draw(5, pyglet.gl.GL_LINE_STRIP,('v2i', (ax,ay,bx,by,cx,cy,dx,dy,ax,ay)))
# -------------------------------------- EVENTS ------------------------------------- #
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
""" handle the mouse scrolling (wheel), zooms in and out """
scrollvalue = .05
if scroll_y < 0:
self.camera.zoom -= self.camera.zoom_speed * scrollvalue
else:
self.camera.zoom += self.camera.zoom_speed * scrollvalue
def on_key_press (self, key, modifiers):
"""This function is called when a key is pressed.
'key' is a constant indicating which key was pressed.
'modifiers' is a bitwise or of several constants indicating which
modifiers are active at the time of the press (ctrl, shift, capslock, etc.)
"""
if key == pyglet.window.key.F1:
if self.zoomedCard:
self.zoomedCard = None
else:
mouse_STW = self.camera.screen_to_world(self.mouseposx, self.mouseposy)
if DEBUG: print "Trying Zoom Card"
self.ZoomCard(mouse_STW[0], mouse_STW[1])
elif key == pyglet.window.key.ENTER and self.chat_menu == False:
self.create_chat_dialog()
self.chat_menu = True
elif key == pyglet.window.key.ESCAPE:
if self.menu_showing:
self.on_escape_menu(self.menu)
self.menu_showing = False
else:
self.menu = self.generateMenu()
elif key == pyglet.window.key.LCTRL:
mouse_STW = self.camera.screen_to_world(self.mouseposx, self.mouseposy)
if DEBUG: print "Trying to put card back on top of the deck"
self.CardToDeck(mouse_STW[0], mouse_STW[1])
elif key == pyglet.window.key.LALT:
mouse_STW = self.camera.screen_to_world(self.mouseposx, self.mouseposy)
if DEBUG: print "Trying to put card under the cursor back into your hand"
self.CardToHand(mouse_STW[0], mouse_STW[1])
elif key == pyglet.window.key.F2:
if DEBUG: print "Starting Drawing"
self.drawing = True
elif key == pyglet.window.key.SPACE:
if DEBUG: print "Clearing"
self.clearLines()
def on_mouse_motion (self, x, y, dx, dy):
"""This function is called when the mouse is moved over the app.
(x, y) are the physical coordinates of the mouse
(dx, dy) is the distance vector covered by the mouse pointer since the
last call.
"""
#mouse_stw = self.camera.screen_to_world(x, y)
#if DEBUG: print "Mouse to world: ", mouse_stw
self.mouseposx, self.mouseposy = x,y #director.get_virtual_coordinates (x, y)
#self.update_mouse_text (x, y)
def on_mouse_drag(self,x,y,dx,dy,buttons, modifiers):
""" Handle dragging cards around """
mouse_STW = self.camera.screen_to_world(x, y)
if self.selected != None:
self.CardMove(mouse_STW[0], mouse_STW[1])
elif self.selectedToken != None:
self.TokenMove(mouse_STW[0], mouse_STW[1])
elif self.selectedMS != None:
self.MSMove(mouse_STW[0], mouse_STW[1])
def on_mouse_press (self, x, y, buttons, modifiers):
"""This function is called when any mouse button is pressed
(x, y) are the physical coordinates of the mouse
'buttons' is a bitwise or of pyglet.window.mouse constants LEFT, MIDDLE, RIGHT
'modifiers' is a bitwise or of pyglet.window.key modifier constants
(values like 'SHIFT', 'OPTION', 'ALT')
"""
mouse_STW = self.camera.screen_to_world(x, y)
if buttons == pyglet.window.mouse.LEFT:
if self.TokenClicked(mouse_STW[0], mouse_STW[1]):
return True
elif self.MSClicked(mouse_STW[0], mouse_STW[1]):
return True
elif self.CardHandClicked(x, y):
return True
elif self.CardClicked(mouse_STW[0], mouse_STW[1]):
return True
else:
if DEBUG: print "No cards clicked on the board at: ", x,y
elif buttons == pyglet.window.mouse.RIGHT:
#self.MSRightClicked(mouse_STW[0], mouse_STW[1])
self.TokenRightClicked(mouse_STW[0], mouse_STW[1])
self.tap_card(mouse_STW[0], mouse_STW[1])
elif buttons == pyglet.window.mouse.MIDDLE:
self.flip_card(mouse_STW[0], mouse_STW[1])
def on_mouse_release(self,x,y,button,modifiers):
""" what happens when you let go of the mouse button based on what you were dragging """
mouse_STW = self.camera.screen_to_world(x, y)
if self.selected != None:
self.CardDrop(mouse_STW[0], mouse_STW[1])
elif self.selectedToken != None:
self.TokenDrop(mouse_STW[0], mouse_STW[1])
elif self.selectedMS != None:
self.MSDrop(mouse_STW[0], mouse_STW[1])
# -------------------------------------- Various actions triggered by the events ---------------------------- #
def passTurn(self):
""" send the network message that your turn is done """
connection.Send({"action": "message", "message": pickle.dumps("Go your turn now.")})
def rollD6(self):
""" Rolls a d6 and sends the results over the network to the server """
roll = randint(1,6)
connection.Send({"action": "message", "message": pickle.dumps("Rolling D6: " + str(roll))})
def quitGame(self):
""" quit """
self.has_exit = True
def createHQMS(self):
""" Create the HQ move-able stats """
ms = MovableStat('Hq: ', len(self.hand.deck))
self.HQuuid = ms.uuid
ms.position = self.camera.screen_to_world(self.width/2, self.height/2)
connection.Send({"action": "addms", "ms": pickle.dumps(ms.getMovableStatN())})
connection.Send({"action": "message", "message": pickle.dumps("created a HQ Stat token")})
def createRNDMS(self):
""" create the RND movable stats """
ms = MovableStat('RnD: ', len(self.playerDeck.deck))
self.RNDuuid = ms.uuid
ms.position = self.camera.screen_to_world(self.width/2, self.height/2)
connection.Send({"action": "addms", "ms": pickle.dumps(ms.getMovableStatN())})
connection.Send({"action": "message", "message": pickle.dumps("created a RND Stat token")})
def createArchivesMS(self):
""" create the archives movable stats """
ms = MovableStat('Archives', 0)
self.ARCHIVEuuid = ms.uuid
ms.position = self.camera.screen_to_world(self.width/2, self.height/2)
connection.Send({"action": "addms", "ms": pickle.dumps(ms.getMovableStatN())})
connection.Send({"action": "message", "message": pickle.dumps("created a Archives Stat token")})
def createBit(self):
""" create a bit locally and propagate it to the network """
token = Token("1bit")
token.position = self.camera.screen_to_world(self.width/2, self.height/2)
connection.Send({"action": "addtoken", "token": pickle.dumps(token.getTokenN())})
connection.Send({"action": "message", "message": pickle.dumps("created a bit")})
def create5Bit(self):
""" create a 5bit and send the message over the network """
token = Token("5bit")
token.position = self.camera.screen_to_world(self.width/2, self.height/2)
connection.Send({"action": "addtoken", "token": pickle.dumps(token.getTokenN())})
connection.Send({"action": "message", "message": pickle.dumps("created a 5bit")})
def createBD(self):
""" create a brain damage token and broadcast it to the network """
bd = Token("bd")
bd.position = self.camera.screen_to_world(self.width/2, self.height/2)
connection.Send({"action": "addtoken", "token": pickle.dumps(bd.getTokenN())})
connection.Send({"action": "message", "message": pickle.dumps("created a Brain Damage")})
def createVirus(self):
""" create a virus token and send it on it's way via the network """
virus = Token("virus")
virus.position = self.camera.screen_to_world(self.width/2, self.height/2)
connection.Send({"action": "addtoken", "token": pickle.dumps(virus.getTokenN())})
connection.Send({"action": "message", "message": pickle.dumps("created a Virus Token")})
def create_tag(self):
""" create a tag token, and send the signal over the network to the server """
tag = Token("tag")
tag.position = self.camera.screen_to_world(self.width/2, self.height/2)
connection.Send({"action": "addtoken", "token": pickle.dumps(tag.getTokenN())})
connection.Send({"action": "message", "message": pickle.dumps("created a tag Token")})
def createBadPublicity(self):
""" create a bad publicity token and send the signal to the server """
tag = Token("badpublicity")
tag.position = self.camera.screen_to_world(self.width/2, self.height/2)
connection.Send({"action": "addtoken", "token": pickle.dumps(tag.getTokenN())})
connection.Send({"action": "message", "message": pickle.dumps("created a Bad Publicity Token")})
def play_top_card(self):
""" play the top card from the deck """
card = self.playerDeck.drawCard()
mouse_STW = self.camera.screen_to_world(self.width/2, self.height/2)
card.position = (mouse_STW[0], mouse_STW[1])
if DEBUG: print "Dropping"
card.dirty = True
card.faceUp = False
self.Send({"action": "movecard", "card": pickle.dumps(card.getCardN())})
connection.Send({"action": "message", "message": pickle.dumps("Has played a card from his deck")})
act = Act(self.RNDuuid, "update", "ms", payload=len(self.playerDeck.deck))
self.Send({"action": "addact", "act": pickle.dumps(act)})
def draw_a_card(self):
""" Draw a card """
card = self.playerDeck.drawCard()
card.inHand = True
self.hand.addCard(card)
act = Act(self.HQuuid, "update", "ms", payload=len(self.hand.deck))
self.Send({"action": "addact", "act": pickle.dumps(act)})
act = Act(self.RNDuuid, "update", "ms", payload=len(self.playerDeck.deck))
self.Send({"action": "addact", "act": pickle.dumps(act)})
connection.Send({"action": "message", "message": pickle.dumps("Drawing a card")})
def CardHandClicked(self, x,y):
""" Has a card in your hand been clicked? """
for card in self.hand.deck:
if card.contains2(x,y):
if DEBUG: print "Clicked from Hand:", card.name
mouse_STW = self.camera.screen_to_world(x, y)
card.sprite.position = (mouse_STW[0], mouse_STW[1])
self.selected = card
self.selected.sprite.batch = None
self.hand.removeCard(card)
act = Act(self.HQuuid, "update", "ms", payload=len(self.hand.deck))
self.Send({"action": "addact", "act": pickle.dumps(act)})
act = Act(self.RNDuuid, "update", "ms", payload=len(self.playerDeck.deck))
self.Send({"action": "addact", "act": pickle.dumps(act)})
return True
return False
def TokenClicked(self, x,y):
""" Has a token been clicked """
for token in self.tokenList.tokens:
if token.clicked(x,y):
if DEBUG: print "Clicked token:", token.uuid
self.selectedToken = token
self.tokenList.tokens.remove(token)
return True
return False
def MSClicked(self, x,y):
""" Have you clicked on a movable stat """
for ms in self.movableStatList.statlist:
if ms.clicked(x,y):
if DEBUG: print "Clicked ms:", ms.uuid
self.selectedMS = ms
self.movableStatList.statlist.remove(ms)
return True
return False
def TokenRightClicked(self, x,y):
""" Right clicks on a token remove them, and send the event / message over the network """
for token in self.tokenList.tokens:
if token.clicked(x,y):
if DEBUG: print "Right Clicked token:", token.uuid
act = Act(token.uuid, "remove", "token")
self.Send({"action": "addact", "act": pickle.dumps(act)})
return True
return False
def CardClicked(self, x,y):
""" Has a card been clicked """
for card in self.localCardList.deck:
if card.clicked(x,y):
if DEBUG: print "card clicked: ", card.name
self.selected = card
self.localCardList.removeCard(card)
return True
return False
def ZoomCard(self, x,y):
""" Zoom in on a card """
#check cards on the board first
for card in self.localCardList.deck:
if card.clicked(x,y) and card.faceUp:
if DEBUG: print "card To Zoom: ", card.name
self.zoomedCard = Sprite(pyglet.image.load(self.baseDeck.findCardByCID(card.cid).imageloc))
#self.zoomedCard.scale = 2
return True
for card in self.hand.deck:
if card.contains2(self.mouseposx, self.mouseposy) and card.faceUp:
if DEBUG: print "card to zoom from hand"
self.zoomedCard = Sprite(pyglet.image.load(self.baseDeck.findCardByCID(card.cid).imageloc))
#self.zoomedCard.scale = 4
return True
return False
def CardToDeck(self, x,y):
""" Put a card back on top of the players deck """
for card in self.localCardList.deck:
if card.clicked(x,y):
if DEBUG: print "card To Deck: ", card.name
card.inHand = False
card.isTapped = False
card.sprite = None
self.localCardList.findCardByUUID(card.uuid)
self.playerDeck.putOnTop(card)