-
Notifications
You must be signed in to change notification settings - Fork 2
/
game.py
1201 lines (978 loc) · 34.5 KB
/
game.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
#!/usr/bin/python
# -*- coding: utf8 -*-
from config import *
if CONFIG_FULLSCREEN:
fullscreen = "#t"
else:
fullscreen = "#f"
from pandac.PandaModules import *
loadPrcFileData("setup", """sync-video 0
show-frame-rate-meter #t
#win-size 800 600
#win-size 1024 768
#win-size 1280 960
#win-size 1280 1024
win-size %s %s
win-fixed-size 1
#yield-timeslice 0
#client-sleep 0
#multi-sleep 0
basic-shaders-only #f
fullscreen %s
#audio-library-name null
text-minfilter linear_mipmap_nearest
text-flatten 0
framebuffer-multisample 1
multisamples 2
""" % (CONFIG_W, CONFIG_H, fullscreen))
import direct.directbase.DirectStart
from direct.showbase.DirectObject import DirectObject
from direct.task import Task
from direct.interval.IntervalGlobal import *
from direct.gui.OnscreenText import OnscreenText
from direct.filter.CommonFilters import CommonFilters
from direct.fsm.FSM import FSM
import sys
import cPickle as pickle
from camHandler import EditorCamHandler, GameCamHandler
from lightManager import LightManager
from mouseCursor import *
#from gui import *
#from guiDialog import *
from guiEditor import EditorGui
from guiGame import GameGui
from guiMenu import MainMenu
from dialog import *
from mapObject import *
from map import Map
from gameUtils import *
#-----------------------------------------------------------------------
# MapManagerBase, for MapManager and MapEditor
#-----------------------------------------------------------------------
class MapManagerBase(DirectObject):
def __init__(self, gm):
self.gm = gm # Game
self.cursor = self.gm.cursor
self.clicker = Clicker()
self.map = self.gm.map
#self.camHandler = self.gm.camHandler
#for obj in self.map.mapObjects.values():
# print "map manager base : %s is at %s" % (obj.name, obj.getPos())
self.keyDic = {}
def startAccept(self):
for key in [
"mouse1", "mouse3",
FORWARD, BACKWARD,
STRAFE_LEFT, STRAFE_RIGHT,
TURN_LEFT, TURN_RIGHT,
UP, DOWN,"h", "b", "t", "g"
]:
self.keyDic[key] = 0
self.accept(key, self.setKey, [key, 1])
keyUp = key + "-up"
self.accept(keyUp, self.setKey, [key, 0])
def setKey(self, key, value):
#print "MapManagerBase received %s" % (key)
self.keyDic[key] = value
def setMap(self, map):
self.map = map
if self.map.collisionGrid.hasGeoMip:
self.clicker.setHeight(self.map.collisionGrid.ground.terrainScale)
else:
self.clicker.setHeight(0)
def getHoverObjectName(self):
if base.mouseWatcherNode.hasMouse():
mpos = base.mouseWatcherNode.getMouse()
pos = self.clicker.getMouseTilePos(mpos)
res = self.clicker.getMouseObject(self.map.mapObjectRoot)
if res is not None:
#print "Found a name : %s " % (res.getIntoNodePath().getName())
name = res.getIntoNodePath().getName()
return name
return None
def getHoverNPCName(self):
if base.mouseWatcherNode.hasMouse():
mpos = base.mouseWatcherNode.getMouse()
pos = self.clicker.getMouseTilePos(mpos)
res = self.clicker.getMouseObject(self.map.NPCroot)
if res is not None:
name = res.getIntoNodePath().getName()
return name
return None
def getHoverCreatureName(self):
if base.mouseWatcherNode.hasMouse():
mpos = base.mouseWatcherNode.getMouse()
pos = self.clicker.getMouseTilePos(mpos)
res = self.clicker.getMouseObject(self.map.creatureRoot)
if res is not None:
name = res.getIntoNodePath().getName()
return name
return None
def updateCam(self, dt=0.01):
if self.keyDic[FORWARD]:
self.camHandler.forward(dt)
if self.keyDic[BACKWARD]:
self.camHandler.backward(dt)
if self.keyDic[STRAFE_LEFT]:
self.camHandler.strafeLeft(dt)
if self.keyDic[STRAFE_RIGHT]:
self.camHandler.strafeRight(dt)
if self.keyDic[TURN_LEFT]:
self.camHandler.turnLeft(dt)
if self.keyDic[TURN_RIGHT]:
self.camHandler.turnRight(dt)
if self.keyDic[UP]:
self.camHandler.lookUp(dt)
if self.keyDic[DOWN]:
self.camHandler.lookDown(dt)
#-----------------------------------------------------------------------
# MapManager : handles the map while in game
#-----------------------------------------------------------------------
class MapManager(MapManagerBase):
def __init__(self, gm):
self.mode = "move" # talk, fight
MapManagerBase.__init__(self, gm)
#self.map.water = True
# player
self.gameState = self.gm.gameState
self.playerState = self.gm.playerState
name = self.playerState.name
sex = self.playerState.sex
if sex == "male":
modelPath = "models/characters/neoMale"
else:
modelPath = "models/characters/neoFemale"
self.player = MapNPC(self, name, modelPath, "models/characters/female1.jpg", "player")
self.player.addEquipment("models/characters/female_hair", "models/characters/female_hair.jpg")
self.player.addEquipment("models/equipment/bag", "models/equipment/bag1.jpg")
startX, startY = self.map.collisionGrid.getRandomTile()
self.player.setTilePos(startX, startY)
self.player.reparentTo(render)
self.player.toggleLabel()
# NPCs
self.NPC = {}
self.NPCAI = {}
for name, sex in [("ula2", "female"), ("Kimmo", "male"), ("Drunkard", "male"), ("Camilla", "female")]:
x, y = self.map.collisionGrid.getRandomTile()
# yes, we will have to think about something smarter in the long run, i know...
if sex == "female":
self.addNPC(name, "models/characters/neoFemale", "models/characters/female1.jpg", x,y)
else:
self.addNPC(name, "models/characters/neoMale", "models/characters/neoMale.jpg", x,y)
self.NPC["Camilla"].addEquipment("models/characters/female_hair", "models/characters/female_hair2.jpg")
self.NPC["Camilla"].addEquipment("models/equipment/stick", "models/equipment/stick.jpg")
self.NPC["ula2"].addEquipment("models/characters/female_hair", "models/characters/female_hair3.jpg")
self.NPC["ula2"].addEquipment("models/equipment/bag", "models/equipment/bag1.jpg")
self.NPC["Kimmo"].addEquipment("models/equipment/bag", "models/equipment/bag1.jpg")
self.NPC["Drunkard"].addEquipment("models/equipment/stick", "models/equipment/stick.jpg")
# monsters
self.mobs = {}
# drops
self.drops = {}
self.addDrop("machin", 5, self.player.getPos()+Vec3(4,0,0.25))
self.addDrop("machin", 5, self.player.getPos()+Vec3(0,2,0.25))
self.addDrop("machin", 5, self.player.getPos()+Vec3(4,2,0.25))
self.dialog = None # current dialog
self.gui = GameGui(self)
self.gui.hide()
#self.map.collisionHide()
#for obj in self.map.mapObjects.values():
# print "map manager init says : %s is at %s" % (obj.name, obj.getPos())
def start(self):
self.gui.show()
self.task = taskMgr.add(self.update, "MapManagerTask")
self.startAccept()
if self.map.bgMusic:
self.map.bgMusic.play()
#self.map.bgMusic.setVolume(0.4)
if self.map.bgSound:
self.map.bgSound.play()
for NPCAI in self.NPCAI:
self.NPCAI[NPCAI].request("Wander")
def stop(self):
self.gui.hide()
taskMgr.remove(self.task)
self.ignoreAll()
if self.map.bgMusic:
self.map.bgMusic.stop()
#self.map.bgMusic.setVolume(0.4)
if self.map.bgSound:
self.map.bgSound.stop()
for NPCAI in self.NPCAI:
self.NPCAI[NPCAI].request("Pause")
def startAccept(self):
for key in [
"mouse1", "mouse3",
FORWARD, BACKWARD,
STRAFE_LEFT, STRAFE_RIGHT,
TURN_LEFT, TURN_RIGHT,
UP, DOWN,"h", "b", "t", "g"
]:
self.keyDic[key] = 0
self.accept(key, self.setKey, [key, 1])
keyUp = key + "-up"
self.accept(keyUp, self.setKey, [key, 0])
self.setMode(self.mode) # mouse click events
self.accept(SAVE, self.save, [self.gameState.filename])
self.accept(OPEN, self.load, [self.gameState.filename])
self.accept(INVENTORY, self.gui.inventory.toggle)
self.accept("mouse2", self.gm.gameCam.startDrag)
self.accept("mouse2-up", self.gm.gameCam.stopDrag)
self.accept("wheel_up", self.gm.gameCam.zoom, [1.0])
self.accept("wheel_down", self.gm.gameCam.zoom, [-1.0])
self.accept("playerDied", self.onPlayerDie)
def onPlayerDie(self):
print "Map Manager : the player has died, let's move to title screen..."
def save(self, filename):
#f = open(filename, 'w')
#pickle.dump(self.gm.playerData, f)
#f.close()
self.gm.gameState.saveAs(filename)
print "player data saved as %s" % (filename)
def load(self, filename):
f = open(filename, 'r')
playerData = pickle.load(f)
f.close()
self.gm.playerData = playerData
#for key in playerData:
# self.gm.playerData[key] = playerData[key]
print("player data loaded from file %s, data = %s" % (filename, self.gm.playerData))
self.playerData = self.gm.playerData
def setMode(self, mode="move"):
if mode == "move":
#print "Map Manager switched to move mode"
self.mode = "move"
self.accept("mouse1", self.onClickObject) # left click
#self.accept("mouse2", self.onClickObject2) # scroll click
self.accept("mouse3", self.onClickObject3) # right click
#self.accept("wheel_up", self.camHandler.moveHeight, [-0.02])
#self.accept("wheel_down", self.camHandler.moveHeight, [0.02])
elif mode == "talk":
print "Map manager switched to talk mode"
self.mode = "talk"
self.ignore("mouse1")
self.ignore("mouse2")
self.ignore("mouse3")
elif mode == "fight":
print "Map Manager switched to fight mode"
self.mode = "fight"
self.accept("mouse1", self.onClickObject) # left click
#self.accept("mouse2", self.onClickObject2) # scroll click
#self.accept("mouse3", self.onClickObject3) # right click
modeMsg = "Game mode : " + self.mode
#self.msgTilePos.setText(modeMsg)
self.gui.setInfo(modeMsg)
def onClickObject(self):
# click on MapObject :
if self.dialog:return
name = self.getHoverNPCName()
if name is not None and not self.gui.inventory.visible and not self.dialog:
print "map manager : left click on NPC : %s, opening dialog" % (name)
if self.getPlayerDistToNPC(name)< 4.0:
self.openDialog(name)
else:
x, y = self.map.getClosestOpenTile(self.NPC[name].getTilePos()[0], self.NPC[name].getTilePos()[1])
self.playerGoto(x, y)
return
name = self.getHoverObjectName()
if name is not None and not self.gui.inventory.visible and not self.dialog:
print "map manager : left click on map object : %s, position = %s" % (name, self.map.mapObjects[name].getPos())
return
name = self.getHoverCreatureName()
if name is not None:
print "Click on %s" % (name)
return
if base.mouseWatcherNode.hasMouse() and not self.gui.inventory.visible and not self.dialog:
mpos = base.mouseWatcherNode.getMouse()
pos = self.clicker.getMouseTilePos(mpos)
self.playerGoto(pos[0], pos[1])
print "Player goto %s/%s" % (pos[0], pos[1])
return
# and this should never happen
print "WARNING : map manager : left click on nothing?!"
return False
def onClickObject3(self):
# click on MapObject :
if self.dialog:return
name = self.getHoverNPCName()
if name is not None and not self.gui.inventory.visible and not self.dialog:
print "map manager : right click on NPC : %s, label toggle" % (name)
#self.NPC[name].toggleLabel()
self.gui.objectMenu.rebuild(["look", "talk", "attack"])
self.gui.objectMenu.buttons[0].bind(DGG.B1PRESS, self.onTalkTo, [name])
self.gui.objectMenu.buttons[1].bind(DGG.B1PRESS, self.onTalkTo, [name])
self.gui.objectMenu.buttons[2].bind(DGG.B1PRESS, self.onTalkTo, [name])
self.gui.objectMenu.expand()
if base.mouseWatcherNode.hasMouse():
mpos = base.mouseWatcherNode.getMouse()
self.gui.objectMenu.setPos(mpos)
self.gm.cursor.setMode()
#self.openDialog(name)
return
name = self.getHoverObjectName()
if name is not None and not self.gui.inventory.visible and not self.dialog:
print "map manager : right click on map object : %s, position = %s" % (name, self.map.mapObjects[name].getPos())
return
name = self.getHoverCreatureName()
if name is not None and not self.gui.inventory.visible and not self.dialog:
print "map manager : right click on map creature / drop : %s, position = %s" % (name, self.drops[name].getPos())
return
if base.mouseWatcherNode.hasMouse() and not self.dialog:
#mpos = base.mouseWatcherNode.getMouse()
#pos = self.clicker.getMouseTilePos(mpos)
#self.playerGoto(pos[0], pos[1])
#print "Player goto %s/%s" % (pos[0], pos[1])
#self.gm.cursor.setMode()
self.gui.inventory.toggle()
return
# and this should never happen
#print "WARNING : map manager : right click on nothing?!"
return False
def onTalkTo(self, name, extraArgs=[]):
self.gui.closeMenu() # in case we asked the talk to from this context menu
if self.getPlayerDistToNPC(name)< 4.0:
self.openDialog(name)
else:
tile = self.map.getClosestOpenTile(self.NPC[name].getTilePos()[0], self.NPC[name].getTilePos()[1])
if tile:
x, y = tile
self.playerGoto(x, y)
self.player.sequence.append(Func(self.onTalkTo, name))
self.player.sequence.resume() # ?
#print "Appended talkTo %s to sequence %s" % (name, self.player.sequence)
else:
print "%s can't be reached." % (name)
self.gm.cursor.setMode()
def getDropNewName(self, genre):
i = 1
tmpName = genre + "_" + str(i)
while tmpName in self.drops:
i = i+1
tmpName = genre + "_" + str(i)
return tmpName
def addDrop(self, genre, nb, pos):
name = self.getDropNewName(genre)
drop = MapDrop(self, name, genre, nb, pos)
self.drops[name] = drop
def addNPC(self, name, modelName, tex, x, y):
npc = MapNPC(self, name, modelName, tex)
npc.setTilePos(x, y)
self.NPC[name] = npc
npc.reparentTo(self.map.NPCroot)
ai = NPCAI(self, name)
self.NPCAI[name] = ai
def removeNPC(self, name):
if name in self.NPC:
self.NPC[name].destroy()
del self.NPC[name]
if name in self.NPCAI:
self.NPCAI[name].stop()
del self.NPCAI[name]
def removeAllNPC(self):
for name in self.NPC.keys():
self.NPC[name].destroy()
del self.NPC[name]
if name in self.NPCAI:
self.NPCAI[name].stop()
del self.NPCAI[name]
def playerGoto(self, x, y):
start = (self.player.getTilePos())
end = (x, y)
data = self.map.collisionGrid.data
path = astar(start, end, data)
if path is []:
#print "... but no good path found"
return False
newPath = []
for tile in path:
newPath.append((tile[0], tile[1], self.map.collisionGrid.getTileHeight(tile[0], tile[1])))
self.player.setPath(newPath)
return True
def getPlayerDistToNPC(self, name):
return Vec3(self.NPC[name].getPos() - self.player.getPos()).length()
def getPlayerDistToMapObject(self, name):
return Vec3(self.map.mapObjects[name].getPos() - self.player.getPos()).length()
def NPCGoto(self, name, x, y):
#print "NPCGoto called!"
if name not in self.NPC:
#print "%s is not a known NPC" % (name)
return False
start = (self.NPC[name].getTilePos())
end = (x, y)
data = self.map.collisionGrid.data
path = astar(start, end, data)
if path is []:
#print "... but no good path found"
return False
#else:
# print "NPCGoto : path found : %s" % (path)
newPath = []
for tile in path:
newPath.append((tile[0], tile[1], self.map.collisionGrid.getTileHeight(tile[0], tile[1])))
self.NPC[name].setPath(newPath)
def openDialog(self, name, extraArgs=[]):
if self.dialog:
#print "There was dialog garbage left, %s got his/her dialog shut unpolitely." % (self.dialog.name)
#self.dialog.destroy()
print "... but a dialog is already open for %s, aborting." % self.dialog.name
return False
if name in self.NPC:
self.NPC[name].stop()
playerPos = self.player.getTilePos()
npcPos = self.NPC[name].getTilePos()
lookDirX, lookDirY = playerPos[0]-npcPos[0], playerPos[1]-npcPos[1]
self.NPC[name].lookAt(lookDirX, lookDirY)
self.player.stop()
self.player.lookAt(-lookDirX, -lookDirY)
if name in dialogDic:
self.gui.openDialog(name)
self.dialog = dialogDic[name](self, name)
else:
self.gui.openDialog(name)
self.dialog = Dialog(self, name)
else:
print "Error, dialog called for unknown NPC : %s" % (name)
def updateCam(self):
self.gm.gameCam.update()
def update(self, task):
self.updateCam()
if self.dialog:
self.cursor.clear()
return task.cont
if self.gui.inventory.visible:
#self.gui.clearObjInfo()
#self.cursor.clear()
#self.gm.cursor.setMode()
return task.cont
dt = globalClock.getDt()
if base.mouseWatcherNode.hasMouse():
mpos = base.mouseWatcherNode.getMouse()
pos = self.clicker.getMouseTilePos(mpos)
else:
mpos = None
pos = None
#return task.cont
if self.mode == "move" and mpos is not None:
name = self.getHoverObjectName()
if name is not None:
msg = "in game object : " + name + "\npos = " + str(self.map.mapObjects[name].getPos())
#self.gui.setObjInfo(mpos, msg)
self.cursor.setMode("hand")
self.cursor.setInfo(msg)
return task.cont
name = self.getHoverNPCName()
if name is not None:
msg = "talk to : " + name + "\npos = " + str(self.NPC[name].getPos())
#self.gui.setObjInfo(mpos, msg)
self.cursor.setInfo(msg)
if not self.gui.objectMenu.open:
self.cursor.setMode("talk")
return task.cont
name = self.getHoverCreatureName()
if name is not None:
self.cursor.setMode("hand")
msg = "drop : " + name
self.cursor.setInfo(msg)
#self.gui.setObjInfo(mpos, msg)
return task.cont
#self.gm.cursor.setMode("default")
#self.gui.clearObjInfo()
if self.cursor.item is None:
self.cursor.clear()
#if self.cursor.item is not None and self.cursor.mode is "default":
else:
self.cursor.setInfo(str(self.cursor.itemNb))
return task.cont
return task.cont
#-----------------------------------------------------------------------
# MapEditor : handles the map editing
#-----------------------------------------------------------------------
class MapEditor(MapManagerBase):
def __init__(self, gm):
self.mode = "collision"
MapManagerBase.__init__(self, gm)
self.camHandler = self.gm.editorCam
# while self.mode == "edit", self.objectMode can become :
# drag, rotating, scaling
self.objectMode = None
self.selectedObj = None
self.gui = EditorGui(self)
#-----------------------------
# modes and input
def start(self):
#print "Starting editor"
self.gui.show()
self.startAccept()
self.task = taskMgr.add(self.update, "MapEditorTask")
#if self.map.bgMusic:
# self.map.bgMusic.stop()
#self.map.collisionShow()
self.map.collisionGrid.rebuild()
print "rebuilding grid"
def stop(self):
#print "Stopping editor"
self.gui.hide()
taskMgr.remove(self.task)
self.ignoreAll()
#self.map.collisionHide()
self.map.collisionGrid.np.flattenStrong()
print "flattening grid"
self.camHandler.stop()
def startAccept(self):
for key in [
"mouse1", "mouse3",
FORWARD, BACKWARD,
STRAFE_LEFT, STRAFE_RIGHT,
TURN_LEFT, TURN_RIGHT,
UP, DOWN,
EDITOR_DOWN, EDITOR_LEFT, EDITOR_RIGHT, EDITOR_UP,
"h", "b", "t", "g"
]:
self.keyDic[key] = 0
self.accept(key, self.setKey, [key, 1])
keyUp = key + "-up"
self.accept(keyUp, self.setKey, [key, 0])
self.setMode(self.mode)
self.accept("space", self.toggle)
self.accept(SAVE, self.save)
self.accept(OPEN, self.load, ["maps/mapCode.txt"])
def setMode(self, mode="collision"):
if mode == "collision":
msg = "Editor switched to collision mode"
self.mode = "collision"
self.gui.setInfo(msg)
for key in ["mouse1", "mouse2", "mouse3"]:
self.keyDic[key] = 0
self.accept(key, self.setKey, [key, 1])
keyUp = key + "-up"
self.accept(keyUp, self.setKey, [key, 0])
self.accept(CLEAR_COLLISION, self.map.clearCollision)
self.accept(FILL_COLLISION, self.map.fillCollision)
elif mode == "object":
msg = "Editor switched to object mode"
self.mode = "object"
self.gui.setInfo(msg)
self.accept("mouse1", self.onClickObject) # left click
self.accept("mouse2", self.onClickObject2) # scroll click
self.accept("mouse3", self.onClickObject3) # right click
self.ignore(CLEAR_COLLISION)
self.ignore(FILL_COLLISION)
self.accept("wheel_up", self.camHandler.moveHeight, [-0.05])
self.accept("wheel_down", self.camHandler.moveHeight, [0.05])
def toggle(self):
if self.mode == "collision":
self.setMode("object")
elif self.mode == "object":
self.setMode("collision")
def stopObjectAction(self):
self.objectMode = None
self.selectedObj = None
self.gui.objectMenu.hide()
self.startAccept()
def startDrag(self, obj, extraArgs=[]):
self.gui.objectMenu.hide()
self.objectMode = "drag"
self.gui.setInfo("dragging")
self.selectedObj = obj
self.accept("mouse1", self.stopDrag)
def stopDrag(self, extraArgs=[]):
self.gui.setInfo("stopped dragging")
self.stopObjectAction()
def startMoveZ(self, obj, extraArgs=[]):
self.gui.objectMenu.hide()
self.objectMode = "moveZ"
self.gui.setInfo("moving object Z")
self.selectedObj = obj
self.accept("mouse1", self.stopMoveZ)
def stopMoveZ(self, extraArgs=[]):
self.gui.setInfo("stopped moving object Z")
self.stopObjectAction()
def startRotate(self, obj, extraArgs=[]):
self.gui.objectMenu.hide()
self.objectMode = "rotate"
self.gui.setInfo("rotating object")
self.selectedObj = obj
self.accept("mouse1", self.stopRotate)
def stopRotate(self, extraArgs=[]):
self.gui.setInfo("stopped rotating object")
self.stopObjectAction()
def startScale(self, obj, extraArgs=[]):
self.gui.objectMenu.hide()
self.objectMode = "scale"
self.gui.setInfo("scaling object")
self.selectedObj = obj
self.accept("mouse1", self.stopScale)
def stopScale(self, extraArgs=[]):
self.gui.setInfo("stopped scaling object")
self.stopObjectAction()
def onClickObject(self):
# click on MapObject :
name = self.getHoverObjectName()
if name is not None:
print "map editor : left click on %s" % (name)
else:
print "map editor : left click on nothing"
def onClickObject2(self):
# click on MapObject :
name = self.getHoverObjectName()
if name is not None:
print "map editor : middle click on %s" % (name)
else:
print "map editor : middle click on nothing"
def onClickObject3(self):
# click on MapObject :
name = self.getHoverObjectName()
if name is not None:
print "map editor : right click on %s" % (name)
if base.mouseWatcherNode.hasMouse():
mpos = base.mouseWatcherNode.getMouse()
self.gui.openObjectMenu(self.map.mapObjects[name], mpos)
self.gui.objectMenu.buttons[1].bind(DGG.B1PRESS, self.startDrag, [self.map.mapObjects[name]])
self.gui.objectMenu.buttons[2].bind(DGG.B1PRESS, self.startRotate, [self.map.mapObjects[name]])
self.gui.objectMenu.buttons[3].bind(DGG.B1PRESS, self.startMoveZ, [self.map.mapObjects[name]])
self.gui.objectMenu.buttons[4].bind(DGG.B1PRESS, self.startScale, [self.map.mapObjects[name]])
self.gui.objectMenu.buttons[5].bind(DGG.B1PRESS, self.duplicateMapObject, [self.map.mapObjects[name]])
self.gui.objectMenu.buttons[6].bind(DGG.B1PRESS, self.removeMapObject, [name])
else:
print "map editor : right click on nothing"
self.gui.objectMenu.hide()
#-----------------------------
# map file handling
def save(self):
msg = "Editor : saving map"
self.gui.setInfo(msg)
self.map.save(self.map.filename)
def load(self, filename, extraArgs=[]):
#print "Editor : loading map %s" % (filename)
msg = "Loading map " + filename + "... Please wait..."
self.gui.setInfo(msg)
self.gm.load(filename)
#-----------------------------
# map objects
def addMapObject(self, genre, name, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1)):
self.map.addMapObject(genre, name, pos, hpr, scale)
def addNewMapObject(self, genre, extraArgs=[]):
self.gui.addObjectMenu.retract()
name = self.map.getAvailableName(genre)
self.addMapObject(genre, name)
obj = self.map.mapObjects[name]
self.setMode("object")
self.startDrag(obj)
def duplicateMapObject(self, obj, extraArgs=[]):
self.gui.addObjectMenu.retract()
genre = obj.genre
name = self.map.getAvailableName(genre)
self.addMapObject(genre, name)
newObj = self.map.mapObjects[name]
newObj.setScale(obj.getScale())
newObj.setRot(obj.getRot())
self.setMode("object")
self.startDrag(newObj)
def removeMapObject(self, name, extraArgs=[]):
if name in self.map.mapObjects:
self.stopObjectAction()
self.map.removeMapObject(name)
#self.map.mapObjects[name].destroy()
#del self.map.mapObjects[name]
def setMapObjectPos(self, name, x, y, z=0):
if name in self.mapObjects:
self.map.mapObjects[name].setPos(x, y, z)
#-----------------------------
# map collisions
def clearCollision(self, args=[]):
if self.mode == "collision":
self.map.collisionGrid.clear()
def fillCollision(self, args=[]):
if self.mode == "collision":
self.map.collisionGrid.fill()
def addCollision(self, x, y):
self.map.collisionGrid.showTile(x, y)
def removeCollision(self, x, y):
self.map.collisionGrid.hideTile(x, y)
def checkObj(self, dt=0.01):
if self.keyDic[EDITOR_LEFT]:
self.selectedObj.rotate(dt)
elif self.keyDic[EDITOR_RIGHT]:
self.selectedObj.rotate(-dt)
if self.keyDic[EDITOR_UP]:
self.selectedObj.moveZ(dt)
elif self.keyDic[EDITOR_DOWN]:
self.selectedObj.moveZ(-dt)
def scaleObj(self, dt=0.01):
if self.keyDic[EDITOR_UP]:
self.selectedObj.scale(dt)
elif self.keyDic[EDITOR_DOWN]:
self.selectedObj.scale(-dt)
def updateCam(self, dt=0.01):
if self.keyDic[FORWARD]:
self.camHandler.forward(dt)
if self.keyDic[BACKWARD]:
self.camHandler.backward(dt)
if self.keyDic[STRAFE_LEFT]:
self.camHandler.strafeLeft(dt)
if self.keyDic[STRAFE_RIGHT]:
self.camHandler.strafeRight(dt)
if self.keyDic[TURN_LEFT]:
self.camHandler.turnLeft(dt)
if self.keyDic[TURN_RIGHT]:
self.camHandler.turnRight(dt)
if self.keyDic[UP]:
self.camHandler.lookUp(dt)
if self.keyDic[DOWN]:
self.camHandler.lookDown(dt)
#-----------------------------
# editor update task
def update(self, task):
dt = globalClock.getDt()
if base.mouseWatcherNode.hasMouse():
mpos = base.mouseWatcherNode.getMouse()
pos = self.clicker.getMouseTilePos(mpos)
else:
mpos = None
pos = None
# collision editing
if self.mode == "collision" and self.keyDic["mouse1"] and pos is not None:
self.addCollision(pos[0], pos[1])
elif self.mode == "collision" and self.keyDic["mouse3"] and pos is not None:
self.removeCollision(pos[0], pos[1])
# map objects control
if self.mode == "object" and mpos is not None:
if self.objectMode == "drag":
objPos = self.clicker.getMousePos(mpos)
objPos = Vec3(objPos[0], objPos[1], self.selectedObj.getZ())
self.selectedObj.setPos(objPos)
self.checkObj(dt)
#elif self.objectMode == "rotate":
elif self.objectMode == "rotate" or self.objectMode == "moveZ":
self.checkObj(dt)
elif self.objectMode == "scale":
self.scaleObj(dt)
name = self.getHoverObjectName()
if name is not None:
#msg = "mapObject : " + name
msg = "Map object : " + name + "\npos = " + str(self.map.mapObjects[name].getPos())
self.gui.setObjInfo(mpos, msg)
else:
self.gui.clearObjInfo()
# camera control
self.updateCam(dt)
return task.cont
#-----------------------------------------------------------------------
# Game : FSM, switch between game playing and map editing
#-----------------------------------------------------------------------
class Game(FSM, DirectObject):
def __init__(self, gamefilename=None):
FSM.__init__(self, 'Game')
self.gameState = GameState()
if gamefilename is None:
gamefilename = "save/default.txt"
self.gameState.load(gamefilename)
self.playerState = self.gameState.playerState
self.gamefilename = gamefilename
self.map = None
self.mapManager = None
self.editor = None
self.prevMode = None # previous mode
self.cursor = MouseCursor()
self.mainMenu = MainMenu()
self.mainMenu.buttons[0].bind(DGG.B1PRESS, self.request, ["Game"])
self.mainMenu.buttons[3].bind(DGG.B1PRESS, self.quit)
self.mainMenu.hide()
self.mainMenuImg = makeImg(0,0,"img/bg/title1.jpg", (RATIO, 0,1))
self.mainMenuImg.setBin("fixed", -150)
self.request("MainMenu")
def initGame(self, gamefilename=None):
if gamefilename is None:
gamefilename = self.gamefilename
self.gameState = GameState()
self.gameState.load(gamefilename)
self.playerState = self.gameState.playerState
self.loadGameMap(self.gameState.playerState.map)
# editor camera handler
self.editorCam = EditorCamHandler()
self.playerData = {}
self.playerData["name"] = "Galya"
self.playerData["sex"] = "female"
#print "Game manager : creating map manager"
self.mapManager = MapManager(self)
self.mapManager.playerData = self.playerData
# game camera handler
self.gameCam = GameCamHandler(self.mapManager.player.model)
self.setMode("playing")
#print "Game manager : creating map editor"
self.editor = MapEditor(self)
# light
if CONFIG_LIGHT:
self.light = LightManager(self.mapManager.player.model)
self.light.lightCenter.setPos(0,0,3)
self.light.lightCenter.reparentTo(self.mapManager.player.model)
self.accept(OPEN_EDITOR, self.toggle)
def quit(self, sentArgs=[]):
sys.exit()
def loadGameMap(self, filename):
print "Game : load game map %s" % (filename)
if self.map:
self.mapManager.removeAllNPC()
self.map.destroy()
#del self.map
self.map = Map(filename)
if self.map.collisionGrid:
#print "Game : loaded new game map %s, it has a collisionGrid %s" % (str(self.map), str(self.map.collisionGrid))
print "Game : loaded new game map from file %s " % (filename)
else: