def test_intransitive_commands_should_not_throw_exceptions(self):
     for word in self.words:
         game = Game()
         load_advent_dat(game)
         game.start()
         game.do_command(['no'])  # WOULD YOU LIKE INSTRUCTIONS?
         game.do_command([word])
示例#2
0
    def start(self) -> str:
        if self.game:
            raise GameAlreadyStartedError

        self.game = Game()
        adventure.load_advent_dat(self.game)
        self.game.start()
        return self.game.output
示例#3
0
 def test_transitive_commands_should_not_throw_exceptions(self):
     for word in self.words:
         game = Game()
         load_advent_dat(game)
         game.start()
         game.do_command(['no'])  # WOULD YOU LIKE INSTRUCTIONS?
         game.do_command(['enter'])  # so we are next to lamp
         game.do_command([word, 'lamp'])
示例#4
0
    def setUp(self):
        self.data = Mock()
        self.player = Mock()
        self.token_processor = Mock()
        self.token_processor.process_tokens.return_value = "goodbye"

        self.game = Game(self.data, self.player)
        self.game.token_processor = self.token_processor
示例#5
0
 def __init__(self, event, conversation):
     match = self.regex.match(event['body'])
     if not match:
         if Adventure in conversation.data:
             game = conversation.data[Adventure]
             words = re.findall('\w+', event['body'])
             event.reply(game.do_command(words).strip()).send()
             if not game.is_finished:
                 conversation.handler = Adventure
         else:
             log.warn('An adventure session was lost.')
             event.reply('You have to start an adventure first.').send()
     elif match.group('cmd') == 'start':
         game = Game()
         load_advent_dat(game)
         savefile = settings['textadventure']['file'].format(
             conversation.jid)
         game.i_suspend = _make_suspend(game, savefile)
         game.t_suspend = game.i_suspend
         game.start()
         conversation.handler = Adventure
         event.reply(game.output.strip()).send()
         conversation.data[Adventure] = game
     else:
         savefile = settings['textadventure']['file'].format(
             conversation.jid)
         game = Game.resume(savefile)
         game.i_suspend = _make_suspend(game, savefile)
         game.t_suspend = game.i_suspend
         event.reply('GAME RESTORED').send()
         conversation.handler = Adventure
         conversation.data[Adventure] = game
 def maybe_end_game(self):
     # end game if no interaction for 10 mins
     if self.playing:
         timed_out = time.time() - self.last_interaction > 10 * 3600
         # disable save and gameplay
         if self.game.is_finished or timed_out:
             self.disable_intent("Save")
             self.playing = False
             self.game = Game()
             load_advent_dat(self.game)
         # save game to allow restoring if timedout
         if timed_out:
             self.handle_save()
示例#7
0
 def __init__(self, event, conversation):
     match = self.regex.match(event['body'])
     if not match:
         if Adventure in conversation.data:
             game = conversation.data[Adventure]
             words = re.findall('\w+', event['body'])
             event.reply(game.do_command(words).strip()).send()
             if not game.is_finished:
                 conversation.handler = Adventure
         else:
             log.warn('An adventure session was lost.')
             event.reply('You have to start an adventure first.').send()
     elif match.group('cmd') == 'start':
         game = Game()
         load_advent_dat(game)
         savefile = settings['textadventure']['file'].format(conversation.jid)
         game.i_suspend = _make_suspend(game, savefile)
         game.t_suspend = game.i_suspend
         game.start()
         conversation.handler = Adventure
         event.reply(game.output.strip()).send()
         conversation.data[Adventure] = game
     else:
         savefile = settings['textadventure']['file'].format(conversation.jid)
         game = Game.resume(savefile)
         game.i_suspend = _make_suspend(game, savefile)
         game.t_suspend = game.i_suspend
         event.reply('GAME RESTORED').send()
         conversation.handler = Adventure
         conversation.data[Adventure] = game
示例#8
0
def resume(savefile, quiet=False):
    global _game

    _game = Game.resume(savefile)
    install_words(_game)
    if not quiet:
        print('GAME RESTORED\n')
示例#9
0
	def process_command(self, linein):
		"""Process a command on the active shell
		
		Arguments:
		linein - The command to be processed
		"""

		# For now, it's a hard coded limitation that a command must be
		# distinguished by its first word alone, and all following data
		# is to be treated as an argument to the command
		command = linein.split()[0]
		args = linein.split()[1:]
		if(command in self.alias_list):
			command = self.alias_list[command]

		if(command in self.command_list):
			# Process the command, currently manual
			if(command == "help"):
				if args == []:
					self.print_help()
				else:
					self.print_help(args[0])
			elif(command == "quit"):
				self.running = False
			elif(command == "load"):
				self.currgame = Game(name="My Game")
				print("Loaded", self.currgame.name)
				print(self.currgame.display_room())
			else:
				raise NotImplementedError()
		else:
			raise KeyError("No such command")
示例#10
0
class GameEngine(GameEngineABC):
    game: Optional[Game]

    def __init__(self) -> None:
        self.game = None

    def start(self) -> str:
        if self.game:
            raise GameAlreadyStartedError

        self.game = Game()
        adventure.load_advent_dat(self.game)
        self.game.start()
        return self.game.output

    def resume(self, save: io.BytesIO) -> None:
        if self.game:
            raise GameAlreadyStartedError

        self.game = Game.resume(save)

    def do_command(self, command: str) -> str:
        if not self.game:
            raise GameNotStartedError

        words = re.findall(r"\w+", command)
        return self.game.do_command(words)

    def save(self) -> io.BytesIO:
        if not self.game:
            raise GameNotStartedError

        save_data_stream = io.BytesIO()
        self.game.t_suspend(verb=None, obj=save_data_stream)
        return save_data_stream

    def last_output(self) -> str:
        if not self.game:
            raise GameNotStartedError

        return self.game.output

    @staticmethod
    def help_prompt() -> str:
        game = Game()
        adventure.load_advent_dat(game)
        return str(game.messages[51])
示例#11
0
class TestGame(unittest.TestCase):
    def setUp(self):
        self.data = Mock()
        self.player = Mock()
        self.token_processor = Mock()
        self.token_processor.process_tokens.return_value = "goodbye"

        self.game = Game(self.data, self.player)
        self.game.token_processor = self.token_processor

    def test_process_input_empty(self):
        response = self.game.process_input("")

        self.assertEqual("", response)
        self.token_processor.process_tokens.assert_not_called()

    def test_process_input_one_token(self):
        response = self.game.process_input("hello")

        self.assertEqual("goodbye", response)
        self.token_processor.process_tokens.assert_called_once_with(
            self.player, ["hello"])

    def test_process_input_two_tokens(self):
        response = self.game.process_input("hello  there   ")

        self.assertEqual("goodbye", response)
        self.token_processor.process_tokens.assert_called_once_with(
            self.player, ["hello", "there"])

    def test_process_input_uppercase(self):
        response = self.game.process_input("HELLO")

        self.assertEqual("goodbye", response)
        self.token_processor.process_tokens.assert_called_once_with(
            self.player, ["hello"])

    def test_process_input_mixed_case(self):
        response = self.game.process_input("HeLlo")

        self.assertEqual("goodbye", response)
        self.token_processor.process_tokens.assert_called_once_with(
            self.player, ["hello"])

    def test_process_input_player_still_playing(self):
        self.player.is_playing.return_value = True

        response = self.game.process_input("hello")

        self.assertEqual("goodbye", response)
        self.assertTrue(self.game.running)

    def test_process_input_player_not_still_playing(self):
        self.player.is_playing.return_value = False

        response = self.game.process_input("hello")

        self.assertEqual("goodbye", response)
        self.assertFalse(self.game.running)
 def handle_restore(self, message):
     if exists(self.save_file):
         self.playing = True
         self.game = Game.resume(self.save_file)
         self.speak_dialog("restore.game")
     else:
         self.speak_dialog("save.not.found")
         new_game = self.ask_yesno("new.game")
         if new_game:
             self.handle_play()
示例#13
0
def loop(args):
    parser = argparse.ArgumentParser(
        description='Adventure into the Colossal Caves.',
        prog='{} -m adventure'.format(os.path.basename(sys.executable)))
    parser.add_argument('savefile',
                        nargs='?',
                        help='The filename of game you have saved.')
    args = parser.parse_args(args)

    if args.savefile is None:
        game = Game()
        load_advent_dat(game)
        game.start()
        baudout(game.output)

    else:
        game = Game.resume(args.savefile)
        baudout('GAME RESTORED\n')

    while not game.is_finished:
        # line = input('> ').lower()
        # words = re.findall(r'\w+', line)
        line = recognition()
        line = line.lower()
        words = re.findall(r'\w+', line)
        print(words)
        if words:
            baudout(game.do_command(words))
