Tofu-0.5/0000755002342000234200000000000010443073753011532 5ustar duckdc-usersTofu-0.5/demo/0000755002342000234200000000000010443073753012456 5ustar duckdc-usersTofu-0.5/demo/demo.py0000644002342000234200000003767710434714565014003 0ustar duckdc-users# TOFU # Copyright (C) 2005 Jean-Baptiste LAMY # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # This is a small Tk-based demo using Tofu. # To run it, execute the run_demo.py script. # Try python ./run_demo.py --help for more info. import sys, random, Tkinter import tofu # Tofu provide some base classes that you must extend, and finally you call # tofu.init() and pass these classes to it. # The first class is the Level class. A level is a level in the game. class Level(tofu.Level): def __init__(self, filename): # Don't forget to call Tofu's implmentation when you override a method!!! tofu.Level.__init__(self, filename) print "* Demo * creating level %s..." % filename # The level contains a 10x10 square array. 3 of them are randomly choosen to # contain a wall. self.walls = [0] * 100 for i in range(3): self.walls[random.randrange(0, 100)] = 1 # These attribute are used when drawing the level in the Tk Canvas. self.canvas = None self.level_tags = [] # Add a bot (see the Bot class below) if filename == "1_0": bot = Bot() self.add_mobile(bot) bot.y = 6 # When we load a level, if the level is not found, we create a new one. # (By default, an error is risen) def load(clazz, filename): try: return tofu.Level.load(filename) except ValueError: return Level(filename) load = classmethod(load) # Returns the level located next to this one (e.g. if delta_x = 1 and delta_y = 0, # returns the level at the left of this one). def neighbour(self, delta_x, delta_y): x, y = map(int, self.filename.split("_")) x += delta_x y += delta_y return Level.get("%s_%s" % (x, y)) def __repr__(self): s = "level %s : \n" % (self.filename,) for y in xrange(10): for x in xrange(10): s += str(self.walls[x + y * 10]) + " " s += "\n" s += "characters :\n" for character in self.mobiles: s = s + " " + `character` + "\n" return s # Sets the Tk canvas and draws the level in this canvas. If the canvas is None, the # level's canva items are destroyed. def set_canvas(self, canvas): if canvas: self.canvas = canvas self._draw() else: if self.canvas: self._clear() self.canvas = self.tag = None # Sets the canvas for all mobiles in the level. for mobile in self.mobiles: mobile.set_canvas(canvas) # Draw the level in the Tk canvas. # Canvas items are stored in self.level_tags for _clear() def _draw (self): self._clear() self.level_tags = [self.canvas.create_rectangle(x * 20, y * 20, (x + 1) * 20, (y + 1) * 20, fill = "black") for x in xrange(10) for y in xrange(10) if self.walls[x + y * 10] ] # Destroy all canvas items used to draw the level. def _clear(self): self.canvas.delete(*self.level_tags) # set_active is called when the level is activated or de-activated. # An active level is a level that contains at least a player, and thus # active levels should be drawn. def set_active(self, active): # tofu.GAME_INTERFACE is the current game interface, i.e. the visible part of the # game (see GameInterface below). # if tofu.GAME_INTERFACE is None, we are running the server, and so we don't have # to draw anything ! if tofu.GAME_INTERFACE: # If the level is active, we set its canvas to the game interface Tk canvas in # order to make the level visible. # Else, we set the canvas to None to hide the level. if active: self.set_canvas(tofu.GAME_INTERFACE.canvas) else: self.set_canvas(None) # Delegates AFTER, because set_active(0) can call save(), and we DON'T WANT to # save the Tk canvas ! tofu.Level.set_active(self, active) def discard(self): # When the level is discarded, we hide it by setting the canavas to None. # Remove the canvas BEFORE discarding, because discard may save the character, and # we DON'T WANT to save the Tk canvas ! self.set_canvas(None) tofu.Level.discard(self) # add_mobile is called when a mobile is added into the level. # When a mobile is added in the level, we set the mobile's canvas to the level canvas, # and thus if the level is displayed in the game interface canvas, the mobile will be # displayed too. def add_mobile(self, mobile): tofu.Level.add_mobile(self, mobile) mobile.set_canvas(self.canvas) # remove_mobile is called when a mobile is removed from the level. # When a mobile is removed from the level, we set the mobile's canvas to None, # in order to hide the mobile if it was displayed. def remove_mobile(self, mobile): mobile.set_canvas(None) tofu.Level.remove_mobile(self, mobile) # add_wall is called when a wall is added in the level. # After adding the wall, we redraw the level if needed. def add_wall(self, x, y): self.walls[x + y * 10] = 1 if self.canvas: self._draw() # A Player represent a human player. class Player(tofu.Player): # Player.__init__ is called when a NEW player is created (NOT when an existent player # logon !). # filename and password are the player's login and password. An additional string data # can be passed by the client, here we ignore them. # Player.__init__ must create at least one mobile for the player, then add this mobile # in a level and finally add the mobile in the player. def __init__(self, filename, password, client_side_data = ""): tofu.Player.__init__(self, filename, password) level = Level.get("0_0") character = PlayerCharacter(self.filename) level.add_mobile(character) self .add_mobile(character) # An Action is an action a mobile can accomplish. # Here, we have 5 actions: 4 moves, and wall creation. ACTION_MOVE_LEFT = 1 ACTION_MOVE_RIGHT = 2 ACTION_MOVE_UP = 3 ACTION_MOVE_DOWN = 4 ACTION_CREATE_WALL = 5 class Action(tofu.Action): def __init__(self, action = 0): tofu.Action.__init__(self) self.action = action # A state is the state of a mobile, here its current X,Y position. # spc is used to indicate special action like wall creation. class State(tofu.State): def __init__(self, x, y, spc = 0): tofu.State.__init__(self) self.x = x self.y = y self.spc = spc # is_crucial must returns true if the state is crucial. # Non-crucial states can be dropped, either for optimization purpose or because of # network protocol (currently we use TCP, but in the future we may use UDP to send # non-crucial states). def is_crucial(self): return self.spc # A mobile is anything that can move and evolve in a level. This include player characters # but also computer-controlled objects (also named bots). class Mobile(tofu.Mobile): def __init__(self, name): tofu.Mobile.__init__(self) # x and y are the position of the mobile. name is the text displayed in the interface. # canvas and tag are the tk canvas in which the mobile is drawn, and the # corresponding canvas item. self.x = 4 self.y = 4 self.name = name[:4] self.canvas = None self.tag = None # Sets the Tk canvas and draws the mobile in this canvas. If the canvas is None, the # mobile's canva items are destroyed. def set_canvas(self, canvas): if self.canvas: self.canvas.delete(self.tag) self.tag = None self.canvas = canvas if canvas: self.tag = canvas.create_text(self.x * 20 + 10, self.y * 20 + 10, text = self.name) # do_action is called when the mobile executes the given action. It is usually called # on the server side. # It must return the new State of the Mobile, after the action is executed. def do_action(self, action): if action: # Computes the new X,Y position. new_x, new_y = self.x, self.y if action.action == ACTION_MOVE_LEFT : new_x -= 1 elif action.action == ACTION_MOVE_RIGHT: new_x += 1 elif action.action == ACTION_MOVE_UP : new_y -= 1 elif action.action == ACTION_MOVE_DOWN : new_y += 1 # Checks if we are out of the level, i.e. if the mobile moves to a new level. new_level = self.level if new_x < 0: new_x += 10; new_level = self.level.neighbour(-1, 0) if new_x > 9: new_x -= 10; new_level = self.level.neighbour( 1, 0) if new_y < 0: new_y += 10; new_level = self.level.neighbour( 0, -1) if new_y > 9: new_y -= 10; new_level = self.level.neighbour( 0, 1) # Checks if the new position is inside a wall. if not new_level.walls[new_x + new_y * 10]: if not new_level is self.level: # Change to new level. self.level.remove_mobile(self) new_level.add_mobile(self) # Return a state with the new position. self.doer.action_done(State(new_x, new_y, action.action)) return #return State(new_x, new_y, action.action) # Else, the mobile doesn't move => we return a state with the previous position. self.doer.action_done(State(self.x, self.y)) #return State(self.x, self.y) # set_state is called when the mobile's state change, due to the execution of an # action. It is called BOTH server-side and client-side. def set_state(self, state): tofu.Mobile.set_state(self, state) # If the new position is different than the old one, update the mobile and, if # needed, move the corresponding canvas item. if (self.x, self.y) != (state.x, state.y): self.x = state.x self.y = state.y if self.tag: self.canvas.coords(self.tag, self.x * 20 + 10, self.y * 20 + 10) # If the action was "create wall", create the wall ! if state.spc == ACTION_CREATE_WALL: self.level.add_wall(self.x, self.y) def discard(self): # When the mobile is discarded, we hide it by setting the canavas to None. # Remove the canvas BEFORE discarding, because discard may save the character, and # we DON'T WANT to save the Tk canvas ! self.set_canvas(None) tofu.Mobile.discard(self) # A PlayerCharacter is a Mobile controlled by a human player. class PlayerCharacter(Mobile): def __init__(self, name): Mobile.__init__(self, name) # action is the next action the character will do; it is set by the game interface. self.action = None # next_action is called when the character must choose its next action. # Here we simply return self.action. def next_action(self): if self.action: action, self.action = self.action, None return action # control_owned is called on the client-side when the player gets the control of the # mobile (i.e. the mobile is not a bot). def control_owned(self): tofu.Mobile.control_owned(self) # Set the game interface player character to this mobile. # The game interface will set the action for this mobile. tofu.GAME_INTERFACE.player_character = self # A Bot is a Mobile controlled by the computer player. class Bot(Mobile): def __init__(self, name = "bot"): Mobile.__init__(self, name = "bot") # Set the bot attribute to true. Tofu will now consider this Mobile as a bot. self.bot = 1 self.direction = -40 # next_action is called when the character must choose its next action. # Here, the bot moves horizontally. def next_action(self): dir = cmp(self.direction, 0) self.direction += 1 if self.direction > 40: self.direction = -49 if self.direction / 10.0 == self.direction // 10 : if self.direction < 0: return Action(ACTION_MOVE_LEFT) elif self.direction > 0: return Action(ACTION_MOVE_RIGHT) # GameInterface is the interface of the game. Here, we use Tk and thus GameInterface # inherits from Tk toplevel window. class GameInterface(tofu.GameInterface, Tkinter.Toplevel): def __init__(self): # Initialises Tk and install Twisted Tk support. tkroot = Tkinter.Tk(className = 'tofu_demo') tkroot.withdraw() import twisted.internet.tksupport twisted.internet.tksupport.install(tkroot) tofu.GameInterface.__init__(self) Tkinter.Toplevel.__init__(self, tkroot) # Creates a canvas. self.canvas = Tkinter.Canvas(self, bg = "white") self.canvas.place(x = 0, y = 0, width = 200, height = 200) # The character we are playing. self.player_character = None # Binds cursor keys. self.bind("" , self.on_move_up) self.bind("" , self.on_move_down) self.bind("" , self.on_move_left) self.bind("", self.on_move_right) self.bind("" , self.on_create_wall) # To quite the game, we call GameInterface.end_game(). self.bind("" , lambda event = None: self.end_game()) self.bind("" , lambda event = None: self.end_game()) # When a key is pressed, we set the current character's action to a new action # according to that key. def on_move_left (self, event = None): self.player_character.action = Action(ACTION_MOVE_LEFT) def on_move_right (self, event = None): self.player_character.action = Action(ACTION_MOVE_RIGHT) def on_move_up (self, event = None): self.player_character.action = Action(ACTION_MOVE_UP) def on_move_down (self, event = None): self.player_character.action = Action(ACTION_MOVE_DOWN) def on_create_wall(self, event = None): self.player_character.action = Action(ACTION_CREATE_WALL) # ready is called when the client has contacted the server and anything is ready. # In particular, we can now call self.notifier.login_player to logon the server. def ready(self, notifier): tofu.GameInterface.ready(self, notifier) login, password = sys.argv[-1], "test" self.notifier.login_player(login, password) # Tofu uses serialization to transfert object from server to client and vice-versa, and # to store level and player data in local file. # Tofu can use 2 different protocol: cPickle and Cerealizer. You can also use different # protocols for local file and network. # Some concerns about these protocols : # - cPickle is not safe for network and must not be used for that !!! # - Cerealizer require that you register the classes that are safe # My advice is to use Cerealizer for network (since it's safe) and either Cerealizer or cPickle # for local file. # If you are using Soya, you should use cPickle for local file, however i'm planning to use # Cerealizer as default in Soya soon. # # To each protocol corresponds a function like : # tofu.enable_(enable_for_local, enable_for_network) # For Cerealizer + cPickle: # #tofu.enable_pickle (1, 0) #tofu.enable_cerealizer(0, 1) # For Cerealizer: # tofu.enable_cerealizer(1, 1) # Registers our classes as safe for Cerealizer # Level and Player class MUST be registred using the tofu.SavedInAPathHandler Cerealizer handler. import cerealizer cerealizer.register(Action) cerealizer.register(State) cerealizer.register(Mobile) cerealizer.register(Bot) cerealizer.register(PlayerCharacter) cerealizer.register(Level , tofu.SavedInAPathHandler(Level )) cerealizer.register(Player, tofu.SavedInAPathHandler(Player)) # Inits Tofu with our classes. tofu.init(GameInterface, Player, Level, Action, State, Mobile) Tofu-0.5/demo/run_demo.py0000644002342000234200000000374310433715771014651 0ustar duckdc-users# TOFU # Copyright (C) 2005 Jean-Baptiste LAMY # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import tofu # Put data file in /tmp/tofu_test, and create the data directories if needed. import os try: os.mkdir("/tmp/tofu_test") except: pass try: os.mkdir("/tmp/tofu_test/players") except: pass try: os.mkdir("/tmp/tofu_test/levels") except: pass tofu.path.append("/tmp/tofu_test") #Import demo from demo import * # Print usage if (not sys.argv[1:]) or ("--help" in sys.argv): print """run_demo.py -- Launch Tofu Demo Usages : python run_demo.py --single [] Starts a single player game python run_demo.py --server Starts the server python run_demo.py --client [] Starts a client and connect to server with login and password . If login doesn't exist, a new player is created. """ else: # Create an Idler (=a main loop) idler = tofu.Idler() # Lauch a single player game, a server or a client. # Calling serve_forever will start the idler. if sys.argv[1] == "--single": import tofu.single tofu.single.serve_forever() elif sys.argv[1] == "--server": import tofu.server tofu.server.serve_forever() elif sys.argv[1] == "--client": import tofu.client hostname = sys.argv[2] tofu.client.serve_forever(hostname) Tofu-0.5/README0000644002342000234200000000246510433715771012423 0ustar duckdc-users ******************* TOFU ******************* Tofu is a practical high-level network game engine, written in Python and based on Twisted. Tofu is designed for games where players play one or several characters accross several levels. This includes jump'n run games, RPG or RTS, but not Tetris-like games or board game (chess, go,...). It currently support client-server and single player mode; peer-to-peer mode may be added later. Tofu is available under the GNU GPL licence. * Requirements: - Python >= 2.3 (http://www.python.org) - Twisted >= 1.3 (http://twistedmatrix.com) * Installation: Do in a console: python ./setup.py build and then as root: python ./setup.py install * Documentation: A small demo is included in demo/ Dosctring are present in almost all modules; read them with pydoc. * TODO Perform long task asynchronously: loading and creating levels and players. Use UDP, at least for non-crucial states and actions. Add peer-to-peer support. * HINTS You may need to increase the maximum size of a message (Twisted limits it by default to 99999 bytes), e.g. with: import tofu.client tofu.client.MAX_LENGTH = 2000000 and / or: import tofu.server tofu.server.MAX_LENGTH = 2000000 Jiba -- jibalamy@free.fr -- jiba on #slune on FreeNodeTofu-0.5/__init__.py0000644002342000234200000010166210435412567013652 0ustar duckdc-users# TOFU # Copyright (C) 2005 Jean-Baptiste LAMY # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """tofu -- a practical high-level network game engine, based on Twisted Tofu is designed for games where players play one or several characters accross several levels. This includes jump'n run games, RPG or RTS, but not Tetris-like games or board game (chess, go,...). Using the same code, Tofu can prodide single-player game (module tofu.single), server (module tofu.server) and client (module tofu.client). The same architecture should also allow a peer-to-peer game, but it is not implemented yet. Tofu defines base classes for game-related objects. To create a Tofu-based game, you need to subclass these classes : tofu.GameInterface, tofu.Player, tofu.Level, tofu.Action, tofu.State, tofu.Mobile. Then you must call tofu.init and pass it your classes. In addition to network, Tofu also manages, loads and saves Player and Levels data. All data are stored in files on the server. tofu.path is the list of directory where these files are located; by default the list is empty by you must add your own data directory in it. For tranfering object through network and for saving them locally, Tofu can use either cPickle or Cerealizer. As cPickle is not secure, you SHOULD NOT use it for network transfer though. The tofu module has the following global variables: - IDLER: the current Idler - NOTIFIER: the current Notifier (for internal purpose) - GAME_INTERFACE: the current GameInterface (None for the server) HOW IT WORK ? This modules define classes for Mobile, i.e. anything that moves of evolve in the network game. In particular, both human-played and computer-played (=bot) characters are Mobile. Tofu uses a 3-level system; the 3 levels are: Controllers, Doers and Mobiles. Mobiles are anything that can move, including both player's characters and bots. Controllers determine which Action a Mobile will do (by reading input like keyboard, or by AI for bots). Doers execute these Actions and return the new States for the Mobile. Finally the Mobile State is updated. The last step (updating Mobile's State) occurs on both client and server. The 2 first ones can be done locally (LocalController, LocalDoer) or remotely (RemoteController, RemoteDoer). Typical configurations are: * single player game Everything is local. | client A ------------|----------------- Mobile | LocalController played by A | LocalDoer ------------|----------------- Bot | LocalController | LocalDoer * client-server multiplayer game On the client-side, Mobile always have a RemoteDoer | client A | server | client B ------------|------------------|------------------|------------------ Mobile | LocalController | RemoteController | RemoteController played by A | RemoteDoer | LocalDoer | RemoteDoer ------------|------------------|------------------|------------------ Bot | RemoteController | LocalController | RemoteController | RemoteDoer | LocalDoer | RemoteDoer * peer-to-peer multiplayer game (NOT YET IMPLEMENTED) |client A | client B ------------|------------------|------------------ Mobile | LocalController | RemoteController played by A | LocalDoer | RemoteDoer ------------|------------------|------------------ Mobile | RemoteController | LocalController played by B | RemoteDoer | LocalDoer ------------|------------------|------------------ Bot | LocalController | RemoteController | LocalDoer | RemoteDoer """ import os.path, time, weakref, struct import twisted.internet.selectreactor from bisect import insort import cerealizer try: set except: from sets import Set as set __all__ = ["init", "Notifier", "GameInterface", "Idler", "Unique", "SavedInAPath", "Player", "Level", "Action", "State", "Mobile", "LocalController", "RemoteController", "LocalDoer", "RemoteDoer"] path = [] VERSION = "0.5" CODE_LOGIN_PLAYER = ">" CODE_LOGOUT_PLAYER = "<" CODE_CHECK_VERSION = "V" CODE_ASK_UNIQUE = "u" CODE_DATA_UNIQUE = "U" CODE_DATA_STATE = "S" CODE_DATA_ACTION = "A" CODE_OWN_CONTROL = "+" CODE_ADD_MOBILE = "M" CODE_REMOVE_MOBILE = "m" CODE_ENTER_LEVEL = "L" CODE_ERROR = "E" class Notifier(object): def __init__(self): global NOTIFIER NOTIFIER = self def notify_action(self, mobile, action): pass def notify_state (self, mobile, state ): pass def notify_add_mobile (self, mobile): pass def notify_remove_mobile(self, mobile): pass def notify_enter_level(self, level): pass def check_level_activity(self, level): pass def notify_discard(self, unique): pass def login_player (self, filename, password, *client_side_data): pass def logout_player(self): pass NOTIFIER = Notifier() GAME_INTERFACE = None class GameInterface(object): """GameInterface The game visible interface. A GameInterface is created for each client, but NOT for the server. You must subclass this class to make a game-specific GameInterface class, and create an instance of your GameInterface when the client starts.""" def __init__(self, *args, **kargs): global GAME_INTERFACE GAME_INTERFACE = self def ready(self, notifier): """GameInterface.ready() Called when the network connection is ready. You should override this method, and call NOTIFIER.login_player().""" self.notifier = notifier def network_error(self, reason): """GameInterface.network_error(reason) Called when the network connection fails or have been lost. You should override this method, and ends the game.""" pass def end_game(self, *return_values): """GameInterface.end_game() Ends the game.""" NOTIFIER.logout_player() IDLER.stop(*return_values) IDLER = None class Idler: """Idler Tofu's main loop. WARNING: the default Tofu Idler is very limited (no FPS regulation,...). You should provide your own Idler (Soya 3D includes a very good one).""" def __init__(self): self.levels = [] self.next_round_tasks = [] self.active = 0 self.round_duration = 0.030 self.return_values = None twisted.internet.selectreactor.install() self.reactor = twisted.internet.reactor global IDLER IDLER = self print "* Tofu * IDLER created !" def stop(self, *return_values): """Idler.stop() Stops the Idler.""" self.active = 0 self.return_values = return_values def idle(self): """Idler.idle() Starts the main loop.""" self.active = 1 self.current_time = time.time() while self.active: self.begin_round() time.sleep(self.round_duration) return self.return_values def begin_round(self): """Idler.begin_round() Called repeatedly when the Idler start idling. You may want to override this method.""" if self.next_round_tasks: for task in self.next_round_tasks: task() self.next_round_tasks = [] self.reactor.iterate() for level in self.levels: level.begin_round() Level.discard_inactives() def add_level(self, level): """Idler.add_level(level) Adds LEVEL in the list of played level. This method is automatically called by Level.set_active(), so you shouldn't care about it.""" self.levels.append(level) def remove_level(self, level): """Idler.remove_level(level) Removes LEVEL in the list of played level. This method is automatically called by Level.set_active(), so you shouldn't care about it.""" self.levels.remove(level) class _Base(object): pass def _getterbyuid(klass, filename): return klass.getbyuid(filename) class Unique(_Base): """Unique A Unique object is an object that has a unique identifiant (UID) on each remote host (server or client). """ _alls = weakref.WeakValueDictionary() def __init__(self): self.uid = id(self) Unique._alls[self.uid] = self def getbyuid(uid): """Unique.getbyuid(uid) -> Unique This static method returns the object of the given UID.""" return Unique._alls.get(uid) or Unique.not_found(uid) getbyuid = staticmethod(getbyuid) def not_found(uid): raise ValueError("No uid %s !" % uid) not_found = staticmethod(not_found) def hasuid(uid): """Unique.hasuid(uid) -> bool This static method returns true if an object with the given UID exists.""" return Unique._alls.has_key(uid) hasuid = staticmethod(hasuid) def loaded(self): """Unique.loaded() Called when the Unique is loaded from a local file.""" self.uid = id(self) Unique._alls[self.uid] = self def received(self): """Unique.received() Called when the Unique is received from the network.""" Unique._alls[self.uid] = self def discard(self): """Unique.discard() Discards the Unique, i.e. this object won't be used any more. If the Unique is needed later, it will be either loaded from a local file, or recovered through network. If the Unique is saveable, this method may call save(), in order to save the Unique before it is garbage collected.""" try: del Unique._alls[self.uid] except: pass else: NOTIFIER.notify_discard(self) def dumpuid (self): return struct.pack("!i", self.uid) def undumpuid(data): return Unique.getbyuid(struct.unpack("!i", data)[0]) undumpuid = staticmethod(undumpuid) def __repr__(self): return "<%s UID:%s>" % (self.__class__.__name__, self.uid) def dump (self): return network_serializer.dumps(self, 1) def undump(data): return network_serializer.loads(data) undump = staticmethod(undump) # Comes from Soya _SAVING = None def _getter(klass, filename): return klass.get (filename) class SavedInAPath(Unique): """SavedInAPath A special class of Unique that can be saved in a file. When a SavedInAPath object is serialized, only the filename is serialized, and not all the object data.""" DIRNAME = "" def __init__(self): Unique.__init__(self) self._filename = "" def __repr__(self): return "<%s %s UID:%s>" % (self.__class__.__name__, self.filename, self.uid) def get(klass, filename): """SavedInAPath.get(filename) -> SavedInAPath This class method gets a SavedInAPath object from its filename. The object will be loaded if needed, but if it is already loaded, the same reference will be returned.""" return klass._alls2.get(filename) or klass._alls2.setdefault(filename, klass.load(filename)) get = classmethod(get) def load(klass, filename): """SavedInAPath.load(filename) -> SavedInAPath This class method loads a SavedInAPath object from its file.""" if ".." in filename: raise ValueError("Cannot have .. in filename (security reason)!") filename = filename.replace("/", os.sep) for p in path: file = os.path.join(p, klass.DIRNAME, filename + ".data") if os.path.exists(file): obj = local_serializer.loads(open(file, "rb").read()) obj.loaded() klass._alls2[filename] = obj return obj raise ValueError("No %s named %s" % (klass.__name__, filename)) load = classmethod(load) def save(self, filename = None): """SavedInAPath.save(filename = None) Saves a SavedInAPath object in the associated file.""" global _SAVING try: _SAVING = self # Hack !! data = local_serializer.dumps(self, 1) # Avoid destroying the file if the serialization causes an error. open(filename or os.path.join(path[0], self.DIRNAME, self.filename.replace("/", os.sep)) + ".data", "wb").write(data) finally: _SAVING = None def delete(self, filename = None): """SavedInAPath.delete(filename = None) Delete a SavedInAPath's file.""" del self._alls2[self.filename] Unique.discard(self) filename = filename or os.path.join(path[0], self.DIRNAME, self.filename.replace("/", os.sep)) + ".data" print "* Tofu * Deleting %s %s (file %s) !" % (self.__class__.__name__, self.filename, filename) os.remove(filename) def get_filename(self): return self._filename def set_filename(self, filename): if self._filename: try: del self._alls2[self.filename] except KeyError: pass if filename: self._alls2[filename] = self self._filename = filename filename = property(get_filename, set_filename) def availables(klass): """SavedInAPath.availables() This class method returns a list of all available files (e.g. a list of all Levels or all Players).""" import dircache filenames = dict(klass._alls2) for p in path: for filename in dircache.listdir(os.path.join(p, klass.DIRNAME)): if filename.endswith(".data"): filenames[filename[:-5]] = 1 filenames = filenames.keys() filenames.sort() return filenames availables = classmethod(availables) def discard(self): print "* Tofu * Discard %s %s %s..." % (self.__class__.__name__.lower(), self.filename, self.uid) del self._alls2[self.filename] Unique.discard(self) def loaded(self): assert not self._alls2.get(self.filename), "Dupplicated SavedInAPath object %s !" % self.filename Unique.loaded(self) self._alls2[self.filename] = self def received(self): assert not self._alls2.get(self.filename), "Dupplicated SavedInAPath object %s !" % self.filename Unique.received(self) self._alls2[self.filename] = self def dump(self): """SavedInAPath.dump() -> str Serialize the object.""" global _SAVING try: _SAVING = self # Hack !! return network_serializer.dumps(self, 1) finally: _SAVING = None def __reduce_ex__(self, i = 0): if (not _SAVING is self) and self._filename: # self is saved in another file, save filename only return (_getter, (self.__class__, self.filename)) return object.__reduce_ex__(self, i) class Player(SavedInAPath): """Player A Player. Player is a subclass of SavedInAPath, and thus Players are associated to a filename. When the Player logout, it is automatically saved into the corresponding file. If he login later, the Player will be loaded from the file. Interesting attributes are : - mobiles: the list of mobile controled by the human Player (no bots) - filename: the Player's login and also the file in which the Player data will be stored - password: the password - address: the address of the remote host, 1 for single player game, and None if not connected. - notifier: the Player's notifier You must subclass this class to make a game-specific Player class.""" DIRNAME = "players" _alls2 = {} def __init__(self, filename, password, client_side_data = ""): """Player(filename, password, client_side_data = "") -> Player Creates a new Player with the given FILENAME and PASSWORD. __init__ is ONLY called for NEW Player at their FIRST login. You must override this contructor, in order to create at least one Mobile for the new Player, and add these Mobiles in some Levels. CLIENT_SIDE_DATA contains additional data given by the client; you can use them to store some data on the client side. Default implementation ignore them.""" if (".." in filename) or ("/" in filename): raise ValueError("Invalide Player name %s (need a valid filename) !" % filename) SavedInAPath.__init__(self) print "* Tofu * Creating new player %s..." % filename self.filename = filename self.password = password self.mobiles = [] self.notifier = None self.address = None def add_mobile(self, mobile): if not mobile.level: raise ValueError("You must add the mobile inside a level before !") mobile.player_name = self.filename self.mobiles.append(mobile) def remove_mobile(self, mobile): self.mobiles.remove(mobile) mobile.player_name = "" if not self.mobiles: self.kill(mobile) def kill(self, last_mobile): self.logout(0) def login(self, notifier, address, client_side_data = ""): """Player.login(notifier, address, client_side_data = "") Login the Player. CLIENT_SIDE_DATA contains additional data given by the client; you can use them to store some data on the client side. Default implementation ignore them.""" if self.address: raise ValueError("Player %s is already logged !" % self.filename) print "* Tofu * Player %s login !" % self.filename for mobile in self.mobiles: if not mobile in mobile.level.mobiles: mobile.level.add_mobile(mobile) self.notifier = notifier self.address = address for mobile in self.mobiles: mobile.send_control_to(self) for level in set([mobile.level for mobile in self.mobiles]): notifier.notify_enter_level(level) def logout(self, save = 1): """Player.logout(SAVE = 1) Logout the Player.""" if self.address: print "* Tofu * Player %s logout !" % self.filename try: self.notifier.transport.loseConnection() except: pass self.notifier = None self.address = None if save: self.discard() # Do this AFTER discard => when discard saves the player's mobiles, the mobiles still have their level, and so the level is saved. for mobile in self.mobiles: if mobile.level: mobile.level.remove_mobile(mobile) if GAME_INTERFACE: GAME_INTERFACE.end_game() def loaded(self): SavedInAPath.loaded(self) for mobile in self.mobiles: mobile.loaded() def discard(self): for mobile in self.mobiles: mobile.discard() SavedInAPath.discard(self) class Level(SavedInAPath): """Level A game Level. Level is a subclass of SavedInAPath, and thus Levels are associated to a filename. When the Level is useless, it is automatically saved into the corresponding file. If needed later, the Level will be loaded from the file. You must subclass this class to make a game-specific Level class.""" DIRNAME = "levels" _alls2 = weakref.WeakValueDictionary() def __init__(self, filename = ""): """Level(filename = "") -> Level Creates a Level called FILENAME.""" SavedInAPath.__init__(self) if filename: self.filename = filename self.mobiles = [] self.round = 0 self.active = 0 def add_mobile(self, mobile): """Level.add_mobile(mobile) Adds a Mobile in the Level. If needed, the addition will be notified to remote users, and the level active state will be updated. """ mobile._added_into_level(self) self.mobiles.append(mobile) NOTIFIER.notify_add_mobile(mobile) NOTIFIER.check_level_activity(self) def remove_mobile(self, mobile): """Level.remove_mobile(mobile) Removes a Mobile from the Level. If needed, the removal will be notified to remote users, and the level active state will be updated.""" if mobile.doer.remote: mobile.doer.purge() NOTIFIER.notify_remove_mobile(mobile) # Notify BEFORE removals => we can use mobile.level self.mobiles.remove(mobile) mobile._added_into_level(None) NOTIFIER.check_level_activity(self) def set_active(self, active): """Level.set_active(active) Sets the level active state. If the level is active, the Mobile in the Level will be played. You should not call this method directly; the level active state is automatically determined by the Mobile of the Level. You may want to override this method, e.g. to display an active level.""" if active != self.active: if active: print "* Tofu * Level %s %s activated !" % (self.filename, self.uid) else: print "* Tofu * Level %s %s inactivated." % (self.filename, self.uid) if self.active: IDLER.remove_level(self) self.active = active if self.active: IDLER.add_level(self) if not active: self.discard() def begin_round(self): """Level.begin_round() If the Level is active, this method is called repeatedly by the Idler. You may override this method; the default implementation calls all Mobile's begin_round.""" if self.active: self.round += 1 for mobile in self.mobiles: mobile.begin_round() def received(self): SavedInAPath.received(self) self.active = 0 for mobile in self.mobiles: mobile.received() NOTIFIER.check_level_activity(self) def loaded(self): SavedInAPath.loaded(self) self.active = 0 for mobile in self.mobiles: mobile.loaded() def discard(self): if not Unique.hasuid(self.uid): return # Already discarded for mobile in self.mobiles: mobile.discard() SavedInAPath.discard(self) def discard_inactives(clazz): """Level.discard_inactives() This class method discards ALL non-active levels. It is called by the Idler each begin_round.""" for level in clazz._alls2.values(): if not level.active: level.discard() discard_inactives = classmethod(discard_inactives) class Action(_Base): """Action An Action is something a Mobile (like a character) wants to accomplish. Typical example of Action are: move forward, turn left,... You must subclass this class to make a game-specific Action class.""" def __init__(self): pass def is_crucial(self): """Action.is_crucial() -> bool Returns true if the Action is crucial, i.e. it MUST not be lost in the network hyperspace (like UDP protocol sometimes does). Default implementation always returns true. You can override it if you have non-crucial Action.""" return 1 def dump(self): """Action.dump() -> str Serialize the Action.""" return network_serializer.dumps(self, 1) def undump(data): """Action.undump(data) -> Action Static method that deserialize an Action (previously serialized by Action.dump).""" return network_serializer.loads(data) undump = staticmethod(undump) class State(_Base): """State A State is the current position of a Mobile (like a character). Typical example of State is: (X, Y) coordinates == (10.0, 5.0),... You must subclass this class to make a game-specific State class.""" droppable = 0 def __init__(self): self.round = -1 # XXX needed ? def __cmp__(self, other): return cmp(self.round, other.round) def is_crucial(self): """State.is_crucial() -> bool Returns true if the State is crucial, i.e. it MUST not be lost in the network hyperspace (like UDP protocol sometimes does). Default implementation always returns true. You can override it if you have non-crucial State.""" return 1 def dump(self): """State.dump() -> str Serialize the State.""" return network_serializer.dumps(self, 1) def undump(data): """State.undump(data) -> Action Static method that deserialize a State (previously serialized by State.dump).""" return network_serializer.loads(data) undump = staticmethod(undump) QUEUE_LENGTH = 3 class LocalController(_Base): """LocalController The Controller is the object responsible for determining the Actions a Mobile will do. The default LocalController implementation delegates this task to Mobile.next_action(), but you may want to subclass the LocalController class, e.g. in KeybordController and AIController.""" remote = 0 def __init__(self, mobile): self.mobile = mobile def begin_round(self): action = self.mobile.next_action() self.mobile.doer.do_action(action) class RemoteController(_Base): """RemoteController A RemoteController is a Controller for a remotely-controled Mobile, i.e. a Mobile who receives its Actions from a remote server.""" remote = 1 def __init__(self, mobile): self.mobile = mobile self.actions = [] def push(self, action): self.actions.append(action) def begin_round(self): if self.actions: while len(self.actions) > QUEUE_LENGTH: action = self.actions.pop(0) if action.is_crucial(): self.mobile.doer.do_action(action) self.mobile.doer.do_action(self.actions.pop(0)) else: self.mobile.doer.do_action(None) class LocalDoer(_Base): """LocalDoer The Doer is the object responsible for doing a Mobile's Action, and returning the resulting State. The default LocalDoer implementation delegates this task to Mobile.do_action(action), you probably won't have to subclass the LocalDoer class.""" remote = 0 def __init__(self, mobile): self.mobile = mobile def do_action(self, action): self.mobile.do_action(action) def action_done(self, state): if state: state.round = self.mobile.round if (not state.droppable) or state.is_crucial(): NOTIFIER.notify_state(self.mobile, state) self.mobile.set_state(state) def begin_round(self): pass class RemoteDoer(_Base): """RemoteDoer A RemoteDoer is a Doer for a remotely-played Mobile, i.e. a Mobile whoose Action are executed on a remote host, and who receives its States from the remote host.""" remote = 1 def __init__(self, mobile): self.mobile = mobile self.states = [] def push(self, state): insort(self.states, state) def do_action(self, action): if action: NOTIFIER.notify_action(self.mobile, action) def begin_round(self): if self.states: while len(self.states) > QUEUE_LENGTH: state = self.states.pop(0) if state.is_crucial(): self.mobile.set_state(state) self.mobile.set_state(self.states.pop(0)) def purge(self): if self.states: while len(self.states) > 1: state = self.states.pop(0) if state.is_crucial(): self.mobile.set_state(state) self.mobile.set_state(self.states.pop(0)) class Mobile(Unique): """Mobile A Mobile is anything that moves of evolve in the network game. In particular, both human-played and computer-played (=bot) characters are Mobile. You must subclass the Mobile class to create your own game-specific Mobiles. Attributes are: - controller: the Mobile's Controller - doer: the Mobile's Doer - round: the round counter - bot: true if the Mobile is an AI-played bot, false if it is a human-played character. Defaults to false. """ def __init__(self): """Mobile() -> Mobile Create a new Mobile. Mobile creation should only be done on the server, i.e. either in Mobile.do_action() or in Player.__init__(), both being called only server-side. Then, when calling Level.add_mobile(mobile), the server will automatically send the mobile to clients. By default, the Mobile has a LocalController and a LocalDoer, i.e. it is totally locally managed. If you want to transfert the control to another player, use Mobile.send_control_to(player). """ Unique.__init__(self) self.round = 0 self.level = None self.controller = LocalController(self) self.doer = LocalDoer (self) self.bot = 0 self.player_name = "" def _added_into_level(self, level): """Mobile._added_into_level(level) Called when the Mobile is added inside a Level, or removed from a Level (in this case, LEVEL is None).""" self.level = level def begin_round(self): """Mobile.begin_round() If the Mobile's Level is active, this method is called repeatedly by the Idler. You don't have to override this method; override rather next_action, do_action and set_state.""" self.round += 1 self.controller.begin_round() self.doer .begin_round() def next_action(self): """Mobile.next_action() -> Action or None Called by LocalController, to get the next Action for this Mobile. You must override this method.""" return None def do_action(self, action): """Mobile.do_action(action) Called by LocalDoer, to accomplish the given ACTION and compute the resulting new State for the Mobile. You must override this method, create the new State and then call : self.doer.action_done(new_state) Notice that, if needed, you can create more than one state, and call self.doer.action_done several time (one per state).""" return None def set_state(self, state): """Mobile.set_state(state) -> State Set the new State of the Mobile. This method is called BOTH server-side and client-side. You must override this method.""" pass def send_control_to(self, player): """Mobile.send_control_to(player) Transfer the control of this Mobile to PLAYER. This method replace the Mobile's Controller by a RemoteController, and notify PLAYER.""" # XXX P2P if not self.controller.remote: self.controller = RemoteController(self) if player: player.notifier.notify_own_control(self) NOTIFIER.check_level_activity(self.level) def control_owned(self): """Mobile.control_owned() Called when the control of a Mobile is acquired locally. This method replace the Mobile's Controller by a LocalController. You can override it, in order to know which Mobile are locally controled.""" self.controller = LocalController(self) NOTIFIER.check_level_activity(self.level) def received(self): Unique.received(self) if not self.controller.remote: self.controller = RemoteController(self) else: self.controller.actions *= 0 if not self.doer .remote: self.doer = RemoteDoer (self) def kill(self): IDLER.next_round_tasks.append(self.killed) def killed(self): if self.level: self.level.remove_mobile(self) player = Player._alls2.get(self.player_name, None) if player: player.remove_mobile(self) YourGameInterface = YourPlayer = YourAction = YourState = None def init(game_interface_class, player_class, level_class, action_class, state_class, mobile_class): """init(game_interface_class, player_class, level_class, action_class, state_class, mobile_class) Initializes Tofu with the given classes. They should be subclasses of the corresponding Tofu base classes.""" global YourGameInterface, YourPlayer, YourAction, YourState YourGameInterface = game_interface_class YourPlayer = player_class YourAction = action_class YourState = state_class # Currently, Level and Mobile are not needed. #if (not local_serializer) or (not network_serializer): raise StandardError("You must define serializer before calling init(). See enable_pickle() and enable_cerealizer().") local_serializer = None network_serializer = None def enable_pickle(local, network): """enable_pickle(local, network) Use the cPickle serialization module for LOCAL and/or NETWORK serialization. Set LOCAL to 1 to use cPickle for local serialization (else use 0). Set NETWORK to 1 to use cPickle for remote serialization (else use 0) -- CAUTION! cPickle by itself is not sure! IF YOU USE CPICKLE OVER NETWORK, YOU ASSUME YOU TRUST THE REMOTE COMPUTER! E.g. to use cPickle for local file only, do: enable_pickle(1, 0) """ import cPickle as pickle global local_serializer, network_serializer if local : local_serializer = pickle if network: network_serializer = pickle def enable_cerealizer(local, network): """enable_cerealizer(local, network) Use the Cerealizer serialization module for LOCAL and/or NETWORK serialization. Set LOCAL to 1 to use Cerealizer for local serialization (else use 0). Set NETWORK to 1 to use Cerealizer for remote serialization (else use 0). E.g. to use Cerealizer for both local file and network transfer, do: enable_cerealizer(1, 1) and to use Cerealizer for only for network transfer, do: enable_cerealizer(0, 1) """ cerealizer.register(LocalController) cerealizer.register(LocalDoer) cerealizer.register(RemoteController) cerealizer.register(RemoteDoer) global local_serializer, network_serializer if local : local_serializer = cerealizer if network: network_serializer = cerealizer # Cerealizer Handler for SavedInAPath and subclass. class SavedInAPathHandler(cerealizer.ObjHandler): def collect(self, obj, dumper): if (not _SAVING is obj) and obj._filename: # self is saved in another file, save filename only return cerealizer.Handler.collect(self, obj, dumper) else: return cerealizer.ObjHandler.collect(self, obj, dumper) def dump_obj(self, obj, dumper, s): cerealizer.ObjHandler.dump_obj(self, obj, dumper, s) if (not _SAVING is obj) and obj._filename: # self is saved in another file, save filename only dumper.dump_ref(obj._filename, s) else: dumper.dump_ref("", s) def dump_data(self, obj, dumper, s): if (not _SAVING is obj) and obj._filename: # self is saved in another file, save filename only return cerealizer.Handler.dump_data(self, obj, dumper, s) else: cerealizer.ObjHandler.dump_data(self, obj, dumper, s) def undump_obj(self, dumper, s): filename = dumper.undump_ref(s) if filename: return self.Class.get(filename) return cerealizer.ObjHandler.undump_obj(self, dumper, s) def undump_data(self, obj, dumper, s): if not getattr(obj, "_filename", 0): # else, has been get'ed cerealizer.ObjHandler.undump_data(self, obj, dumper, s) Tofu-0.5/client.py0000644002342000234200000002102210434107001013337 0ustar duckdc-users# TOFU # Copyright (C) 2005 Jean-Baptiste LAMY # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """tofu.client This module implements a Tofu client. To lauch a server, create a GameInterface instance, import this module, and then call serve_forever(). """ from twisted.internet.protocol import DatagramProtocol, Protocol, Factory, ClientFactory from twisted.protocols.basic import LineReceiver, NetstringReceiver from twisted.python.failure import Failure #from twisted.internet import reactor import twisted.internet.selectreactor #reactor = twisted.internet.selectreactor.SelectReactor() import sys, struct import tofu try: set except: from sets import Set as set class ClientServerError(StandardError): pass class UDP(DatagramProtocol): def startProtocol(self): a = "hello" self.transport.write(a, ("127.0.0.1", 9999)) def datagramReceived(self, data, (host, port)): print "UDP received %r from %s:%d" % (data, host, port) PLANNED_ARRIVAL_UIDS = set() WAITERS = {} class Waiter(object): def __init__(self, callback = lambda *args: None): self.callback = callback self.uniques = set([]) self.nb_waited_unique = 0 def wait_for(self, uid, ask_for_it = 1): if tofu.Unique.hasuid(uid): # Already available self.uniques.add(tofu.Unique.getbyuid(uid)) else: #if ask_for_it: # if not uid in tofu.NOTIFIER.uids_arrival_planned: # tofu.NOTIFIER.ask_unique(uid) self.nb_waited_unique += 1 waiters = WAITERS.get(uid) if not waiters: waiters = WAITERS[uid] = [] waiters.append(self) def arrived(self, unique): self.uniques.add(unique) self.nb_waited_unique -= 1 if self.nb_waited_unique == 0: self.callback(*self.uniques) def start(self): if self.nb_waited_unique == 0: self.callback(*self.uniques) MAX_LENGTH = 99999 class Notifier(NetstringReceiver, tofu.Notifier): def __init__(self): tofu.Notifier.__init__(self) self.errors = [] self.MAX_LENGTH = MAX_LENGTH self.uids_arrival_planned = set() def connectionMade(self): self.sendString(tofu.CODE_CHECK_VERSION + tofu.VERSION) tofu.GAME_INTERFACE.ready(self) def login_player(self, filename, password, client_side_data = ""): self.sendString("%s%s\n%s\n%s" % (tofu.CODE_LOGIN_PLAYER, filename, password, client_side_data)) def logout_player(self): self.sendString(tofu.CODE_LOGOUT_PLAYER) def stringReceived(self, data): #print "TCP receive:", repr(data) #print len(data) code = data[0] #print "* Tofu * receiving code %s..." % code if code == tofu.CODE_DATA_STATE: state = tofu.YourState.undump(data[5:]) uid = struct.unpack("!i", data[1:5])[0] if tofu.Unique.hasuid(uid): tofu.Unique.getbyuid(uid).doer.push(state) elif state.is_crucial(): pass # XXX # waiter = Waiter(lambda mobile: mobile.doer.push(state)) # waiter.wait_for(uid) # waiter.start() elif code == tofu.CODE_OWN_CONTROL: uid = struct.unpack("!i", data[1:])[0] print "* Tofu * Owning mobile %s..." % uid #def own_control(mobile): # print "own_control", mobile.level # tofu.IDLER.next_round_tasks.append(mobile.control_owned) #waiter = Waiter(own_control) waiter = Waiter(lambda mobile: mobile.control_owned()) waiter.wait_for(uid, 0) waiter.start() elif code == tofu.CODE_REMOVE_MOBILE: uid = struct.unpack("!i", data[1:])[0] print "* Tofu * Removing mobile %s..." % uid def remove_mobile(mobile): mobile.level.remove_mobile(mobile) mobile.discard() #def remove_mobile(mobile): # def remove_mobile2(): # print "* Tofu * Mobile %s removed !" % mobile.uid # mobile.level.remove_mobile(mobile) # mobile.discard() # tofu.IDLER.next_round_tasks.append(remove_mobile2) waiter = Waiter(remove_mobile) waiter.wait_for(uid, 0) waiter.start() elif code == tofu.CODE_ADD_MOBILE: mobile_uid = struct.unpack("!i", data[1:5])[0] level_uid = struct.unpack("!i", data[5:9])[0] print "* Tofu * Adding mobile %s in level %s..." % (mobile_uid, level_uid) def add_mobile(*args): mobile = tofu.Unique.getbyuid(mobile_uid) level = tofu.Unique.getbyuid(level_uid ) if not mobile in level.mobiles: mobile.level.add_mobile(mobile) waiter = Waiter(add_mobile) waiter.wait_for(mobile_uid) waiter.wait_for(level_uid) waiter.start() elif code == tofu.CODE_DATA_UNIQUE: print "* Tofu * Receiving unique..." unique = tofu.Unique.undump(data[1:]) unique.received() assert (not hasattr(unique, "level")) or (not unique.level) or (unique.level in unique.level._alls2.values()), "Level sent with non-level unique !" self.arrived(unique) elif code == tofu.CODE_ENTER_LEVEL: uid = struct.unpack("!i", data[1:])[0] print "* Tofu * Entering level %s..." % uid #self.uids_arrival_planned.add(uid) # The server will send it # Previous level is outdated => drop it if tofu.Unique.hasuid(uid): tofu.Unique.getbyuid(uid).set_active(0) waiter = Waiter(lambda *uniques: None) waiter.wait_for(uid) waiter.start() elif code == tofu.CODE_ERROR: print "* Tofu * Server error: %s" % data[1:] #self.errors.append(data[1:]) raise ClientServerError(data[1:]) def arrived(self, unique): print "* Tofu * Received unique %s %s." % (unique.uid, unique) waiters = WAITERS.get(unique.uid) if waiters: for waiter in waiters: waiter.arrived(unique) del WAITERS[unique.uid] if hasattr(unique, "mobiles"): for mobile in unique.mobiles: self.arrived(mobile) self.uids_arrival_planned.discard(unique.uid) def ask_unique(self, uid): print "* Tofu * Ask for UID %s..." % uid self.uids_arrival_planned.add(uid) self.sendString(tofu.CODE_ASK_UNIQUE + struct.pack("!i", uid)) def notify_action(self, mobile, action): self.sendString(tofu.CODE_DATA_ACTION + "%s%s" % (mobile.dumpuid(), action.dump())) def notify_add_mobile (self, mobile): pass def notify_remove_mobile(self, mobile): pass def check_level_activity(self, level): for mobile in level.mobiles: if not mobile.controller.remote: level.set_active(1) return # No local user for this level => we can inactive it level.set_active(0) def notify_discard(self, unique): # The client NEVER saves data pass class TCPFactory(ClientFactory): protocol = Notifier def clientConnectionFailed(self, connector, reason): m = reason.getErrorMessage() print "* Tofu * Connection failed:", m tofu.GAME_INTERFACE.network_error(m) def clientConnectionLost(self, connector, reason): m = reason.getErrorMessage() print "* Tofu * Connection lost:", m tofu.GAME_INTERFACE.network_error(m) def serve_forever(host = "localhost", port = 6900, *args, **kargs): """serve_forever(host = "localhost", port = 6900, *ARGS, **KARGS) Starts a game client, and connect to HOST on port PORT. ARGS and KARGS are passed to GameInterface.__init__().""" #reactor.listenUDP(0, UDP()) #twisted.internet.selectreactor.install() reactor = twisted.internet.reactor tofu.YourGameInterface(*args, **kargs) factory = TCPFactory() twisted.internet.reactor.connectTCP(host, port, factory) try: return tofu.IDLER.idle() finally: tofu.NOTIFIER.transport.loseConnection() tofu.IDLER.reactor.iterate() tofu.IDLER.reactor.runUntilCurrent() tofu.IDLER.reactor.removeAll() tofu.IDLER.reactor.disconnectAll() # We need to start the reactor in order to be able to stop it !!! # Else the program cannot ends normally. tofu.IDLER.reactor.callLater(0.0, reactor.stop); reactor.run() Tofu-0.5/server.py0000644002342000234200000001650410434107075013413 0ustar duckdc-users# TOFU # Copyright (C) 2005 Jean-Baptiste LAMY # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """tofu.server This module implements a Tofu server. To lauch a server, you just have to import this module, and then call serve_forever(). """ from twisted.internet.protocol import DatagramProtocol, Protocol, Factory from twisted.protocols.basic import LineReceiver, NetstringReceiver from twisted.internet import reactor import sys, struct import tofu class UDP(DatagramProtocol): def datagramReceived(self, data, (host, port)): print "UDP received %r from %s:%d" % (data, host, port) self.transport.write(data, (host, port)) #reactor.listenUDP(6900, UDP()) class SecurityError(StandardError): pass MAX_LENGTH = 99999 class PlayerNotifier(NetstringReceiver): def __init__(self): self.player = None self.version_checked = 0 self.MAX_LENGTH = MAX_LENGTH def stringReceived(self, data): #print "TCP received %r" % (data,) try: code = data[0] #print "* Tofu * receiving code %s..." % code if code == tofu.CODE_LOGIN_PLAYER : self.login_player (*data[1:].split("\n", 2)) elif code == tofu.CODE_LOGOUT_PLAYER: self.logout_player() elif code == tofu.CODE_ASK_UNIQUE : #XXX Verify if the player has the rigth to see the asked unique. unique = tofu.Unique.undumpuid(data[1:]) #print "TCP send:", tofu.CODE_DATA_UNIQUE + repr(unique.dump()) #print len(tofu.CODE_DATA_UNIQUE + unique.dump()) self.send_unique(unique) elif code == tofu.CODE_DATA_ACTION : uid = struct.unpack("!i", data[1:5])[0] if tofu.Unique.hasuid(uid): mobile = tofu.Unique.undumpuid(data[1:5]) if not mobile in self.player.mobiles: # XXX optimize this (use Set) raise SecurityError("Player %s does not have the right to send action for mobile %s !" % (self.player.filename, mobile.uid)) mobile.controller.push(tofu.YourAction.undump(data[5:])) elif code == tofu.CODE_CHECK_VERSION: if data[1:] != tofu.VERSION: raise ValueError("Server and client use incompatible version (server: %s, client %s)" % (VERSION, data[1:])) self.version_checked = 1 except StandardError, e: print "* Tofu * Error occured:" sys.excepthook(*sys.exc_info()) self.sendString(tofu.CODE_ERROR + "%s: %s" % (e.__class__.__name__, str(e))) def login_player(self, filename, password, client_side_data): try: player = tofu.YourPlayer.get(filename) except ValueError: player = tofu.YourPlayer(filename, password, client_side_data) if password != player.password: raise ValueError("Password is wrong !") # XXX delay that player.login(self, self.transport.socket.getpeername(), client_side_data) self.player = player def logout_player(self): self.player.logout() self.player = None def connectionLost(self, reason): Protocol.connectionLost(self, reason) if self.player: print "* Tofu * Connection lost with player %s:" % self.player.filename, reason.getErrorMessage() self.logout_player() def send_unique(self, unique): print "* Tofu * Sending unique %s..." % unique.uid self.sendString(tofu.CODE_DATA_UNIQUE + unique.dump()) def notify_state(self, mobile, state): self.sendString(tofu.CODE_DATA_STATE + "%s%s" % (mobile.dumpuid(), state.dump())) def notify_add_mobile(self, mobile): self.sendString(tofu.CODE_ADD_MOBILE + mobile.dumpuid() + mobile.level.dumpuid()) self.send_unique(mobile) def notify_remove_mobile(self, mobile): self.sendString(tofu.CODE_REMOVE_MOBILE + mobile.dumpuid()) def notify_enter_level(self, level): self.sendString(tofu.CODE_ENTER_LEVEL + level.dumpuid()) self.send_unique(level) def notify_own_control(self, mobile): self.sendString(tofu.CODE_OWN_CONTROL + mobile.dumpuid()) class Notifier(tofu.Notifier): def notify_action(self, mobile, action): #raise AssertionError("Server does not send action !") pass def notify_state(self, mobile, state): for player in tofu.YourPlayer._alls2.values(): # XXX optimize this (maintain a list of player for each level) if player.notifier: for m in player.mobiles: if m.level is mobile.level: player.notifier.notify_state(mobile, state) break def notify_add_mobile(self, mobile): for player in tofu.YourPlayer._alls2.values(): # XXX optimize this if player.notifier: for m in player.mobiles: if (not m is mobile) and (m.level is mobile.level): if mobile in player.mobiles: player.notifier.notify_own_control(mobile) player.notifier.notify_add_mobile(mobile) #def doit(): # if mobile in player.mobiles: # print "SEND OWN_CONTROL" # player.notifier.notify_own_control(mobile) # print "SEND ADD_MOBILE" # player.notifier.notify_add_mobile(mobile) # #tofu.IDLER.next_round_tasks.append(doit) break else: if mobile in player.mobiles: # XXX optimize this # Not notified, because the player doesn't have the level yet # => send ENTER_LEVEL and OWN_CONTROL #player.notifier.notify_own_control(mobile) mobile.send_control_to(player) player.notifier.notify_enter_level(mobile.level) def notify_remove_mobile(self, mobile): for player in tofu.YourPlayer._alls2.values(): # XXX optimize this if player.notifier: for m in player.mobiles: if m.level is mobile.level: player.notifier.notify_remove_mobile(mobile) break def check_level_activity(self, level): for mobile in level.mobiles: if mobile.controller.remote: level.set_active(1) return # No remote user for this level => we can inactive it level.set_active(0) def notify_discard(self, unique): # The server is ALWAYS responsible for saving data if isinstance(unique, tofu.SavedInAPath): unique.save() def game_ended(self): for player in tofu.Player._alls2.values(): if player.notifier: player.notifier.logout_player() def serve_forever(port = 6900): """serve_forever(port = 6900) Starts a game server on TCP port PORT.""" tofu.NOTIFIER = Notifier() f = Factory() f.protocol = PlayerNotifier reactor.listenTCP(6900, f) print "* Tofu * Server ready !" try: tofu.IDLER.idle() except: sys.excepthook(*sys.exc_info()) tofu.NOTIFIER.game_ended() Tofu-0.5/setup.cfg0000644002342000234200000000022710433715771013356 0ustar duckdc-users[install_lib] compile = 1 optimize = 1 [sdist] force-manifest = 1 dist-dir = /home/jiba/dist formats = bztar Tofu-0.5/setup.py0000644002342000234200000000320710434641500013235 0ustar duckdc-users#! /usr/bin/env python # TOFU # Copyright (C) 2005 Jean-Baptiste LAMY # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import os.path, sys, distutils.core distutils.core.setup(name = "Tofu", version = "0.5", license = "GPL", description = "A practical high-level network game engine", long_description = """Tofu is a practical high-level network game engine, written in Python and based on Twisted. It currently support client-server and single player mode; peer-to-peer mode may be added later. A small Tk-based demo is included, as well as docstring.""", author = "Lamy Jean-Baptiste (Jiba)", author_email = "jibalamy@free.fr", # url = "http://home.gna.org/oomadness/fr/slune/index.html", package_dir = {"tofu" : ""}, packages = ["tofu"], ) Tofu-0.5/single.py0000644002342000234200000000467610434107075013375 0ustar duckdc-users# TOFU # Copyright (C) 2005 Jean-Baptiste LAMY # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """tofu.single This module implements a Tofu single-player game (no network). To lauch a single-player game, create a GameInterface instance, import this module, and then call serve_forever(). """ #from twisted.internet import reactor import tofu class Notifier(tofu.Notifier): def __init__(self): tofu.Notifier.__init__(self) self.player = None def login_player(self, filename, password, client_side_data = ""): try: player = tofu.YourPlayer.get(filename) except ValueError: player = tofu.YourPlayer(filename, password, client_side_data) if password != player.password: raise ValueError("Password is wrong !") player.login(self, 1, client_side_data) self.player = player def logout_player(self): self.player.logout() self.player = None def notify_own_control(self, mobile): mobile.control_owned() def check_level_activity(self, level): # XXX bots for mobile in level.mobiles: if (not mobile.controller.remote) and (not mobile.bot): level.set_active(1) return # No local user for this level => we can inactive it level.set_active(0) def notify_discard(self, unique): # Saves all data locally if isinstance(unique, tofu.SavedInAPath) and unique.filename: unique.save() def serve_forever(*args, **kargs): """serve_forever(*ARGS, **KARGS) Starts a single-player game. ARGS and KARGS are passed to GameInterface.__init__().""" tofu.YourGameInterface(*args, **kargs) notifier = Notifier() #reactor.callLater(0.0, lambda : tofu.GAME_INTERFACE.ready(notifier)) tofu.IDLER.next_round_tasks.append(lambda : tofu.GAME_INTERFACE.ready(notifier)) return tofu.IDLER.idle() Tofu-0.5/PKG-INFO0000644002342000234200000000101210443073753012621 0ustar duckdc-usersMetadata-Version: 1.0 Name: Tofu Version: 0.5 Summary: A practical high-level network game engine Home-page: UNKNOWN Author: Lamy Jean-Baptiste (Jiba) Author-email: jibalamy@free.fr License: GPL Description: Tofu is a practical high-level network game engine, written in Python and based on Twisted. It currently support client-server and single player mode; peer-to-peer mode may be added later. A small Tk-based demo is included, as well as docstring. Platform: UNKNOWN