예제 #1
0
def print_table(table, header=None, sep='   ', numfmt='%g'):
    """Print a list of lists as a table, so that columns line up nicely.
    header, if specified, will be printed as the first row.
    numfmt is the format for all numbers; you might want e.g. '%6.2f'.
    (If you want different formats in different columns,
    don't use print_table.) sep is the separator between columns."""
    justs = ['rjust' if isnumber(x) else 'ljust' for x in table[0]]

    if header:
        r = 0
        for row in header:
            table.insert(r, row)
            r += 1

    table = [[numfmt.format(x) if isnumber(x) else x for x in row]
             for row in table]

    sizes = list(
        map(lambda seq: max(map(len, seq)),
            list(zip(*[map(str, row) for row in table]))))

    for row in table:
        print(
            sep.join(
                getattr(str(x), j)(size)
                for (j, size, x) in zip(justs, sizes, row)))
예제 #2
0
def print_table(table,
                header=[],
                leftColumn=[],
                topLeft=[],
                sep='   ',
                numfmt='%g',
                njust='rjust',
                tjust='ljust'):
    """Print a list of lists as a table, so that columns line up nicely.
    header, if specified, will be printed as the first rows.
    sep is the separator between columns, e.g. '|' or ', '
    numfmt is the format for all numbers; you might want e.g. '%6.2f'.
    (If you want different formats in different columns,
    don't use print_table.)
    njust and tjust justify the numbers and text, e.g. 'center'
    """
    if len(table) == 0:
        return

    pTable = []
    if len(header) > 0:
        r = 0
        for row in header:
            pTable.insert(r, row)
            r += 1

    pTable.extend([[(numfmt % x) if isnumber(x) else x for x in row]
                   for row in table])

    if len(leftColumn) > 0:
        #justs.insert(0, njust if isnumber(leftColumn[0]) else tjust)
        pLeft = []
        if header:
            hr = 0
            for h in header:
                topLeft.append(' ')
                pLeft.insert(0, topLeft[hr])
                hr += 1
        for cell in leftColumn:
            pLeft.append(cell)
        r = 0
        for row in pTable:
            row.insert(0, pLeft[r])
            r += 1

    justs = [njust if isnumber(x) else tjust for x in pTable[len(header)]]

    sizes = list(
        map(lambda seq: max(map(len, seq)),
            list(zip(*[map(str, row) for row in pTable]))))

    for row in pTable:
        columns = zip(justs, sizes, row)
        jrow = []
        for (j, size, x) in columns:
            jfun = getattr(str(x), j)
            jrow += [jfun(size)]
        line = sep.join(jrow)
        print(line)
예제 #3
0
def diff(y, x):
    if y == x:
        return 1
    elif not y.args:
        return 0
    else:
        u, op, v = y.args[0], y.op, y.args[-1]
        if op == '+':
            return diff(u, x) + diff(v, x)
        elif op == '-' and len(y.args) == 1:
            return -diff(u, x)
        elif op == '-':
            return diff(u, x) - diff(v, x)
        elif op == '*':
            return u * diff(v, x) + v * diff(u, x)
        elif op == '/':
            return (v * diff(u, x) - u * diff(v, x)) / (v * v)
        elif op == '**' and isnumber(x.op):
            return (v * u**(v - 1) * diff(u, x))
        elif op == '**':
            return (v * u**(v - 1) * diff(u, x) +
                    u**v * Expr('log')(u) * diff(v, x))
        elif op == 'log':
            return diff(u, x) / u
        else:
            raise ValueError("Unknown op: {} in diff({}, {})".format(op, y, x))
예제 #4
0
def simp(x):
    "Simplify the expression x."
    if isnumber(x) or not x.args:
        return x
    args = list(map(simp, x.args))
    u, op, v = args[0], x.op, args[-1]
    if op == '+':
        if v == 0:
            return u
        if u == 0:
            return v
        if u == v:
            return 2 * u
        if u == -v or v == -u:
            return 0
    elif op == '-' and len(args) == 1:
        if u.op == '-' and len(u.args) == 1:
            return u.args[0]  # --y ==> y
    elif op == '-':
        if v == 0:
            return u
        if u == 0:
            return -v
        if u == v:
            return 0
        if u == -v or v == -u:
            return 0
    elif op == '*':
        if u == 0 or v == 0:
            return 0
        if u == 1:
            return v
        if v == 1:
            return u
        if u == v:
            return u**2
    elif op == '/':
        if u == 0:
            return 0
        if v == 0:
            return Expr('Undefined')
        if u == v:
            return 1
        if u == -v or v == -u:
            return 0
    elif op == '**':
        if u == 0:
            return 0
        if v == 0:
            return 1
        if u == 1:
            return 1
        if v == 1:
            return u
    elif op == 'log':
        if u == 1:
            return 0
    else:
        raise ValueError("Unknown op: " + op)
    return Expr(op, *args)
예제 #5
0
def diff(y, x):
    """Return the symbolic derivative, dy/dx, as an Expr.
    However, you probably want to simplify the results with simp.
    >>> diff(x * x, x)
    ((x * 1) + (x * 1))
    """
    if y == x:
        return 1
    elif not y.args:
        return 0
    else:
        u, op, v = y.args[0], y.op, y.args[-1]
        if op == '+':
            return diff(u, x) + diff(v, x)
        elif op == '-' and len(y.args) == 1:
            return -diff(u, x)
        elif op == '-':
            return diff(u, x) - diff(v, x)
        elif op == '*':
            return u * diff(v, x) + v * diff(u, x)
        elif op == '/':
            return (v * diff(u, x) - u * diff(v, x)) / (v * v)
        elif op == '**' and isnumber(x.op):
            return (v * u**(v - 1) * diff(u, x))
        elif op == '**':
            return (v * u**(v - 1) * diff(u, x) +
                    u**v * Expr('log')(u) * diff(v, x))
        elif op == 'log':
            return diff(u, x) / u
        else:
            raise ValueError("Unknown op: {} in diff({}, {})".format(op, y, x))
예제 #6
0
파일: logic.py 프로젝트: 99731/aima-python
def diff(y, x):
    """Return the symbolic derivative, dy/dx, as an Expr.
    However, you probably want to simplify the results with simp.
    >>> diff(x * x, x)
    ((x * 1) + (x * 1))
    """
    if y == x:
        return 1
    elif not y.args:
        return 0
    else:
        u, op, v = y.args[0], y.op, y.args[-1]
        if op == '+':
            return diff(u, x) + diff(v, x)
        elif op == '-' and len(y.args) == 1:
            return -diff(u, x)
        elif op == '-':
            return diff(u, x) - diff(v, x)
        elif op == '*':
            return u * diff(v, x) + v * diff(u, x)
        elif op == '/':
            return (v*diff(u, x) - u*diff(v, x)) / (v * v)
        elif op == '**' and isnumber(x.op):
            return (v * u ** (v - 1) * diff(u, x))
        elif op == '**':
            return (v * u ** (v - 1) * diff(u, x) +
                    u ** v * Expr('log')(u) * diff(v, x))
        elif op == 'log':
            return diff(u, x) / u
        else:
            raise ValueError("Unknown op: {} in diff({}, {})".format(op, y, x))
def num_value(x):
    x = resolve1(x)
    if not isnumber(x):
        if STRICT:
            raise PDFTypeError('Int or Float required: %r' % x)
        return 0
    return x
예제 #8
0
def parseGetCarriedObjects(ch, argL, cmd):
    """
    Parse and return the items carried by the player, listed in argL.
    Supports:
    cmd item
    cmd i.item
    cmd n item
    cmd all item
    cmd money
    cmd n currency
    cmd all currency
    """

    if utils.isnumber(argL[0]):
	n = int(argL[0])
	i = 1
	if n <= 0:
	    ch.writeToSelf("Heh heh.. sure.. why don't you try that in some alternative universe?\r\n")
	    return 1	    
    elif utils.isfloat(argL[0]):
	n = string.atof(argL[0])
	i = 1
	if n <= 0:
	    ch.writeToSelf("Heh heh.. sure.. why don't you try that in some alternative universe?\r\n")
	    return 1
    elif argL[0] == "all":
	n = -1
	i = 1
    else:
	n = 1
	i = 0


    if len(argL)-1 < i:
	ch.writeToOthers("How many of what do you want to "+cmd+"?\r\n")
	return None


    if n == 1:
	obj = ch.findCarriedObject(argL[i])
	if not obj:
	    ch.writeToSelf("You don't have "+argL[i]+".\r\n")
	    return None

	objL = [obj]
    else:
	objL = ch.findCarriedObjects(argL[i], n)
	if not objL:
	    ch.writeToSelf("You don't have "+argL[i]+".\r\n")
	    return None

	if len(objL) != n and not isinstance(objL[0], Money):
	    ch.writeToSelf("You don't have that many "+argL[i]+".\r\n")
	    return None

    return (objL, i)
예제 #9
0
    def handleCommand(self, performer, command, argument):
	if command != "push":
	    return 0

	if not utils.isnumber(argument):
	    return 0

	performer.writeToSelf("You push a button in the "+self.getName()+".\r\n")
	performer.writeToOthers(performer.getName()+" pushes a button in the "
			+self.getName()+".\r\n")

	self.doPush(performer, int(argument))

	return 1
예제 #10
0
def print_table(table,
                header=None,
                sep='   ',
                numfmt='%g',
                njust='rjust',
                tjust='ljust'):
    """Print a list of lists as a table, so that columns line up nicely.
    header, if specified, will be printed as the first rows.
    sep is the separator between columns, e.g. '|' or ', '
    numfmt is the format for all numbers; you might want e.g. '%6.2f'.
    (If you want different formats in different columns,
    don't use print_table.)
    njust and tjust justify the numbers and text, e.g. 'center'
    """
    if len(table) == 0:
        return
    justs = [njust if isnumber(x) else tjust for x in table[0]]

    if header:
        r = 0
        for row in header:
            table.insert(r, row)
            r += 1

    table = [[(numfmt % x) if isnumber(x) else x for x in row]
             for row in table]

    sizes = list(
        map(lambda seq: max(map(len, seq)),
            list(zip(*[map(str, row) for row in table]))))

    for row in table:
        print(
            sep.join(
                getattr(str(x), j)(size)
                for (j, size, x) in zip(justs, sizes, row)))
예제 #11
0
def cmdSet(ch, cmd, args):
    
    argL = utils.splitArgs(args)
    if len(argL) != 3:
	ch.writeToSelf("What do you want set?\r\n")
	return 1

    
    victim = ch.findVictim(argL[0])
    if not victim:
	ch.writeToSelf("There's noone called "+argL[0]+" around.\r\n")
	return 1

    if not _MobileAttributes.has_key(argL[1]):
	ch.writeToSelf("That's not a valid attribute. Try one of these:\r\n")

	for k, _ in _MobileAttributes.items():
	    ch.writeToSelf(string.ljust(k, 10))
	ch.writeToSelf("\r\n")

	return 1

    type = _MobileAttributes[argL[1]]

    if type == _INTEGER:
	if not utils.isnumber(argL[2]):
	    ch.writeToSelf("Value must be a integer number.\r\n")
	    return 1

	value = int(argL[2])


    if argL[1] == "level":
	value = max(min(value, LEV_ADMIN), 1)
	victim._level = value
    elif argL[1] == "title":
	victim._title = value


    ch.writeToSelf("You set "+victim.getName()+"'s "+argL[1]+" to "
	+`value`+".\r\n")

    if cmd[0] != ".":
	victim.writeToSelf(ch.getName()+" puts "+ch.his()
		+" hand over your head and as "+ch.he()+" lifts it,\r\nyou "
		+"feel something different about your "+argL[1]+".\r\n",
		WRI_ANYONE)
예제 #12
0
    def dial(self, ch, number):
	if not utils.isnumber(number) or len(number)!=5:
	    if not PHF_MEMORY in self._flags:
		ch.writeToSelf("That's not a phone number.\r\n")
		return 0
	    else:
		if self._memory.has_key(number):
		    number = self._memory[number]
		else:
		    ch.writeToSelf("There are no numbers in the memory for "+number+".\r\n")
		    return 0

	if number == self._number:
	    ch.writeToSelf("A telephone is not the best way to speak to "
		    +"your inner self...\r\n")
	    return 0

	other = _REGISTRY.findPhoneWithNumber(number)

	if not other:
	    ch.writeToSelf("beep.. beep.. beep.. beep.. The dialed number is "
		    +"currently not accessible.\r\n")
	    return 0

	assert other != None

	if other._status != _IDLE:
	    ch.writeToSelf("beep.. beep.. beep.. The dialed number is "
		    +"currently busy.\r\n")
	    return 0


	self._talkingWith = other
	other._talkingWith = self

	self._talker = ch

	self._status = _CALLING|_CALLER
	other._status = _CALLING|_CALLEE

	self._world.registerForTimer(self)
	self._world.registerForTimer(other)

	self.__timeCount = 0
	other.__timeCount = 0

	return 1
def get_widths(seq):
    widths = {}
    r = []
    for v in seq:
        if isinstance(v, list):
            if r:
                char1 = r[-1]
                for (i, w) in enumerate(v):
                    widths[char1+i] = w
                r = []
        elif isnumber(v):
            r.append(v)
            if len(r) == 3:
                (char1, char2, w) = r
                for i in xrange(char1, char2+1):
                    widths[i] = w
                r = []
    return widths
예제 #14
0
 def render_string_horizontal(self, seq, matrix, pos,
                              font, fontsize, scaling, charspace, wordspace, rise, dxscale):
     (x, y) = pos
     needcharspace = False
     for obj in seq:
         if isnumber(obj):
             x -= obj*dxscale
             needcharspace = True
         else:
             for cid in font.decode(obj):
                 if needcharspace:
                     x += charspace
                 x += self.render_char(translate_matrix(matrix, (x, y)),
                                       font, fontsize, scaling, rise, cid)
                 if cid == 32 and wordspace:
                     x += wordspace
                 needcharspace = True
     return (x, y)
def get_widths2(seq):
    widths = {}
    r = []
    for v in seq:
        if isinstance(v, list):
            if r:
                char1 = r[-1]
                for (i, (w, vx, vy)) in enumerate(choplist(3, v)):
                    widths[char1+i] = (w, (vx, vy))
                r = []
        elif isnumber(v):
            r.append(v)
            if len(r) == 5:
                (char1, char2, w, vx, vy) = r
                for i in xrange(char1, char2+1):
                    widths[i] = (w, (vx, vy))
                r = []
    return widths
예제 #16
0
def get_widths2(seq):
    widths = {}
    r = []
    for v in seq:
        if isinstance(v, list):
            if r:
                char1 = r[-1]
                for (i, (w, vx, vy)) in enumerate(choplist(3, v)):
                    widths[char1 + i] = (w, (vx, vy))
                r = []
        elif isnumber(v):
            r.append(v)
            if len(r) == 5:
                (char1, char2, w, vx, vy) = r
                for i in xrange(char1, char2 + 1):
                    widths[i] = (w, (vx, vy))
                r = []
    return widths
예제 #17
0
def get_widths(seq):
    widths = {}
    r = []
    for v in seq:
        if isinstance(v, list):
            if r:
                char1 = r[-1]
                for (i, w) in enumerate(v):
                    widths[char1 + i] = w
                r = []
        elif isnumber(v):
            r.append(v)
            if len(r) == 3:
                (char1, char2, w) = r
                for i in xrange(char1, char2 + 1):
                    widths[i] = w
                r = []
    return widths
class PDFTextDevice(PDFDevice):
    def render_string(self, textstate, seq):
        matrix = mult_matrix(textstate.matrix, self.ctm)
        font = textstate.font
        fontsize = textstate.fontsize
        scaling = textstate.scaling * .01
        charspace = textstate.charspace * scaling
        wordspace = textstate.wordspace * scaling
        rise = textstate.rise
        if font.is_multibyte():
            wordspace = 0
        dxscale = .001 * fontsize * scaling
        if font.is_vertical():
            textstate.linematrix = self.render_string_vertical(
                seq, matrix, textstate.linematrix, font, fontsize, scaling,
                charspace, wordspace, rise, dxscale)
        else:
            textstate.linematrix = self.render_string_horizontal(
                seq, matrix, textstate.linematrix, font, fontsize, scaling,
                charspace, wordspace, rise, dxscale)
        return

    def render_string_horizontal(self, seq, matrix, (x, y), font, fontsize,
                                 scaling, charspace, wordspace, rise, dxscale):
        needcharspace = False
        for obj in seq:
            if isnumber(obj):
                x -= obj * dxscale
                needcharspace = True
            else:
                for cid in font.decode(obj):
                    if needcharspace:
                        x += charspace
                    x += self.render_char(translate_matrix(matrix, (x, y)),
                                          font, fontsize, scaling, rise, cid)
                    if cid == 32 and wordspace:
                        x += wordspace
                    needcharspace = True
        return (x, y)
예제 #19
0
def cmdRegPhone(ch, cmd, args):

    argL = utils.splitArgs(args)

    if len(argL) != 3:
	ch.writeToSelf(_RegPhoneHelp)
	return
    
    phone = ch.findCarriedObject(argL[0])
    if not phone:
	phone = ch.findObject(argL[0])

    if not phone:
	ch.writeToSelf("There aren't any "+argL[0]+" around.\r\n")
	return

    if not isinstance(phone, Phone):
	ch.writeToSelf("That's not a telephone.\r\n")
	return

    if len(argL[2]) != 5 and not utils.isnumber(argL[2]):
	ch.writeToSelf("The phone number must have 5 digits.\r\n")
	return

    if ch._world._phones.has_key(argL[2]):
	ch.writeToSelf("That number is already taken.\r\n")
	return

    if phone._number:
	ch.writeToSelf("That phone is already registered for "+phone._owner
	    +", as "+phone._number+".\r\n")
	return

    phone.registerFor(argL[1], argL[2])
    ch.writeToSelf("The "+phone.getTheName()+" is now registered for "+argL[1]
	    +" as "+argL[2]+".\r\n")
예제 #20
0
def expr(s):
    """Create an Expr representing a logic expression by parsing the input
    string. Symbols and numbers are automatically converted to Exprs.
    In addition you can use alternative spellings of these operators:
      'x ==> y'   parses as   (x >> y)    # Implication
      'x <== y'   parses as   (x << y)    # Reverse implication
      'x <=> y'   parses as   (x % y)     # Logical equivalence
      'x =/= y'   parses as   (x ^ y)     # Logical disequality (xor)
    But BE CAREFUL; precedence of implication is wrong. expr('P & Q ==> R & S')
    is ((P & (Q >> R)) & S); so you must use expr('(P & Q) ==> (R & S)').
    >>> expr('P <=> Q(1)')
    (P <=> Q(1))
    >>> expr('P & Q | ~R(x, F(x))')
    ((P & Q) | ~R(x, F(x)))
    """
    if isinstance(s, Expr): return s
    if isnumber(s): return Expr(s)
    ## Replace the alternative spellings of operators with canonical spellings
    s = s.replace('==>', '>>').replace('<==', '<<')
    s = s.replace('<=>', '%').replace('=/=', '^')
    ## Replace a symbol or number, such as 'P' with 'Expr("P")'
    s = re.sub(r'([a-zA-Z0-9_.]+)', r'Expr("\1")', s)
    ## Now eval the string.  (A security hole; do not use with an adversary.)
    return eval(s, {'Expr':Expr})
예제 #21
0
파일: logic.py 프로젝트: 99731/aima-python
def simp(x):
    "Simplify the expression x."
    if isnumber(x) or not x.args:
        return x
    args = list(map(simp, x.args))
    u, op, v = args[0], x.op, args[-1]
    if op == '+':
        if v == 0:
            return u
        if u == 0:
            return v
        if u == v:
            return 2 * u
        if u == -v or v == -u:
            return 0
    elif op == '-' and len(args) == 1:
        if u.op == '-' and len(u.args) == 1:
            return u.args[0]  # --y ==> y
    elif op == '-':
        if v == 0:
            return u
        if u == 0:
            return -v
        if u == v:
            return 0
        if u == -v or v == -u:
            return 0
    elif op == '*':
        if u == 0 or v == 0:
            return 0
        if u == 1:
            return v
        if v == 1:
            return u
        if u == v:
            return u ** 2
    elif op == '/':
        if u == 0:
            return 0
        if v == 0:
            return Expr('Undefined')
        if u == v:
            return 1
        if u == -v or v == -u:
            return 0
    elif op == '**':
        if u == 0:
            return 0
        if v == 0:
            return 1
        if u == 1:
            return 1
        if v == 1:
            return u
    elif op == 'log':
        if u == 1:
            return 0
    else:
        raise ValueError("Unknown op: " + op)
    # If we fall through to here, we can not simplify further
    return Expr(op, *args)
예제 #22
0
def cmdRoom(ch, cmd, args):

    def checkFlag(f):
	for k, v in ROOM_FLAGS.items():
	    if k == f or v == f:
		return k
	return None


    def checkType(t):
	for k, v in ROOM_TYPES.items():
	    if k == t or v == t:
		return k
	return None


    def connectRooms(ch, room1, dir, room2):
	if room1._exits.has_key(dir):
	    ch.writeToSelf(room1._id+" already has an exit at "+dir+".\r\n")
	    return 0

	dir2 = DIR_OPPOSITE[dir]
	if room2._exits.has_key(dir2):
	    ch.writeToSelf(room2._id+" already has an exit at "+dir2+".\r\n")
	    return 0

	exit1 = Things.Room.Exit()
	exit2 = Things.Room.Exit()
	exit1._direction = dir
	exit2._direction = dir2
	exit1._to = room2._id+"@"+room2._zone._id
	exit2._to = room1._id+"@"+room1._zone._id

	room1._exits[dir] = exit1
	room2._exits[dir2] = exit2

	return 1


    def disconnectRooms(ch, room1, dir):
	if not room1._exits.has_key(dir):
	    ch.writeToSelf(room1._id+" has no exit at "+dir+".\r\n")
	    return None, 0

	dir2 = DIR_OPPOSITE[dir]

	exit1 = room1._exits[dir]

	room2 = room1._world.getRoom(exit1._to)
	if room2:
	    exit2 = room2._exits[dir2]
	    if exit2 and exit2._to == room1._id:
		del room2._exits[dir2]
	    else:
		room2 = None

	del room1._exits[dir]

	return room2, 1


    argL = utils.splitArgs(args, utils.LOWER_NONE)

    if len(argL) < 1:
	ch.writeToSelf(_RoomHelp)
	return 1


    room = ch.getRoom()
    world = ch._world

    action = "edited"

    l = len(argL[0])

    if "reset"[:l] == argL[0]:
	room.reset()
	ch.writeToSelf("Room was reseted.\r\n")
	return 1

    if "new"[:l] == argL[0]:
	res = parseArguments(ch, argL[1:], ['new id'])
	if not res:
	    return 1

	id, = res

	nroom = room._zone.newRoom(id)
	if not nroom:
	    ch.writeToSelf("There's already a room with that id.\r\n")
	    return 1

	room._zone.setRoomEdited(nroom)
	room = nroom
	action = "created"

    elif "name"[:l] == argL[0]:
	res = parseArguments(ch, argL[1:], ['room name'])
	if not res:
	    return 1

	room._name, = res


    elif "type"[:l] == argL[0]:
	res = parseArguments(ch, argL[1:], ['room type'])
	if not res:
	    return 1

	res, = res

	t = checkType(res)
	if not t:
	    ch.writeToSelf("Unknown room type "+`res`+"\r\n")
	    ch.writeToSelf("Valid types: "+`ROOM_TYPES`+"\r\n")
	    return 1

	room._roomType = t


    elif "description"[:l] == argL[0]:
	_startEditor(ch, room._descriptionForLook, _editDescription, None)
	return 1

    elif "aflags"[:l] == argL[0]: # add flags
	ok = 0
	for r in argL[1:]:
	    f = checkFlag(r)
	    if not f:
		ch.writeToSelf("Unknown flag "+`r`+"\r\n")
	    elif f not in room._flags:
	    	room._flags.append(f)
		ok = 1

	if not ok:
	    return 1

    elif "rflags"[:l] == argL[0]: # rem flags
	ok = 0
	for r in argL[1:]:
	    f = checkFlag(r)
	    if f != None and f in room._flags:
		room._flags.remove(f)
		ok = 1

	if not ok:
	    return 1

    elif "sflags"[:l] == argL[0]: # set the flag list
	room._flags = []
	for r in argL[1:]:
	    f = checkFlag(r)
	    if not f:
		ch.writeToSelf("Unknown flag "+`r`+"\r\n")

	    room._flags = room._flags.append(f)
	    
    elif "amob"[:l] == argL[0]: # add mob
	ok = 0
	for r in argL[1:]:
	    if not world.getMobile(r):
		ch.writeToSelf("Unknown mob "+`r`+"\r\n")
	    else:
	    	room._mobiles.append(r)
		ok = 1
	if not ok:
	    return 1

    elif "rmob"[:l] == argL[0]: # remove mob
	ok = 0
	for r in argL[1:]:
	    if r in room._mobiles:
		room._mobiles.remove(r)
		ok = 1
	if not ok:
	    return 1

    elif "aobj"[:l] == argL[0]: # add obj
	ok = 0
	for r in argL[1:]:
	    if not world.getObject(r):
		ch.writeToSelf("Unknown object "+`r`+"\r\n")
	    else:
		room._objects.append(r)
		ok = 1
	if not ok:
	    return 1

    elif "robj"[:l] == argL[0]: # remove obj
	ok = 0
	for r in argL[1:]:
	    if r in room._objects:
		room._objects.remove(r)
		ok = 1

	if not ok:
	    ch.writeToSelf("There is no "+string.join(argL[1:])+" in the room.\r\n")
	    return 1

    elif "aextra"[:l] == argL[0]: # add extra description
	if len(argL) < 2:
	    ch.writeToSelf("You must supply at least 1 keyword.\r\n")
	    return 1
	keywords = argL[1:]
	_startEditor(ch, None, _editExtraDescription, (keywords, -1))

	return 1

    elif "rextra"[:l] == argL[0]: # remove extra description
	res = parseArguments(ch, argL[1:], ['number'])
	if not res:
	    return 1

	index, = res
	if index >= 0 and index < len(room._extraDescriptions):
	    del room._extraDescriptions[index]
	    ch.writeToSelf("Extra description "+`index`+" was removed.")
	else:
	    ch.writeToSelf("No such extra description.\r\n")

	return 1

    elif "kextra"[:l] == argL[0]: # change keywords from extra descr
	if len(argL) < 3:
	    ch.writeToSelf("You must supply the index and at least 1 keyword.\r\n")
	    return 1
	if not utils.isnumber(argL[1]):
	    ch.writeToSelf("Invalid index number.\r\n")
	    return 1
	index = int(argL[1])
	keywords = argL[2:]
	k, descr = room._extraDescriptions[index]
	room._extraDescriptions[index] = keywords, descr

	return 1


    elif "dextra"[:l] == argL[0]: # change extra description text
	res = parseArguments(ch, argL[1:], ['number'])
	if not res:
	    return 1
	index, = res

	if res < 0 and res >= len(room._extraDescriptions):
	    ch.writeToSelf("No such extra description.\r\n")
	    return 1

	keywords, text = room._extraDescriptions[index]

	_startEditor(ch, text, _editExtraDescription, (keywords, index))

	return 1


    elif "exit"[:l] == argL[0]:
	res = parseArguments(ch, argL[1:], ['direction', 'exit type'])
	if not res:
	    return 1

	dir, type = res

	if dir not in _EXIT_NAMES:
	    ch.writeToSelf(dir+" is not a valid direction.\r\n")
	    return 1
	if type == "none":
	    if room._exits.has_key(dir):
		del room._exits[dir]

	elif type in ["normal", "door", "pickproof"]:
	    if room._exits.has_key(dir):
		exit = room._exits[dir]
	    else:
		exit = Things.Room.Exit()
		room._exits[dir] = exit

	    if type == "normal":
	    	exit._type = EXT_NORMAL
	    elif type == "door":
		exit._type = EXT_DOOR
	    else:
		exit._type = EXT_PICKPROOF_DOOR
	else:
	    ch.writeToSelf("Invalid exit type.\r\n")
	    return 1

    elif "toroom"[:l] == argL[0]:
	res = parseArguments(ch, argL[1:], ['direction', 'room id'])
	if not res:
	    return 1

	dir, room2 = res

	if dir not in _EXIT_NAMES:
	    ch.writeToSelf(dir+" is not a valid direction.\r\n")
	    return 1

	if room._exits.has_key(dir):
	    exit = room._exits[dir]
	else:
	    ch.writeToSelf("You must create an exit first.\r\n")
	    return 1

	exit._to = room2._id+"@"+room2._zone._id

    elif "connect"[:l] == argL[0]:
	res = parseArguments(ch, argL[1:], ['direction', 'room id'])
	if not res:
	    return 1

	dir, room2 = res

	if dir not in _EXIT_NAMES:
	    ch.writeToSelf(dir+" is not a valid direction.\r\n")
	    return 1

	if not connectRooms(ch, room, dir, room2):
	    return 1
	room._zone.setRoomEdited(room2)

    elif "disconnect"[:l] == argL[0]:
	res = parseArguments(ch, argL[1:], ['direction'])
	if not res:
	    return 1

	dir, = res

	if dir not in _EXIT_NAMES:
	    ch.writeToSelf(dir+" is not a valid direction.\r\n")
	    return 1

	room2, res = disconnectRooms(ch, room, dir)
	if not res:
	    return 1
	if room2:
	    room._zone.setRoomEdited(room2)


    elif "chzone"[:l] == argL[0]:
	res = parseArguments(ch, argL[1:], ['room id', 'zone id'])
	if not res:
	    return 1

	room, zone = res

	room._zone.destroyRoom(room)
	zone.addRoom(room)


    elif "destroy"[:l] == argL[0]:
	res = parseArguments(ch, argL[1:], ['room id'])
	if not res:
	    return 1

	room, = res

	if room._contains:
	    ch.writeToSelf("Room "+argL[1]+" is not empty and can't be destroyed.\r\n")
	    return 1

	room._zone.destroyRoom(room)
	action = "destroyed"

	return 1

    else:
	ch.writeToSelf("Unknown room editing command "+argL[0]+".\r\n")
	return 1

    room._zone.setRoomEdited(room)

    ch.writeToSelf("Room "+room._id+" "+action+".\r\n")
    ch.writeToOthers(ch.getName()+" "+action+" a room.\r\n")
예제 #23
0
def parseArguments(ch, argL, template):
    res = []

    if len(argL) != len(template):
	msg = "Incorrect # of arguments. Must be: "
	for a in template:
	    msg = msg+" <"+a+">"

	ch.writeToSelf(msg+"\r\n")

	return None

    i = 0
    for a in template:
	b = argL[i]
	i = i+1
	if a == 'room id':
	    if '@' not in b:
		id = b+'@'+ch.getRoom()._zone._id
	    else:
		id = b
	    room = ch._world.getRoom(id)
	    if not room:
		ch.writeToSelf(b+" is not a valid room id.\r\n")
	    	return None
	    res.append(room)

	elif a == 'zone id':
	    zone = ch._world.getZone(b)
	    if not zone:
		ch.writeToSelf(b+" is not a valid zone id.\r\n")
	    	return None
	    res.append(zone)

	elif a == 'new id':
	    for c in b:
	    	if c not in string.letters and c not in ['#', '-', '_']:
		    ch.writeToSelf(b+" contains invalid characters.\r\n")
		    return None

	    res.append(string.lower(b))

	elif a == 'number':
	    if utils.isnumber(b):
		res.append(int(b))
	    else:
		ch.writeToSelf("Expected positive number but got "+b+"\r\n")
		return None

	elif a == 'integer':
	    try:
		res.append(int(b))
	    except:
		ch.writeToSelf("Expected integer number but got "+b+"\r\n")
		return None

	else:
	    res.append(b)



    return tuple(res)
예제 #24
0
파일: types.py 프로젝트: joelgoop/gamspy
 def __mul__(self,other):
     if isnumber(other):
         return GamspyExpression('*',self.parenthesized(),other)
     if not isinstance(other,GamspyArithmeticExpression):
         raise ValueError('Arithmetic not allowed on instance of {}.'.format(other.__class__.__name__))
     return GamspyExpression('*',self.parenthesized(),other.parenthesized())
예제 #25
0
 def __init__(self, op, *args):
     "Op is a string or number; args are Exprs (or are coerced to Exprs)."
     assert isinstance(op, str) or (isnumber(op) and not args)
     self.op = num_or_str(op)
     self.args = map(expr, args) ## Coerce args to Exprs
예제 #26
0
            else:
                for cid in font.decode(obj):
                    if needcharspace:
                        x += charspace
                    x += self.render_char(translate_matrix(matrix, (x, y)),
                                          font, fontsize, scaling, rise, cid)
                    if cid == 32 and wordspace:
                        x += wordspace
                    needcharspace = True
        return (x, y)

    def render_string_vertical(self, seq, matrix, (x, y),
                               font, fontsize, scaling, charspace, wordspace, rise, dxscale):
        needcharspace = False
        for obj in seq:
            if isnumber(obj):
                y -= obj*dxscale
                needcharspace = True
            else:
                for cid in font.decode(obj):
                    if needcharspace:
                        y += charspace
                    y += self.render_char(translate_matrix(matrix, (x, y)),
                                          font, fontsize, scaling, rise, cid)
                    if cid == 32 and wordspace:
                        y += wordspace
                    needcharspace = True
        return (x, y)

    def render_char(self, matrix, font, fontsize, scaling, rise, cid):
        return 0
예제 #27
0
    def performBuy(self, ch, args):
	currency = self.getLocation()._zone._currency
    
	argL = utils.splitArgs(args)

	if len(argL) == 0:
	    ch.writeToSelf("What do you want to buy?\r\n")
	    return 1
    
	if utils.isnumber(argL[0]):
	    n = int(argL[0])
	    i = 1
	    if n <= 0:
		ch.writeToSelf("Heh heh.. sure.. why don't you try that in some alternative universe?\r\n")
		return 1	    
	else:
	    n = 1
	    i = 0


	if len(argL)-1 < i:
	    ch.writeToSelf("What do you want to buy?\r\n")
	    return

	#
	# Get the product to be bought
	#
	what = argL[i]
	if what[0] == '#':
	    i = abs(int(what[1:]))
	else:
	    i = -1

	idx = 0
	found = 0
	for id, qty in self._products:
	    p = self._world.makeObject(id)
	    if not p:
		continue

	    price = utils.convertCurrency(p._value, CUR_DOLLAR, currency)

	    i = i - 1

	    if p.matchAlias(what):
		found = 1
		break

	    p.destroy()

	    if i == 0:
		found = 1
		break

	    idx = idx + 1


	if not found:
	    text = utils.substNames(self._shopMessages['notFound'], self, 
				    ch, None)
	    self._world.execute(self, "say "+text)
	    return

	if qty <= 0:
	    text = utils.substNames(self._shopMessages['outOfStock'], self,
				    ch, None)
	    self._world.execute(self, "say "+text)
	    return

	n = min(qty, n)

	money = ch.findCarriedObjects(currency, price*n)
	if not money:
	    text = utils.substNames(self._shopMessages['youCantPay'], self,
				    ch, None)
	    self._world.execute(self, "say "+text)
	    return
	money = money[0]


	count = 0
	for j in range(n):
	    obj = self._world.makeObject(id)
	    if not obj:
		self.warning("shopkeeper could not make product "+id)
		continue

	    if not ch.canCarryThing(obj):
		text = utils.substNames(self._shopMessages['cantCarry'],
					self, ch, obj)
		self._world.execute(self, "say "+text)

		break
	    #
	    # Finish the transaction.
	    #
	    ch.carryThing(obj)
	    count = count + 1

	    self._products[idx] = (self._products[idx][0],
				    self._products[idx][1]-1)

	
	if count == 0:
	    return
	
	money = ch.findCarriedObjects(currency, price*count)
	ch.uncarryThing(money[0])

	text = utils.substNames(self._shopMessages['bought'], self, ch, obj)
	self._world.execute(self, "say "+text)

	if n == 1:
	    ch.writeToSelf("You buy "+obj.getName()+".\r\n")
	    ch.writeToOthers(ch.getName()+" buys "+obj.getName()+".\r\n")
	else:
	    ch.writeToSelf("You buy "+`count`+" "+obj.getTheName()+".\r\n")
	    ch.writeToOthers(ch.getName()+" buys "+`count`+" "+obj.getTheName()
			    +".\r\n")
            else:
                for cid in font.decode(obj):
                    if needcharspace:
                        x += charspace
                    x += self.render_char(translate_matrix(matrix, (x, y)),
                                          font, fontsize, scaling, rise, cid)
                    if cid == 32 and wordspace:
                        x += wordspace
                    needcharspace = True
        return (x, y)

    def render_string_vertical(self, seq, matrix, (x, y), font, fontsize,
                               scaling, charspace, wordspace, rise, dxscale):
        needcharspace = False
        for obj in seq:
            if isnumber(obj):
                y -= obj * dxscale
                needcharspace = True
            else:
                for cid in font.decode(obj):
                    if needcharspace:
                        y += charspace
                    y += self.render_char(translate_matrix(matrix, (x, y)),
                                          font, fontsize, scaling, rise, cid)
                    if cid == 32 and wordspace:
                        y += wordspace
                    needcharspace = True
        return (x, y)

    def render_char(self, matrix, font, fontsize, scaling, rise, cid):
        return 0
예제 #29
0
파일: types.py 프로젝트: joelgoop/gamspy
 def __add__(self,other):
     if not (isinstance(other,GamspyArithmeticExpression) or isnumber(other)):
         raise ValueError('Arithmetic not allowed on instance of {}.'.format(other.__class__.__name__))
     return GamspyExpression('+',self,other)