# Archive built by par.py version 1.0 files = ( ("runme", 365, r"""#!/usr/local/bin/python from cmdline import User User().Run('www.mired.org', 7902) """) , ("cmdline.py", 365, r"""#!/usr/local/bin/python """ '"""' r"""Command line commands for dopewars testing. A framework for testing, and to provide an interface for the rest of the system.""" '"""' r""" import string, sys, traceback from dopewars import * from player import * class User(Game, Commands, Messages): """ '"""' r"""The User Interface object. This provides the interface that the mixins in player need to talk to the server. See player.py for details.""" '"""' r""" def __init__(my, name = None): my.Name = name or my.Read_Name("Hey dude, what's your name?") # # Game play things methods. # def Run(my, host, port): "The loop that runs the game" my.Server = Server(my, host, port) while 1: my.Set_Prompt() if not my.Play(): return my.Server.Close() Running = 1 Prompt = 0 def Play(my): "Play a game with the server." my.Tell_Server(NAME, my.Name, frm = "") my.Server.Process_Messages() while my.Running: (ready, x, x) = select.select([my.Server, sys.stdin], [], []) if my.Server in ready: try: my.Server.Process_Messages() except: traceback.print_tb() if sys.stdin in ready: try: my.Read_Command().Run(my) except: traceback.print_tb() if my.Prompt: sys.stdout.write("%s%d%s? " % (my.Names.TurnPrefix, my.Turn, my.Names.TurnPostfix)) sys.stdout.flush() my.Prompt = 0 return my.Question("YN", "Play again?") == 'Y' def Stop(my): "Time to stop playing." my.Running = 0 def Set_Prompt(my): "Arrange to prompt the use before continuing." my.Prompt = 1 def Read_Command(my): """ '"""' r"""Create an object for a command from the user. This does type selection based on the command, and returns an object of the appropriate subtype.""" '"""' r""" my.Set_Prompt() line = string.strip(sys.stdin.readline()) data = string.split(line) if not data: return Null(None) c = string.lower(data[0]) a = data[1:] try: return Command_Table[c](a) except KeyError: return Command(line) # # Features to manipulate the display # def Udpate(my): pass def Update(my, type, index): pass def Display_String(my, text, confirm = 0): "Spit something out for the user to see." print text if confirm: my.Set_Prompt() def Display_Message(my, text): "Messages dealing with users!" print "==>", text my.Set_Prompt() def Display_Subway(my): "Tell the user who moved!" print "*** Moving to", \ my.Objects[Location][my.Is_at].Name my.Set_Prompt() def Display_List(my, title, data, select = None): "Print a list for the user." if title: print "%s:" % title for i in data: if select is None: print "\t%s" % i else: print "\t%s: %s" % (select, i) select = chr(ord(select) + 1) if not select: my.Delay() def Delay(my): "Stop processing until the user lets us know he read this." sys.stdout.write("Hit enter...") sys.stdin.readline() my.Set_Prompt() def Question(my, answers, query, count = None): "Ask the user a question, return y/n answer." ans = 'a' # answers must be *upper* case answers = string.upper(answers) if count: start = ord(answers[0]) answers = string.join(map(chr, range(start, start + count)), '') while not (ans and ans in answers): ans = string.strip(my.Read_String(query)) if ans: ans = string.upper(ans[0]) my.Set_Prompt() if count: ans = ord(ans) - start return ans def Read_String(my, prompt = None): "Get a string from the user." if prompt: sys.stdout.write(prompt) sys.stdout.write(' ') return string.strip(sys.stdin.readline()) def Read_Number(my, prompt = None): "Get a *number* from the user." try: return string.atoi(my.Read_String(prompt)) except ValueError: return 0 class Command: "A command from the user." def __init__(my, args = None): my.Args = args def Run(my, user): "Run the command for player." user.Display_String("Command not recognized: %s" % my.Args, 1) class Null(Command): def Run(my, game): pass class Inventory(Command): "A command for seeing things that are normally always on display." def Run(my, game): "Run an inventory command for the user." bitches = game.Names.Bitches guns = game.Names.Guns drugs = game.Names.Drugs extra = [] args = map(string.capwords, my.Args) if not args: args = 'Name', 'Cash', 'Debt', 'Bank', 'Health', 'Where', \ bitches, 'Coatsize', guns, drugs for name in args: if name == guns: out = [] for gun in game.Objects[Gun]: if gun.Carried: out.append("%d %s" % (gun.Carried, gun.Name)) game.Display_List(guns, out) elif name == drugs: out = [] for drug in game.Objects[Drug]: if drug.Carried: out.append("%d %s ($%d)" % (drug.Carried, drug.Name, drug.Price)) game.Display_List(drugs, out) else: extra.append(name) for i in extra: if i == 'Where': game.Display_String("Location: %s" % game.Objects[Location][game.Is_at].Name) elif i == bitches: game.Display_String("%s: %d" % (bitches, game.Bitches)) elif hasattr(game, i): game.Display_String("%s: %s" % (i, getattr(game, i))) else: game.Display_String("%s: -" % i) if extra: game.Delay() game.Set_Prompt() class Buy(Command): def Run(my, game): game.Deal(1) class Fight(Command): def Run(my, game): game.Fight() class Give(Command): def Run(my, game): game.Give() class Jet(Command): def Run(my, game): game.Jet() class List(Command): def Run(my, game): game.List() class Page(Command): def Run(my, game): game.Page() class Sell(Command): def Run(my, game): game.Deal(0) class Stand(Command): def Run(my, game): game.Stand() class Talk(Command): def Run(my, game): game.Talk() class Quit(Command): def Run(my, game): game.Quit() Command_Table = {'i': Inventory, 'j': Jet, 'q': Quit, 'p': Page, 't': Talk, 'l': List, 'g': Give, 'f': Fight, 'b': Buy, 's': Sell} if __name__ == '__main__': User().Run('localhost', 7902) """) , ("dopewars.py", 365, r"""#/usr/local/bin/python """ '"""' r"""Dopewars - classes of dopewars objects This file is designed so that you can safely do "from dopewars import *" to get the message class names. It defines the following objects: Version - the protocol version this represents. Server - an interface to the dopewars server Game - a mixin providing one of the interfaces that Server expects it's player to understand. Drug, Gun, Location - defined as indexes into the Objects attribute. Classes for the various message objects that the Server method Send_Message uses to figure out what to send. """ '"""' r""" import sys, string, socket, select # The version number of the protocol we talk. Version = "1.4.4" class _record: "A dictionary with fixed names that look like attributes." def __repr__(my): return "%s: %s" % (my.__class__.__name__, repr(my.__dict__)) class _inventory(_record): "Item in the players inventory." Carried = 0 class Location(_record): "A location that the player can visit." def __init__(my, name): my.Name = name class Gun(_inventory): "A gun the player can buy." def __init__(my, name, price, space, damage): my.Name = name my.Price = int(price) my.Space = int(space) my.Damage = int(damage) class Drug(_inventory): "A drug the player can buy." Price = 0 # Price is set at each new location. def __init__(my, name, min, max): my.Name = name my.Min = int(min) my.Max = int(max) class _names(_record): "A record of the names we call things." # Default values for the names. Bitch = "bitch" Bitches = "bitches" Gun = "gun" Guns = "guns" Drug = "drug" Drugs = "drugs" TurnPrefix = "12-" TurnPostfix = "-1984" def Set(my, data): "Assign the names from the tuple, in order." data = map(string.capwords, map(string.strip, data)) try: my.Bitch = data[0] my.Bitches = data[1] my.Gun = data[2] my.Guns = data[3] my.Drun = data[4] my.Drugs = data[5] my.TurnPrefix = data[6] my.TurnPostfix = data[7] except IndexError: pass class Game: """ '"""' r"""Game data from the server This class is a mixin to provide Player objects with the data manipulation interface expected by server objects that don't need to talk to the user.""" '"""' r""" # Bits for my.Flags FIRSTTURN=1 DEADHARDASS=2 TIPPEDOFF=4 SPIEDON=8 SPYINGON=16 FIGHTING=32 CANSHOOT=64 TRADING=128 # Data values from the server Cash = 0 Debt = 0 Bank = 0 Health = 0 Coatsize = 0 Is_at = 0 Turn = 0 Flags = 0 Bitches = 7 # Not from the server, but it's handy to have, so we track it here. Guns = 0 def Set_Data(my, data): "My fixed dictionary of things to work with." try: my.Cash = int(data[0]); my.Debt = int(data[1]); my.Bank = int(data[2]); my.Health = int(data[3]); my.Coatsize = int(data[4]); my.Is_at = int(data[5]); my.Turn = int(data[6]); my.Flags = int(data[7]); del data[:8] my.Guns = 0 for gun in my.Objects[Gun]: gun.Carried = int(data[0]); del data[0] my.Guns = my.Guns + gun.Carried for drug in my.Objects[Drug]: drug.Carried = int(data[0]); del data[0] my.Bitches = int(data[0]); del data[0] except: pass # Set up defaults for the data objects. # WARNING: These may need to be *deep* copied!!! - MWM Objects = { Drug: [Drug("Acid",1000,4400), Drug("Cocaine",15000,29000), Drug("Hashish",480,1280), Drug("Heroin",5500,13000), Drug("Ludes",11,60), Drug("MDA",1500,4400), Drug("Opium",540,1250), Drug("PCP",1000,2500), Drug("Peyote",220,700), Drug("Shrooms",630,1300), Drug("Speed",90,250), Drug("Weed",315,890)], Location: [Location("Bronx"), Location("Ghetto"), Location("Central Park"), Location("Manhattan"), Location("Coney Island"), Location("Brooklyn"), Location("Queens"), Location("Staten Island")], Gun: [Gun("Baretta",3000,4,5), Gun(".38 Special",3500,4,9), Gun("Ruger",2900,4,4), Gun("Saturday Night Special",3100,4,7)]} def Set_Counters(my, counters): "Sets up the arrays so the remote end can safely poke into them." try: for l, o in map(None, map(int, counters), (Location, Gun, Drug)): c = l - len(my.Objects[o]) if c > 0: my.Objects[o] = my.Objects[o] + [None] * c elif c < 0: del my.Objects[o][l:] except IndexError: pass def Set_Object(my, value, index): "Store a value for one of the objects we deal with." my.Objects[value.__class__][int(index)] = value def Set_Drug_Prices(my, prices): "Set current drug prices." del prices[-1] for drug, price in map(None, my.Objects[Drug], prices): drug.Price = int(price) Names = _names() def Set_Names(my, names): "Stash away the names object I use." my.Names.Set(names) Players = [] def Add_Player(my, name): "Add a player's name to the list of players in the game." my.Players.append(name) def Remove_Player(my, name): "Remove a player's name from the list of players in the game." my.Players.remove(name) def Start_Scores(my): "Create an empty list of scores." my.Scores = [] def Add_Score(my, score): "Add a score to the list." my.Scores.append(score) # # Messages to the server go through me so I can add the appropriate # name to them if needed. # def Tell_Server(my, type, text = "", ai = None, to = None, frm = None): "Foreward a request to the server to send a message." if frm is None: frm = my.Name my.Server.Send_Message(type, text, frm, to, ai) class Server: """ '"""' r"""The connection to the server. The player object a server interfaces to must support the two interfaces. First it must provide the interface from the Game class for manipulating game data. Second, it must deal with the following actions from the server: Do_Gunshop(): A routine that sends 0 or more BUYOBJECT messages for guns, ending with a DONE message. Do_Loanshark(): A routine that may send back a PAYLOAN message with an amount, and again ending with a DONE. Do_Bank(): A routine that may send back a DEPOSIT message with an amount - possibly negative for a withdrawal - and ends with a DONE message. Now I have to figure out what to do about the Display calls... """ '"""' r""" def __init__(my, player, host, port): """ '"""' r"""Set up the socket to the requested port and host. The invoking code must deal with socket exceptions so it can decide how to deal with the issue.""" '"""' r""" my.Player = player s = None s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(host, port) s.setblocking(0) my.Socket = s my.File = s.makefile() def Process_Messages(my): "Process all outstanding messages from the server." msg = my.Read_Message() while msg: msg.Process(my.Player) msg = my.Read_Message() def Read_Message(my): """ '"""' r"""Get a message from the server. Each message occupies one line, and consists of fields separated by '^'. The first field is who the message is from, the second is who it's two. The third (and further?) is data, with the first two characters of data determining the message type.""" '"""' r""" line = my.File.readline() if not len(line): return None if line[-1] == '\012': line = line[:-1] data = string.split(line, '^') frm = to = '' ai = AI_Types['NONE'] type = PRINTMESSAGE try: frm = data[0]; del data[0] to = data[0]; del data[0] ai = data[0][0] type = _types[data[0][1]] data[0] = data[0][2:] except IndexError: data = [] msg = type() msg.Parse(frm, to, ai, data) return msg def Send_Message(my, type, data, frm, to = None, ai = None): "Send the specified message to the server." line = type().Build(data, frm, to or "", ai or 'NONE') my.Socket.send(line) def Close(my): "Shut it down, twice" my.Socket.close() my.File.close() def fileno(my): "Unix file number." return my.File.fileno() class _message(_record): """ '"""' r"""The data object attached to a message from a dopewars server. The message's data attribute is set depending on the type of the message. The _message object includes a Process method that does whatever needs to be done for that message type.""" '"""' r""" def Parse(my, frm, to, ai, data): "Parse the data fields, if needed." my.From = frm my.To = to my.AI_Type = ai my.Data = data def Process(my, player): "Does Player's processing for this message." player.Display_String("Trying to process for unfished class: %s" % my.__class__.__name__) player.Display_String("Objects Data is %s" % str(my.Data), 1) def Build(my, text, to, frm, ai): "Build a string message of my type to send to the server." return "%s^%s^%c%c%s\012" % (to, frm, AI_Types[ai], my.Code, text) # # These messages are event notifications from the server to the player, # and need to be passed on to the player. # # First set - these are handled by the Game class above. class DRUGHERE(_message): def Process(my, player): player.Set_Drug_Prices(my.Data) class LIST(_message): def Process(my, player): player.Add_Player(string.join(my.Data, '^')) class HISCORE(_message): def Process(my, player): player.Add_Score(my.Data) class STARTHISCORE(_message): def Process(my, player): player.Start_Scores() # Second set - must interact with the user, so implemented elsewhere. class BANK(_message): def Process(my, player): player.Do_Bank() class DATA(_message): "A message that initializes an object for the player." def Parse(*args): apply(_message.Parse, args) my = args[0] data = my.Data del data[-1] my.Index = data[0]; del data[0] type = _data_classes[data[0][0]] data[0] = data[0][1:] my.Data = apply(type, data) def Process(my, player): player.Set_Object(my.Data, my.Index) class ENDHISCORE(_message): def Process(my, player): "Print the game's high scores list." player.Display_Scores() if my.Data[0] == 'end': player.Stop() class ENDLIST(_message): def Process(my, player): player.Display_Players() class FIGHTPRINT(_message): def Process(my, player): for w in my.Data: player.Display_String(w) class GUNSHOP(_message): def Process(my, player): player.Do_Gunshop() class INIT(_message): "The message that inits the names structure." def Parse(*args): apply(_message.Parse, args) my = args[0] data = my.Data; del my.Data my.Version = data[0] my.Counters = data[1:4] my.Names = data[4:] def Process(my, player): if Version != my.Version: player.Display_String( """ '"""' r"""This server is version %s, while your client is version %s. Be warned that different versions may not be fully compatible! Refer to the website at http://bellatrix.pcl.ox.ac.uk/~dopewars/ for the latest version.""" '"""' r""" % (my.Version, Version), 1) player.Set_Names(my.Names) player.Set_Counters(my.Counters) class JOIN(_message): def Process(my, player): name = string.join(my.Data, '^') player.Add_Player(name) player.Display_Message("%s joins the game!" % name) class LEAVE(_message): def Process(my, player): name = string.join(my.Data, '^') player.Remove_Player(name) player.Display_Message("%s leaves the game!" % name) class LOANSHARK(_message): def Process(my, player): player.Do_Loanshark() class MSG(_message): def Process(my, player): player.Display_Message("%s: %s" % (my.From, string.join(my.Data, '^'))) class MSGTO(_message): def Process(my, player): player.Display_Message("%s->%s: %s" % (my.From, my.To, string.join(my.Data, '^'))) class NEWNAME(_message): def Process(my, player): player.Choose_Name() class PRINTMESSAGE(_message): def Process(my, player): "Display the data as a message for the user." if my.Data: player.Display_String(string.join(my.Data, '\n'), 1) class SUBWAYFLASH(_message): def Process(my, player): player.Display_Subway() class UPDATE(_message): def Process(my, player): "Update the player information via the game interface." if not my.From: player.Set_Data(my.Data) else: names = ('Cash', 'Debt', 'Bank', 'Health', 'Coatsize', 'Location', 'Turn', 'Flags') out = [] for name, value in map(None, names, my.Data[:7]): out.append("%s: %s" % (name, value)) player.Display_List("%s's data" % my.From, out) del my.Data[:8] out = [] for g in player.Objects[Gun]: out.append("%s %ss" % (my.Data[0], g.Name)) del my.Data[0] player.Display_List("%s's guns" % my.From, out) out = [] for g in player.Objects[Drug]: out.append("%s %ss" % (my.Data[0], g.Name)) del my.Data[0] player.Display_List("%s's drugs" % my.From, out) player.Set_Prompt() class QUESTION(_message): def Process(my, player): player.Tell_Server(ANSWER, player.Question(my.Data[0], string.join(my.Data[1:], '\n'))) # # Message types I haven't dealt with yet. # class BUYOBJECT(_message): pass class CHANGEDISP(_message): pass class KILL(_message): pass class PUSH(_message): pass class RENAME(_message): pass class TRADE(_message): pass # # I believe these messages are all *to* the server, never from it. So the # classes need to exist, but are just placeholders for the names. # class ANSWER(_message): pass class DONE(_message): pass class DEPOSIT(_message): pass class FIGHTACT(_message): pass class CONTACTSPY(_message): pass class NAME(_message): pass class PAYLOAN(_message): pass class QUIT(_message): pass class REQUESTJET(_message): pass class REQUESTSCORE(_message): pass class SACKBITCH(_message): pass class SPYON(_message): pass class TIPOFF(_message): pass class WANTQUIT(_message): pass # # Tables for mapping from names/chars to classes. # # We'll have to decide what to do about these - someday. AI_Types = { 'NONE': 'A', 'ASKLOAN': 'B', 'COPS': 'C', 'ASKBITCH': 'D', 'ASKGUN': 'E', 'ASKGUNSHOP': 'F', 'ASKPUB': 'G', 'ASKBANK': 'H', 'ASKRUN': 'I', 'ASKRUNFIGHT': 'J', 'ASKSEW': 'K', 'MEETPLAYER': 'L' } _types = {'A': PRINTMESSAGE, 'B': LIST, 'C': ENDLIST, 'D': NEWNAME , 'E': MSG, 'F': MSGTO, 'G': JOIN, 'H': LEAVE, 'I': SUBWAYFLASH, 'J': UPDATE, 'K': DRUGHERE, 'L': GUNSHOP, 'M': LOANSHARK, 'N': BANK, 'O': QUESTION, 'Q': HISCORE, 'R': STARTHISCORE, 'S': ENDHISCORE, 'T': BUYOBJECT, 'U': DONE, 'V': REQUESTJET, 'W': PAYLOAN, 'X': ANSWER, 'Y': DEPOSIT, 'Z': PUSH, 'a': QUIT, 'b': RENAME, 'c': NAME, 'd': SACKBITCH, 'e': TIPOFF, 'f': SPYON, 'g': WANTQUIT, 'h': CONTACTSPY, 'i': KILL, 'j': REQUESTSCORE, 'k': INIT, 'l': DATA, 'm': FIGHTPRINT, 'n': FIGHTACT, 'o': TRADE, 'p': CHANGEDISP } # Add the Code attribute to those classes, and build the reverse type table for code, Class in _types.items(): Class.Code = code # And now the objects from dopewarspy that we need to map for DATA messages. _data_classes = { 'A': Location, 'B': Drug, 'C': Gun } """) , ("player.py", 365, r"""#!/usr/local/bin/python """ '"""' r"""Objects to be used by a dopewars player (client) This is a set of mixins that can be used to construct the player class that the dopewars server expects to find. They expect to be mixed into an object that provides the following features: Input is pretty simple: Read_Command: Call to read a command from the user and process it. Used by the main game loop. It prints a prompt, then waits for the network or user to do something, then calls Read_Command when fileno returns true. Read_String: Reads a string from the user, with an optional prompt. Question: Ask the user a question. The question is the second argument. The first argument is either a string of characters, or a single character. If the optional count argument is not present, then the first argument is a string of valid answers and the system will wait for the user to enter one of those (case insensitve), then return it. Answers are mapped to upper case. If the optional count argument is present, then the first character of the first argument is the first valid answer character, and the following count-1 characters are also valid. The returned value is the integer representing the ordinal position of the input charcter. Display is more complicated: Update: Updates the static display of status information. Update_inventory: Updates the display of an inventory list. It is passed an index into the Player Objects dictionary, and an index into the list in the dictionary. Display_String: Display a string in the context-sensitve data display area. Display_Message: Display a string in the communications area. Display_Subway: Notify the user that he is moving. It is passed the new location. Prompt: Prints a prompt string and continues processing user commands and server messages. Delay: Asks the user to confirm that they are paying attention. User commands and network messages are not processed during this period. Display_List: takes the title and list to display, possibly in columns. If the optional select parameter is set, then successive characters are added to each item as a label, starting with select. If select is *not* set, then it is the user will be prompted before things continue. """ '"""' r""" from dopewars import * class Messages: "Handle requests from the server that require user interaction." def Display_Players(my): "Display my list of players." if my.Players: my.Display_List("Users in this game", my.Players) def Display_Scores(my): "Display the high scores list." if not my.Scores: return hs = [] for g in my.Scores: hs.append(string.atoi(g[0]), g[1][1:]) hs.sort() out = [] for s in hs: out.append(string.rstrip(s[1][:-1])) my.Display_List("H I G H S C O R E S", out) def Do_Gunshop(my): "Handle a visit to the gunshop." display = my.Display_List names = my.Names gunlist = [] count = 0 for gun in my.Objects[Gun]: if gun.Carried > 0: count = count + 1 x = "A %s (you have %d) for $%d?" % \ (gun.Name, gun.Carried, gun.Price) gunlist.append(x) display(None, gunlist, 'A') while 1: action = my.Question("LSB", "Will you B>uy, S>ell or L>eave?") if action == 'L': break if action == 'S': if count == 0: my.Display_String("You don't have any %s to sell!" % names.Guns) continue action = 'sell' elif action == 'B': if count > my.Bitches + 2: my.Display_String("You'll need more %s to carry any more "\ " %s!" % (names.Bitches, names.Guns)) continue action = 'buy' what = my.Question('A', "What do you wish to %s?" % action, len(my.Objects[Gun])) gun = my.Objects[Gun][what] if action == 'buy': if gun.Space > my.Coatsize: my.Display_String("You don't have enough space to carry " \ "that %s!" % names.Gun) continue elif gun.Price > my.Cash: my.Display_String("You don't have enough cash to buy that"\ "%s!" % names.Gun) continue my.Cash = my.Cash - gun.Price my.Coatsize = my.Coatsize - gun.Space gun.Carried = gun.Carried + 1 else: if gun.Carried == 0: display("You don't have any to sell!") continue my.Cash = my.Cash + gun.Price my.Coatsize = my.Coatsize + gun.Price gun.Carried = gun.Carried - 1 if action == 'buy': c = 1 else: c = -1 my.Tell_Server(BUYOBJECT, "gun^%d^%d" % (what, c)) my.Tell_Server(DONE) def Do_Loanshark(my): "A visit to the loan shark." count = 0 for gun in my.Objects[Gun]: count = count + gun.Carried my.Guns = count my.Tell_Server(DONE) "A visit to the loan shark." amount = abs(my.Read_Number("How much money do you " "give the loan shark?")) if amount > my.Debt: amount = my.Debt if amount > my.Cash: my.Display_String("You don't have that much money!") else: my.Tell_Server(PAYLOAN, str(amount)) my.Tell_Server(DONE) my.Set_Prompt() def Do_Bank(my): "A visit to the bank." while 1: what = my.Question("LDW", "Do you want to L>eave, D>eposit " "or W>ithdraw from the bank?") if what == 'L': break amount = my.Read_Number("How much money?") if what == 'W': amount = -amount if amount > my.Cash: my.Display_String("You don't have that much money!") elif -amount > my.Bank: my.Display_String("You don't have that much money in the " "Bank...") else: my.Tell_Server(DEPOSIT, str(amount)) break my.Tell_Server(DONE) my.Set_Prompt() def Choose_Name(my): "We need to choose a different name." my.Display_String("Unfortunately, somebody else is already using" \ '"your" name. Please change it.') my.Tell_Server(NAME, my.Read_Name("New name:"), frm = "") # Some utility functions... def Choose_Player(my, prompt): "Helper function to let the user choose a player." my.Display_List("Players currently logged on:", my.Players, 'A') who = my.Question('A', prompt, len(my.Players)) return my.Players[who] def Read_Name(my, prompt): "Read a name in and sanitize it." return string.replace(my.Read_String(prompt), '^', ' ') class Commands: "Handle commands from the user." def Deal(my, buy): "Time to deal some drugs, my man!" drugs = my.Objects[Drug] if not buy: action = "sell" elif not my.Coatsize: my.Display_String("You can't carry any more drugs, dude!", 1) return else: action = "buy" out = [] for drug in drugs: if drug.Price and (buy or drug.Carried): out.append("%s for $%d?" % (drug.Name, drug.Price)) if not out: my.Display_String("Nobody wants to buy your stuff, man!", 1) return my.Display_List(None, out, 'A') what = my.Question('A', "What do you wish to %s?" % action, len(out)) i = -1 while what >= 0 : i = i + 1 if drugs[i].Price and (buy or drugs[i].Carried): what = what - 1 drug = drugs[i] if buy: if drug.Price > my.Cash: my.Display_String("You can't afford that, dude!", 1) return my.Display_String("You can afford %d and can carry %d." % (my.Cash / drug.Price, my.Coatsize)) new = my.Read_Number("How many do you buy?") if new > 0: my.Tell_Server(BUYOBJECT, "drug^%d^%d" % (i, new)) else: my.Display_String("You have %d." % drug.Carried) gone = my.Read_Number("How many do you sell?") if gone > 0: my.Tell_Server(BUYOBJECT, "drug^%d^%d" % (i, -gone)) def Give(my): "Give an errand to a bitch." if not my.Bitches: return answers = "STGN" question = "Choose an errand to give one of your %s...\n" \ " S>py on another drug dealer" \ " (cost: $20,000)\n" \ " T>ip off the cops to another drug dealer" \ " (cost: $10000)\n" \ " G>et stuffed\n" % my.Names.Bitches if my.Flags & my.SPYINGON: answers = answers + "C" question = question + \ " C>ontact your spies and receive reports\n" question = question + " or N>o errand ?" what = my.Question(answers, question) if what == 'G': check = my.Question("YN", "Are you sure?") if check == 'Y': my.Tell_Server(SACKBITCH) elif what == 'T': my.Tell_Server(TIPOFF, to = my.Choose_Player("Who do you want to tip " "the cops off to?")) elif what == 'S': my.Tell_Server(SPYON, to = my.Choose_Player("Who do you want to spy on?")) elif what == 'C': my.Tell_Server(CONTACTSPY) def Fight(my): "Fight - or try to!" if my.Guns: my.Tell_Server(FIGHTACT, 'F') def Jet(my): "Jet off to somewhere else." loclist = [] for l in my.Objects[Location]: loclist.append(l.Name) my.Display_List(None, loclist, '1') who = my.Question('1', "Where to, dude?", len(loclist)) my.Tell_Server(REQUESTJET, who) def List(my): "List either players or scores." what = my.Question("PS", "List what? P>layers or S>cores?") if what == 'P': my.Display_List("Players currently logged on", my.Players) my.Set_Prompt() else: my.Tell_Server(REQUESTSCORE) def Page(my): "Send a private page to a user." to = my.Choose_Player("Who do you want to page (talk privately to) ?") msg = string.replace(my.Read_String("Talk:"), '^', ' ') if msg: my.Tell_Server(MSGTO, msg, to = to) my.Display_Message('%s->%s: %s' % (my.Name, to, msg)) def Stand(my): "Stand around and get shot." my.Tell_Server(FIGHTACT, 'S') def Talk(my): "Send a message to all users." msg = string.replace(my.Read_String("Talk:"), '^', ' ') if msg: my.Tell_Server(MSG, msg) my.Display_Message('%s: %s' % (my.Name, msg)) def Quit(my): "User wants to leave." if my.Question("YN", "Are you sure you want to quit?") == 'Y': my.Tell_Server(WANTQUIT) """) , ) # The code to build the files starts here. import os def file(name, mode, data): f = open(name, 'w') f.write(data) f.close() os.chmod(name, mode) for f in files: apply(file, f)