Advertisement
Guest User

Untitled

a guest
Jun 2nd, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.94 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] == 'R':
  159.                 room = int(line[1])
  160.                 rooms.append(Room())
  161.                 which = rooms[room]
  162.                
  163.                 if line[2] == 'N':
  164.                     self.writeTo = 1
  165.                     self.lineToWrite += self._sameLineAsStart(line, room)
  166.                
  167.                     if self.readyToWrite == 1:
  168.                         which.set_name(self.lineToWrite)
  169.                         self._resetStuff()
  170.                        
  171.                 elif line[2] == 'E':
  172.                     self.writeTo = 2
  173.                     self.lineToWrite += self._sameLineAsStart(line, room)
  174.                
  175.                     if self.readyToWrite == 1:
  176.                         which.set_entry_desc(self.lineToWrite)
  177.                         self._resetStuff()
  178.                        
  179.                 elif line[2] == 'D':
  180.                     self.writeTo = 3
  181.                     self.lineToWrite += self._sameLineAsStart(line, room)
  182.                    
  183.                     if self.readyToWrite == 3:
  184.                         which.set_description(self.lineToWrite)
  185.                         self._resetStuff()
  186.                        
  187.                 elif line[2] == 'X':
  188.                     line2 = line[3:]
  189.                     for i in range(len(line2)):
  190.                         if line2[i] == 'R':
  191.                             direction = line2[i-1]
  192.                             room = line2[i+1]
  193.                            
  194.                             if direction == 'N':
  195.                                 which.exits.update({'North':room})
  196.                                
  197.                             elif direction == 'S':
  198.                                 which.exits.update({'South':room})
  199.                                
  200.                             elif direction == 'W':
  201.                                 which.exits.update({'West':room})
  202.                                
  203.                             elif direction == 'E':
  204.                                 which.exits.update({'East':room})
  205.                                
  206.                             elif direction == 'U':
  207.                                 which.exits.update({'Up':room})
  208.                                
  209.                             elif direction == 'D':
  210.                                 which.exits.update({'Down':room})
  211.                        
  212.                 elif line[2] == 'H':
  213.                     line2 = line[3:]
  214.                     for i in range(len(line2)):
  215.                         if line2[i] == 'R':
  216.                             direction = line2[i-1]
  217.                             room = line2[i+1]
  218.                            
  219.                             if direction == 'N':
  220.                                 which.hidden.update({'North':room})
  221.                                
  222.                             elif direction == 'S':
  223.                                 which.hidden.update({'South':room})
  224.                                
  225.                             elif direction == 'W':
  226.                                 which.hidden.update({'West':room})
  227.                                
  228.                             elif direction == 'E':
  229.                                 which.hidden.update({'East':room})
  230.                                
  231.                             elif direction == 'U':
  232.                                 which.hidden.update({'Up':room})
  233.                                
  234.                             elif direction == 'D':
  235.                                 which.hidden.update({'Down':room})
  236.            
  237.             if line[0] == '+' and line[1] != '+':
  238.                 self.lineToWrite += '\r\n'
  239.                
  240.             elif line[0] == '-':
  241.                 self.lineToWrite += ' '
  242.                
  243.             if (line[0] == '+' and line[1] != '+') or line[0] == '-':
  244.                 endChar = '\n'
  245.                
  246.                 line2 = line[1:]
  247.                
  248.                 if '\r\n' in line2:
  249.                     endChar = '\r\n'
  250.                          
  251.                 if line2[(-2 - len(endChar)):] == '++' + endChar:
  252.                     self.lineToWrite += line2[:(-2 - len(endChar))] + '\r\n'
  253.                     self._writeTo(which)
  254.                     self._resetStuff()
  255.                 else:      
  256.                     self.lineToWrite += line2[:(0 - len(endChar))]
  257.                
  258.             elif line[0:2] == '++':
  259.                 self.lineToWrite += '\r\n'
  260.                 self._writeTo(which)
  261.                 self._resetStuff()
  262.            
  263.         f.close()
  264.        
  265.     def _resetStuff(self):
  266.         self.lineToWrite = ''
  267.         self.writeTo = 0
  268.         self.readyToWrite = 0
  269.        
  270.     def _writeTo(self, which):
  271.         if self.writeTo == 1:
  272.             which.set_name(self.lineToWrite)
  273.             self._resetStuff()
  274.            
  275.         elif self.writeTo == 2:
  276.             which.set_entry_desc(self.lineToWrite)
  277.             self._resetStuff()
  278.            
  279.         elif self.writeTo == 3:
  280.             which.set_description(self.lineToWrite)
  281.             self._resetStuff()
  282.            
  283.     def _sameLineAsStart(self, line, room):
  284.         endChar = '\n'
  285.         line2 = line[4:]
  286.         if line2[0:2] == '++':
  287.             if '\r\n' in line2:
  288.                 endChar = '\r\n'
  289.                          
  290.             if line2[(-2 - len(endChar)):] == '++' + endChar:
  291.                 self.readyToWrite = 1
  292.                 return line2[2:(-2 - len(endChar))] + '\r\n'
  293.            
  294.             return line2[2:(0 - len(endChar))]
  295.         return ''
  296.  
  297. class Mob (Cont):
  298.  
  299.     """ any creature or person or NPC etc """
  300.    
  301.     def __init__(self, name, location):
  302.         Cont.__init__(self,name, location)
  303.    
  304.     def move(self, to):
  305.         Cont.move(self, to)
  306.        
  307. class NPC (Mob):
  308.  
  309.     """Well... i got nothing ... ill write it soon"""
  310.  
  311.     pass
  312.    
  313. class MUDMsg:
  314.  
  315.     """Basic Template for a MUDMsg"""
  316.    
  317.     def __init__(self, data, caller):
  318.         self.caller = caller
  319.         self.contents = data
  320.  
  321.     def get_caller(self):
  322.         return self.caller
  323.    
  324.     def set_caller(self, obj):
  325.         self.caller = obj
  326.    
  327.     def get_content(self):
  328.         return self.contents
  329.    
  330.     def set_content(self, data):
  331.         self.contents = data
  332.    
  333. class MessageLoop:
  334.  
  335.     """Should be named EventHandler... not sure
  336.        Reads the globalQueue and processes events on it"""
  337.        
  338.     def handle_messages(self):
  339.         for event in globalQueue:
  340.             caller = event.get_caller()
  341.             callerState = caller.get_state()
  342.            
  343.             if isinstance(caller, Konnection):
  344.                 if callerState == PLAYER_STATE_LOGIN:
  345.                     if event.get_content() == "LOGGING IN":
  346.                         self.greet(caller)
  347.                         caller.write("\r\nUser Name: ")
  348.                         caller.set_state(PLAYER_STATE_USERNAME)
  349.                        
  350.                 elif callerState == PLAYER_STATE_USERNAME:
  351.                     if len(event.get_content()) > 0:
  352.                         caller.assign_player(event.get_content(), 0)
  353.                         caller.set_state(PLAYER_STATE_PASSWORD)
  354.                         globalQueue.append(MUDMsg("ENTERING PASSWORD SCREEN", caller))
  355.                        
  356.                 elif callerState == PLAYER_STATE_PASSWORD:
  357.                     if event.get_content() == "ENTERING PASSWORD SCREEN":
  358.                         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"
  359.                         caller.write(passmasg)
  360.                         caller.set_state(PLAYER_STATE_INGAME)
  361.                         caller.move(1)
  362.                    
  363.                 elif callerState == PLAYER_STATE_INGAME:
  364.                     Command(caller, event.get_content())
  365.                     self.prompt(caller)
  366.                    
  367.                 #elif callerState:
  368.                     #pass
  369.                    
  370.             elif isinstance(event.get_caller(), NPC):
  371.                 pass
  372.            
  373.             globalQueue.remove(event)
  374.            
  375.     def prompt(self, caller):
  376.         pass
  377.        
  378.     def greet(self, caller):
  379.         greetmsg = """
  380.         Hello, and welcome to the test Server im working
  381.         on for my newest project!\r\n"""
  382.         caller.write(greetmsg)
  383.                
  384. class Command:
  385.    
  386.     """Parses and handles commands"""
  387.    
  388.     def __init__(self, caller, data):
  389.         if data == "look":
  390.             self.look(caller)
  391.         elif data == 'exit':
  392.             self.exit(caller)
  393.         elif data.lower() == 'n' or data.lower() == 'north':
  394.             self.move(caller, 'North')
  395.         elif data.lower() == 's' or data.lower() == 'south':
  396.             self.move(caller, 'South')
  397.         elif data.lower() == 'w' or data.lower() == 'west':
  398.             self.move(caller, 'West')
  399.         elif data.lower() == 'e' or data.lower() == 'east':
  400.             self.move(caller, 'East')
  401.         elif data.lower() == 'u' or data.lower() == 'up':
  402.             self.move(caller, 'Up')
  403.         elif data.lower() == 'd' or data.lower() == 'down':
  404.             self.move(caller, 'Down')
  405.            
  406.     def look(self,caller):
  407.         caller.write(rooms[caller.location].get_name())
  408.         caller.write(rooms[caller.location].get_description())
  409.         caller.write(rooms[caller.location].get_exits())
  410.        
  411.     def exit(self,caller):
  412.         caller.write("\r\nDisconectting from server...\r\n")
  413.         caller.end_connection()
  414.        
  415.     def move(self, caller, dir):
  416.         if dir in rooms[caller.location].get_exits():
  417.             caller.move(int(rooms[caller.location].exits[dir]))
  418.         else:
  419.             caller.write("\r\nCan't move there\r\n")
  420.            
  421. class Konnection (dispatcher, Mob):
  422.    
  423.     """Client Connections"""
  424.    
  425.     def __init__(self, address, sk, server):
  426.         self.realSelf = self
  427.         dispatcher.__init__(self, sk)
  428.         self.conn = sk
  429.         self.ip = address[0]
  430.         self.server = server
  431.         self.buffer = []
  432.         self.playState = PLAYER_STATE_LOGIN
  433.         self.write("\r\nConnecting to the Server...\r\n")
  434.         print "Login from " + self.ip
  435.         globalQueue.append(MUDMsg("LOGGING IN",self))
  436.    
  437.     def writable(self):
  438.         return self.buffer
  439.        
  440.     def end_connection(self):
  441.         self.buffer.append(None)
  442.    
  443.     def write(self, data):
  444.         self.buffer.append(data)
  445.    
  446.     def handle_read(self):
  447.         data = self.recv(1024)
  448.  
  449.         if  data != "\n" and  data != "\r\n":
  450.             data = data.strip()
  451.        
  452.         if data:
  453.             globalQueue.append(MUDMsg(data, self))
  454.    
  455.     def handle_write(self):
  456.         if self.buffer[0] is None:
  457.             self.close()
  458.             return
  459.        
  460.         sent = self.send(self.buffer[0])
  461.         if sent >= len(self.buffer[0]):
  462.             self.buffer.pop(0)
  463.         else:
  464.             self.buffer[0] = self.buffer[0][send:]
  465.    
  466.     def handle_close(self):
  467.         print "Disconnected from " + self.ip
  468.         self.server.connections.insert(0, self)
  469.         for x in reversed(self.server.connections):
  470.             if x == self.server.connections[0]:
  471.                 self.server.connections.remove(x)
  472.                
  473.     def get_state(self):
  474.         return self.playState
  475.    
  476.     def set_state(self,STATE):
  477.         self.playState = STATE
  478.    
  479.     def assign_player(self, name, location):
  480.         self.name = name
  481.         self.location = location
  482.        
  483.     def move(self, to):
  484.         Mob.move(self, to)
  485.         self.write(rooms[to].entryDesc)
  486.         self.write(rooms[to].description)
  487.         self.write(rooms[to].get_exits())
  488.        
  489. class NetServer (dispatcher):
  490.    
  491.     """ Server class, listens for incoming connections and passes them off to
  492.         a new Konnection """   
  493.  
  494.     def __init__(self, host, port):
  495.         dispatcher.__init__(self)
  496.         self.create_socket(AF_INET, SOCK_STREAM)
  497.         self.set_reuse_addr()
  498.         self.bind((host,port))
  499.         self.listen(5)
  500.         self.connections = []
  501.         print 'Listening on port ' +  `port` + '.'
  502.  
  503.     def writable(self):
  504.         return 0
  505.        
  506.     def handle_accept(self):
  507.         conn, addr= self.accept()
  508.         self.connections.append(Konnection(addr, conn, self))
  509.        
  510.     def end_server(self):
  511.             self.close()
  512.             for co in self.connections:
  513.                 co.write("\r\nSERVER IS SHUTTING DOWN\r\n")
  514.                 co.end_connection()
  515.        
  516.        
  517. # Main
  518.  
  519. server = NetServer("0.0.0.0",2002)
  520. game = MessageLoop()
  521. rF = RoomFactory()
  522.  
  523. rF.load_from_file("roomList")
  524.  
  525. try:
  526.     while 1:
  527.         game.handle_messages()
  528.         poll() #loop(1.0, count = 1)
  529. except KeyboardInterrupt:
  530.     pass
  531.  
  532. server.end_server()
  533. loop(1.0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement