-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTAPL.py
More file actions
1548 lines (1300 loc) · 56.7 KB
/
TAPL.py
File metadata and controls
1548 lines (1300 loc) · 56.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Created on 4 Feb 2012
@author: Hens
'''
import math
import socket
import threading
import thread
from exceptions import ValueError
from difflib import get_close_matches, SequenceMatcher
import pickle
import string
import os
import copy
class SpecialBadge(object):
def __init__(self, badgeTitle, grantsFunctionName, rewardDescription):
self.title = badgeTitle
self.functionGranted = grantsFunctionName
self.description = rewardDescription
def aOrAn(name):
if name[0] in "aeiou":
return "an"
return "a"
SPACE_CREATE_BADGES = {3:"Novice Bricklayer",
8:"Apprentice Builder",
16:"Builders Mate",
24:"Professional Builder",
48:SpecialBadge("Experienced Professional Builder",
"copySpace",
"""Use copySpace to create copies of spaces you've already made,
including items they contain.\n\nusage: @me.copySpace(dirIn, dirBack, space)"""),
70:"Master Builder",
100:"Architect Novice",
130:"Architect Apprentice",
160:"Architect",
200:SpecialBadge("Expert Architect",
"destroySpace",
"""Use destroySpace to completely remove a space that you have created. All
items inside are destroyed, and players are moved randomly to adjacent spaces,
possibly resulting in them being cut off from the rest of the world!"""),
240:"Master Architect",
300:SpecialBadge("Master Architect of Creation",
"createArea",
"""Grants the ability to create multiple spaces in a single command""")
}
EXPLORATION_BADGES = {5:"Traveller",
15:"Journeyman",
30:"Interested Explorer",
50:"Weary Explorer",
80:"Experienced Explorer",
120:"Reknowned Explorer",
160:"Great Explorer",
200:"Legendary Explorer"
}
ITEM_CREATION_BADGES = {5:"Amateur Tinkerer",
20:"Novice Item Maker",
40:"Adept Item Maker",
70:"Artisan",
110:"Master Artisan"
}
welcome = '''
<div id='game_welcome'>
<h1>==[ Text Adventure Programming Language ]==</h1>
Welcome to the text adventure programming
language. Please read the documentation to
learn how to start creating your own worlds
to enjoy with friends.
<hr/><br/>
</div>
'''
class GameEvent(object):
def __init__(self, eventType, target, *args):
self.type = eventType
self.target = target
self.args = args
class PlayerEvent(GameEvent):
PLAYER_ENTERED = "player_entered"
PLAYER_LEFT = "player_left"
PLAYER_CREATED_ITEM = "player_created_item"
PLAYER_SAID = "player_said"
PLAYER_CREATED_WORLD = "player_created_world"
PLAYER_CHANGED_NAME = "player_changed_name"
PLAYER_EMOTE = "player_emote"
PLAYER_SHOUTED = "player_shouted"
class WorldEvent(GameEvent):
SUNDOWN = "sundown"
SUNRISE = "sunrise"
class SocketForwarder(threading.Thread):
def __init__(self, host, port_in, port_out):
threading.Thread.__init__(self)
self.sock = None
def run(self):
pass
#gameCommands =[ 'help', 'say', 'examine', 'go', 'shout', 'take', 'drop', 'tell', 'use', 'look', 'give', 'inventory' ,'print_state', "warp", "list_worlds", "download_world", "save_world", "who"]
gameCommands = {
'help' : 'get help',
'say' : "say something to all occupants in the room you're in",
'examine' : 'examine an item',
'go' : 'go somewhere',
'shout' : 'say to all users in the current world',
'take' : 'pick up an item in the current location',
'drop' : 'drop an item in your inventory in the current room',
'tell' : 'message a specific user - syntax = tell Norman Granger: some message',
'use' : 'try to use an item',
'give' : 'give an item to a user, syntax = give Norman Granger: sword',
'inventory' : 'show all items you are carrying',
'print_state' : 'show all variables defined in the current scope',
'warp' : 'warp to a different world',
'look': 'see what is around you',
'list_worlds' : 'show a list of all the worlds running on the current server',
'download_world' : 'save the current world and make it available to download',
'save_world': 'save the current world',
'who': 'list users in the current room'
}
shortcuts = {'>':'say'}
def closestMatchItem(u, sequence):
items = [i._name for i in sequence]
#result = min(_items, key=lambda v: len(set(u) ^ set(v)))
result = get_close_matches(u, items, 1, 0.4)
if len(result)<1:
return "[NO MATCH]"
return result[0]
def closestMatchString(u,sequence):
result = get_close_matches(u, sequence, 1, 0.4)
if len(result)<1:
return "[NO MATCH]"
return result[0]
class Player(object):
def __init__(self, name, conn, addr):
self._name=name
self._handler = conn
#self._handler.send(welcome)
self._health = 100
self._inventory = []
self._emotes = {}
self._description = ""
self._sneaking = False
self._currentLocation = None
self._joined = False
self._avatar = "http://www.gravatar.com/avatar/00000000000000000000000000000000?d=mm&f=y"
self._email = ""
self._password = ""
self._userName = ""
self._creationStage = 0
self._loginStage = 0
self._title = "Greenling"
#self._handler = None
def __repr__(self):
return "[Player - %s, %s]" % (self._name, self._title)
def _setTitle(self, title):
self._title = title
self._message_confirmation("Your title is set to %s" % title)
self._currentLocation._fireEvent(PlayerEvent(PlayerEvent.PLAYER_SAID, self, "changed their title to %s" % title))
def _save(self, arg=None):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
valid_name = ''.join(c for c in self._userName if c in valid_chars) + ".taplPlayer"
print "SAVING PLAYER:", valid_name
return TAPL()._savePlayer(self, valid_name)
self._creationStage = 4
#obj = pickle.dumps(self)
#f = open(os.path.join(os.path.abspath(os.curdir), valid_name), "w")
#f.write(obj)
#f.close()
def save(self, player=None):
'''
Save your character.
If you have not saved before,
you can set a user name and
password to load the character
later on.
'''
if self._loginStage == 3:
self._save(None)
return
self._creationStage = 1
self._message_notification("Please choose a user name")
def _message_notification(self,message):
html = "<div class='notification'><p>%s</p></div>" % message
if self._handler:
self._handler.sendMessage(html)
def _message_alert(self,message):
html = "<div class='alert'><p>%s</p></div>" % message
if self._handler:
self._handler.sendMessage(html)
def _message_confirmation(self, message):
html = "<div class='confirmation'><img src='/images/tick.png' align='left'><p>%s</p></div>" % message
if self._handler:
self._handler.sendMessage(html)
def emote(self, player, trigger, action):
'''
Add an emote to your character.
@param trigger: the command you want to assign for
the emote
@param action: the action as you want it to appear
in the world.
Example:
@me.emote("slap", "bitch slaps")
>>slap ryan
Norman bitch slaps Ryan
'''
self._emotes[trigger] = action
self._message_confirmation("Emote '%s' set." % trigger)
return self
def setAvatar(self, player, avatarUrl):
'''
Set an image for your character
@param url: The URL to an image to display
'''
self._avatar = avatarUrl
self._message_confirmation("Your avatar has changed to<br/><img src='%s'/>" % avatarUrl)
return self
def _joinGame(self):
self._joined = True
self._handler.sendMessage(welcome)
def say(self, player, message):
'''
Say something to everyone in your current location
aliases:
@me.say("Something")
say Something
>something
'''
if self._currentLocation:
self._currentLocation._fireEvent(PlayerEvent( PlayerEvent.PLAYER_SAID, self, message))
#self._message_notification("You say, " + message)
def shout(self, player, message):
'''
shout something to everyone in your current location
aliases:
@me.shout("Something")
shout Something
'''
if self._currentLocation:
self._currentLocation._fireEvent(PlayerEvent( PlayerEvent.PLAYER_SHOUTED, self, message))
def _setHandler(self, handler):
self._handler = handler
#self._handler.send(welcome)
def _setLocation(self, location):
if self._currentLocation:
if self in self._currentLocation._occupants:
self._currentLocation._occupants.remove(self)
self._currentLocation._fireEvent( PlayerEvent( PlayerEvent.PLAYER_LEFT, self ) )
self._currentLocation = location
if self not in location._occupants:
location._occupants.append(self)
location._fireEvent( PlayerEvent( PlayerEvent.PLAYER_ENTERED, self ))
if self._handler and self._joined:
self._message_notification("You are in " + self._currentLocation._name)
return self
def setName(self, player, name):
'''
Change your display name.
@param name: Your new chosen name
'''
oldname = self._name
self._name = name
if self._currentLocation:
self._currentLocation._fireEvent( PlayerEvent( PlayerEvent.PLAYER_CHANGED_NAME, self, name, oldname))
self._message_confirmation("Your name has changed to " + name)
return self;
def describe(self, player, description):
'''
Give yourself a description
@param description: the description you want others to see
@return: The Player
'''
self._description = description
self._message_confirmation("You are now described as ")
return self;
def createItem(self, player, name):
'''
Create an item and add it straight to your inventory
@me.createItem("A new Item")
@param name: name of the item
@return: The newly created Item
'''
item = Item(name)
self._inventory.append(item)
if self._currentLocation:
self._currentLocation._fireEvent(PlayerEvent( PlayerEvent.PLAYER_CREATED_ITEM, self, item ))
self._message_confirmation("Item created")
return item
def addItem(self, player, item):
'''
Not yet implemented!
'''
self._inventory.append(item)
return self
def removeItem(self, player, item):
'''
Not yet implemented!
'''
if item in self._inventory:
self._inventory.remove(item)
return self
def getItem(self, itemName):
'''
Not yet implemented!
'''
match = closestMatchItem(itemName, self._inventory)
#print "[----------" + str(self._inventory)
if match != "[NO MATCH]":
for i in self._inventory:
if i._name == itemName:
return i
return "You Aren't carrying a " + itemName
def createWorld(self, player, name):
'''
Create an entirely new world
and warp to the entrance room in that
world
@param name: The name of the new world
@return: The newly created world object
'''
w = World(name)
TAPL().addWorld(w)
if self._currentLocation:
self._currentLocation._fireEvent(PlayerEvent(PlayerEvent.PLAYER_CREATED_WORLD, self, w))
self._currentLocation._fireEvent(PlayerEvent(PlayerEvent.PLAYER_LEFT, self ))
self._setLocation(w.spaces[0])
return w
class PortalDoorway(object):
def __init__(self, portal, space, direction):
# direction is the way this door goes ( eg 'E', 'SE' )
self.space = space
self.direction = direction
self.portal
def getCompassOpposite(direction):
d = direction.lower();
if d == "n":
return "s"
if d == "ne":
return "sw"
if d == "e":
return "w"
if d == "se":
return "nw"
if d == "s":
return "n"
if d == "sw":
return "ne"
if d == "w":
return "e"
if d == "nw":
return "se"
return "n"
class Portal(object):
def __init__(self,dirIn,dirOut,spaceOne,spaceTwo,name="door"):
self._name = name
self.spaceOne = spaceOne
self.spaceTwo = spaceTwo
self.dirIn = dirIn
self.dirOut = dirOut
self.shortDirIn = ""
self.shortDirOut = ""
if dirIn.find("[") > -1 and dirIn.find("]") > -1:
self.shortDirIn = dirIn[dirIn.find("[")+1:dirIn.find("]")]
self.dirIn = self.dirIn[self.dirIn.find("]")+1:]
if not len(self.shortDirIn) : self.shortDirIn = dirIn[0:1]
if dirOut.find("[") > -1 and dirOut.find("]") > -1:
self.shortDirOut = dirOut[dirOut.find("[")+1:dirOut.find("]")]
self.dirOut = self.dirOut[self.dirOut.find("]")+1:]
if not len(self.shortDirOut) : self.shortDirOut = dirOut[0:1]
def addExit(self, doorway):
if len(self.doorways) < 2:
if self.doorways[0] != doorway:
self.doorways.append(doorway)
def setName(self, player, name):
self._name = name
return self
def describe(self, player, description):
self._description = description
return self
class Space(object):
def __init__(self, name):
self._name = name
self._description = "";
self._items = []
self._portals = []
self._occupants = []
self._world = None
def __repr__(self):
return "[SPACE: %s]" % self._name
def _fireEvent(self, event):
self._propagateEvent(event)
if event.type == PlayerEvent.PLAYER_ENTERED:
msg = event.target._name + " entered."
self._messageOccupants(msg, event.target)
return
if event.type == PlayerEvent.PLAYER_LEFT:
msg = event.target._name + " left."
self._messageOccupants(msg, event.target)
return
if event.type == PlayerEvent.PLAYER_SAID:
msg = event.args[0]
self._occupantSaid(msg, event.target)
return
if event.type == PlayerEvent.PLAYER_SHOUTED:
self._occupantSaid("<h2>" + event.args[0] + "</h2>", event.target)
if event.type == PlayerEvent.PLAYER_CREATED_ITEM:
msg = event.target._name + " created a " + event.args[0]._name
self._messageOccupants(msg, event.target)
return
if event.type == PlayerEvent.PLAYER_CHANGED_NAME:
msg = event.args[1] + " changed their _name to " + event.args[0]
self._messageOccupants(msg, event.target)
return
if event.type == PlayerEvent.PLAYER_EMOTE:
msg = event.args[0]
self._messageOccupants(msg, event.target)
def _propagateEvent(self, event):
for i in self._items:
if i.eventHandlers.has_key(event.type):
self._messagePlayer(event.target, i.eventHandlers[event.type])
def _messagePlayer(self, target, message):
if isinstance(target, Player):
if target._joined:
target._message_notification(message)
def _messageOccupants(self, msg, originator):
for o in self._occupants:
if o._handler and o is not originator:
o._message_notification(msg)
def _occupantSaid(self, msg, originator):
message = """<div class='speech'><p>
<img src='%s' align='left' /><br/>
<span class='player_name'>%s</span><br/>
<span class='player_title'>%s</span>
</p>
<p>
<span>%s</span>
</p>
</div>""" % (originator._avatar,
originator._name,
originator._title,
msg)
for o in self._occupants:
if o._joined:
o._handler.sendMessage(message)
def _setWorld( self, world ):
self._world = world
if not self in world.spaces:
world.spaces.append(self)
return self
def setName(self, player, name):
'''
Set the name for this space
@param name: the new name
@return: the Space
'''
self._name = name
player._message_confirmation("Done")
self._messageOccupants("%s changed the name of this location to %s." % ( player._name, name ), player)
return self;
def describe(self, player, description):
'''
Set the description for this space
@param description: The new description
'''
self._description = description
player._message_confirmation("Done")
self._messageOccupants("%s changed the description of this location to %s." % ( player._name, description ), player)
return self;
def createItem(self, player, name):
'''
Create a new item in this location
@param name: the name for the item
@return: The new item
'''
item = Item(name)
player._message_confirmation("Done")
self._messageOccupants("%s created a %s." % ( player._name, name ), player)
self._items.append(item)
return item
def addItem(self, player, item):
self._items.append(item)
return self
def removeItem(self, player, item):
if item in self._items:
self._items.remove(item)
return self
def _getPossibleDirections(self):
directions = []
for p in self._portals:
if p.spaceOne == self:
directions.append(p.dirIn)
directions.append(p.shortDirIn)
else:
directions.append(p.dirOut)
directions.append(p.shortDirOut)
return directions
def _goPortal(self, name):
destination = self
via = ""
for p in self._portals:
if p.direction == name:
via = p._name
if p.start._name == self._name:
destination = p.end
else:
destination = p.start
break
#print "you travel to", destination._name, "via", via
return destination
def dig(self, player, directionIn, directionOut, roomName, portalName = "door"):
'''
Create a tunnel to a new location ( also creates the new space at the same time )
@param directionIn: the direction of the room
@param directionBack: the direction BACK to this room
@param roomName: the name of the new room
@param portalName: [OPTIONAL] the name of the portal, defaults to "door"
'''
r = Space( roomName )
r._setWorld(self._world)
p = Portal( directionIn, directionOut, self, r, portalName )
r._portals.append(p)
self._messageOccupants("%s created a %s leading %s to %s" % ( player._name, portalName, directionOut, roomName ), player)
player._message_confirmation("Done")
self._portals.append( p )
return r
class World(object):
def __init__(self, name="DefaultWorld"):
self.name = name
basePlayer = Player("DefualtPlayer", None, None)
self.spaces = [Space("The Entrance Hall").describe(basePlayer, "An empty, blank room")]
self.spaces[0]._setWorld(self)
self._items = []
self.npcs = []
self.players = []
self._currentLocation = None;
self.defaultLocation = self.spaces[0]
def download(self, player):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
valid_name = ''.join(c for c in self.name if c in valid_chars) + ".taplWorld"
print "saving " + valid_name
dup = copy.deepcopy(self)
# delete the player objects from this copy
for s in dup.spaces:
s._occupants = []
f=open(os.path.join(os.path.abspath(os.curdir), "static", "worlds", valid_name), 'wb')
pickle.dump(dup, f, -1)
f.close()
player._message_confirmation("Click <a href='%s' target='_blank'>Here</a> to download the world" % (TAPL().getHostName() + "/worlds/" + valid_name))
#player._handler.offerFile(os.path.join(os.path.abspath(os.curdir), valid_name))
return "Downloading world from %s" % (TAPL().getHostName() + "/worlds/" + valid_name)
def createItem(self, player, name):
item = Item( name )
self._items.append(item)
return item
def save(self, player):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
valid_name = ''.join(c for c in self.name if c in valid_chars) + ".taplWorld"
print "saving " + valid_name
dup = copy.deepcopy(self)
# delete the player objects from this copy
for s in dup.spaces:
s._occupants = []
f=open(os.path.join(os.path.abspath(os.curdir), valid_name), 'w')
f.write(pickle.dumps(dup))
f.close()
return "World saved as '" + valid_name + "'"
def load(self, player, filename):
try:
f=open(filename, "r")
world = pickle.reads(f.read())
return world
except:
return "Cannot load world!"
def getWorlds(self, player=None):
worlds = "Available worlds on this server:\n" + "\n".join([w.name for w in TAPL().worlds])
return worlds
def createSpace(self, player, name):
space = Space(name)
self.spaces.append(space)
return space
def setCurrentLocation(self,spaceName):
#print "Setting Location", spaceName
if type( spaceName ) == Space:
self._currentLocation=spaceName
return
for s in self.spaces:
if s._name == spaceName:
self._currentLocation = s
return
def setEntrance( self, space ):
self.defaultLocation = space
return self
class Item:
def __init__(self, name):
self._name = name
self._description = ""
self.alias = ""
self.verbs = {}
self.props = {}
self.eventHandlers = {}
self.contents = []
self.openable = False
def __repr__(self):
return "[ ITEM: %s ]" % self._name
def putInside(self, player, container):
if isinstance(container, Item):
container.contents.append(self)
container.openable = True
def removeItem(self, player, item):
pass
def notify(self, player, eventName, response):
self.eventHandlers[eventName] = response
return self
def describe(self, player, description):
self._description = description
return self
def setAlias(self, player, alias):
self.alias = alias
return self
def verb(self, player, verbName, response, item=None):
self.verbs[verbName] = response
return self
def setProp(self, player, propName, propValue):
self.props[propName]=propValue
return self
def getProp(self, player, propName):
if self.props.has_key(propName):
return self.props[propName]
return "Error: No property named: " + propName + " on "
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
##get auto complete arrays
p = Player("Nob", None, None)
PlayerCommands = ["@me." + i for i in dir(p) if not (i.startswith("_"))]
PlayerDocs = []
AllDocs = {}
for i in dir(p):
if not i.startswith("_"):
AllDocs["@me." + i] = getattr(p, i).__doc__
AllDocs.update(gameCommands)
itm = Item("TestItem")
ItemCommands = [i for i in dir(itm) if not (i.startswith("_"))]
ItemDocs = []
for i in dir(itm):
if not i.startswith("_"):
AllDocs[i] = getattr(itm, i).__doc__
#ItemDocs = map( lambda x : (x[0], "") if x[1] == None else x, ItemDocs )
spc = Space("TestSpace")
SpaceCommands = [ "@here." + i for i in dir(spc) if not (i.startswith("_"))]
SpaceDocs = []
for i in dir(spc):
if not i.startswith("_"):
AllDocs["@here." + i] = getattr(spc, i).__doc__
#SpaceDocs = map( lambda x : (x[0], "") if x[1] == None else x, SpaceDocs )
wrld = World("TestWorld")
WorldCommands = ["@world." + i for i in dir(wrld) if not (i.startswith("_"))]
WorldDocs = []
for i in dir(wrld):
if not i.startswith("_"):
AllDocs["@world." + i] = getattr(wrld, i).__doc__
#WorldDocs = map( lambda x : (x[0], "") if x[1] == None else x, WorldDocs )
print SpaceCommands
#AllDocs = map( lambda x : (x[0], "") if x[1] == None else x, AllDocs )
class TAPL(object):
'''
classdocs
'''
__metaclass__ = Singleton
def jsonArray(self, array):
return "[" + ",".join(['{ "id" : "%s", "label" : "%s", "value" : "%s" }' % ( i, i, i ) for i in array]) + "]"
def getAutoComplete(self, val):
ret = []
if val.find(".") > -1:
precedent = val[0:val.index(".")]
if precedent == "@me":
return self.jsonArray([i for i in PlayerCommands if i.startswith(val)])
elif precedent == "@here":
return self.jsonArray([i for i in SpaceCommands if i.startswith(val)])
elif precedent == "@world":
return self.jsonArray([i for i in WorldCommands if i.startswith(val)])
else:
# here we need to search in the current namespace for items
return self.getContextAutoComplete(precedent, val)
elif val[0] == "@":
return self.jsonArray(["@me", "@here", "@world"])
coms = [g for g in gameCommands.keys() if g.startswith(val)]
if len(coms):
return self.jsonArray(coms)
return '[]'
def getContextAutoComplete(self, var, fullCommand):
print "Context auto complete", var, fullCommand
if self.variables.has_key(var):
if isinstance(self.variables[var], Item):
ar = [var + "." + i for i in ItemCommands]
return self.jsonArray( [k for k in ar if k.startswith(fullCommand) ] )
return "[]"
def getAllCommands(self):
ret = "<span class='title'>-=[ HELP ]=-</span><br/><br/>"
ret += "<table cellspacing='10'><tr>"
ret += "<td valign='top'><b>Game Commands:</b><br/>" + "<br/>".join(gameCommands.keys()) + "</td></tr><tr>"
ret += "<td valign='top'><b>Player Commands:</b><br/>" + "<br/>".join(PlayerCommands) + "</td>"
ret += "<td valign='top'><b>Location Commands:</b><br/>" + "<br/>".join(SpaceCommands) + "</td>"
ret += "</tr><tr>"
ret += "<td valign='top'><b>Item Commands:</b><br/>" + "<br/>".join(ItemCommands) + "</td>"
ret += "<td valign='top'><b>World Commands:</b><br/>" + "<br/>".join(WorldCommands) + "</td>"
ret += "</tr></table>"
ret += "<br/><br/>type 'help <command>' to get help on a specific command. eg:<br/>help @me.createItem<br/>"
return ret
def __init__(self):
'''
Constructor
'''
self.variables = {}
self._world = World()
self.worlds = [self._world]
self.loadWorlds()
self.hostName = ""
self.loggedInPlayers = []
#self.createServer()
#self.createDefaultLocation()
def getLoggedInPlayers(self):
return self.loggedInPlayers
def isPlayerLoggedIn(self, player):
for p in self.loggedInPlayers:
if p._userName == player._userName:
return True
return False
def getPlayerByUserName(self, name):
for p in self.loggedInPlayers:
if p._userName == name:
return p
return None
def setHostName(self, name):
self.hostName = name
def getHostName(self):
return self.hostName
def loadWorlds(self):
path = os.path.abspath(os.curdir)
files = os.listdir(path)
toLoad = []
for f in files:
root, ext = os.path.splitext(f)
if ext == ".taplWorld":
toLoad.append(os.path.join(os.path.abspath(os.curdir), f))
for n in toLoad:
print "server loading world: " + n
fl = open(n, "r")
self.worlds.append(pickle.load(fl))
fl.close()
for w in self.worlds:
for s in w.spaces:
s._occupants = []
def createDefaultLocation(self):
'''
Create a default space in the _world that
players arrive in
'''
space = self._world.createSpace("Starting Room")
space.describe("A white room with bare walls.")
self._world.setCurrentLocation(space)
self.defaultLocation = space
def playerLoggedIn(self, name, conn, addr):
'''
This function is called from the websocket server
for each player that logs in. It returns the corresponding
game player object so the connection can identify itself
when passing commands from the web console
'''
#print "player _joined: " + _name + ", " + str(conn)
p = Player(name, conn, addr)
self.loggedInPlayers.append(p)
self.worlds[0].defaultLocation._occupants.append(p)
p._setLocation(self.worlds[0].defaultLocation)
return p
def playerLoggedOut(self, player):
pass
def addWorld( self, world ):
if not world in self.worlds:
self.worlds.append( world )
print "Adding new _world"
def closestMatchItem(self, u, player):
'''
Fuzzy match a _name typed in by the player to a real object
'''
items = [i._name for i in player._currentLocation._items]
#result = min(_items, key=lambda v: len(set(u) ^ set(v)))
result = get_close_matches(u, items, 1, 0.4)
if len(result)<1:
return "[NO MATCH]"
return result[0]
def doPlayerLogin(self, player):
player._loginStage = 1
player._message_notification("<b>LOGIN:</b> Please enter your user name")
return
def processLogin(self, msg, client):
if client._loginStage == 1:
# we're expecting a username here
# try to load the pickled user state
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
fileName = ''.join(c for c in msg if c in valid_chars) + ".taplPlayer"
try:
f = open(os.path.join(os.path.abspath(os.curdir), fileName))
client._player = pickle.loads(f.read())
print "Desired Password", client._player._password
client._message_notification("Please enter your password")
client._loginStage = 2
f.close()
except:
client._message_alert("No user named %s on this server!" % msg)
client._loginStage = 0
return
return
if client._loginStage == 2:
# we're expecting a password now
# the correct password ( and the loaded
# user ) are currently stored as variables
# on the 'client' object. Currently
# the client is still a 'Guest', if the password
# is correct, we replace the player object
# with the loaded pickled version
# and set _loginStage to 3
if hasattr(client, '_player'):
if client._player != None: