Advertisement
Guest User

Untitled

a guest
Jun 2nd, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.06 KB | None | 0 0
  1. ########
  2. # some classes for the game... still thinking this out
  3. #
  4. #   -World Classes-
  5. #
  6. #   Objects(Obj) ->  Containers(Cont)
  7. #
  8. #   Containers(Cont) -> Rooms(Room)
  9. #
  10. #   Containers(Cont) -> Mobs(Mob)
  11. #  
  12. #   Mobs(Mob) -> (NPCs,Monsters,Misc)(NPC)
  13. #   Mobs(Mob) -> Player(Konnection)
  14. #
  15. #
  16. #   RoomFactory - generates a room list
  17. #   RoomFactory.generate(amount) - generates a random room list
  18. #   RoomFactory.load_from_file(filename) - loads a room list from a file
  19. #
  20. #   -Net handling- merges with world classes by having the client connection
  21. #   part of the Player
  22. #  
  23. #   Konnection(dispatcher,Mob)
  24. #   NetServer(dispatcher)
  25. #
  26. #   -Game Logic-
  27. #
  28. #   MUDMsg
  29. #   MessageLoop
  30. #   Command
  31. #
  32. ########
  33.  
  34.  
  35. from asyncore import *
  36. from socket import *
  37.  
  38. # Constants and stuff
  39. PLAYER_STATE_LOGIN = 0
  40. PLAYER_STATE_USERNAME = 1
  41. PLAYER_STATE_PASSWORD = 2
  42. PLAYER_STATE_INGAME = 3
  43. PLAYER_STATE_FIGHTING = 4
  44. PLAYER_STATE_SHOPPING = 5
  45. PLAYER_STATE_DEAD = 6
  46.  
  47. AI_STATE_IDLE = 0
  48. AI_STATE_MOVING = 1
  49. AI_STATE_FIGHTING = 2
  50.  
  51. # GlobalEvent Queue
  52. globalQueue = []
  53.  
  54. # rooms list?
  55. rooms = []
  56.  
  57. class Obj:
  58.    
  59.     """ Root Class of all game objects """
  60.    
  61.     def __init__(self):
  62.         self.name = ''
  63.         self.location = 0
  64.    
  65.     def __init__(self, name, location):
  66.         self.name = name
  67.         self.location = location
  68.        
  69.     def move(self, to):
  70.         if self.location != 0:
  71.             rooms[self.location].remove(self)
  72.        
  73.         self.location = to
  74.         rooms[self.location].insert(self)
  75.  
  76. class Cont (Obj):
  77.  
  78.     """ A container, all Mobs are containers and rooms as well """
  79.    
  80.     def __init__(self):
  81.         Obj.__init__(self)
  82.         self.inventory = []
  83.        
  84.     def __init__(self, name, location):
  85.         Obj.__init__(self, name, location)
  86.         self.inventory = []
  87.        
  88.     def contents(self):
  89.         pass
  90.    
  91.     def push(self, data):
  92.         pass
  93.        
  94.     def pop(self):
  95.         pass
  96.    
  97.     def insert(self, data):
  98.         self.inventory.append(data)
  99.    
  100.     def remove(self, data):
  101.         self.inventory.remove(data)
  102.    
  103.     def move(self, to):
  104.         Obj.move(self, to)
  105.        
  106. class Room (Cont):
  107.  
  108.     """A Room is just a fancy container"""
  109.    
  110.     def __init__(self):
  111.         self.name = "void"
  112.         self.entryDesc = "sucked into darkness"
  113.         self.description = "You are in nothingness\r\n"
  114.         self.exits = {}
  115.         self.hidden = {}
  116.         Cont.__init__(self, self.name, 0)
  117.    
  118.     def set_name(self, data):
  119.         self.name = data
  120.    
  121.     def get_name(self):
  122.         return self.name
  123.    
  124.     def set_entry_desc(self, data):
  125.         self.entryDesc = data
  126.    
  127.     def get_entry_desc(self, data):
  128.         return self.entryDesc
  129.    
  130.     def set_description(self, data):
  131.         self.description = data
  132.    
  133.     def get_description(self):
  134.         return self.description
  135.    
  136.     def get_exits(self):
  137.         lineToWrite = "\r\nObvious Exits:\r\n"
  138.         for dir in self.exits:
  139.             lineToWrite += dir + ', '
  140.         return lineToWrite[:-2] + '\r\n'
  141.        
  142. class RoomFactory:
  143.    
  144.     """ Generate a Random World or Load one from a file """
  145.    
  146.     def generate(self, amount):
  147.         for x in range(amount):
  148.             rooms.append(Room())
  149.            
  150.     def load_from_file(self, filename):
  151.         rooms.append(Room())
  152.         self.readyToWrite = 0
  153.         f = open(filename)
  154.         self.writeTo = 0
  155.         which = None
  156.         self.lineToWrite = ''
  157.         for line in f:
  158.             if line[0] == '#':
  159.                 continue
  160.                
  161.             if line[0] == 'R':
  162.                 room = int(line[1])
  163.                 rooms.append(Room())
  164.                 which = rooms[room]
  165.                
  166.                 if line[2] == 'N':
  167.                     self.writeTo = 1
  168.                     self.lineToWrite += self._sameLineAsStart(line, room)
  169.                
  170.                     if self.readyToWrite == 1:
  171.                         which.set_name(self.lineToWrite)
  172.                         self._resetStuff()
  173.                        
  174.                        
  175.                 elif line[2] == 'D':
  176.                     self.writeTo = 3
  177.                     self.lineToWrite += self._sameLineAsStart(line, room)
  178.                    
  179.                     if self.readyToWrite == 3:
  180.                         which.set_description(self.lineToWrite)
  181.                         self._resetStuff()
  182.                 elif line[2] == 'C':
  183.                     pass
  184.                        
  185.                 elif line[2] == 'X':
  186.                     line2 = line[3:]
  187.                     for i in range(len(line2)):
  188.                         if line2[i] == 'R':
  189.                             direction = line2[i-1]
  190.                             room = line2[i+1]
  191.                            
  192.                             if direction == 'N':
  193.                                 which.exits.update({'North':room})
  194.                                
  195.                             elif direction == 'S':
  196.                                 which.exits.update({'South':room})
  197.                                
  198.                             elif direction == 'W':
  199.                                 which.exits.update({'West':room})
  200.                                
  201.                             elif direction == 'E':
  202.                                 which.exits.update({'East':room})
  203.                                
  204.                             elif direction == 'U':
  205.                                 which.exits.update({'Up':room})
  206.                                
  207.                             elif direction == 'D':
  208.                                 which.exits.update({'Down':room})
  209.                        
  210.                 elif line[2] == 'H':
  211.                     line2 = line[3:]
  212.                     for i in range(len(line2)):
  213.                         if line2[i] == 'R':
  214.                             direction = line2[i-1]
  215.                             room = line2[i+1]
  216.                            
  217.                             if direction == 'N':
  218.                                 which.hidden.update({'North':room})
  219.                                
  220.                             elif direction == 'S':
  221.                                 which.hidden.update({'South':room})
  222.                                
  223.                             elif direction == 'W':
  224.                                 which.hidden.update({'West':room})
  225.                                
  226.                             elif direction == 'E':
  227.                                 which.hidden.update({'East':room})
  228.                                
  229.                             elif direction == 'U':
  230.                                 which.hidden.update({'Up':room})
  231.                                
  232.                             elif direction == 'D':
  233.                                 which.hidden.update({'Down':room})
  234.            
  235.             if line[0] == '+' and line[1] != '+':
  236.                 self.lineToWrite += '\r\n'
  237.                
  238.             elif line[0] == '-':
  239.                 self.lineToWrite += ' '
  240.                
  241.             if (line[0] == '+' and line[1] != '+') or line[0] == '-':
  242.                 endChar = '\n'
  243.                
  244.                 line2 = line[1:]
  245.                
  246.                 if '\r\n' in line2:
  247.                     endChar = '\r\n'
  248.                          
  249.                 if line2[(-2 - len(endChar)):] == '++' + endChar:
  250.                     self.lineToWrite += line2[:(-2 - len(endChar))] + '\r\n'
  251.                     self._writeTo(which)
  252.                     self._resetStuff()
  253.                 else:      
  254.                     self.lineToWrite += line2[:(0 - len(endChar))]
  255.                
  256.             elif line[0:2] == '++':
  257.                 self.lineToWrite += '\r\n'
  258.                 self._writeTo(which)
  259.                 self._resetStuff()
  260.            
  261.         f.close()
  262.        
  263.     def _resetStuff(self):
  264.         self.lineToWrite = ''
  265.         self.writeTo = 0
  266.         self.readyToWrite = 0
  267.        
  268.     def _writeTo(self, which):
  269.         if self.writeTo == 1:
  270.             which.set_name(self.lineToWrite)
  271.             self._resetStuff()
  272.            
  273.         elif self.writeTo == 2:
  274.             which.set_entry_desc(self.lineToWrite)
  275.             self._resetStuff()
  276.            
  277.         elif self.writeTo == 3:
  278.             which.set_description(self.lineToWrite)
  279.             self._resetStuff()
  280.            
  281.     def _sameLineAsStart(self, line, room):
  282.         endChar = '\n'
  283.         line2 = line[4:]
  284.         if line2[0:2] == '++':
  285.             if '\r\n' in line2:
  286.                 endChar = '\r\n'
  287.                          
  288.             if line2[(-2 - len(endChar)):] == '++' + endChar:
  289.                 self.readyToWrite = 1
  290.                 return line2[2:(-2 - len(endChar))] + '\r\n'
  291.            
  292.             return line2[2:(0 - len(endChar))]
  293.         return ''
  294.  
  295. class Mob (Cont):
  296.  
  297.     """ any creature or person or NPC etc """
  298.    
  299.     def __init__(self, name, location):
  300.         Cont.__init__(self, name, location)
  301.    
  302.     def move(self, to):
  303.         Cont.move(self, to)
  304.        
  305. class NPC (Mob):
  306.  
  307.     """Well... i got nothing ... ill write it soon"""
  308.  
  309.     def __init__(self, name, location):
  310.         Mob.__init__(self, name, location)
  311.    
  312.        
  313. class NPCLoader:
  314.     def __init__(self):
  315.         pass
  316.    
  317.     def load_from_file(self, filename):
  318.         pass
  319. class MUDMsg:
  320.  
  321.     """Basic Template for a MUDMsg"""
  322.    
  323.     def __init__(self, data, caller):
  324.         self.caller = caller
  325.         self.contents = data
  326.  
  327.     def get_caller(self):
  328.         return self.caller
  329.    
  330.     def set_caller(self, obj):
  331.         self.caller = obj
  332.    
  333.     def get_content(self):
  334.         return self.contents
  335.    
  336.     def set_content(self, data):
  337.         self.contents = data
  338.    
  339. class MessageLoop:
  340.  
  341.     """Should be named EventHandler... not sure
  342.        Reads the globalQueue and processes events on it"""
  343.        
  344.     def handle_messages(self):
  345.         for event in globalQueue:
  346.             caller = event.get_caller()
  347.             callerState = caller.get_state()
  348.            
  349.             if isinstance(caller, Konnection):
  350.                 if callerState == PLAYER_STATE_LOGIN:
  351.                     if event.get_content() == "LOGGING IN":
  352.                         self.greet(caller)
  353.                         caller.write("\r\nUser Name: ")
  354.                         caller.set_state(PLAYER_STATE_USERNAME)
  355.                        
  356.                 elif callerState == PLAYER_STATE_USERNAME:
  357.                     if len(event.get_content()) > 0:
  358.                         caller.assign_player(event.get_content(), 0)
  359.                         caller.set_state(PLAYER_STATE_PASSWORD)
  360.                         globalQueue.append(MUDMsg("ENTERING PASSWORD SCREEN", caller))
  361.                        
  362.                 elif callerState == PLAYER_STATE_PASSWORD:
  363.                     if event.get_content() == "ENTERING PASSWORD SCREEN":
  364.                         passmasg = "\r\nHi!, " + caller.name + ". Use the Look command. Since this is just for testing" + "\r\nYou will be signed in without an account\r\n"
  365.                         caller.write(passmasg)
  366.                         caller.set_state(PLAYER_STATE_INGAME)
  367.                         caller.move(1)
  368.                    
  369.                 elif callerState == PLAYER_STATE_INGAME:
  370.                     Command(caller, event.get_content())
  371.                     self.prompt(caller)
  372.                    
  373.                 #elif callerState:
  374.                     #pass
  375.                    
  376.             elif isinstance(event.get_caller(), NPC):
  377.                 pass
  378.            
  379.             globalQueue.remove(event)
  380.            
  381.     def prompt(self, caller):
  382.         pass
  383.        
  384.     def greet(self, caller):
  385.         greetmsg = """
  386.         Hello, and welcome to the test Server im working
  387.         on for my newest project!\r\n"""
  388.         caller.write(greetmsg)
  389.                
  390. class Command:
  391.    
  392.     """Parses and handles commands"""
  393.    
  394.     def __init__(self, caller, data):
  395.         if data == "look":
  396.             self.look(caller)
  397.         elif data == 'exit':
  398.             self.exit(caller)
  399.         elif data.lower() == 'n' or data.lower() == 'north':
  400.             self.move(caller, 'North')
  401.         elif data.lower() == 's' or data.lower() == 'south':
  402.             self.move(caller, 'South')
  403.         elif data.lower() == 'w' or data.lower() == 'west':
  404.             self.move(caller, 'West')
  405.         elif data.lower() == 'e' or data.lower() == 'east':
  406.             self.move(caller, 'East')
  407.         elif data.lower() == 'u' or data.lower() == 'up':
  408.             self.move(caller, 'Up')
  409.         elif data.lower() == 'd' or data.lower() == 'down':
  410.             self.move(caller, 'Down')
  411.            
  412.     def look(self,caller):
  413.         caller.write(rooms[caller.location].get_name())
  414.         caller.write(rooms[caller.location].get_description())
  415.         caller.write(rooms[caller.location].get_exits())
  416.        
  417.     def exit(self,caller):
  418.         caller.write("\r\nDisconectting from server...\r\n")
  419.         caller.end_connection()
  420.        
  421.     def move(self, caller, dir):
  422.         if dir in rooms[caller.location].get_exits():
  423.             caller.move(int(rooms[caller.location].exits[dir]))
  424.         elif dir in rooms[caller.location].hidden:
  425.             caller.move(int(rooms[caller.location].hidden[dir]))
  426.         else:
  427.             caller.write("Can't move there\r\n")
  428.            
  429. class Konnection (dispatcher, Mob):
  430.    
  431.     """Client Connections"""
  432.    
  433.     def __init__(self, address, sk, server):
  434.         self.realSelf = self
  435.         dispatcher.__init__(self, sk)
  436.         self.conn = sk
  437.         self.ip = address[0]
  438.         self.server = server
  439.         self.buffer = []
  440.         self.playState = PLAYER_STATE_LOGIN
  441.         self.write("\r\nConnecting to the Server...\r\n")
  442.         print "Login from " + self.ip
  443.         globalQueue.append(MUDMsg("LOGGING IN",self))
  444.    
  445.     def writable(self):
  446.         return self.buffer
  447.        
  448.     def end_connection(self):
  449.         self.buffer.append(None)
  450.    
  451.     def write(self, data):
  452.         self.buffer.append(data)
  453.    
  454.     def handle_read(self):
  455.         data = self.recv(1024)
  456.  
  457.         if  data != "\n" and  data != "\r\n":
  458.             data = data.strip()
  459.        
  460.         if data:
  461.             globalQueue.append(MUDMsg(data, self))
  462.    
  463.     def handle_write(self):
  464.         if self.buffer[0] is None:
  465.             self.close()
  466.             return
  467.        
  468.         sent = self.send(self.buffer[0])
  469.         if sent >= len(self.buffer[0]):
  470.             self.buffer.pop(0)
  471.         else:
  472.             self.buffer[0] = self.buffer[0][send:]
  473.    
  474.     def handle_close(self):
  475.         print "Disconnected from " + self.ip
  476.         self.server.connections.insert(0, self)
  477.         for x in reversed(self.server.connections):
  478.             if x == self.server.connections[0]:
  479.                 self.server.connections.remove(x)
  480.                
  481.     def get_state(self):
  482.         return self.playState
  483.    
  484.     def set_state(self,STATE):
  485.         self.playState = STATE
  486.    
  487.     def assign_player(self, name, location):
  488.         self.name = name
  489.         self.location = location
  490.        
  491.     def move(self, to):
  492.         Mob.move(self, to)
  493.         self.write(rooms[to].entryDesc)
  494.         self.write(rooms[to].description)
  495.         self.write(rooms[to].get_exits())
  496.        
  497. class NetServer (dispatcher):
  498.    
  499.     """ Server class, listens for incoming connections and passes them off to
  500.         a new Konnection """   
  501.  
  502.     def __init__(self, host, port):
  503.         dispatcher.__init__(self)
  504.         self.create_socket(AF_INET, SOCK_STREAM)
  505.         self.set_reuse_addr()
  506.         self.bind((host,port))
  507.         self.listen(5)
  508.         self.connections = []
  509.         print 'Listening on port ' +  `port` + '.'
  510.  
  511.     def writable(self):
  512.         return 0
  513.        
  514.     def handle_accept(self):
  515.         conn, addr= self.accept()
  516.         self.connections.append(Konnection(addr, conn, self))
  517.        
  518.     def end_server(self):
  519.             self.close()
  520.             for co in self.connections:
  521.                 co.write("\r\nSERVER IS SHUTTING DOWN\r\n")
  522.                 co.end_connection()
  523.        
  524.        
  525. # Main
  526.  
  527. server = NetServer("0.0.0.0",2002)
  528. game = MessageLoop()
  529. rF = RoomFactory()
  530.  
  531. rF.load_from_file("roomList")
  532.  
  533. try:
  534.     while 1:
  535.         game.handle_messages()
  536.         poll() #loop(1.0, count = 1)
  537. except KeyboardInterrupt:
  538.     pass
  539.  
  540. server.end_server()
  541. loop(1.0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement