Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ########
- # some classes for the game... still thinking this out
- #
- # -World Classes-
- #
- # Objects(Obj) -> Containers(Cont)
- #
- # Containers(Cont) -> Rooms(Room)
- #
- # Containers(Cont) -> Mobs(Mob)
- #
- # Mobs(Mob) -> (NPCs,Monsters,Misc)(NPC)
- # Mobs(Mob) -> Player(Konnection)
- #
- #
- # RoomFactory - generates a room list
- # RoomFactory.generate(amount) - generates a random room list
- # RoomFactory.load_from_file(filename) - loads a room list from a file
- #
- # -Net handling- merges with world classes by having the client connection
- # part of the Player
- #
- # Konnection(dispatcher,Mob)
- # NetServer(dispatcher)
- #
- # -Game Logic-
- #
- # MUDMsg
- # MessageLoop
- # Command
- #
- ########
- from asyncore import *
- from socket import *
- # Constants and stuff
- PLAYER_STATE_LOGIN = 0
- PLAYER_STATE_USERNAME = 1
- PLAYER_STATE_PASSWORD = 2
- PLAYER_STATE_INGAME = 3
- PLAYER_STATE_FIGHTING = 4
- PLAYER_STATE_SHOPPING = 5
- PLAYER_STATE_DEAD = 6
- AI_STATE_IDLE = 0
- AI_STATE_MOVING = 1
- AI_STATE_FIGHTING = 2
- # GlobalEvent Queue
- globalQueue = []
- # rooms list?
- rooms = []
- class Obj:
- """ Root Class of all game objects """
- def __init__(self):
- self.name = ''
- self.location = 0
- def __init__(self, name, location):
- self.name = name
- self.location = location
- def move(self, to):
- if self.location != 0:
- rooms[self.location].remove(self)
- self.location = to
- rooms[self.location].insert(self)
- class Cont (Obj):
- """ A container, all Mobs are containers and rooms as well """
- def __init__(self):
- Obj.__init__(self)
- self.inventory = []
- def __init__(self, name, location):
- Obj.__init__(self, name, location)
- self.inventory = []
- def contents(self):
- pass
- def push(self, data):
- pass
- def pop(self):
- pass
- def insert(self, data):
- self.inventory.append(data)
- def remove(self, data):
- self.inventory.remove(data)
- def move(self, to):
- Obj.move(self, to)
- class Room (Cont):
- """A Room is just a fancy container"""
- def __init__(self):
- self.name = "void"
- self.entryDesc = "sucked into darkness"
- self.description = "You are in nothingness\r\n"
- self.exits = {}
- self.hidden = {}
- Cont.__init__(self, self.name, 0)
- def set_name(self, data):
- self.name = data
- def get_name(self):
- return self.name
- def set_entry_desc(self, data):
- self.entryDesc = data
- def get_entry_desc(self, data):
- return self.entryDesc
- def set_description(self, data):
- self.description = data
- def get_description(self):
- return self.description
- def get_exits(self):
- lineToWrite = "\r\nObvious Exits:\r\n"
- for dir in self.exits:
- lineToWrite += dir + ', '
- return lineToWrite[:-2] + '\r\n'
- class RoomFactory:
- """ Generate a Random World or Load one from a file """
- def generate(self, amount):
- for x in range(amount):
- rooms.append(Room())
- def load_from_file(self, filename):
- rooms.append(Room())
- self.readyToWrite = 0
- f = open(filename)
- self.writeTo = 0
- which = None
- self.lineToWrite = ''
- for line in f:
- if line[0] == '#':
- continue
- if line[0] == 'R':
- room = int(line[1])
- rooms.append(Room())
- which = rooms[room]
- if line[2] == 'N':
- self.writeTo = 1
- self.lineToWrite += self._sameLineAsStart(line, room)
- if self.readyToWrite == 1:
- which.set_name(self.lineToWrite)
- self._resetStuff()
- elif line[2] == 'D':
- self.writeTo = 3
- self.lineToWrite += self._sameLineAsStart(line, room)
- if self.readyToWrite == 3:
- which.set_description(self.lineToWrite)
- self._resetStuff()
- elif line[2] == 'C':
- pass
- elif line[2] == 'X':
- line2 = line[3:]
- for i in range(len(line2)):
- if line2[i] == 'R':
- direction = line2[i-1]
- room = line2[i+1]
- if direction == 'N':
- which.exits.update({'North':room})
- elif direction == 'S':
- which.exits.update({'South':room})
- elif direction == 'W':
- which.exits.update({'West':room})
- elif direction == 'E':
- which.exits.update({'East':room})
- elif direction == 'U':
- which.exits.update({'Up':room})
- elif direction == 'D':
- which.exits.update({'Down':room})
- elif line[2] == 'H':
- line2 = line[3:]
- for i in range(len(line2)):
- if line2[i] == 'R':
- direction = line2[i-1]
- room = line2[i+1]
- if direction == 'N':
- which.hidden.update({'North':room})
- elif direction == 'S':
- which.hidden.update({'South':room})
- elif direction == 'W':
- which.hidden.update({'West':room})
- elif direction == 'E':
- which.hidden.update({'East':room})
- elif direction == 'U':
- which.hidden.update({'Up':room})
- elif direction == 'D':
- which.hidden.update({'Down':room})
- if line[0] == '+' and line[1] != '+':
- self.lineToWrite += '\r\n'
- elif line[0] == '-':
- self.lineToWrite += ' '
- if (line[0] == '+' and line[1] != '+') or line[0] == '-':
- endChar = '\n'
- line2 = line[1:]
- if '\r\n' in line2:
- endChar = '\r\n'
- if line2[(-2 - len(endChar)):] == '++' + endChar:
- self.lineToWrite += line2[:(-2 - len(endChar))] + '\r\n'
- self._writeTo(which)
- self._resetStuff()
- else:
- self.lineToWrite += line2[:(0 - len(endChar))]
- elif line[0:2] == '++':
- self.lineToWrite += '\r\n'
- self._writeTo(which)
- self._resetStuff()
- f.close()
- def _resetStuff(self):
- self.lineToWrite = ''
- self.writeTo = 0
- self.readyToWrite = 0
- def _writeTo(self, which):
- if self.writeTo == 1:
- which.set_name(self.lineToWrite)
- self._resetStuff()
- elif self.writeTo == 2:
- which.set_entry_desc(self.lineToWrite)
- self._resetStuff()
- elif self.writeTo == 3:
- which.set_description(self.lineToWrite)
- self._resetStuff()
- def _sameLineAsStart(self, line, room):
- endChar = '\n'
- line2 = line[4:]
- if line2[0:2] == '++':
- if '\r\n' in line2:
- endChar = '\r\n'
- if line2[(-2 - len(endChar)):] == '++' + endChar:
- self.readyToWrite = 1
- return line2[2:(-2 - len(endChar))] + '\r\n'
- return line2[2:(0 - len(endChar))]
- return ''
- class Mob (Cont):
- """ any creature or person or NPC etc """
- def __init__(self, name, location):
- Cont.__init__(self, name, location)
- def move(self, to):
- Cont.move(self, to)
- class NPC (Mob):
- """Well... i got nothing ... ill write it soon"""
- def __init__(self, name, location):
- Mob.__init__(self, name, location)
- class NPCLoader:
- def __init__(self):
- pass
- def load_from_file(self, filename):
- pass
- class MUDMsg:
- """Basic Template for a MUDMsg"""
- def __init__(self, data, caller):
- self.caller = caller
- self.contents = data
- def get_caller(self):
- return self.caller
- def set_caller(self, obj):
- self.caller = obj
- def get_content(self):
- return self.contents
- def set_content(self, data):
- self.contents = data
- class MessageLoop:
- """Should be named EventHandler... not sure
- Reads the globalQueue and processes events on it"""
- def handle_messages(self):
- for event in globalQueue:
- caller = event.get_caller()
- callerState = caller.get_state()
- if isinstance(caller, Konnection):
- if callerState == PLAYER_STATE_LOGIN:
- if event.get_content() == "LOGGING IN":
- self.greet(caller)
- caller.write("\r\nUser Name: ")
- caller.set_state(PLAYER_STATE_USERNAME)
- elif callerState == PLAYER_STATE_USERNAME:
- if len(event.get_content()) > 0:
- caller.assign_player(event.get_content(), 0)
- caller.set_state(PLAYER_STATE_PASSWORD)
- globalQueue.append(MUDMsg("ENTERING PASSWORD SCREEN", caller))
- elif callerState == PLAYER_STATE_PASSWORD:
- if event.get_content() == "ENTERING PASSWORD SCREEN":
- 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"
- caller.write(passmasg)
- caller.set_state(PLAYER_STATE_INGAME)
- caller.move(1)
- elif callerState == PLAYER_STATE_INGAME:
- Command(caller, event.get_content())
- self.prompt(caller)
- #elif callerState:
- #pass
- elif isinstance(event.get_caller(), NPC):
- pass
- globalQueue.remove(event)
- def prompt(self, caller):
- pass
- def greet(self, caller):
- greetmsg = """
- Hello, and welcome to the test Server im working
- on for my newest project!\r\n"""
- caller.write(greetmsg)
- class Command:
- """Parses and handles commands"""
- def __init__(self, caller, data):
- if data == "look":
- self.look(caller)
- elif data == 'exit':
- self.exit(caller)
- elif data.lower() == 'n' or data.lower() == 'north':
- self.move(caller, 'North')
- elif data.lower() == 's' or data.lower() == 'south':
- self.move(caller, 'South')
- elif data.lower() == 'w' or data.lower() == 'west':
- self.move(caller, 'West')
- elif data.lower() == 'e' or data.lower() == 'east':
- self.move(caller, 'East')
- elif data.lower() == 'u' or data.lower() == 'up':
- self.move(caller, 'Up')
- elif data.lower() == 'd' or data.lower() == 'down':
- self.move(caller, 'Down')
- def look(self,caller):
- caller.write(rooms[caller.location].get_name())
- caller.write(rooms[caller.location].get_description())
- caller.write(rooms[caller.location].get_exits())
- def exit(self,caller):
- caller.write("\r\nDisconectting from server...\r\n")
- caller.end_connection()
- def move(self, caller, dir):
- if dir in rooms[caller.location].get_exits():
- caller.move(int(rooms[caller.location].exits[dir]))
- elif dir in rooms[caller.location].hidden:
- caller.move(int(rooms[caller.location].hidden[dir]))
- else:
- caller.write("Can't move there\r\n")
- class Konnection (dispatcher, Mob):
- """Client Connections"""
- def __init__(self, address, sk, server):
- self.realSelf = self
- dispatcher.__init__(self, sk)
- self.conn = sk
- self.ip = address[0]
- self.server = server
- self.buffer = []
- self.playState = PLAYER_STATE_LOGIN
- self.write("\r\nConnecting to the Server...\r\n")
- print "Login from " + self.ip
- globalQueue.append(MUDMsg("LOGGING IN",self))
- def writable(self):
- return self.buffer
- def end_connection(self):
- self.buffer.append(None)
- def write(self, data):
- self.buffer.append(data)
- def handle_read(self):
- data = self.recv(1024)
- if data != "\n" and data != "\r\n":
- data = data.strip()
- if data:
- globalQueue.append(MUDMsg(data, self))
- def handle_write(self):
- if self.buffer[0] is None:
- self.close()
- return
- sent = self.send(self.buffer[0])
- if sent >= len(self.buffer[0]):
- self.buffer.pop(0)
- else:
- self.buffer[0] = self.buffer[0][send:]
- def handle_close(self):
- print "Disconnected from " + self.ip
- self.server.connections.insert(0, self)
- for x in reversed(self.server.connections):
- if x == self.server.connections[0]:
- self.server.connections.remove(x)
- def get_state(self):
- return self.playState
- def set_state(self,STATE):
- self.playState = STATE
- def assign_player(self, name, location):
- self.name = name
- self.location = location
- def move(self, to):
- Mob.move(self, to)
- self.write(rooms[to].entryDesc)
- self.write(rooms[to].description)
- self.write(rooms[to].get_exits())
- class NetServer (dispatcher):
- """ Server class, listens for incoming connections and passes them off to
- a new Konnection """
- def __init__(self, host, port):
- dispatcher.__init__(self)
- self.create_socket(AF_INET, SOCK_STREAM)
- self.set_reuse_addr()
- self.bind((host,port))
- self.listen(5)
- self.connections = []
- print 'Listening on port ' + `port` + '.'
- def writable(self):
- return 0
- def handle_accept(self):
- conn, addr= self.accept()
- self.connections.append(Konnection(addr, conn, self))
- def end_server(self):
- self.close()
- for co in self.connections:
- co.write("\r\nSERVER IS SHUTTING DOWN\r\n")
- co.end_connection()
- # Main
- server = NetServer("0.0.0.0",2002)
- game = MessageLoop()
- rF = RoomFactory()
- rF.load_from_file("roomList")
- try:
- while 1:
- game.handle_messages()
- poll() #loop(1.0, count = 1)
- except KeyboardInterrupt:
- pass
- server.end_server()
- loop(1.0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement