def test_door_pair(self): loc1 = Location("room1", "room one") loc2 = Location("room2", "room two") key = Key("key") door_one_two = Door("two", loc2, "door to room two", locked=True, opened=False) door_two_one = door_one_two.reverse_door("one", loc1, "door to room one", reverse_open_msg="door one open", reverse_close_msg="door one close", this_open_msg="door two open", this_close_msg="door two close") loc1.add_exits([door_one_two]) loc2.add_exits([door_two_one]) door_one_two.key_code = 555 key.key_for(door_one_two) pubsub1 = PubsubCollector() pubsub2 = PubsubCollector() loc1.get_wiretap().subscribe(pubsub1) loc2.get_wiretap().subscribe(pubsub2) self.assertTrue(door_two_one.locked) self.assertFalse(door_two_one.opened) lucy = Living("lucy", "f") door_two_one.unlock(lucy, item=key) self.assertFalse(door_one_two.locked) door_two_one.open(lucy) self.assertTrue(door_one_two.opened) pubsub.sync() self.assertEqual(["door one open"], pubsub1.messages) self.assertEqual([], pubsub2.messages) door_one_two.close(lucy) door_one_two.lock(lucy, item=key) self.assertTrue(door_two_one.locked) self.assertFalse(door_two_one.opened) pubsub1.clear() pubsub2.clear() pubsub.sync() self.assertEqual([], pubsub1.messages) self.assertEqual(["door two close"], pubsub2.messages)
def test_exits(self): hall = Location("hall") attic = Location("attic") exit1 = Exit("ladder1", attic, "The first ladder leads to the attic.") exit2 = Exit("up", attic, "Second ladder to attic.") exit3 = Exit("ladder3", attic, "Third ladder to attic.") exit4 = Exit("window", attic, "A window.", "A window, maybe if you open it you can get out?") hall.add_exits([exit1, exit2, exit3, exit4]) self.assertTrue(hall.exits["up"] is exit2) self.assertTrue(hall.exits["ladder3"] is exit3) self.assertTrue(hall.exits["window"] is exit4) self.assertEqual(['[hall]', 'The first ladder leads to the attic. Third ladder to attic. Second ladder to attic. A window.'], strip_text_styles(hall.look())) self.assertEqual("Third ladder to attic.", exit3.description) self.assertEqual("A window, maybe if you open it you can get out?", exit4.description) with self.assertRaises(ActionRefused): exit1.activate(None) with self.assertRaises(ActionRefused): exit1.deactivate(None) with self.assertRaises(ActionRefused): exit1.close(None, None) with self.assertRaises(ActionRefused): exit1.open(None, None) with self.assertRaises(ActionRefused): exit1.lock(None, None) with self.assertRaises(ActionRefused): exit1.unlock(None, None) with self.assertRaises(ActionRefused): exit1.manipulate("frobnitz", None) with self.assertRaises(ActionRefused): exit1.read(None)
def test_move(self): hall = Location("hall") person = Living("person", "m", race="human") monster = NPC("dragon", "f", race="dragon") monster.aggressive = True key = Item("key") stone = Item("stone") hall.init_inventory([person, key]) stone.move(hall, person) wiretap = Wiretap(hall) self.assertTrue(person in hall) self.assertTrue(key in hall) key.contained_in = person # hack to force move to actually check the source container with self.assertRaises(KeyError): key.move(person, person) key.contained_in = hall # put it back as it was key.move(person, person) self.assertFalse(key in hall) self.assertTrue(key in person) self.assertEqual([], wiretap.msgs, "item.move() should be silent") with self.assertRaises(ActionRefused) as x: key.move(monster, person) # aggressive monster should fail self.assertTrue("not a good idea" in str(x.exception)) monster.aggressive = False key.move(monster, person) # non-aggressive should be ok
def test_move(self): hall = Location("hall") attic = Location("attic") rat = Living("rat", "n", race="rodent") hall.init_inventory([rat]) wiretap_hall = Wiretap(hall) wiretap_attic = Wiretap(attic) self.assertTrue(rat in hall.livings) self.assertFalse(rat in attic.livings) self.assertEqual(hall, rat.location) rat.move(attic) self.assertTrue(rat in attic.livings) self.assertFalse(rat in hall.livings) self.assertEqual(attic, rat.location) self.assertEqual([("hall", "Rat leaves.")], wiretap_hall.msgs) self.assertEqual([("attic", "Rat arrives.")], wiretap_attic.msgs) # now try silent wiretap_hall.clear() wiretap_attic.clear() rat.move(hall, silent=True) self.assertTrue(rat in hall.livings) self.assertFalse(rat in attic.livings) self.assertEqual(hall, rat.location) self.assertEqual([], wiretap_hall.msgs) self.assertEqual([], wiretap_attic.msgs)
def test_custom_verbs(self): player = Player("julie", "f") player.verbs["xywobble"] = "p1" room = Location("room") chair1 = Item("chair1") chair1.verbs["frobnitz"] = "c1" chair2 = Item("chair2") chair2.verbs["frobnitz"] = "c2" chair_in_inventory = Item("chair3") chair_in_inventory.verbs["kowabooga"] = "c3" room.init_inventory([chair1, player, chair2]) # check inventory NOT affecting player custom verbs, but DOES affect location verbs self.assertEqual({"xywobble": "p1"}, player.verbs) self.assertEqual({"frobnitz": "c2", "xywobble": "p1"}, room.verbs) player.insert(chair_in_inventory, player) self.assertEqual({"xywobble": "p1"}, player.verbs) self.assertEqual({"frobnitz": "c2", "xywobble": "p1", "kowabooga": "c3"}, room.verbs) player.remove(chair_in_inventory, player) self.assertEqual({"frobnitz": "c2", "xywobble": "p1"}, room.verbs) player.insert(chair_in_inventory, player) self.assertEqual({"frobnitz": "c2", "xywobble": "p1", "kowabooga": "c3" }, room.verbs) room2 = Location("room2") self.assertEqual({}, room2.verbs) chair1.move(room2, player) self.assertEqual({"xywobble": "p1", "kowabooga": "c3" }, room.verbs) self.assertEqual({"frobnitz": "c1"}, room2.verbs) chair2.move(room2, player) self.assertEqual({"xywobble": "p1", "kowabooga": "c3"}, room.verbs) self.assertEqual({"frobnitz": "c2"}, room2.verbs) player.move(room2) self.assertEqual({}, room.verbs) self.assertEqual({"frobnitz": "c2", "xywobble": "p1", "kowabooga": "c3"}, room2.verbs)
def test_move(self): hall = Location("hall") attic = Location("attic") rat = Living("rat", "n", race="rodent") hall.init_inventory([rat]) wiretap_hall = Wiretap(hall) wiretap_attic = Wiretap(attic) self.assertTrue(rat in hall.livings) self.assertFalse(rat in attic.livings) self.assertEqual(hall, rat.location) rat.move(attic) self.assertTrue(rat in attic.livings) self.assertFalse(rat in hall.livings) self.assertEqual(attic, rat.location) pubsub.sync() self.assertEqual([("hall", "Rat leaves.")], wiretap_hall.msgs) self.assertEqual([("attic", "Rat arrives.")], wiretap_attic.msgs) # now try silent wiretap_hall.clear() wiretap_attic.clear() rat.move(hall, silent=True) pubsub.sync() self.assertTrue(rat in hall.livings) self.assertFalse(rat in attic.livings) self.assertEqual(hall, rat.location) self.assertEqual([], wiretap_hall.msgs) self.assertEqual([], wiretap_attic.msgs)
def test_socialize(self): player = Player("fritz", "m") attic = Location("Attic", "A dark attic.") julie = NPC("julie", "f") julie.move(attic) player.move(attic) parsed = player.parse("wave all") self.assertEqual("wave", parsed.verb) self.assertEqual([julie], parsed.who_order) who, playermsg, roommsg, targetmsg = player.soul.process_verb_parsed( player, parsed) self.assertEqual({julie}, who) self.assertEqual("You wave happily at julie.", playermsg) with self.assertRaises(tale.soul.UnknownVerbException): player.parse("befrotzificate all and me") with self.assertRaises(NonSoulVerb) as x: player.parse("befrotzificate all and me", external_verbs={"befrotzificate"}) parsed = x.exception.parsed self.assertEqual("befrotzificate", parsed.verb) self.assertEqual([julie, player], parsed.who_order) attic.add_exits([Exit("south", "target", "door")]) try: player.parse("push south") self.fail( "push south should throw a parse error because of the exit that is used" ) except ParseError: pass with self.assertRaises(NonSoulVerb): player.parse("fart south") parsed = player.parse("hug julie") player.validate_socialize_targets(parsed)
def test_print_location(self): p = Player("julie", "f") key = Item("key") bag = Container("bag") room = Location("room") bag.insert(key, p) p.insert(bag, p) room.insert(p, p) with self.assertRaises(Exception): p.tell_object_location(None, None) p.tell_object_location(key, None) self.assertEqual(["(It's not clear where key is).\n"], p.test_get_output_paragraphs()) p.tell_object_location(key, None, print_parentheses=False) self.assertEqual(["It's not clear where key is.\n"], p.test_get_output_paragraphs()) p.tell_object_location(key, bag) result = "".join(p.test_get_output_paragraphs()) self.assertTrue("in bag" in result and "in your inventory" in result) p.tell_object_location(key, room) self.assertTrue("in your current location" in "".join( p.test_get_output_paragraphs())) p.tell_object_location(bag, p) self.assertTrue( "in your inventory" in "".join(p.test_get_output_paragraphs())) p.tell_object_location(p, room) self.assertTrue("in your current location" in "".join( p.test_get_output_paragraphs()))
def test_socialize(self): player = Player("fritz", "m") attic = Location("Attic", "A dark attic.") julie = NPC("julie", "f") julie.move(attic) player.move(attic) parsed = player.parse("wave all") self.assertEqual("wave", parsed.verb) self.assertEqual([julie], parsed.who_order) who, playermsg, roommsg, targetmsg = player.soul.process_verb_parsed(player, parsed) self.assertEqual({julie}, who) self.assertEqual("You wave happily at julie.", playermsg) with self.assertRaises(tale.soul.UnknownVerbException): player.parse("befrotzificate all and me") with self.assertRaises(NonSoulVerb) as x: player.parse("befrotzificate all and me", external_verbs={"befrotzificate"}) parsed = x.exception.parsed self.assertEqual("befrotzificate", parsed.verb) self.assertEqual([julie, player], parsed.who_order) attic.add_exits([Exit("south", "target", "door")]) try: player.parse("push south") self.fail("push south should throw a parse error because of the exit that is used") except ParseError: pass with self.assertRaises(NonSoulVerb): player.parse("fart south") parsed = player.parse("hug julie") player.validate_socialize_targets(parsed)
def setUp(self): mud_context.driver = TestDriver() mud_context.config = DemoStory()._get_config() self.hall = Location("Main hall", "A very large hall.") self.attic = Location("Attic", "A dark attic.") self.street = Location("Street", "An endless street.") e1 = Exit("up", self.attic, "A ladder leads up.") e2 = Exit(["door", "east"], self.street, "A heavy wooden door to the east blocks the noises from the street outside.") self.hall.add_exits([e1, e2]) self.table = Item("table", "oak table", "a large dark table with a lot of cracks in its surface") self.key = Item("key", "rusty key", "an old rusty key without a label", short_description="Someone forgot a key.") self.magazine = Item("magazine", "university magazine") self.magazine2 = Item("magazine", "university magazine") self.rat = NPC("rat", "n", race="rodent") self.rat2 = NPC("rat", "n", race="rodent") self.fly = NPC("fly", "n", race="insect", short_description="A fly buzzes around your head.") self.julie = NPC("julie", "f", title="attractive Julie", description="She's quite the looker.") self.julie.aliases = {"chick"} self.player = Player("player", "m") self.pencil = Item("pencil", title="fountain pen") self.pencil.aliases = {"pen"} self.bag = Container("bag") self.notebook_in_bag = Item("notebook") self.bag.insert(self.notebook_in_bag, self.player) self.player.insert(self.pencil, self.player) self.player.insert(self.bag, self.player) self.hall.init_inventory([self.table, self.key, self.magazine, self.magazine2, self.rat, self.rat2, self.julie, self.player, self.fly])
def test_aliases(self): loc = Location("hall", "empty hall") exit = Exit("up", "attic", "ladder to attic") door = Door("door", "street", "door to street") exit2 = Exit(["down", "hatch", "manhole"], "underground", "hatch to underground") door2 = Door(["east", "garden"], "garden", "door east to garden") self.assertEqual("up", exit.name) self.assertEqual("door", door.name) loc.add_exits([exit, door, exit2, door2]) self.assertEqual({"up", "door", "down", "hatch", "manhole", "east", "garden"}, set(loc.exits.keys())) self.assertEqual(loc.exits["down"], loc.exits["hatch"])
def test_aliases(self): loc = Location("hall", "empty hall") exit = Exit("up", "attic", "ladder to attic") door = Door("door", "street", "door to street") exit2 = Exit(["down", "hatch", "manhole"], "underground", "hatch to underground") door2 = Door(["east", "garden"], "garden", "door east to garden") self.assertEqual("up", exit.name) self.assertEqual("door", door.name) loc.add_exits([exit, door, exit2, door2]) self.assertEqual( {"up", "door", "down", "hatch", "manhole", "east", "garden"}, set(loc.exits.keys())) self.assertEqual(loc.exits["down"], loc.exits["hatch"])
def test_destroy_deferreds(self): ctx = Context(driver=mud_context.driver, clock=None, config=None, player_connection=None) thing = Item("thing") player = Player("julie", "f") wolf = NPC("wolf", "m") loc = Location("loc") mud_context.driver.defer(datetime.datetime.now(), thing.move) mud_context.driver.defer(datetime.datetime.now(), player.move) mud_context.driver.defer(datetime.datetime.now(), wolf.move) mud_context.driver.defer(datetime.datetime.now(), loc.move) self.assertEqual(4, len(mud_context.driver.deferreds)) thing.destroy(ctx) player.destroy(ctx) wolf.destroy(ctx) loc.destroy(ctx) self.assertEqual(0, len(mud_context.driver.deferreds), "all deferreds must be removed")
def test_destroy_deferreds(self): ctx = Context(driver=mud_context.driver) thing = Item("thing") player = Player("julie", "f") wolf = Monster("wolf", "m") loc = Location("loc") mud_context.driver.defer(datetime.datetime.now(), thing, "method") mud_context.driver.defer(datetime.datetime.now(), player, "method") mud_context.driver.defer(datetime.datetime.now(), wolf, "method") mud_context.driver.defer(datetime.datetime.now(), loc, "method") self.assertEqual(4, len(mud_context.driver.deferreds)) thing.destroy(ctx) player.destroy(ctx) wolf.destroy(ctx) loc.destroy(ctx) self.assertEqual(0, len(mud_context.driver.deferreds), "all deferreds must be removed")
def test_destroy_player(self): ctx = Context() loc = Location("loc") player = Player("julie", "f") player.privileges = {"wizard"} player.create_wiretap(loc) player.insert(Item("key"), player) loc.init_inventory([player]) self.assertEqual(loc, player.location) self.assertTrue(len(player.inventory) > 0) self.assertTrue(player in loc.livings) player.destroy(ctx) import gc gc.collect() self.assertTrue(len(player.inventory) == 0) self.assertFalse(player in loc.livings) self.assertIsNone(player.location, "destroyed player should end up nowhere (None)")
def test_wiretap(self): attic = Location("Attic", "A dark attic.") player = Player("fritz", "m") io = ConsoleIo(None) io.supports_smartquotes = False pc = PlayerConnection(player, io) player.set_screen_sizes(0, 100) julie = NPC("julie", "f") julie.move(attic) player.move(attic) julie.tell("message for julie") attic.tell("message for room") self.assertEqual(["message for room\n"], player.test_get_output_paragraphs()) with self.assertRaises(ActionRefused): player.create_wiretap(julie) player.privileges = {"wizard"} player.create_wiretap(julie) player.create_wiretap(attic) julie.tell("message for julie") attic.tell("message for room") pubsub.sync() output = pc.get_output() self.assertTrue("[wiretapped from 'Attic': message for room]" in output) self.assertTrue("[wiretapped from 'julie': message for julie]" in output) self.assertTrue("[wiretapped from 'julie': message for room]" in output) self.assertTrue("message for room " in output) # test removing the wiretaps player.clear_wiretaps() import gc gc.collect() julie.tell("message for julie") attic.tell("message for room") self.assertEqual(["message for room\n"], player.test_get_output_paragraphs())
def test_destroy_player(self): ctx = Context(None, None, None, None) loc = Location("loc") player = Player("julie", "f") player.privileges = {"wizard"} player.create_wiretap(loc) player.insert(Item("key"), player) loc.init_inventory([player]) self.assertEqual(loc, player.location) self.assertTrue(len(player.inventory) > 0) self.assertTrue(player in loc.livings) player.destroy(ctx) import gc gc.collect() self.assertTrue(len(player.inventory) == 0) self.assertFalse(player in loc.livings) self.assertIsNone(player.location, "destroyed player should end up nowhere (None)")
def setUp(self): mud_context.driver = TestDriver() mud_context.config = DemoStory()._get_config() self.hall = Location("Main hall", "A very large hall.") self.attic = Location("Attic", "A dark attic.") self.street = Location("Street", "An endless street.") e1 = Exit("up", self.attic, "A ladder leads up.") e2 = Exit( ["door", "east"], self.street, "A heavy wooden door to the east blocks the noises from the street outside." ) self.hall.add_exits([e1, e2]) self.table = Item( "table", "oak table", "a large dark table with a lot of cracks in its surface") self.key = Item("key", "rusty key", "an old rusty key without a label", short_description="Someone forgot a key.") self.magazine = Item("magazine", "university magazine") self.magazine2 = Item("magazine", "university magazine") self.rat = NPC("rat", "n", race="rodent") self.rat2 = NPC("rat", "n", race="rodent") self.fly = NPC("fly", "n", race="insect", short_description="A fly buzzes around your head.") self.julie = NPC("julie", "f", title="attractive Julie", description="She's quite the looker.") self.julie.aliases = {"chick"} self.player = Player("player", "m") self.pencil = Item("pencil", title="fountain pen") self.pencil.aliases = {"pen"} self.bag = Container("bag") self.notebook_in_bag = Item("notebook") self.bag.insert(self.notebook_in_bag, self.player) self.player.insert(self.pencil, self.player) self.player.insert(self.bag, self.player) self.hall.init_inventory([ self.table, self.key, self.magazine, self.magazine2, self.rat, self.rat2, self.julie, self.player, self.fly ])
def test_look_brief(self): player = Player("fritz", "m") attic = Location("Attic", "A dark attic.") cellar = Location("Cellar", "A gloomy cellar.") julie = NPC("julie", "f") julie.move(attic, silent=True) player.move(attic, silent=True) player.brief = 0 # default setting: always long descriptions player.look() self.assertEqual(["[Attic]\n", "A dark attic.\n", "Julie is here.\n"], player.test_get_output_paragraphs()) player.look() self.assertEqual(["[Attic]\n", "A dark attic.\n", "Julie is here.\n"], player.test_get_output_paragraphs()) player.look(short=True) # override self.assertEqual(["[Attic]\n", "Present: julie\n"], player.test_get_output_paragraphs()) player.brief = 1 # short for known, long for new locations player.look() self.assertEqual(["[Attic]\n", "Present: julie\n"], player.test_get_output_paragraphs()) player.move(cellar, silent=True) player.look() self.assertEqual(["[Cellar]\n", "A gloomy cellar.\n"], player.test_get_output_paragraphs()) player.look() self.assertEqual(["[Cellar]\n"], player.test_get_output_paragraphs()) player.brief = 2 # short always player.known_locations.clear() player.look() self.assertEqual(["[Cellar]\n"], player.test_get_output_paragraphs()) player.move(attic, silent=True) player.look() self.assertEqual(["[Attic]\n", "Present: julie\n"], player.test_get_output_paragraphs()) player.look(short=True) # override self.assertEqual(["[Attic]\n", "Present: julie\n"], player.test_get_output_paragraphs()) player.look(short=False) # override self.assertEqual(["[Attic]\n", "A dark attic.\n", "Julie is here.\n"], player.test_get_output_paragraphs())
def test_custom_verbs(self): player = Player("julie", "f") player.verbs["xywobble"] = "p1" monster = NPC("snake", "f") monster.verbs["snakeverb"] = "s1" room = Location("room") chair1 = Item("chair1") chair1.verbs["frobnitz"] = "c1" chair2 = Item("chair2") chair2.verbs["frobnitz"] = "c2" chair_in_inventory = Item("chair3") chair_in_inventory.verbs["kowabooga"] = "c3" box_in_inventory = Item("box") box_in_inventory.verbs["boxverb"] = "c4" player.init_inventory([box_in_inventory, chair_in_inventory]) exit = Exit("e", "dummy", None, None) exit.verbs["exitverb"] = "c5" room.init_inventory([chair1, player, chair2, monster]) room.add_exits([exit]) custom_verbs = mud_context.driver.current_custom_verbs(player) all_verbs = mud_context.driver.current_verbs(player) self.assertEqual( { "xywobble", "snakeverb", "frobnitz", "kowabooga", "boxverb", "exitverb" }, set(custom_verbs)) self.assertEqual(set(), set(custom_verbs) - set(all_verbs))
def test_exits(self): hall = Location("hall") attic = Location("attic") exit1 = Exit("ladder1", attic, "The first ladder leads to the attic.") exit2 = Exit("up", attic, "Second ladder to attic.") exit3 = Exit("ladder3", attic, "Third ladder to attic.") exit4 = Exit("window", attic, "A window.", "A window, maybe if you open it you can get out?") hall.add_exits([exit1, exit2, exit3, exit4]) self.assertTrue(hall.exits["up"] is exit2) self.assertTrue(hall.exits["ladder3"] is exit3) self.assertTrue(hall.exits["window"] is exit4) self.assertEqual([ '[hall]', 'The first ladder leads to the attic. Third ladder to attic. Second ladder to attic. A window.' ], strip_text_styles(hall.look())) self.assertEqual("Third ladder to attic.", exit3.description) self.assertEqual("A window, maybe if you open it you can get out?", exit4.description) with self.assertRaises(ActionRefused): exit1.activate(None) with self.assertRaises(ActionRefused): exit1.deactivate(None) with self.assertRaises(ActionRefused): exit1.close(None, None) with self.assertRaises(ActionRefused): exit1.open(None, None) with self.assertRaises(ActionRefused): exit1.lock(None, None) with self.assertRaises(ActionRefused): exit1.unlock(None, None) with self.assertRaises(ActionRefused): exit1.manipulate("frobnitz", None) with self.assertRaises(ActionRefused): exit1.read(None)
def test_bind_exit(self): class ModuleDummy(object): pass zones = ModuleDummy() zones.town = ModuleDummy() zones.town.square = Location("square") exit = Exit("square", "town.square", "someplace") self.assertFalse(exit.bound) exit._bind_target(zones) self.assertTrue(exit.bound) self.assertTrue(zones.town.square is exit.target) exit._bind_target(zones)
def make_location(vnum): """ Get a Tale location object for the given circle room vnum. This performs an on-demand conversion of the circle room data to Tale. """ try: return converted_rooms[vnum] # get cached version if available except KeyError: c_room = rooms[vnum] loc = Location(c_room.name, c_room.desc) loc.vnum = vnum # keep the circle vnum for ed in c_room.extradesc: loc.add_extradesc(ed["keywords"], ed["text"]) converted_rooms[vnum] = loc for circle_exit in c_room.exits.values(): if circle_exit.roomlink >= 0: xt = make_exit(circle_exit) while True: try: xt.bind(loc) break except LocationIntegrityError as x: if x.direction in xt.aliases: # circlemud exit keywords can be duplicated over various exits # if we have a conflict, just remove the alias from the exit and try again xt.aliases = xt.aliases - {x.direction} continue else: if loc.exits[x.direction] is xt: # this can occur, the exit is already bound break else: # in this case a true integrity error occurred raise else: # add the description of the inaccessible exit to the room's own description. loc.description += " " + circle_exit.desc return loc
def test_custom_verbs(self): player = Player("julie", "f") player.verbs["xywobble"] = "p1" monster = NPC("snake", "f") monster.verbs["snakeverb"] = "s1" room = Location("room") chair1 = Item("chair1") chair1.verbs["frobnitz"] = "c1" chair2 = Item("chair2") chair2.verbs["frobnitz"] = "c2" chair_in_inventory = Item("chair3") chair_in_inventory.verbs["kowabooga"] = "c3" box_in_inventory = Item("box") box_in_inventory.verbs["boxverb"] = "c4" player.init_inventory([box_in_inventory, chair_in_inventory]) exit = Exit("e", "dummy", None, None) exit.verbs["exitverb"] = "c5" room.init_inventory([chair1, player, chair2, monster]) room.add_exits([exit]) custom_verbs = mud_context.driver.current_custom_verbs(player) all_verbs = mud_context.driver.current_verbs(player) self.assertEqual({"xywobble", "snakeverb", "frobnitz", "kowabooga", "boxverb", "exitverb"}, set(custom_verbs)) self.assertEqual(set(), set(custom_verbs) - set(all_verbs))
def test_print_location(self): p = Player("julie", "f") key = Item("key") bag = Container("bag") room = Location("room") bag.insert(key, p) p.insert(bag, p) room.insert(p, p) with self.assertRaises(Exception): p.tell_object_location(None, None) p.tell_object_location(key, None) self.assertEqual(["(It's not clear where key is).\n"], p.test_get_output_paragraphs()) p.tell_object_location(key, None, print_parentheses=False) self.assertEqual(["It's not clear where key is.\n"], p.test_get_output_paragraphs()) p.tell_object_location(key, bag) result = "".join(p.test_get_output_paragraphs()) self.assertTrue("in bag" in result and "in your inventory" in result) p.tell_object_location(key, room) self.assertTrue("in your current location" in "".join(p.test_get_output_paragraphs())) p.tell_object_location(bag, p) self.assertTrue("in your inventory" in "".join(p.test_get_output_paragraphs())) p.tell_object_location(p, room) self.assertTrue("in your current location" in "".join(p.test_get_output_paragraphs()))
def test_location(self): thingy = Item("thing") with self.assertRaises(TypeError): thingy.location = "foobar" hall = Location("hall") thingy.location = hall self.assertEqual(hall, thingy.contained_in) self.assertEqual(hall, thingy.location) person = Living("person", "m", race="human") key = Item("key") backpack = Container("backpack") person.insert(backpack, person) self.assertIsNone(key.contained_in) self.assertIsNone(key.location) self.assertTrue(backpack in person) self.assertEqual(person, backpack.contained_in) self.assertEqual(_limbo, backpack.location) hall.init_inventory([person, key]) self.assertEqual(hall, key.contained_in) self.assertEqual(hall, key.location) self.assertEqual(hall, backpack.location) key.move(backpack, person) self.assertEqual(backpack, key.contained_in) self.assertEqual(hall, key.location)
def test_location(self): thingy = Item("thing") with self.assertRaises(TypeError): thingy.location = "foobar" hall = Location("hall") thingy.location = hall self.assertEqual(hall, thingy.contained_in) self.assertEqual(hall, thingy.location) person = Living("person", "m", race="human") key = Item("key") backpack = Container("backpack") person.insert(backpack, person) self.assertIsNone(key.contained_in) self.assertIsNone(key.location) self.assertTrue(backpack in person) self.assertEqual(person, backpack.contained_in) self.assertEqual(_Limbo, backpack.location) hall.init_inventory([person, key]) self.assertEqual(hall, key.contained_in) self.assertEqual(hall, key.location) self.assertEqual(hall, backpack.location) key.move(backpack, person) self.assertEqual(backpack, key.contained_in) self.assertEqual(hall, key.location)
def test_look(self): player = Player("fritz", "m") attic = Location("Attic", "A dark attic.") player.look() self.assertEqual([ "[Limbo]\n", "The intermediate or transitional place or state. There's only nothingness.\nLiving beings end up here if they're not in a proper location yet.\n" ], player.test_get_output_paragraphs()) player.move(attic, silent=True) player.look(short=True) self.assertEqual(["[Attic]\n"], player.test_get_output_paragraphs()) julie = NPC("julie", "f") julie.move(attic, silent=True) player.look(short=True) self.assertEqual(["[Attic]\n", "Present: julie\n"], player.test_get_output_paragraphs())
def make_location(vnum: int) -> Location: """ Get a Tale location object for the given circle room vnum. This performs an on-demand conversion of the circle room data to Tale. """ # @todo deal with location type ('inside') and attributes ('nomob', 'dark', 'death'...) try: return converted_rooms[vnum] # get cached version if available except KeyError: c_room = rooms[vnum] loc = None # type: Location if vnum in circle_dump_rooms or "death" in c_room.attributes: loc = Garbagedump(c_room.name, c_room.desc) elif vnum in circle_pet_shops: loc = PetShop(c_room.name, c_room.desc) else: loc = Location(c_room.name, c_room.desc) loc.circle_vnum = vnum # type: ignore # keep the circle vnum loc.circle_zone = c_room.zone # type: ignore # keep the circle zone number for ed in c_room.extradesc: loc.add_extradesc(ed["keywords"], ed["text"]) converted_rooms[vnum] = loc for circle_exit in c_room.exits.values(): if circle_exit.roomlink >= 0: xt = make_exit(circle_exit) while True: try: xt.bind(loc) break except LocationIntegrityError as x: if x.direction in xt.aliases: # circlemud exit keywords can be duplicated over various exits # if we have a conflict, just remove the alias from the exit and try again xt.aliases = xt.aliases - {x.direction} continue else: if loc.exits[x.direction] is xt: # this can occur, the exit is already bound break else: # in this case a true integrity error occurred raise else: # add the description of the inaccessible exit to the room's own description. loc.description += " " + circle_exit.desc return loc
def test_others(self): attic = Location("Attic", "A dark attic.") player = Player("merlin", "m") player.title = "wizard Merlin" julie = MsgTraceNPC("julie", "f", "human") fritz = MsgTraceNPC("fritz", "m", "human") julie.move(attic, silent=True) fritz.move(attic, silent=True) player.move(attic, silent=True) player.tell_others("one", "two", "three") self.assertEqual([], player.test_get_output_paragraphs()) self.assertEqual(["one", "two", "three"], fritz.messages) self.assertEqual(["one", "two", "three"], julie.messages) fritz.clearmessages() julie.clearmessages() player.tell_others("{title} and {Title}") self.assertEqual(["wizard Merlin and Wizard Merlin"], fritz.messages)
def test_tell(self): rat = MsgTraceNPC("rat", "n", "rodent") self.assertTrue(rat._init_called, "init() must be called from __init__") julie = MsgTraceNPC("julie", "f", "human") hall = Location("hall") hall.livings = [rat, julie] hall.tell("roommsg") self.assertEqual(["roommsg"], rat.messages) self.assertEqual(["roommsg"], julie.messages) rat.clearmessages() julie.clearmessages() hall.tell("roommsg", rat, [julie], "juliemsg") self.assertEqual([], rat.messages) self.assertEqual(["juliemsg"], julie.messages)
def test_destroy_loc(self): ctx = Context(None, None, None, None) loc = Location("loc") i = Item("item") liv = Living("rat", "n", race="rodent") loc.add_exits([Exit("north", "somewhere", "exit to somewhere")]) player = Player("julie", "f") player.privileges = {"wizard"} player.create_wiretap(loc) loc.init_inventory([i, liv, player]) self.assertTrue(len(loc.exits) > 0) self.assertTrue(len(loc.items) > 0) self.assertTrue(len(loc.livings) > 0) self.assertEqual(loc, player.location) self.assertEqual(loc, liv.location) loc.destroy(ctx) self.assertTrue(len(loc.exits) == 0) self.assertTrue(len(loc.items) == 0) self.assertTrue(len(loc.livings) == 0) self.assertEqual(_limbo, player.location) self.assertEqual(_limbo, liv.location)
def test_wiretap(self): attic = Location("Attic", "A dark attic.") player = Player("fritz", "m") io = ConsoleIo(None) io.supports_smartquotes = False pc = PlayerConnection(player, io) player.set_screen_sizes(0, 100) julie = NPC("julie", "f") julie.move(attic) player.move(attic) julie.tell("message for julie") attic.tell("message for room") self.assertEqual(["message for room\n"], player.test_get_output_paragraphs()) with self.assertRaises(ActionRefused): player.create_wiretap(julie) player.privileges = {"wizard"} player.create_wiretap(julie) player.create_wiretap(attic) julie.tell("message for julie") attic.tell("message for room") pubsub.sync() output = pc.get_output() self.assertTrue( "[wiretapped from 'Attic': message for room]" in output) self.assertTrue( "[wiretapped from 'julie': message for julie]" in output) self.assertTrue( "[wiretapped from 'julie': message for room]" in output) self.assertTrue("message for room " in output) # test removing the wiretaps player.clear_wiretaps() import gc gc.collect() julie.tell("message for julie") attic.tell("message for room") self.assertEqual(["message for room\n"], player.test_get_output_paragraphs())
def test_title_name(self): door = Door("north", "hall", "a locked door", locked=True, opened=False) self.assertEqual("north", door.name) self.assertEqual("Exit to <unbound:hall>", door.title) exit = Exit("outside", "town.square", "someplace") self.assertEqual("outside", exit.name) self.assertEqual("Exit to <unbound:town.square>", exit.title) class ModuleDummy(object): pass zones = ModuleDummy() zones.town = ModuleDummy() zones.town.square = Location("square") exit._bind_target(zones) self.assertEqual("Exit to square", exit.title) self.assertEqual("exit to square", exit.name)
def test_destroy_loc(self): ctx = Context() loc = Location("loc") i = Item("item") liv = Living("rat", "n", race="rodent") loc.add_exits([Exit("north", "somewhere", "exit to somewhere")]) player = Player("julie", "f") player.privileges = {"wizard"} player.create_wiretap(loc) loc.init_inventory([i, liv, player]) self.assertTrue(len(loc.exits) > 0) self.assertTrue(len(loc.items) > 0) self.assertTrue(len(loc.livings) > 0) self.assertEqual(loc, player.location) self.assertEqual(loc, liv.location) loc.destroy(ctx) self.assertTrue(len(loc.exits) == 0) self.assertTrue(len(loc.items) == 0) self.assertTrue(len(loc.livings) == 0) self.assertEqual(_Limbo, player.location) self.assertEqual(_Limbo, liv.location)
def test_with_key(self): player = Player("julie", "f") key = Key("key", "door key") key.key_for(code=12345) hall = Location("hall") door = Door("north", hall, "a locked door", locked=True, opened=False) door2 = Door("south", hall, "another locked door", locked=True, opened=False) with self.assertRaises(ActionRefused): door.unlock(player) with self.assertRaises(ActionRefused): door.unlock(player, key) door.key_code = 12345 door2.key_code = 9999 key.key_for(door) self.assertTrue(door.locked) door.unlock(player, key) self.assertFalse(door.locked) with self.assertRaises(ActionRefused): door2.unlock(key) door.locked = True with self.assertRaises(ActionRefused): door.unlock(player) key.move(player, player) door.unlock(player) self.assertFalse(door.locked) door.lock(player) self.assertTrue(door.locked) door.unlock(player) player.remove(key, player) with self.assertRaises(ActionRefused): door.lock(player) door.key_code = None with self.assertRaises(LocationIntegrityError): key.key_for(door)
def test_verbs(self): room = Location("room") room.verbs["smurf"] = "" self.assertTrue("smurf" in room.verbs) del room.verbs["smurf"] self.assertFalse("smurf" in room.verbs)
def test_actions(self): player = Player("julie", "f") hall = Location("hall") attic = Location("attic") unbound_exit = Exit("random", "foo.bar", "a random exit") with self.assertRaises(Exception): self.assertFalse(unbound_exit.allow_passage( player)) # should fail because not bound exit1 = Exit("ladder", attic, "first ladder to attic") exit1.allow_passage(player) door = Door("north", hall, "open unlocked door", locked=False, opened=True) with self.assertRaises(ActionRefused) as x: door.open(player) # fail, it's already open self.assertEqual("It's already open.", str(x.exception)) door.close(player) self.assertFalse(door.opened, "must be closed") with self.assertRaises(ActionRefused) as x: door.lock(player) # default door can't be locked self.assertEqual("You don't seem to have the means to lock it.", str(x.exception)) with self.assertRaises(ActionRefused) as x: door.unlock(player) # fail, it's not locked self.assertEqual("It's not locked.", str(x.exception)) door = Door("north", hall, "open locked door", locked=False, opened=True) with self.assertRaises(ActionRefused) as x: door.open(player) # fail, it's already open self.assertEqual("It's already open.", str(x.exception)) door.close(player) door.locked = True with self.assertRaises(ActionRefused) as x: door.lock(player) # it's already locked self.assertEqual("It's already locked.", str(x.exception)) self.assertTrue(door.locked) with self.assertRaises(ActionRefused) as x: door.unlock(player) # you can't unlock it self.assertEqual("You don't seem to have the means to unlock it.", str(x.exception)) self.assertTrue(door.locked) door = Door("north", hall, "closed unlocked door", locked=False, opened=False) door.open(player) self.assertTrue(door.opened) door.close(player) self.assertFalse(door.opened) with self.assertRaises(ActionRefused) as x: door.close(player) # it's already closed self.assertEqual("It's already closed.", str(x.exception)) door = Door("north", hall, "closed locked door", locked=True, opened=False) with self.assertRaises(ActionRefused) as x: door.open(player) # can't open it, it's locked self.assertEqual("You try to open it, but it's locked.", str(x.exception)) with self.assertRaises(ActionRefused) as x: door.close(player) # it's already closed self.assertEqual("It's already closed.", str(x.exception)) door = Door("north", hall, "Some door.") self.assertEqual("Some door.", door.short_description) self.assertEqual("Some door. It is open and unlocked.", door.description) self.assertTrue(door.opened) self.assertFalse(door.locked) door = Door("north", hall, "Some door.", "This is a peculiar door leading north.") self.assertEqual("Some door.", door.short_description) self.assertEqual( "This is a peculiar door leading north. It is open and unlocked.", door.description)
def test_enter_leave(self): hall = Location("hall") rat1 = NPC("rat1", "n") rat2 = NPC("rat2", "n") julie = NPC("julie", "f") with self.assertRaises(TypeError): hall.insert(12345, julie) self.assertEqual(_Limbo, rat1.location) self.assertFalse(rat1 in hall.livings) wiretap = Wiretap(hall) hall.insert(rat1, julie) self.assertEqual(hall, rat1.location) self.assertTrue(rat1 in hall.livings) self.assertEqual([], wiretap.msgs, "insert shouldn't produce arrival messages") hall.insert(rat2, julie) self.assertTrue(rat2 in hall.livings) self.assertEqual([], wiretap.msgs, "insert shouldn't produce arrival messages") # now test leave wiretap.clear() hall.remove(rat1, julie) self.assertFalse(rat1 in hall.livings) self.assertIsNone(rat1.location) self.assertEqual([], wiretap.msgs, "remove shouldn't produce exit message") hall.remove(rat2, julie) self.assertFalse(rat2 in hall.livings) self.assertEqual([], wiretap.msgs, "remove shouldn't produce exit message") # test random leave hall.remove(rat1, julie) hall.remove(12345, julie)
from tale.pubsub import Listener from tale import mud_context from npcs.teachers import Librarian from tale.errors import ActionRefused from tale.items.basic import Note def init(driver): # called when zone is first loaded pass english = Location( "English Class", """ You step into the classroom and your teacher, Mr. Bushel, clears his throat. "You're late, as usual. I sincerely hope you remembered your homework." He holds out his hand expectantly. """, ) library = Location( "Library", """ You're in the library, where you usually spend your after-school time in detention. """, ) hallway_door = Door( ["hallway", "hallway door", "south", "s", "out"], "hallways.north_hallway", short_description="An open door to the south leads back into the hallway.",
rose street north, crossing, rose street south butcher, storage room """ import random import zones.houses import zones.npcs from tale.base import Location, Exit, Door, Key, Living, ParseResult, _limbo from tale.items.basic import Money from tale.errors import ParseError, ActionRefused, StoryCompleted from tale.util import call_periodically, Context from tale import mud_context north_street = Location("Rose Street", "The northern part of Rose Street.") south_street = Location("Rose Street", "The southern part of Rose Street.") crossing = Location("Crossing", "Town Crossing.") crossing.add_exits([ Exit("west", "magnolia_st.street2", "Westwards lies Magnolia Street."), Exit("east", "magnolia_st.street3", "Magnolia Street extends to the east, eventually leading towards the factory."), ]) Exit.connect(crossing, "north", "A part of Rose Street lies to the north.", None, north_street, ["south", "crossing"], "The street goes south towards the crossing.", None) Exit.connect(crossing, "south", "Rose Street continues to the south.", None, south_street, ["north", "crossing"], "The crossing is back towards the north.", None) playground = Location("Playground", "Children's playground. You see a rusty merry-go-round, and a little swing. " "To the west, a house is visible.")
from tale.driver import Driver from tale.errors import ActionRefused, TaleError, StoryCompleted from tale.items.basic import trashcan, newspaper, gem, gameclock, pouch from tale.items.board import bulletinboard from tale.player import Player def init(driver: Driver) -> None: # called when zone is first loaded board.load() board.save() # make sure the storage file exists square = Location( "Town square", "The old town square of the village. It is not much really, " "and narrow streets quickly lead away from the small fountain in the center." ) lane = Location( "Lane of Magicks", "A long straight road leading to the horizon. Apart from a nearby small tower, " "you can't see any houses or other landmarks. The road seems to go on forever though." ) Exit.connect(square, ["north", "lane"], "A long straight lane leads north towards the horizon.", None, lane, "south", "The town square lies to the south.", None) paper = newspaper.clone() paper.aliases = {"paper"}
""" The Wizard Tower, which is the place where Wizards start/log in 'Tale' mud driver, mudlib and interactive fiction framework Copyright by Irmen de Jong ([email protected]) """ import random from tale import lang, util from tale.base import Location, Exit, Item, Living hall = Location("Main hall of the Tower of Magic", "The main hall of this ancient wizard tower sparkles with traces of magic. " "Everything seems to glow a little from within. You can hear a very faint hum.") table = Item("table", "oak table", descr="A large dark table with a lot of cracks in its surface.") key = Item("key", "rusty key", descr="An old rusty key without a label.") class Drone(Living): @util.call_periodically(2) def do_whizz(self, ctx: util.Context) -> None: rand = random.random() if rand < 0.14: self.do_socialize("twitch erra") elif rand < 0.28: self.do_socialize("rotate random") elif rand < 0.40: self.location.tell("%s hums softly." % lang.capital(self.title))
The house, where the player starts the game. Also defines the Neighbor's house, where other things can be found. """ from __future__ import absolute_import, print_function, division, unicode_literals from tale.base import Location, Exit, Door def init(driver): # called when zone is first loaded pass # ----------------- START House & Kitchen ------------------------- livingroom = Location("Living room", "The living room in your little home. Your big TV hangs on a wall.") livingroom.add_extradesc({"plasma", "tv"}, "You recently bought a bigger TV, but haven't yet found the time to actually watch anything.") kitchen = Location("Kitchen", "A small but well supplied kitchen. Rather than ordering take-away, " "you prefer cooking your own meals -- unlike most of the other people you know in town. A window lets you look outside.") kitchen.add_extradesc({"window", "outside"}, "Through the kitchen window you can see your small garden and behind that, the children's playground.") # Exits front_door = Door(["door", "outside", "street"], "magnolia_st.street1", "Your front door leads outside, to the street.", "There's a heavy front door here that leads to the streets outside.", opened=False) house_door = front_door.reverse_door(["house", "north", "inside"], livingroom, "You can go back inside your house.", "It's your house, on the north side of the street.", reverse_open_msg="Someone outside opens the door.", reverse_close_msg="Someone outside closes the door.", this_open_msg="Someone in the house opens the door.", this_close_msg="Someone in the house closes the door.")
def test_notify(self): room = Location("room") room2 = Location("room2") player = Player("julie", "f") room.notify_player_arrived(player, room2) room.notify_player_left(player, room2) room.notify_npc_arrived(player, room2) room.notify_npc_left(player, room2) parsed = ParseResult("verb") room.notify_action(parsed, player)
def test_names(self): loc = Location("The Attic", "A dusty attic.") self.assertEqual("The Attic", loc.name) self.assertEqual("A dusty attic.", loc.description)
def test_handle_and_notify_action(self): class SpecialPlayer(Player): def init(self): self.handled = False self.handle_verb_called = False self.notify_called = False def handle_verb(self, parsed, actor): self.handle_verb_called = True if parsed.verb in self.verbs: self.handled = True return True else: return False def notify_action(self, parsed, actor): self.notify_called = True player = SpecialPlayer("julie", "f") player.verbs["xywobble"] = "" room = Location("room") class Chair(Item): def init(self): self.handled = False self.handle_verb_called = False self.notify_called = False def handle_verb(self, parsed, actor): self.handle_verb_called = True if parsed.verb in self.verbs: self.handled = True return True else: return False def notify_action(self, parsed, actor): self.notify_called = True chair_in_inventory = Chair("littlechair") chair_in_inventory.verbs["kerwaffle"] = "" player.insert(chair_in_inventory, player) chair = Chair("chair") chair.verbs["frobnitz"] = "" room.init_inventory([player, chair]) # first check if the handle_verb passes to all objects including inventory parsed = ParseResult("kowabungaa12345") handled = room.handle_verb(parsed, player) self.assertFalse(handled) self.assertTrue(chair.handle_verb_called) self.assertTrue(player.handle_verb_called) self.assertTrue(chair_in_inventory.handle_verb_called) self.assertFalse(chair.handled) self.assertFalse(player.handled) self.assertFalse(chair_in_inventory.handled) # check item handling player.init() chair.init() chair_in_inventory.init() parsed = ParseResult("frobnitz") handled = room.handle_verb(parsed, player) self.assertTrue(handled) self.assertTrue(chair.handled) self.assertFalse(player.handled) self.assertFalse(chair_in_inventory.handled) # check living handling player.init() chair.init() chair_in_inventory.init() parsed = ParseResult("xywobble") handled = room.handle_verb(parsed, player) self.assertTrue(handled) self.assertFalse(chair.handled) self.assertTrue(player.handled) self.assertFalse(chair_in_inventory.handled) # check inventory handling player.init() chair.init() chair_in_inventory.init() parsed = ParseResult("kerwaffle") handled = room.handle_verb(parsed, player) self.assertTrue(handled) self.assertFalse(chair.handled) self.assertFalse(player.handled) self.assertTrue(chair_in_inventory.handled) # check notify_action player.init() chair.init() chair_in_inventory.init() room.notify_action(parsed, player) self.assertTrue(chair.notify_called) self.assertTrue(player.notify_called) self.assertTrue(chair_in_inventory.notify_called)
from __future__ import absolute_import, print_function, division, unicode_literals import random from tale.base import Location, Exit, Item, heartbeat from tale.npc import NPC import tale.lang def init(driver): # called when zone is first loaded pass hall = Location("Main hall of the Tower of Magic", """ The main hall of this ancient wizard tower sparkles with traces of magic. Everything seems to glow a little from within. You can hear a very faint hum. """) table = Item("table", "oak table", "A large dark table with a lot of cracks in its surface.") key = Item("key", "rusty key", "An old rusty key without a label.") @heartbeat class Drone(NPC): def heartbeat(self, ctx): rand = random.random() if rand < 0.07: self.do_socialize("twitch erra") elif rand < 0.14: self.do_socialize("rotate random") elif rand < 0.21:
""" The house, where the player starts the game. Their pet cat is also here and you can interact with him a little. The generated demo code below is provided for you to use or modify as you wish. (it creates a trivial location similar to the built-in demo story of the Tale library itself) """ from tale.base import Location, Exit, Door from zones.sarah import Sarah from zones.descriptions import room_descriptions, sarah_text ##### Lobby ##### foyer = Location(name="Foyer", descr=room_descriptions['foyer']) # Build Exits foyer_closet = Exit(directions="closet", target_location="inn.foyer_closet", short_descr="There is a small closet in the foyer.", long_descr=None) foyer_sitting = Exit(directions=["north", "sitting"], target_location="inn.sitting_room", short_descr="There is a sitting room to the north.", long_descr="""Through the archway you can see a cozy room flickering to the light of a fire.""") foyer.add_exits([foyer_closet, foyer_sitting]) # Insert items & npcs
import random import zones.houses import zones.npcs from tale.base import Location, Exit, Door, Key, Living, ParseResult, _limbo from tale.items.basic import Money from tale.errors import ParseError, ActionRefused, StoryCompleted from tale.util import call_periodically, Context from tale import mud_context north_street = Location("Rose Street", "The northern part of Rose Street.") south_street = Location("Rose Street", "The southern part of Rose Street.") crossing = Location("Crossing", "Town Crossing.") crossing.add_exits([ Exit("west", "magnolia_st.street2", "Westwards lies Magnolia Street."), Exit("east", "magnolia_st.street3", "Magnolia Street extends to the east, eventually leading towards the factory."), ]) Exit.connect(crossing, "north", "A part of Rose Street lies to the north.", None, north_street, ["south", "crossing"], "The street goes south towards the crossing.", None) Exit.connect(crossing, "south", "Rose Street continues to the south.", None, south_street, ["north", "crossing"], "The crossing is back towards the north.", None) playground = Location("Playground", "Children's playground. You see a rusty merry-go-round, and a little swing. " "To the west, a house is visible.") playground.add_extradesc({"west", "house"}, "You can see your house from here!") playground.add_exits([ Door("fence", _limbo, "On the north end of the playground is a sturdy looking padlocked fence.",
def test_message_nearby_location(self): plaza = Location("plaza") road = Location("road") house = Location("house") attic = Location("attic") plaza.add_exits([Exit("north", road, "road leads north"), Exit("door", house, "door to a house")]) road.add_exits([Exit("south", plaza, "plaza to the south")]) house.add_exits([Exit("door", plaza, "door to the plaza"), Exit("ladder", attic, "dusty attic")]) attic.add_exits([Exit("ladder", house, "the house")]) wiretap_plaza = Wiretap(plaza) wiretap_road = Wiretap(road) wiretap_house = Wiretap(house) wiretap_attic = Wiretap(attic) util.message_nearby_locations(plaza, "boing") pubsub.sync() self.assertEqual([], wiretap_plaza.msgs, "the plaza doesnt receive tells") self.assertEqual([], wiretap_attic.msgs, "the attic is too far away to receive msgs") self.assertTrue(("road", "boing") in wiretap_road.msgs) self.assertTrue( ("road", "The sound is coming from the south.") in wiretap_road.msgs, "road should give sound direction" ) self.assertTrue(("house", "boing") in wiretap_house.msgs) self.assertTrue( ("house", "You can't hear where the sound is coming from.") in wiretap_house.msgs, "in the house you can't locate the sound direction", )
from tale import mud_context from tale.lang import capital # define the various locations class GameEnd(Location): def init(self): pass def notify_player_arrived(self, player, previous_location): # player has entered! player.story_completed() livingroom = Location("Living room", "The living room in your home in the outskirts of the city.") closet = Location("Closet", "A small room.") outside = GameEnd("Outside", "It is beautiful weather outside.") # define the exits that connect the locations door = Door( ["garden", "door"], outside, "A door leads to the garden.", "There's a heavy door here that leads to the garden outside the house.", locked=True, opened=False) door.door_code = 1 closet_exit = Exit("closet", closet, "There's a small closet in your house.") livingroom.add_exits([door, closet_exit]) closet.add_exits([Exit("living room", livingroom, "You can see the living room.")])
def test_door_pair(self): loc1 = Location("room1", "room one") loc2 = Location("room2", "room two") key = Key("key") door_one_two = Door("two", loc2, "door to room two", locked=True, opened=False) door_two_one = door_one_two.reverse_door( "one", loc1, "door to room one", reverse_open_msg="door one open", reverse_close_msg="door one close", this_open_msg="door two open", this_close_msg="door two close") loc1.add_exits([door_one_two]) loc2.add_exits([door_two_one]) door_one_two.key_code = 555 key.key_for(door_one_two) pubsub1 = PubsubCollector() pubsub2 = PubsubCollector() loc1.get_wiretap().subscribe(pubsub1) loc2.get_wiretap().subscribe(pubsub2) self.assertTrue(door_two_one.locked) self.assertFalse(door_two_one.opened) lucy = Living("lucy", "f") door_two_one.unlock(lucy, item=key) self.assertFalse(door_one_two.locked) door_two_one.open(lucy) self.assertTrue(door_one_two.opened) pubsub.sync() self.assertEqual(["door one open"], pubsub1.messages) self.assertEqual([], pubsub2.messages) door_one_two.close(lucy) door_one_two.lock(lucy, item=key) self.assertTrue(door_two_one.locked) self.assertFalse(door_two_one.opened) pubsub1.clear() pubsub2.clear() pubsub.sync() self.assertEqual([], pubsub1.messages) self.assertEqual(["door two close"], pubsub2.messages)
class TestLocations(unittest.TestCase): def setUp(self): mud_context.driver = DummyDriver() self.hall = Location("Main hall", "A very large hall.") self.attic = Location("Attic", "A dark attic.") self.street = Location("Street", "An endless street.") e1 = Exit("up", self.attic, "A ladder leads up.") e2 = Exit(["door", "east"], self.street, "A heavy wooden door to the east blocks the noises from the street outside.") self.hall.add_exits([e1, e2]) self.table = Item("table", "oak table", "a large dark table with a lot of cracks in its surface") self.key = Item("key", "rusty key", "an old rusty key without a label", short_description="Someone forgot a key.") self.magazine = Item("magazine", "university magazine") self.rat = NPC("rat", "n", race="rodent") self.fly = NPC("fly", "n", race="insect", short_description="A fly buzzes around your head.") self.julie = NPC("julie", "f", title="attractive Julie", description="She's quite the looker.") self.julie.aliases = {"chick"} self.player = Player("player", "m") self.pencil = Item("pencil", title="fountain pen") self.pencil.aliases = {"pen"} self.bag = Container("bag") self.notebook_in_bag = Item("notebook") self.bag.insert(self.notebook_in_bag, self.player) self.player.insert(self.pencil, self.player) self.player.insert(self.bag, self.player) self.hall.init_inventory([self.table, self.key, self.magazine, self.rat, self.julie, self.player, self.fly]) def test_names(self): loc = Location("The Attic", "A dusty attic.") self.assertEqual("The Attic", loc.name) self.assertEqual("A dusty attic.", loc.description) def test_contains(self): self.assertTrue(self.julie in self.hall) self.assertTrue(self.magazine in self.hall) self.assertFalse(self.pencil in self.hall) self.assertFalse(self.magazine in self.attic) self.assertFalse(self.julie in self.attic) def test_look(self): expected = ["[Main hall]", "A very large hall.", "A heavy wooden door to the east blocks the noises from the street outside. A ladder leads up.", "Someone forgot a key. You see a university magazine and an oak table. Player, attractive Julie, and rat are here. A fly buzzes around your head."] self.assertEqual(expected, strip_text_styles(self.hall.look())) expected = ["[Main hall]", "A very large hall.", "A heavy wooden door to the east blocks the noises from the street outside. A ladder leads up.", "Someone forgot a key. You see a university magazine and an oak table. Attractive Julie and rat are here. A fly buzzes around your head."] self.assertEqual(expected, strip_text_styles(self.hall.look(exclude_living=self.player))) expected = ["[Attic]", "A dark attic."] self.assertEqual(expected, strip_text_styles(self.attic.look())) def test_look_short(self): expected = ["[Attic]"] self.assertEqual(expected, strip_text_styles(self.attic.look(short=True))) expected = ["[Main hall]", "Exits: door, east, up", "You see: key, magazine, table", "Present: fly, julie, player, rat"] self.assertEqual(expected, strip_text_styles(self.hall.look(short=True))) expected = ["[Main hall]", "Exits: door, east, up", "You see: key, magazine, table", "Present: fly, julie, rat"] self.assertEqual(expected, strip_text_styles(self.hall.look(exclude_living=self.player, short=True))) def test_search_living(self): self.assertEqual(None, self.hall.search_living("<notexisting>")) self.assertEqual(None, self.attic.search_living("<notexisting>")) self.assertEqual(self.rat, self.hall.search_living("rat")) self.assertEqual(self.julie, self.hall.search_living("Julie")) self.assertEqual(self.julie, self.hall.search_living("attractive julie")) self.assertEqual(self.julie, self.hall.search_living("chick")) self.assertEqual(None, self.hall.search_living("bloke")) def test_search_item(self): # almost identical to locate_item so only do a few basic tests self.assertEqual(None, self.player.search_item("<notexisting>")) self.assertEqual(self.pencil, self.player.search_item("pencil")) def test_locate_item(self): item, container = self.player.locate_item("<notexisting>") self.assertEqual(None, item) self.assertEqual(None, container) item, container = self.player.locate_item("pencil") self.assertEqual(self.pencil, item) self.assertEqual(self.player, container) item, container = self.player.locate_item("fountain pen") self.assertEqual(self.pencil, item, "need to find the title") item, container = self.player.locate_item("pen") self.assertEqual(self.pencil, item, "need to find the alias") item, container = self.player.locate_item("pencil", include_inventory=False) self.assertEqual(None, item) self.assertEqual(None, container) item, container = self.player.locate_item("key") self.assertEqual(self.key, item) self.assertEqual(self.hall, container) item, container = self.player.locate_item("key", include_location=False) self.assertEqual(None, item) self.assertEqual(None, container) item, container = self.player.locate_item("KEY") self.assertEqual(self.key, item, "should work case-insensitive") self.assertEqual(self.hall, container, "should work case-insensitive") item, container = self.player.locate_item("notebook") self.assertEqual(self.notebook_in_bag, item) self.assertEqual(self.bag, container, "should search in bags in inventory") item, container = self.player.locate_item("notebook", include_containers_in_inventory=False) self.assertEqual(None, item) self.assertEqual(None, container, "should not search in bags in inventory") def test_tell(self): rat = MsgTraceNPC("rat", "n", "rodent") self.assertTrue(rat._init_called, "init() must be called from __init__") julie = MsgTraceNPC("julie", "f", "human") hall = Location("hall") hall.livings = [rat, julie] hall.tell("roommsg") self.assertEqual(["roommsg"], rat.messages) self.assertEqual(["roommsg"], julie.messages) rat.clearmessages() julie.clearmessages() hall.tell("roommsg", rat, [julie], "juliemsg") self.assertEqual([], rat.messages) self.assertEqual(["juliemsg"], julie.messages) def test_verbs(self): room = Location("room") room.verbs["smurf"] = "" self.assertTrue("smurf" in room.verbs) del room.verbs["smurf"] self.assertFalse("smurf" in room.verbs) def test_enter_leave(self): hall = Location("hall") rat1 = NPC("rat1", "n") rat2 = NPC("rat2", "n") julie = NPC("julie", "f") with self.assertRaises(TypeError): hall.insert(12345, julie) self.assertEqual(_Limbo, rat1.location) self.assertFalse(rat1 in hall.livings) wiretap = Wiretap(hall) hall.insert(rat1, julie) self.assertEqual(hall, rat1.location) self.assertTrue(rat1 in hall.livings) self.assertEqual([], wiretap.msgs, "insert shouldn't produce arrival messages") hall.insert(rat2, julie) self.assertTrue(rat2 in hall.livings) self.assertEqual([], wiretap.msgs, "insert shouldn't produce arrival messages") # now test leave wiretap.clear() hall.remove(rat1, julie) self.assertFalse(rat1 in hall.livings) self.assertIsNone(rat1.location) self.assertEqual([], wiretap.msgs, "remove shouldn't produce exit message") hall.remove(rat2, julie) self.assertFalse(rat2 in hall.livings) self.assertEqual([], wiretap.msgs, "remove shouldn't produce exit message") # test random leave hall.remove(rat1, julie) hall.remove(12345, julie) def test_custom_verbs(self): player = Player("julie", "f") player.verbs["xywobble"] = "p1" room = Location("room") chair1 = Item("chair1") chair1.verbs["frobnitz"] = "c1" chair2 = Item("chair2") chair2.verbs["frobnitz"] = "c2" chair_in_inventory = Item("chair3") chair_in_inventory.verbs["kowabooga"] = "c3" room.init_inventory([chair1, player, chair2]) # check inventory NOT affecting player custom verbs, but DOES affect location verbs self.assertEqual({"xywobble": "p1"}, player.verbs) self.assertEqual({"frobnitz": "c2", "xywobble": "p1"}, room.verbs) player.insert(chair_in_inventory, player) self.assertEqual({"xywobble": "p1"}, player.verbs) self.assertEqual({"frobnitz": "c2", "xywobble": "p1", "kowabooga": "c3"}, room.verbs) player.remove(chair_in_inventory, player) self.assertEqual({"frobnitz": "c2", "xywobble": "p1"}, room.verbs) player.insert(chair_in_inventory, player) self.assertEqual({"frobnitz": "c2", "xywobble": "p1", "kowabooga": "c3" }, room.verbs) room2 = Location("room2") self.assertEqual({}, room2.verbs) chair1.move(room2, player) self.assertEqual({"xywobble": "p1", "kowabooga": "c3" }, room.verbs) self.assertEqual({"frobnitz": "c1"}, room2.verbs) chair2.move(room2, player) self.assertEqual({"xywobble": "p1", "kowabooga": "c3"}, room.verbs) self.assertEqual({"frobnitz": "c2"}, room2.verbs) player.move(room2) self.assertEqual({}, room.verbs) self.assertEqual({"frobnitz": "c2", "xywobble": "p1", "kowabooga": "c3"}, room2.verbs) def test_notify(self): room = Location("room") room2 = Location("room2") player = Player("julie", "f") room.notify_player_arrived(player, room2) room.notify_player_left(player, room2) room.notify_npc_arrived(player, room2) room.notify_npc_left(player, room2) parsed = ParseResult("verb") room.notify_action(parsed, player)