示例#14
0
    def NewGame(self):
        Game.NewGame(self)
        self.questName = "Get Elevator"
        self.quest = self.world.verbs['GO'], self.world.objects['BUILDING']

        self.state.location = self.world.locations['ON A BUSY STREET']

        self.state['playerName'] = None
        code = ""
        for _ in range(5):
            code += str(random.choice(range(9)))
        self.state['secretCode'] = '1 2 3 4 5'  # code
        self.state['upButtonPushed'] = False
        self.state['floor'] = 1
        self.state['ropeThrown'] = False
        self.state['glovesWorn'] = False
        self.state['fellFromFrame'] = False
        self.state['capsuleDropped'] = False
        self.state['boxButtonPushed'] = False
        self.state['batteryInserted'] = False
        self.state['tvConnected'] = False
        self.state['guardAwakened'] = False
        self.state['tapeInserted'] = False
        self.state['wallButtonPushed'] = False
        self.state['sculptureMessage'] = False
        self.state['electricityOff'] = False
        self.state['combination'] = 12345
        self.state['guardTicks'] = -1

        self.defaultReward = -0.01
        self.rewards = {
            Response.Success: self.defaultReward,
            Response.QuestCompleted: 1,
            Response.IllegalCommand: -0.1 + self.defaultReward,
            Response.Fatal: -1,
            Response.MaybeLater: 0.04 + self.defaultReward,
            Response.NotUseful: -0.02 + self.defaultReward,
            Response.NewlySeen: 0.06 + self.defaultReward,
            Response.MightBeUseful: 0.02 + self.defaultReward,
        }

        self.state.inventory.Add(self.world.objects['BADGE'])
        return self.state.location.Name(), self.quest, False
示例#15
0
    def parse_file(self, json_content):
        resolvers = self.init_resolvers()

        data, player, validation = self.parse_content(json_content, resolvers)
        if validation:
            with open(DataParser.VALIDATION_MESSAGE_FILENAME,
                      "w") as validation_file:
                for validation_line in validation:
                    validation_file.write(
                        validation_line.get_formatted_message() + "\n")
            print("Validation errors found, see {0}.".format(
                DataParser.VALIDATION_MESSAGE_FILENAME))

        resolvers.argument_resolver.init_data(data)
        resolvers.command_handler.init_data(data)
        resolvers.vision_resolver.init_data(data)
        resolvers.event_resolver.init_data(data)
        resolvers.life_resolver.init_data(data)

        return Game(data, player)
示例#16
0
    def NewGame(self):
        Game.NewGame(self)
        n = random.choice(range(len(self.quests)))
        q = self.quests[n]
        self.questCommand = self.world.verbs[q[0]].i, self.world.objects[q[1]].i
        self.questName = self.questNames[n]
        self.prompt = self.questName + ":"

        self.state['quest'] = self.world.verbs[self.questCommand[0]].abbreviation + ' ' + self.world.objects[self.questCommand[1]].abbreviation

        self.defaultReward = -0.01
        self.rewards = {
            Response.Success: self.defaultReward,
            Response.QuestCompleted: 1,
            Response.IllegalCommand: -0.1 + self.defaultReward,
            Response.NewlySeen: 0,
        }

        self.state.location = self.world.locations[random.choice(range(len(self.world.locations)))]

        return self.state.location.Name(), self.questName, False
示例#17
0
    def resume(self, save: io.BytesIO) -> None:
        if self.game:
            raise GameAlreadyStartedError

        self.game = Game.resume(save)
示例#18
0
 def Run(self, commands, steps=None):
     #        self.world.print()
     Game.Run(self, commands, steps=steps)
示例#19
0
class ShellInterface:

	"""Class for a very simple shell interface."""

	shellname = "Adventure Core Testing Shell ver. NaN"
	initmessage = """\
		Copyright (c) 2011 Dylan Nugent. All Rights Reserved.
		This program is licensed freely under the NCSA license.
		Source code is available, and a copy of the license should be included.
	"""
	initmessage = textwrap.dedent(initmessage)
	prompt = "command> "
	case_insensitive = True
	command_list = {}
	alias_list = {}

	def __init__(self):
		"""Initializes the shell interface.

		Loads shell builtins and prints the initialization (welcome)
		message for the shell.
		"""

		print(self.shellname)
		print(self.initmessage)
		if DEBUG:
			print("Debug mode is active. Bumpy road ahead.")
		
		self.load()
		self.running = False

	def run(self):
		"""Begins running the shell interface.

		Note that this will take over an application until run terminates.
		"""

		self.running = True

		while(self.running):
			indata = self.get_command()
			try:
				self.process_command(indata)
			except NotImplementedError:
				print("Error: Command not yet implemented")
			except KeyError as e:
				print("Error: {}".format(e))

	def load(self):
		"""Load up the commands for the shell interface."""

		# TODO: Come up with a better way to do this than hardcoded commands
		self.command_list["help"] = "Display this help message"
		self.command_list["quit"] = "Exit the shell"
		self.command_list["load"] = "Load an Adventure Core game into the shell"
		self.alias_list["q"] = "quit"
		self.alias_list["exit"] = "quit"
		self.currgame = None

	def get_command(self):
		"""Display a shell prompt and get the command from it"""

		command = input(self.prompt)
		if self.case_insensitive:
			command = command.lower()

		return command

	def process_command(self, linein):
		"""Process a command on the active shell
		
		Arguments:
		linein - The command to be processed
		"""

		# For now, it's a hard coded limitation that a command must be
		# distinguished by its first word alone, and all following data
		# is to be treated as an argument to the command
		command = linein.split()[0]
		args = linein.split()[1:]
		if(command in self.alias_list):
			command = self.alias_list[command]

		if(command in self.command_list):
			# Process the command, currently manual
			if(command == "help"):
				if args == []:
					self.print_help()
				else:
					self.print_help(args[0])
			elif(command == "quit"):
				self.running = False
			elif(command == "load"):
				self.currgame = Game(name="My Game")
				print("Loaded", self.currgame.name)
				print(self.currgame.display_room())
			else:
				raise NotImplementedError()
		else:
			raise KeyError("No such command")

	def print_help(self, command="shell"):
		"""Access the help system and print the requested help to the shell.

		Arguments:
		command - (default: shell) The command to get help on. If command is
			'shell', prints help on all shell commands.
		"""
		if command == "shell":
			print()
			print(self.shellname)
			print("Shell commands:")
			for command in self.command_list:
				print(command, ": ", self.command_list[command], sep="")
			print()
		elif command in self.command_list:
			print(command, ": ", self.command_list[command], sep="")
		else:
			print("No help for that command")
示例#20
0
 def Init(self):
     state = State()
     world = World(objects, verbs, locations)
     prompts = ('WHAT DO YOU THINK WE SHOULD DO? ', 'ENTER YOUR NAME PARTNER? ', 'TELL ME,IN ONE WORD,AT WHAT? ')
     outputFile = None
     Game.Init(self, world, state, prompts, outputFile=outputFile)
示例#21
0
 def __init__(self):
     Game.__init__(self)
     self.quests = (('watch', 'tv'), ('exercise', 'bike'), ('eat', 'apple'), ('sleep', 'bed'))
     self.questNames = ('You are bored.', 'You are getting fat.', 'You are hungry.','You are sleepy.')
示例#22
0
    def Run(self, commands):
#        self.world.print()
        Game.Run(self, commands)
class ColossalCaveAdventureSkill(MycroftSkill):
    save_file = expanduser("~/cave_adventure.save")
    playing = False
    container = None

    def initialize(self):
        self.game = Game()
        load_advent_dat(self.game)
        self.last_interaction = time.time()
        self._init_padatious()
        self.disable_intent("save.intent")

    def _init_padatious(self):
        # i want to check in converse method if some intent by this skill will trigger
        # however there is no mechanism to query the intent parser
        # PR incoming
        intent_cache = expanduser(
            self.config_core['padatious']['intent_cache'])
        self.container = IntentContainer(intent_cache)
        for intent in ["restore.intent", "play.intent", "credits.intent"]:
            name = str(self.skill_id) + ':' + intent
            filename = self.find_resource(intent, 'vocab')
            if filename is not None:
                with open(filename, "r") as f:
                    self.container.add_intent(name, f.readlines())
        self.container.train()

    def will_trigger(self, utterance):
        # check if self will trigger for given utterance
        # adapt match
        if self.voc_match(utterance, "save"):
            return True
        # padatious match
        intent = self.container.calc_intent(utterance)
        if intent.conf < 0.5:
            return False
        return True

    def get_intro_message(self):
        """ Get a message to speak on first load of the skill.

        Useful for post-install setup instructions.

        Returns:
            str: message that will be spoken to the user
        """
        self.speak_dialog("thank.you")
        return None

    def speak_output(self, line):
        # dont speak parts of the intro
        # replace type with say because its voice game
        # re join words split across lines
        # reformat \n and separate by sentence
        line = line.lower().replace("type", "say").replace("-\n", "")
        line = line.replace(
            '  i should warn\nyou that i look at only the first five letters of each word, so you\'ll\nhave to enter "northeast" as "ne" to distinguish it from "north".',
            "")
        line = line.replace(
            "- - this program was originally developed by willie crowther.  most of the\nfeatures of the current program were added by don woods (don @ su-ai).\ncontact don if you have any questions, comments, etc.",
            "")
        line = line.replace("\n", " ").replace("(",
                                               "").replace(")", "").replace(
                                                   "etc.", "etc")
        lines = line.split(".")
        for line in lines:
            self.speak(line.strip(), expect_response=True, wait=True)
        self.last_interaction = time.time()
        self.maybe_end_game()

    @intent_file_handler("credits.intent")
    def handle_credits(self, message=None):
        self.speak_dialog("credits")

    @intent_file_handler("play.intent")
    def handle_play(self, message=None):
        self.playing = True
        self.enable_intent("save.intent")
        self.game.start()
        self.speak_output(self.game.output)

    @intent_handler(
        IntentBuilder("Save").require("save").optionally("cave").optionally(
            "adventure"))
    def handle_save(self, message=None):
        if not self.playing:
            self.speak_dialog("save.not.found")
        else:
            with open(self.save_file, "wb") as f:
                self.game.t_suspend("save", f)
                self.speak_dialog("game.saved")

    @intent_file_handler("restore.intent")
    def handle_restore(self, message):
        if exists(self.save_file):
            self.playing = True
            self.game = Game.resume(self.save_file)
            self.speak_dialog("restore.game")
        else:
            self.speak_dialog("save.not.found")
            new_game = self.ask_yesno("new.game")
            if new_game:
                self.handle_play()

    def maybe_end_game(self):
        # end game if no interaction for 10 mins
        if self.playing:
            timed_out = time.time() - self.last_interaction > 10 * 3600
            # disable save and gameplay
            if self.game.is_finished or timed_out:
                self.disable_intent("Save")
                self.playing = False
                self.game = Game()
                load_advent_dat(self.game)
            # save game to allow restoring if timedout
            if timed_out:
                self.handle_save()

    def converse(self, utterances, lang="en-us"):
        """ Handle conversation.

        This method gets a peek at utterances before the normal intent
        handling process after a skill has been invoked once.

        To use, override the converse() method and return True to
        indicate that the utterance has been handled.

        Args:
            utterances (list): The utterances from the user
            lang:       language the utterance is in

        Returns:
            bool: True if an utterance was handled, otherwise False
        """
        # check if game was abandoned midconversation and we should clean it up
        self.maybe_end_game()
        if self.playing:
            ut = utterances[0]
            # if self will trigger do nothing and let intents handle it
            if self.will_trigger(ut):
                # save / restore will trigger
                return False
            # capture speech and pipe to the game
            words = ut.split(" ")
            if words:
                self.speak_output(self.game.do_command(words))
                return True
        return False
 def initialize(self):
     self.game = Game()
     load_advent_dat(self.game)
     self.last_interaction = time.time()
     self._init_padatious()
     self.disable_intent("save.intent")
示例#25
0
 def setUp(self):
     game = Game()
     load_advent_dat(game)
     self.words = set(w.synonyms[0].text for w in game.vocabulary.values())
     self.words.remove('suspend')
示例#26
0
 def help_prompt() -> str:
     game = Game()
     adventure.load_advent_dat(game)
     return str(game.messages[51])