A-level Computing/AQA/Paper 1/Skeleton program/2019

From Wikibooks, open books for an open world
Jump to navigation Jump to search

This is for the AQA A-level Computer Science Specification.

This is where suggestions can be made about what some of the questions might be and how we can solve them.

Please be respectful and do not vandalise or tamper with the page, as this would affect students' preparation for their exams!

If just 'help' is typed, a list of existing commands appear[edit]

Create 'help <instruction>' which lists details about individual instruction,

If just 'help' is typed, a list of existing commands appear.

C#:

private static void PlayGame(List<Character> characters, List<Item> items, List<Place> places)
        {
            List<string> help = new List<string>();
            help.Add("get");
            help.Add("use");
            help.Add("go");
            help.Add("read");
            help.Add("examine");
            help.Add("open");
            help.Add("close");
            help.Add("move");
            help.Add("say");
            help.Add("playdice");
            string helplist = string.Join(", ", help.ToArray());
            bool stopGame = false;
            string instruction, Command;
            bool moved = true;
            int resultOfOpenClose;
            while (!stopGame)
            {
                if (moved)
                {
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine(places[characters[0].CurrentLocation - 1].Description);
                    DisplayGettableItemsInLocation(items, characters[0].CurrentLocation);
                    moved = false;
                }
                instruction = GetInstruction();
                Command = ExtractCommand(ref instruction);
                switch (Command)
                {
                    case "help":
                        Console.WriteLine(helplist);
                        break;

Delphi/Pascal:

Java:

//By Harington Student
private String[] commandList =
	{ "COMMAND(S)					EFFECT(S)",   //Complete with custom commands. The odd spacings keep everything formatted in a readable way, may be different for different systems
			"go:  	  					direction, up or down", 
			"get; take:  	  				any gettable item", 
			"use:    					usable item",
			"examine:  	  				item, object, inventory or room", 
			"inventory:	    				displays inventory",
			"search:	    					displays room", 
			"say:    					string",
			"quit; exit:   	 				leaves the game",
			"read:    					any readable item or object", 
			"move:    					any movable object in the room",
			"open:    					door, trapdoor, chest etc.",
			"close:    					door, trapdoor, chest, etc.",
			"playdice; play dice; play dice with:		entity. You cannot choose which dice you use if you have more than one",
			"help:    					displays this list" }; 
//Within the playGame() function add in a new switch case:
			case "help":
				for (int i = 0; i < commandList.length; i++)
					Console.println(commandList[i]);
				break;

Python:

#add into playgame function

    elif Command == "help":
      cmds = ["get","use","go","read","examine","open","close","move","say","playdice"]
      print("Commands:")
      for i in cmds:
        print(i,end="\n")

VB.NET:

Add into Playgame subroutine:

                Case "help"
                    Help(Instruction)

Add new subroutine:

   Sub Help(ByVal Instruction As String)
        'Created by student from Folkestone School for Girls
        Select Case Instruction
            Case "help"
                Console.WriteLine("The Commands are: Go, Get, Use, Examine, Say, Quit, Read, Move, Open, Close, PlayDice")
            Case "go"
                Console.WriteLine("Moves the player from one location to another. The go command needs to be followed by one of the six valid directions: north, south, east, west, up, down.")
            Case "get"
                Console.WriteLine("Allows the player to pick up an object that is in the same location as they are. The get command needs to be followed by the name of the object that the player wants to get. If the object can be got then it is added to the player’s inventory and is no longer in its original location.")
            Case "use"
                Console.WriteLine("Allows the player to use an object that is in their location or their inventory. The use command needs to be followed by the name of the object that the player wants to use. The effect of using an object depends on which object is being used, e.g. using a key in a room with a locked door will unlock the door (if it is the right key for that door).")
            Case "examine"
                Console.WriteLine("Provides the player with a more detailed description of an object or character in the same location as they are or an object in their inventory. The examine command needs to be followed by the name of the object or character that the player wants to examine. Examine inventory will display a list of the items the player is currently carrying.")
            Case "say"
                Console.WriteLine("The player will speak, saying the text that follows the say command.")
            Case "quit"
                Console.WriteLine("Ends the game, quitting the program.")
            Case "read"
                Console.WriteLine("Will display the text of objects that can be read e.g. books, notes, signs.")
            Case "move"
                Console.WriteLine("Allows the player to move an object that is in the same location as they are. The move command needs to be followed by the name of the object that the player wants to move. If the object can be moved then the result of moving the object will be displayed on the screen.")
            Case "open"
                Console.WriteLine("Allows the player to open an openable item that is in the same location as they are. The open command needs to be followed by the name of the item to open. This command is often used to open a door that is in-between two locations.")
            Case "close"
                Console.WriteLine("Allows the player to close a closable item that is in the same location as they are. The close command needs to be followed by the name of the item to close.")
            Case "playdice"
                Console.WriteLine("The player will play a dice game with another character. If the player wins then a list of the items that the losing character is carrying is displayed and the user chooses an item to take; if the player loses, the other character takes a random item from the player’s inventory. The playdice command needs to be followed by the name of a character to play the dice game with. The character and the player need to be in the same location and both need to have a die.")

            Case Else
                Console.WriteLine("Command Unknown.")
        End Select

    End Sub

Create 'teleport <location>' command[edit]

Create 'teleport <location>' command. Useful for testing game..

C#:

//Add to PlayGame()
case "teleport":
                        moved = Teleport(ref characters, int.Parse(instruction));
                        break;

//Add Function Teleport()
static bool Teleport(ref List<Character> You, int NewPlace)
        {
            bool Moved = true;
            if (NewPlace >= 0 && NewPlace <= 8)
            {
                You[0].CurrentLocation = NewPlace;
            }
            else
            {
                Console.WriteLine("Cannot Teleport Here");
                Moved = false;
            }
            return Moved;
        }

Delphi/Pascal:

Java:

//Add to playGame()
                case "teleport":
                	teleport(instruction, characters);
                	break;

//New function

    private void teleport(String instruction, ArrayList<Character> characters) {
    	try{
    		characters.get(0).currentLocation = Integer.parseInt(instruction);
    	}catch(Exception e){
    		System.out.println("Location ID " + instruction + " does not exist.");
    	}
		
	}

Python:


def Teleport(You,Location):
  You.CurrentLocation = int(Location)
  return You, True


#Add into playgame function
elif Command == "teleport":
  Characters[0], Moved = Teleport(Characters[0],Instruction)

Python method 2:

#created by Abisade 

#in play game function

elif Command == "teleport":
      Teleport(Characters, Items, Places)

#in teleport function

def Teleport(Characters, Items, Places):
  cont=False
  while cont == False:
    userinput=input("where do you want to go?\n(type a number or C to cancel teleportation)\n1:blue walls room\n2:store cupboard\n3:bare bed room\n4:empty corridor\n5:guardroom\n6:flag jail cell\n7:skeleton jail cell\n8:cellar\n>")
    try:
      userval=int(userinput)
      if Characters[0].CurrentLocation == userval:
        print("you are already there")
      else:
        if userval<0 or userval>8:
          print("invalid interval")
        else:
          Characters[0].CurrentLocation = userval
          cont=True
    except:
      if userinput.upper()=="C":
        cont=True
      else:
        print("invalid character")
  print(Places[Characters[0].CurrentLocation - 1].Description)
  DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation)
  print([Characters[0].CurrentLocation])

VB.NET:

Add the following to Playgame case statement:
         Case "teleport"
             Moved = Teleport(Characters(0), Instruction)




Add new function:

    Function Teleport(ByRef You As Character, ByVal NewPlace As Integer) As Boolean
        'Created by teacher from Folkestone School for Girls
        Dim Moved As Boolean = True

        If NewPlace >= 0 And NewPlace <= 8 Then
            You.CurrentLocation = NewPlace
        Else
            Console.WriteLine("You are unable to teleport to this location")
            Moved = False
        End If

        Return Moved
    End Function

Create 'save <filename>' command[edit]

Create 'save <filename>' command. Saves the current status of game.

C#:

// add to PlayGame
case "Save":
	Save(Characters, Items, Places);
	break;
	
// add function Save()
Private static Void Save( list<Characters> characters, list<items> items, list<places> places)
{
	string filename 
	
	//this will make the save name and make sure it has no spaces
	bool file_name_valid = false;
	while file_name_valid = false
	{
		int no_spaces = 0;
		Console.WriteLine("Please enter Your file name...");
		filename = Console.ReadLine();
		//this checks for spaces
		foreach (char a in filename)
		{
			if ( a == " ")
				no_spaces ++;
		}
		
		//this will let the user save the file if the file name has no spaces
		if (no_spaces == 0)
			file_name_valid = true;
		else
			Console.WriteLine("You can't have any spaces in your file name");
	}
	
	try
	{
		//this writes and saves a new binary file
		BinaryWriter writer = new BinaryWriter(File.Open(filename, FileMode.Create));
		
		//this saves the number of characters and saves all of their attributes
		writer.wrie(characters.Count);
		foreach(character in characters)
		{
			writer.write(character.ID);
			writer.write(character.Name);
			writer.write(character.);
			writer.write(character.ID);
		}
		
		//this saves the number of items and saves all of their attributes
		Writer.Write(items.Count);
        foreach (Item in items)
		{
			Writer.Write(Item.ID);
			Writer.Write(Item.Description);
			Writer.Write(Item.Status);
			Writer.Write(Item.Location);
			Writer.Write(Item.Name);
			Writer.Write(Item.Commands);
			Writer.Write(Item.Results);
		}
		
		//this saves the number of places and saves all of their attributes
		writer.write(places.Count);
		foreach (Place in Places)
		{
			Writer.Write(Place.ID);
			Writer.Write(Place.Description);
			Writer.Write(Place.North);
			Writer.Write(Place.East);
			Writer.Write(Place.South);
			Writer.Write(Place.West);
			Writer.Write(Place.Up);
			Writer.Write(Place.Down);
		}
		
		//this will tell the user that their file has been saved
		Console.WriteLine("saved " + filename);
	}
	catch
	{	
	//this will tell the user that the file couldn't be saved
		Console.WriteLine("unable to save " + filename);
	}
}

Delphi/Pascal:

Java:

//add to playgame
case "save":
	String filename = instruction+".gme";
	say("saving to "+instruction+".gme");
	say("Saving game...");
	saveGame(filename, characters,items,places);
	break;

//create as new method
boolean saveGame(String filename, ArrayList<Character> characters, ArrayList<Item> items, ArrayList<Place> places)
	{
		int noOfCharacters = characters.size(),
			noOfPlaces = places.size(),
			count,
			noOfItems = items.size();
		Character tempCharacter;
		Place tempPlace;
		Item tempItem;
		try
		{
			FileOutputStream binaryWriter = new FileOutputStream(filename);
			DataOutputStream writer = new DataOutputStream(binaryWriter);
			writer.writeInt(noOfCharacters);
			for (count = 0; count < noOfCharacters; count++)
			{
				writer.writeInt(characters.get(count).id);
				writer.writeUTF(characters.get(count).name);
				writer.writeUTF(characters.get(count).description);
				writer.writeInt(characters.get(count).currentLocation);
			}
			writer.writeInt(noOfPlaces);
			for (count = 0; count < noOfPlaces; count++)
			{
				writer.writeInt(places.get(count).id);
				writer.writeUTF(places.get(count).description);
				writer.writeInt(places.get(count).north);
				writer.writeInt(places.get(count).east);
				writer.writeInt(places.get(count).south);
				writer.writeInt(places.get(count).west);
				writer.writeInt(places.get(count).up);
				writer.writeInt(places.get(count).down);
			}
			writer.writeInt(noOfItems);
			for (count = 0; count < noOfItems; count++)
			{
				writer.writeInt(items.get(count).id);
				writer.writeUTF(items.get(count).description);
				writer.writeUTF(items.get(count).status);
				writer.writeInt(items.get(count).location);
				writer.writeUTF(items.get(count).name);
				writer.writeUTF(items.get(count).commands);
				writer.writeUTF(items.get(count).results);
			}
			Console.write("Saved!");
			return true;
		}
		catch (Exception e)
		{
			Console.write("Error Saving File");
			return false;
		}
	}

Python:

def Save(Characters,Items,Places):
  print("What would you like to save the file as?")
  filename = input("> ")
  f = open(filename+".gme","wb")
  pickle.dump(len(Characters),f)
  for Count in range(len(Characters)):
    pickle.dump(Characters[Count].ID,f)
    pickle.dump(Characters[Count].Name,f)
    pickle.dump(Characters[Count].Description,f)
    pickle.dump(Characters[Count].CurrentLocation,f)
  pickle.dump(len(Places),f)
  for Count in range(len(Places)):
    pickle.dump(Places[Count].ID,f)
    pickle.dump(Places[Count].Description,f)
    pickle.dump(Places[Count].North,f)
    pickle.dump(Places[Count].East,f)
    pickle.dump(Places[Count].South,f)
    pickle.dump(Places[Count].West,f)
    pickle.dump(Places[Count].Up,f)
    pickle.dump(Places[Count].Down,f)
  pickle.dump(len(Items),f)
  for Count in range(len(Items)):
    pickle.dump(Items[Count].ID,f)
    pickle.dump(Items[Count].Description,f)
    pickle.dump(Items[Count].Status,f)
    pickle.dump(Items[Count].Location,f)
    pickle.dump(Items[Count].Name,f)
    pickle.dump(Items[Count].Commands,f)
    pickle.dump(Items[Count].Results,f)
  f.close()


#Add into playgame function
    elif Command == "save":
      Save(Characters,Items,Places)

VB.NET:

Add the following to Playgame case statement:

     Case "save"
         Save(Instruction, Characters, Items, Places)


Add new subroutine (error trapping code omitted for simplicity):

    Sub Save(ByVal Filename As String, ByVal Characters As ArrayList, ByVal Items As ArrayList, ByVal Places As ArrayList)
        'Created by teacher from Folkestone School for Girls

        Try
            Using Writer As BinaryWriter = New BinaryWriter(File.Open(Filename, FileMode.Create))

                Writer.Write(Characters.Count)
                For Each Character In Characters
                    Writer.Write(Character.ID)
                    Writer.Write(Character.Name)
                    Writer.Write(Character.Description)
                    Writer.Write(Character.CurrentLocation)
                Next

                Writer.Write(Places.Count)
                For Each Place In Places
                    Writer.Write(Place.ID)
                    Writer.Write(Place.Description)
                    Writer.Write(Place.North)
                    Writer.Write(Place.East)
                    Writer.Write(Place.South)
                    Writer.Write(Place.West)
                    Writer.Write(Place.Up)
                    Writer.Write(Place.Down)
                Next

                Writer.Write(Items.Count)
                For Each Item In Items

                    Writer.Write(Item.ID)
                    Writer.Write(Item.Description)
                    Writer.Write(Item.Status)
                    Writer.Write(Item.Location)
                    Writer.Write(Item.Name)
                    Writer.Write(Item.Commands)
                    Writer.Write(Item.Results)

                Next
            End Using
            Console.WriteLine("Save Successful")

        Catch
            Console.WriteLine("Unable to Save")
        End Try

    End Sub

Add instruction to add a new character to game[edit]

Add instruction to add a new character to game. eg 'addcharacter <name>'

C#:

Add the following to Playgame case statement:

        case "addcharacter":
            AddCharacter(ref characters, ref places);
            break;

Then add the new procedure:

        static void AddCharacter(ref List <Character>characters, ref List <Place>places)
        {
            Character TempCharacter = new Character();

            Console.WriteLine("Please enter the details the character called " + characters);
            Console.Write("ID (eg 1003):");
            TempCharacter.ID = Convert.ToInt32(Console.ReadLine());
            Console.Write("Name:");
            TempCharacter.Name = Console.ReadLine();
            Console.Write("Description:");
            TempCharacter.Description = Console.ReadLine();
            Console.Write("Initial Location (eg 1-8):");
            TempCharacter.CurrentLocation = Convert.ToInt32(Console.ReadLine());
            Console.Write("Room Description (how it describes your character found in room):");
            string RoomDescription = Console.ReadLine();

            // Adds the characters details to arraylist
            characters.Add(TempCharacter);

            Place TempPlace = new Place();
            int counter = 0;
            // You need to add a description to the room that the character is in or you will not know about it.
            // You need to locate where the room details are stored in the array so that you update the room description.
            foreach (Place place in places)
            {
                if (place.id == TempCharacter.CurrentLocation)
                    break;
                counter++;
             }

            TempPlace.id = places[counter].id;
            TempPlace.Description = places[counter].Description + " " + RoomDescription;
            TempPlace.North = places[counter].North;
            TempPlace.East = places[counter].East;
            TempPlace.South = places[counter].South;
            TempPlace.West = places[counter].West;
            TempPlace.Up = places[counter].Up;
            TempPlace.Down = places[counter].Down;


            places[counter] = TempPlace;
        }

Delphi/Pascal:

Java:

Python:

def AddCharacter():
  TempCharacter = Character()
  TempCharacter.Name = input("Input the name of the character: ")
  TempCharacter.Description = input("Input the description of the character: ")
  TempCharacter.ID = int(input("Input the ID of the character: "))
  TempCharacter.CurrentLocation = int(input("Input the current location of the character: "))
  return TempCharacter

#Add to playgame function
    elif Command == "addcharacter":
      Characters.append(AddCharacter())

VB.NET:

Add the following to Playgame case statement:
     Case "addcharacter"
        AddCharacter(Instruction, Characters, Places)

Add new subroutine:

    Sub AddCharacter(ByVal Character As String, ByVal Characters As ArrayList, ByVal Places As ArrayList)
        ' Created by teacher from Folkestone School for Girls
        ' Error trapping omitted to keep the code simple/short

        Dim TempCharacter As Character
        Dim TempPlace As Place
        Dim Counter As Integer = 0
        Dim RoomDescription As String

        ' Get details for new character including a description of character when room is described
        Console.WriteLine("Please enter the details the character called " & Character)
        Console.Write("ID (eg 1003):")
        TempCharacter.ID = Console.ReadLine()
        Console.Write("Name:")
        TempCharacter.Name = Console.ReadLine()
        Console.Write("Description:")
        TempCharacter.Description = Console.ReadLine()
        Console.Write("Initial Location (eg 1-8):")
        TempCharacter.CurrentLocation = Console.ReadLine()
        Console.Write("Room Description (how it describes your character found in room):")
        RoomDescription = Console.ReadLine()

        ' Adds the characters details to arraylist
        Characters.Add(TempCharacter)


        ' You need to add a description to the room that the character is in or you will not know about it.
        ' You need to locate where the room details are stored in the array so that you update the room description.
        For Each Place In Places
            If Place.ID = TempCharacter.CurrentLocation Then
                Exit For
            End If
            Counter += 1
        Next

        TempPlace.ID = Places(Counter).ID
        TempPlace.Description = Places(Counter).Description + " " + RoomDescription
        TempPlace.North = Places(Counter).North
        TempPlace.East = Places(Counter).East
        TempPlace.South = Places(Counter).South
        TempPlace.West = Places(Counter).West
        TempPlace.Up = Places(Counter).Up
        TempPlace.Down = Places(Counter).Down


        Places(Counter) = TempPlace

    End Sub

Add 'examine room' option to view details of room again[edit]

Add 'examine room' option to view details of room again. Fairly simple but a useful option when developing 'addcharacter' or 'additem'.

C#:

private static void Examine(List<Item> items, List<Character> characters, string itemToExamine, int currentLocation, List<Place> places)
       {
           int Count = 0;
           if (itemToExamine == "inventory")
           {
               DisplayInventory(items);
           }
           if (itemToExamine == "room")
           {
               Console.Write(places[characters[0].CurrentLocation - 1].Description);
               DisplayGettableItemsInLocation(items, characters[0].CurrentLocation);
           }

Delphi/Pascal:

Java:

void examine(ArrayList<Item> items, ArrayList<Character> characters, String itemToExamine, int currentLocation, ArrayList<Place> places) {
        int count = 0;
        if (itemToExamine.equals("inventory")) {
            displayInventory(items);
        } else if (itemToExamine.equals("room")){
            Console.writeLine(places.get(characters.get(0).currentLocation - 1).description);
            displayGettableItemsInLocation(items, characters.get(0).currentLocation);
        } else {
            int indexOfItem = getIndexOfItem(itemToExamine, -1, items);
            if (indexOfItem != -1) {
                if (items.get(indexOfItem).name.equals(itemToExamine) && (items.get(indexOfItem).location == INVENTORY || items.get(indexOfItem).location == currentLocation)) {
                    Console.writeLine(items.get(indexOfItem).description);
                    if (items.get(indexOfItem).name.contains("door")) {
                        displayDoorStatus(items.get(indexOfItem).status);
                    }
                    if(items.get(indexOfItem).status.contains("container")) {
                        displayContentsOfContainerItem(items, items.get(indexOfItem).id);
                    }
                    return;
                }
            }
            while (count < characters.size()) {
                if (characters.get(count).name.equals(itemToExamine) && characters.get(count).currentLocation == currentLocation) {
                    Console.writeLine(characters.get(count).description);
                    return;
                }
                count++;
            }
            Console.writeLine("You cannot find " + itemToExamine + " to look at.");
        }
    }

 

void playGame(ArrayList<Character> characters, ArrayList<Item> items, ArrayList<Place> places) {
        boolean stopGame = false, moved = true;
        String instruction, command;
        int resultOfOpenClose;
        while (!stopGame) {
            if (moved) {
                Console.writeLine();
                Console.writeLine();
                Console.writeLine(places.get(characters.get(0).currentLocation - 1).description);
                displayGettableItemsInLocation(items, characters.get(0).currentLocation);
                moved = false;
            }
            instruction = getInstruction();
            String[] returnStrings = extractCommand(instruction);
            command = returnStrings[0];
            instruction = returnStrings[1];
            switch (command)
            {
                case "get":
                    stopGame = getItem(items, instruction, characters.get(0).currentLocation);
                    break;
                case "use":
                    useItem(items, instruction, characters.get(0).currentLocation, places);
                    break;
                case "go":
                    moved = go(characters.get(0), instruction, places.get(characters.get(0).currentLocation - 1));
                    break;
                case "read":
                    readItem(items, instruction, characters.get(0).currentLocation);
                    break;
                case "examine":
                    examine(items, characters, instruction, characters.get(0).currentLocation, places);
                    break;
                case "open":
                    resultOfOpenClose = openClose(true, items, places, instruction, characters.get(0).currentLocation);
                    displayOpenCloseMessage(resultOfOpenClose, true);
                    break;
                case "close":
                    resultOfOpenClose = openClose(false, items, places, instruction, characters.get(0).currentLocation);
                    displayOpenCloseMessage(resultOfOpenClose, false);
                    break;
                case "move":
                    moveItem(items, instruction, characters.get(0).currentLocation);
                    break;
                case "say":
                    say(instruction);
                    break;
                case "playdice":
                    playDiceGame(characters, items, instruction);
                    break;
                case "quit":
                    say("You decide to give up, try again another time.");
                    stopGame = true;
                    break;
                default:
                    Console.writeLine("Sorry, you don't know how to " + command + ".");
            }
        }
        Console.readLine();
    }

Python:

Answer 1 - Alter Examine function to take in Places as well.

def Examine(Items, Characters, ItemToExamine, CurrentLocation, Places):
  Count = 0
  if ItemToExamine == "inventory":
    DisplayInventory(Items)
  elif ItemToExamine == "room":
    print(Places[Characters[0].CurrentLocation - 1].Description)
    DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation)
  else:
    IndexOfItem = GetIndexOfItem...

Answer 2 - alter the selection statement in PlayGame

elif Command == "examine":
      if Instruction == "room":
        Moved = True
      else: 
        Examine(Items, Characters, Instruction, Characters[0].CurrentLocation, Places)

VB.NET:

Adjust case statement within Playgame subroutine:

                Case "examine"
                    If Instruction = "room" Then
                        Moved = True
                    Else
                        Examine(Items, Characters, Instruction, Characters(0).CurrentLocation)
                    End If

Create new items for the game via an 'additem <name>'[edit]

Create new items for the game via an 'additem <name>' command. Useful once you have created 'save <filename>' option.

C#:

Delphi/Pascal:

Java:

Python:

#MS Maqsud HGS

def addItem(Items):
      print(Items)
      TempItem = Item()
      TempItem.ID = input("ID: ")
      TempItem.Description = input("Description: ")
      TempItem.Status = input("Status: ")
      TempItem.Location = input("Location: ")
      TempItem.Name = input("Name: ")
      TempItem.Commands = input("Commands: ")
      TempItem.Results = input("Results: ")
      Items.append(TempItem)
      print(Items)

def PlayGame(Characters, Items, Places):
  StopGame = False
  Moved = True
  while not StopGame:
    if Moved:
      print()
      print()
      print(Places[Characters[0].CurrentLocation - 1].Description)
      DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation)
      Moved = False
    Instruction = GetInstruction()
    Command, Instruction = ExtractCommand(Instruction)
    if Command == "get":
      StopGame, Items = GetItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "use":
      StopGame, Items = UseItem(Items, Instruction, Characters[0].CurrentLocation, Places)
    elif Command == "go":
      Characters[0], Moved = Go(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1])
    elif Command == "read":
      ReadItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "examine":
      Examine(Items, Characters, Instruction, Characters[0].CurrentLocation)
    elif Command == "open":
      ResultOfOpenClose, Items, Places = OpenClose(True, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, True)
    elif Command == "close":
      ResultOfOpenClose, Items, Places = OpenClose(False, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, False)
    elif Command == "move":
      MoveItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "say":
      Say(Instruction)
    elif Command == "playdice":
      Items = PlayDiceGame(Characters, Items, Instruction)
    elif Command == "add":
      addItem(Items)
    elif Command == "quit":
      Say("You decide to give up, try again another time.")
      StopGame = True
    else:
      print("Sorry, you don't know how to " + Command + ".")
  input()

VB.NET:

the command is used as such
additem <Name> <Description> <ID> <location> <status> <commands> <result>
Sub AddItem(ByRef items As ArrayList, ByVal command As String)
        'NOTE I find it very unlikely such a complex question would be asked BUT while identifying statuses, there are a few unused ones which may come of use?
        'Syntax for ITEMS 
        'Commands – comma separates commands, results will correspond To positions 
        'Example “move,get”
        'Description – a String that will be said When the item Is examined
        'ID – a unique ID For the item
        'Status – currently questionable use, contains properties referring To the item itself, need To test whether this affects anything, most likely doors And useable items.
        'Location – the ID Of the location the item Is currently In
        'Name – the name Of the item
        'Results – correspond With reactions To given commands formatted With semicolons separating the commands And commas representing the response command And parameters.
        'e.g. say,This is too heavy;say,you cant pick this up

        'Statuses:
        'Gettable – the item can be picked up
        'Useable – the item can be used
        'Large – the item Is too large To pick up 
        'Edible,Weapon - ???
        'Open/ close – whether the item Is open Or closed
        'Locked/ Unlocked – whether the item Is locked Or unlocked
        'more exist that need to be researched


        'also a useful location is your inventory which is ID 1001, though I wouldn't put imoveable objects in there
        Dim newItem As New Item
        Dim count, cursor As Integer
        Dim parameter As String = ""
        Dim ParameterStart As Integer
        count = 0
        cursor = 7
        While count = 0 'name
            If command(cursor) = "_" Then
                parameter &= " "
                cursor += 1
            ElseIf command(cursor) <> " " Then
                parameter &= command(cursor)
                cursor += 1
            ElseIf cursor = 7 Then
                Console.WriteLine("Incorrect syntax at <name>")
                Exit Sub
            Else

                newItem.Name = parameter
                cursor += 1
                count += 1
            End If

        End While
        parameter = ""
        ParameterStart = cursor
        While count = 1 And command(cursor) <> "-" ' Description
            If command(cursor) = "_" Then
                parameter &= " "
                cursor += 1
            ElseIf command(cursor) <> " " Then
                parameter &= command(cursor)
                cursor += 1
            ElseIf cursor = ParameterStart Then
                Console.WriteLine("Incorrect syntax at <description>")
                Exit Sub
            Else
                newItem.Description = parameter
                cursor += 1
                count += 1
            End If
        End While
        parameter = ""
        ParameterStart = cursor
        While count = 2 And command(cursor) <> "-" 'ID

            If command(cursor) <> " " Then
                parameter &= command(cursor)
                cursor += 1
            ElseIf cursor = ParameterStart Then
                Console.WriteLine("Incorrect syntax at <ID>")
                Exit Sub
            Else
                newItem.ID = CInt(parameter)
                cursor += 1
                count += 1
            End If
        End While
        parameter = ""
        ParameterStart = cursor
        While count = 3 And command(cursor) <> "-" 'Location

            If command(cursor) <> " " Then
                parameter &= command(cursor)
                cursor += 1
            ElseIf cursor = ParameterStart Then
                Console.WriteLine("Incorrect syntax at <Location>")
                Exit Sub
            Else
                newItem.Location = CInt(parameter)
                cursor += 1
                count += 1
            End If
        End While
        parameter = ""
        ParameterStart = cursor
        While count = 4 And command(cursor) <> "-" 'Status
            If command(cursor) = "_" Then
                parameter &= " "
                cursor += 1
            ElseIf command(cursor) <> " " Then
                parameter &= command(cursor)
                cursor += 1
            ElseIf cursor = ParameterStart Then
                Console.WriteLine("Incorrect syntax at <Status>")
                Exit Sub
            Else
                newItem.Status = parameter
                cursor += 1
                count += 1
            End If
        End While
        parameter = ""
        ParameterStart = cursor
        While count = 5 And command(cursor) <> "-" 'Command
            If command(cursor) = "_" Then
                parameter &= " "
                cursor += 1
            ElseIf command(cursor) <> " " Then
                parameter &= command(cursor)
                cursor += 1
            ElseIf cursor = ParameterStart Then
                Console.WriteLine("Incorrect syntax at <Command>")
                Exit Sub
            Else
                newItem.Commands = parameter
                cursor += 1
                count += 1
            End If
        End While
        parameter = ""
        ParameterStart = cursor
        While count = 5 And command(cursor) <> "-" 'Result
            If command(cursor) = "_" Then
                parameter &= " "
                cursor += 1
            ElseIf command(cursor) <> " " Then
                parameter &= command(cursor)
                cursor += 1
            ElseIf cursor = ParameterStart Then
                Console.WriteLine("Incorrect syntax at <Result>")
                Exit Sub
            Else
                newItem.Results = parameter
                cursor += 1
                count += 1
            End If
        End While
        If GetIndexOfItem(newItem.Name, newItem.ID, items) = -1 And ((newItem.Commands = "" And newItem.Results = "") Or (newItem.Commands <> "" And newItem.Results <> "")) Then
            items.Add(newItem)
            Try
                Using Writer As BinaryWriter = New BinaryWriter(File.Open(Filename, FileMode.Create))
                    Writer.Write(items.Count)
                    For Each Item In items

                        Writer.Write(Item.ID)
                        Writer.Write(Item.Description)
                        Writer.Write(Item.Status)
                        Writer.Write(Item.Location)
                        Writer.Write(Item.Name)
                        Writer.Write(Item.Commands)
                        Writer.Write(Item.Results)

                    Next
                End Using
                Console.WriteLine("{0} was successfully created", newItem.Name)
            Catch ex As FileNotFoundException
                Console.WriteLine("Error save file not found")
            End Try
        Else
            Console.WriteLine("Syntax error")
        End If
        'created by student from Epsom College
    End Sub

Filename will need to be made global as such (in sub main())
 Dim Filename As String
    Sub Main()

        Dim Items, Characters, Places As New ArrayList
            Console.Write("Enter filename> ")
            Filename = Console.ReadLine & ".gme"
            Console.WriteLine()
            If LoadGame(Filename, Characters, Items, Places) Then
                PlayGame(Characters, Items, Places)
            Else
                Console.WriteLine("Unable to load game.")
                Console.ReadLine()
            End If
        End Sub
The following edit will need to be made to the select case in playgame
               Case "additem"
                    AddItem(Items, Instruction)

Create a new 'drop <item>' command.[edit]

Create 'drop <item>' command that drops the item selected from the user's Inventory

C#:

// add this function:
        private static void DropItem(List<Item> items, string itemToDrop, int currentLocation)
        {
            int position = currentLocation, indexOfItem;
            indexOfItem = GetIndexOfItem(itemToDrop, -1, items);
            if (items[indexOfItem].Location != Inventory)
            {
                Console.WriteLine("You can't find " + itemToDrop + " to drop.");
            }
            else if (items[indexOfItem].Location == Inventory)
            {
                position = GetPositionOfCommand(items[indexOfItem].Commands, "drop");
                ChangeLocationOfItem(items, indexOfItem, currentLocation);

                Console.WriteLine("The item has been dropped");
            }
        }
// also add this to the switch at line number 859:
                    case "drop":
                        DropItem(items, instruction, characters[0].CurrentLocation);
                        break;

Delphi/Pascal:

Java:

//Created by Harington School Student
//add to playGame method
case "drop":
	drop(instruction,items,characters.get(0).currentLocation);
	break;

//create as new method
void drop (String itemToDrop, ArrayList<Item> items, int currentLocation)
	{
		int indexOfItem = getIndexOfItem(itemToDrop, -1, items);
		if (indexOfItem == -1)
		{
			Console.writeLine("You can't find " + itemToDrop + ".");
		}
		else if (items.get(indexOfItem).location == INVENTORY)
		{
			Console.writeLine("You dropped " + itemToDrop);
			changeLocationOfItem(items, indexOfItem, currentLocation);
		}
		else if (items.get(indexOfItem).location != INVENTORY)
		{
			Console.writeLine("You cannot find that in your inventory.");
		}
	}

Python:

def Drop(Items, Characters, ItemToDrop, CurrentLocation):
  Count = 0
  IndexOfItem = GetIndexOfItem(ItemToDrop, -1, Items)
  if IndexOfItem != -1:
    if Items[IndexOfItem].Name == ItemToDrop and Items[IndexOfItem].Location == INVENTORY:
      print(Items[IndexOfItem].Name+" was dropped")
      Items[IndexOfItem].Location = CurrentLocation
      return Items
  print("You cannot find " + ItemToDrop + " to drop.")
  return Items

#Add into PlayGame Function
    elif Command == "drop":
      Items = Drop(Items,Characters,Instruction,Characters[0].CurrentLocation)
def Drop(Items, Characters, ItemToDrop, CurrentLocation):
  Count = 0
  IndexOfItem = GetIndexOfItem(ItemToDrop, -1, Items)
  if IndexOfItem != -1:
    if Items[IndexOfItem].Name == ItemToDrop and Items[IndexOfItem].Location == INVENTORY:
      print(Items[IndexOfItem].Name+" was dropped")
      Items[IndexOfItem].Location = CurrentLocation
      return Items
    else:
      print("You cannot find " + Items[IndexOfItem].Name + " to drop.")
  else:
    Say('This item does not exist, sorry try again')
  return Items
       
#Add into PlayGame Function
elif Command == "drop":
      Items = DropItem(Items, Instruction, Characters[0].CurrentLocation)
#add new function
def Drop(Items, Characters, Instruction):
  itemExist = False
  for item in Items:
    if item.Name == Instruction and item.Location == INVENTORY:
      itemExist = True
      item.Location = Characters[0].CurrentLocation
      print("You have droppped: " + item.Name)
  if itemExist == False:
    print("You can't find that item in your inventory")
#add to play game
    elif Command == "drop":
      Drop(Items, Characters, Instruction)

VB.NET:

Add into PlayGame case statement
    Case "drop"
        DropItem(Items, Instruction, Characters(0).CurrentLocation)



Add new Procedure

    Sub DropItem(ByVal Items As ArrayList, ByVal ItemToDrop As String, ByVal CurrentLocation As Integer)
        Dim CanDrop As Boolean = False
        Dim IndexOfItem As Integer

        IndexOfItem = GetIndexOfItem(ItemToDrop, -1, Items)

        If Items(IndexOfItem).Location = Inventory Then
            CanDrop = True
        Else
            Console.WriteLine(ItemToDrop & " is not in your inventory")
        End If

        If CanDrop Then
            ChangeLocationOfItem(Items, IndexOfItem, CurrentLocation)
            Console.WriteLine("You have dropped " & ItemToDrop & ".")
        End If
    End Sub

Count the number of moves a player makes / Save a high score[edit]

Display the number of moves a player has made. Used to determine a high score once the flag has been found. High score can be compared to a stored high score, and updated if greater.

C#:

// by using a generic class the UI can accept any type of input string/int etc
class GenerateUI<T>
        {      
            T information;

            public GenerateUI(T input)
            {   
                information = input;
                DisplayInfo();
            }

            public void DisplayInfo()
            {
                Console.WriteLine("Moves: " + Convert.ToString(information) + "\n");
            }
        }
...
int numMoves = -1;       // -1 means the beginning of the game
while (!stopGame)
        {   
            if (moved)
               {   
                   Console.WriteLine();
                   Console.WriteLine();
                   // new code here
                   numMoves++;
                   GenerateUI<int> movesUI = new GenerateUI<int>(numMoves);
                   Console.WriteLine(places[characters[0].CurrentLocation - 1].Description);
                   DisplayGettableItemsInLocation(items, characters[0].CurrentLocation);
                   moved = false;
               }
...

Delphi/Pascal:

Java:

Python:

#MS Maqsud HGS
#Please note that you will need to create a "score" text file beforehand
#with just the number 0 in it.

def PlayGame(Characters, Items, Places):
  line = 12
  StopGame = False
  Moved = True
  NumOfTurns = 0
  print()
  Score = open("score.txt", "r+")
  for line in Score:
    HScore = line
  print("The current highscore is: ", HScore)
  while not StopGame:
    print(NumOfTurns)
    if Moved:
      print()
      print()
      print(Places[Characters[0].CurrentLocation - 1].Description)
      DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation)
      Moved = False
    Instruction = GetInstruction()
    Command, Instruction = ExtractCommand(Instruction)
    if Command == "get":
      StopGame, Items = GetItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "use":
      StopGame, Items = UseItem(Items, Instruction, Characters[0].CurrentLocation, Places)
    elif Command == "go":
      Characters[0], Moved = Go(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1])
    elif Command == "read":
      ReadItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "examine":
      Examine(Items, Characters, Instruction, Characters[0].CurrentLocation)
    elif Command == "open":
      ResultOfOpenClose, Items, Places = OpenClose(True, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, True)
    elif Command == "close":
      ResultOfOpenClose, Items, Places = OpenClose(False, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, False)
    elif Command == "move":
      MoveItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "say":
      Say(Instruction)
    elif Command == "playdice":
      Items = PlayDiceGame(Characters, Items, Instruction)
    elif Command == "quit":
      Say("You decide to give up, try again another time.")
      StopGame = True
    else:
      print("Sorry, you don't know how to " + Command + ".")
      NumOfTurns -= 1
    NumOfTurns += 1
  if NumOfTurns > int(HScore):
    Score = open("score.txt", "w")
    Score.write(str(NumOfTurns))
    Score.close()
  input()

VB.NET:

This version counts all the commands even if they were not completed, for example, go north when the you can't go in that direction will still add to your number of moves.


Modify the PlayGame Sub

           Dim NoOfMoves As Integer = -1
Modify the while loop in PlayGame Sub
           NoOfMoves += 1
Modify the case statement
                Case Else
                    Console.WriteLine("Sorry, you don't know how to " & Command & ".")
                    NoOfMoves -= 1
Modify GetItem Sub

Sub GetItem(ByVal Items As ArrayList, ByVal ItemToGet As String, ByVal CurrentLocation As Integer, ByRef StopGame As Boolean, ByVal NoOfMoves As Integer)

ElseIf SubCommand = "win" Then
                Say("You have won the game in " & NoOfMoves & " moves.")
                StopGame = True
                Exit Sub
            End If
'created by a student from Epsom College

Prevent guard from taking the dice if you lose[edit]

Prevent guard from taking the dice if you lose. Alternatively restart game.

C#:

        private static void TakeRandomItemFromPlayer(List<Item> items, int otherCharacterID)
        {
            List<int> listOfIndicesOfItemsInInventory = new List<int>();
            int count = 0;
            while (count < items.Count)
            {
                // Modify the take random item sub so that it doesnt add die to the items in inventory array.
                if (items[count].Location == Inventory && items[count].Name.Contains("die") == false)
                {
                    listOfIndicesOfItemsInInventory.Add(count);
                }
                count++;
            }
            // Add exception handling so if they only have a dice the guard just wont take anything
            if (listOfIndicesOfItemsInInventory.Count < 1)
                Console.WriteLine("The guard takes pity on you and doesnt take anything.");
            else
            {
                int rNo = GetRandomNumber(0, listOfIndicesOfItemsInInventory.Count - 1);
                Console.WriteLine("They have taken your " + items[Convert.ToInt32(listOfIndicesOfItemsInInventory[rNo])].Name + ".");
                ChangeLocationOfItem(items, Convert.ToInt32(listOfIndicesOfItemsInInventory[rNo]), otherCharacterID);
            }
        }

Delphi/Pascal:

Java:

    void takeRandomItemFromPlayer(ArrayList<Item> items, int otherCharacterID) {
        ArrayList<Integer> listofIndicesOfItemsInInventory = new ArrayList<>();
        int count = 0;
        while (count < items.size()) {
            if (items.get(count).location == INVENTORY && !items.get(count).name.contains("die")) {
                listofIndicesOfItemsInInventory.add(count);
            }
            count++;
        }
	    int rno = getRandomNumber(0, listofIndicesOfItemsInInventory.size() - 1);
	    Console.writeLine("They have taken your " + items.get(listofIndicesOfItemsInInventory.get(rno)).name + ".");
	    changeLocationOfItem(items, listofIndicesOfItemsInInventory.get(rno), otherCharacterID);
        
    }

Python:

def TakeRandomItemFromPlayer(Items, OtherCharacterID):
  ListOfIndicesOfItemsInInventory = []
  Count = 0
  while Count < len(Items):
    if Items[Count].Location == INVENTORY and Items[Count].Name.find("die") == -1:
      ListOfIndicesOfItemsInInventory.append(Count)
    Count += 1
  if (len(ListOfIndicesOfItemsInInventory) < 1):
    print("The guard takes pity on you and doesn't take anything.")
  else:
    rno = GetRandomNumber(0, len(ListOfIndicesOfItemsInInventory) - 1)
    print("They have taken your " + Items[ListOfIndicesOfItemsInInventory[rno]].Name + ".")
    Items = ChangeLocationOfItem(Items, ListOfIndicesOfItemsInInventory[rno], OtherCharacterID)
  return Items

VB.NET:

    'Created by student of Riddlesdown Collegiate Joshua
    'Edit the take random item sub so that it doesnt add die to the items in inventory array.
    Sub TakeRandomItemFromPlayer(ByVal Items As ArrayList, ByVal OtherCharacterID As Integer)
        Dim ListofIndicesOfItemsInInventory As New ArrayList
        Dim Count As Integer = 0
        While Count < Items.Count
            If Items(Count).Location = Inventory And Items(Count).Name.contains("die") = False Then
                ListofIndicesOfItemsInInventory.Add(Count)
            End If
            Count += 1
        End While
        'Add exception handling so if they only have a dice the guard just wont take anything
        If ListofIndicesOfItemsInInventory.Count < 1 Then
            Console.WriteLine("The guard takes pity on you and doesnt take anything.")
        Else
            Dim rno As Integer = GetRandomNumber(0, ListofIndicesOfItemsInInventory.Count - 1)
            Console.WriteLine("They have taken your " & Items(ListofIndicesOfItemsInInventory(rno)).Name & ".")
            ChangeLocationOfItem(Items, ListofIndicesOfItemsInInventory(rno), OtherCharacterID)
        End If
    End Sub

Create 'time' command.[edit]

Create 'time' command. It should tell you how many minutes you have been playing. Alternative add the time (eg how many mins) you have been in the game each time you move from room to room - Note: I doubt that they would ask you to do this as it is trivial in some languages and more difficult in others. More realistically it may ask you to count the number of instructions the player has typed throughout the game.

C#:

//add to top of playgame
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
//add to switch
                    case "time":
                        Console.WriteLine("Time elapsed: {0:hh\\:mm\\:ss}", sw.Elapsed);
                        break;
//could edit the get command
 private static void GetItem(List<Item> items, string itemToGet, int currentLocation, ref bool stopGame, System.Diagnostics.Stopwatch stopwatch) //editing this
        {
            string resultForCommand, subCommand = "", subCommandParameter = "";
            int indexOfItem, position;
            bool canGet = false;
            indexOfItem = GetIndexOfItem(itemToGet, -1, items);
            if (indexOfItem == -1)
            {
                Console.WriteLine("You can't find " + itemToGet + ".");
            }
            else if (items[indexOfItem].Location == Inventory)
            {
                Console.WriteLine("You have already got that!");
            }
            else if (!items[indexOfItem].Commands.Contains("get"))
            {
                Console.WriteLine("You can't get " + itemToGet + ".");
            }
            else if (items[indexOfItem].Location >= MinimumIDForItem && items[GetIndexOfItem("", items[indexOfItem].Location, items)].Location != currentLocation)
            {
                Console.WriteLine("You can't find " + itemToGet + ".");
            }
            else if (items[indexOfItem].Location < MinimumIDForItem && items[indexOfItem].Location != currentLocation)
            {
                Console.WriteLine("You can't find " + itemToGet + ".");
            }
            else
            {
                canGet = true;
            }
            if (canGet)
            {
                position = GetPositionOfCommand(items[indexOfItem].Commands, "get");
                resultForCommand = GetResultForCommand(items[indexOfItem].Results, position);
                ExtractResultForCommand(ref subCommand, ref subCommandParameter, resultForCommand);
                if (subCommand == "say")
                {
                    Say(subCommandParameter);
                }
                else if (subCommand == "win")
                {
                    stopwatch.Stop(); //adding this
                    Console.WriteLine("You have won the game in {0:hh\\:mm\\:ss}", stopwatch.Elapsed); //and changing this
                    stopGame = true;
                    return;
                }
                if (items[indexOfItem].Status.Contains("gettable"))
                {
                    ChangeLocationOfItem(items, indexOfItem, Inventory);

                    Console.WriteLine("You have got that now.");
                }
            }
        }
//would then have to change the case to this:
                    case "get":
                        GetItem(items, instruction, characters[0].CurrentLocation, ref stopGame, sw);
                        break;
//code was made by RSFC gang

Delphi/Pascal:

Java:

Python:

import time 

def PlayGame(Characters, Items, Places, StartTime):
  StopGame = False
  Moved = True
  while not StopGame:
    if Moved:
      print()
      print()
      print(Places[Characters[0].CurrentLocation - 1].Description)
      DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation)
      Moved = False
    Instruction = GetInstruction()
    Command, Instruction = ExtractCommand(Instruction)
    if Command == "get":
      StopGame, Items = GetItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "use":
      StopGame, Items = UseItem(Items, Instruction, Characters[0].CurrentLocation, Places)
    elif Command == "go":
      Characters[0], Moved = Go(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1])
    elif Command == "read":
      ReadItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "examine":
      Examine(Items, Characters, Instruction, Characters[0].CurrentLocation)
    elif Command == "open":
      ResultOfOpenClose, Items, Places = OpenClose(True, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, True)
    elif Command == "close":
      ResultOfOpenClose, Items, Places = OpenClose(False, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, False)
    elif Command == "move":
      MoveItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "say":
      Say(Instruction)
    elif Command == "playdice":
      Items = PlayDiceGame(Characters, Items, Instruction)
    elif Command == "quit":
      Say("You decide to give up, try again another time.")
      StopGame = True
    else:
      print("Sorry, you don't know how to " + Command + ".")

  EndTime = time.time()
  print(time.strftime("You spent %M Minutes, %S Seconds playing.", time.localtime(EndTime - StartTime)))
  input()

def Main():
  Items = []
  Characters = []
  Places = []
  Filename = input("Enter filename> ") + ".gme"
  print()
  GameLoaded, Characters, Items, Places = LoadGame(Filename, Characters, Items, Places)
  if GameLoaded:
    StartTime = time.time()
    PlayGame(Characters, Items, Places, StartTime)
  else:
    print("Unable to load game.")
    input()

VB.NET:

' Edit the PlayGame sub by adding and starting a stopwatch instance before the game begins playing,
' then display the elapsed time after the user quits or when the user wins in the GetItem sub

    Sub PlayGame(ByVal Characters As ArrayList, ByVal Items As ArrayList, ByVal Places As ArrayList)

        '...

        ' create new stopwatch instance
        Dim totalTime As Stopwatch = Stopwatch.StartNew()
        totalTime.Start() ' starting stopwatch

        '...
            Select Case Command
                Case "get"
                    GetItem(Items, Instruction, Characters(0).CurrentLocation, StopGame, totalTime)
                '...                
                Case "quit"
                    Say("You decide to give up, try again another time.")

                    'tells user how many minutes they've been playing for
                    Console.WriteLine("That took you a total of {0} Minutes", Math.Round(totalTime.Elapsed.TotalMinutes))

                    StopGame = True
            End Select
        End While
        Console.ReadLine()
    End Sub

Sub GetItem(ByVal Items As ArrayList, ByVal ItemToGet As String, ByVal CurrentLocation As Integer, ByRef StopGame As Boolean, ByRef totalTime As Stopwatch)
        '...
            ElseIf SubCommand = "win" Then
                Say("You have won the game")

                'tells user how many minutes they've been playing for
                Console.WriteLine("That took you a total of {0} Minutes", Math.Round(totalTime.Elapsed.TotalMinutes))

                StopGame = True
                Exit Sub
            End If
                  
    End Sub

Limited number of spaces in the inventory[edit]

Limit the number of items that can be added to the inventory

C#:

//Create new subroutine
private static int LimitInvSpace(List<Item> items)
        {
            int InvSpace = 0;
            foreach (var thing in items)
            {
                if (thing.Location == Inventory)
                {
                    InvSpace++;
                }
            }
            return InvSpace;
        }
//In GetItem subroutine, add new variable:
int InvSpace = LimitInvSpace(items);

//In GetItem subroutine, add else if statement:
else if (InvSpace >= 3)
            {
                Console.WriteLine("You can't carry " + itemToGet);
                Console.WriteLine("Drop an item to create space");
            }
//Solution by Rahid Miah

Delphi/Pascal:

Java:

Python:

#create const at top of script
INVENTORYLIMIT = 5

def LookForSpaceInInventory(Items):
  spaceInInventory = INVENTORYLIMIT
  for item in Items:
    if item.Location == INVENTORY:
      spaceInInventory -= 1
  return spaceInInventory

#call function in GetItemFunction
elif LookForSpaceInInventory(Items) == 0:
    print("Sorry your inventory is full!")
    CanGet = False

VB.NET:

 done by richie
'Added Constant at top of script
    Const InventoryLimit As Integer = 7


'Edited DisplayInventory Sub
Dim Count As Integer
        Console.WriteLine()
        Console.WriteLine("You are currently carrying the following items:")
        For Each Thing In Items
            If Thing.Location = Inventory Then
                Console.WriteLine(Thing.Name)
                Count += 1
            End If
        Next
        Console.WriteLine("You have " & Count & " items in your inventory. You can have a maximum of " & InventoryLimit & ".")
        Console.WriteLine()


'Edited GetItem Sub
        ElseIf Items(IndexOfItem).Location < MinimumIDForItem And Items(IndexOfItem).Location <> CurrentLocation Then
            Console.WriteLine("You can't find " & ItemToGet & ".")
        ElseIf CanRetrieveItem(Items) = False Then
            Console.WriteLine("You cannot carry that item, your inventory is full.")
        Else
            CanGet = True
        End If



'Created CanRetrieveItems Function
Function CanRetrieveItem(ByVal Items As ArrayList)

        Dim Count As Integer
        For Each Thing In Items
            If Thing.Location = Inventory Then
                Count += 1
            End If
        Next

        If Count < InventoryLimit Then
            Return True
        Else
            Return False
        End If

End Function

Hit the guard with a weapon[edit]

Hit the guard(or any character in the room) with an object with weapon status and then take an item from them.

C#:

Delphi/Pascal:

Java:

Python:

#in the PlayGame function
elif Command == "hit":
      Items = UseWeapon(Characters,Items,Instruction)

def UseWeapon(Characters, Items, CharacterToAttack):
 AttackPossible,IndexOfPlayerWeapon,IndexOfOtherCharacter = CheckIfAttackPossible(Items, Characters, CharacterToAttack)
  if not AttackPossible:
    print("You can't hit.")
  else:
    print("You wacked " + CharacterToAttack)
    Items = TakeItemFromOtherCharacter(Items,Characters[IndexOfOtherCharacter].ID)
  return Items
  
def CheckIfAttackPossible(Items,Characters, CharacterToAttack):
  PlayerHasWeapon = False
  PlayersInSameRoom = False
  IndexOfOtherCharacter = -1
  IndexOfPlayerWeapon = -1
  for Thing in Items:
    if Thing.Location == INVENTORY and "weapon" in Thing.Status:
      PlayerHasWeapon = True
      IndexOfPlayerWeapon = GetIndexOfItem("",Thing.ID,Items)
  count = 1
  while count < len(Characters) and not PlayersInSameRoom:
    if Characters[0].CurrentLocation == Characters[count].CurrentLocation and Characters[count].Name == CharacterToAttack:
      PlayersInSameRoom = True
    count += 1
  return (PlayerHasWeapon and PlayersInSameRoom),IndexOfPlayerWeapon,IndexOfOtherCharacter

#the truncheon is the only existing weapon. if you added further weapons the command could be HIT CHARACTERNAME WEAPONNAME and you'd pass that into the ExtractCommand function to separate weapon and player then pass both of these into the CheckIfAttackPossible function to check the user has the named weapon in their inventory.

VB.NET:

Create a Dynamic Map[edit]

Create a map which displays the users location and where they have been in relation to their position.


C#:

Delphi/Pascal:

Java:

Can anyone say why loading the .gme file in Java calls an error?  Can't find the file?
-->You need to use the absolute path of the .gme file, without ".gme" at the end

Python:

#need these two global variables
PLACESVISITED = []
MAP = {}

def Go(You, Direction, CurrentPlace):
  ParentRoom = CurrentPlace.ID
  ...
  if Moved and You.CurrentLocation not in PLACESVISITED:
     PLACESVISITED.append(You.CurrentLocation)
     buildMap(You.CurrentLocation, Direction, ParentRoom)

def createRoom(printOrder):
  #how each room is printed.
  placeHolder = "%-2s"
  line1 = ""
  line2 = ""
  line3 = ""
  line4 = ""
  line5 = ""
  for room in printOrder:
    if room == 0:
      line1 = line1+"       "
      line2 = line2+"       "
      line3 = line3+"       "
      line4 = line4+"       "
      line5 = line5+"       "
    else:
      line1 = line1+" _____ "
      line2 = line2+" |   | "
      line3 = line3+" | "+ placeHolder % (str(room)) +"| "
      line4 = line4+" |   | "
      line5 = line5+" ̅̅̅̅̅ "  #this is a bar across - something wrong with wikibooks?
      
  print(line1)
  print(line2)
  print(line3)
  print(line4)
  print(line5)

def showMap():
  #how the map is printed.
  #Finds out how far east/west and north/south the user has gone.
  smallesty = 0 
  smallestx = 0
  largesty = 0
  largestx = 0
  for key in MAP:
    if MAP[key][4] < smallesty:
      smallesty = MAP[key][4] 
    if MAP[key][3] < smallestx:
      smallestx = MAP[key][3]
    if MAP[key][4] > largesty:
      largesty = MAP[key][4] 
    if MAP[key][3] > largestx:
      largestx = MAP[key][3]
  #adds each room in order from the top left most corner to the bottom right most corner.
  for i in range(smallesty,largesty+1):
    printOrder = []
    for j in range(smallestx,largestx+1):
      foundRoom = 0 #starts as 0 which will print nothing, but will also print a space.
      for key in MAP:
        if MAP[key][3] == j and MAP[key][4] == i:
          foundRoom = key
          break
      printOrder.append(foundRoom)
    createRoom(printOrder)
      
          
    print("\n")
    
    
def buildMap(currentPlace, directionFromParentRoom, ParentRoom):
  #function finds out what way the person travelled, then gives the new room as a coordinate from the room you started in.
  xoffset = 0 
  yoffset = 0
  if ParentRoom != "null":
    parentRoomx = MAP[ParentRoom][3]
    parentRoomy = MAP[ParentRoom][4]
    if directionFromParentRoom == "west":
      yoffset = parentRoomy
      xoffset = parentRoomx - 1
    if directionFromParentRoom == "east":
      yoffset = parentRoomy
      xoffset = parentRoomx + 1
    if directionFromParentRoom == "north":
      xoffset = parentRoomx
      yoffset = parentRoomy - 1
    if directionFromParentRoom == "south":
      xoffset = parentRoomx
      yoffset = parentRoomy + 1
  MAP[currentPlace] = [currentPlace, directionFromParentRoom, ParentRoom, xoffset, yoffset] #adds each new room to MAP dictionary, with all directions

  #add to play game function
  def PlayGame(Characters, Items, Places):
  buildMap(Places[Characters[0].CurrentLocation-1].ID, "null", "null")
  ...
  while not StopGame:
    if Places[Characters[0].CurrentLocation-1].ID not in PLACESVISITED:
      PLACESVISITED.append(Places[Characters[0].CurrentLocation-1].ID)
  ...
  elif Command == "showmap":
      showMap()

VB.NET:

Add Eat Command[edit]

At start of game the character is carrying an apple. Allow them to eat it. Perhaps introduce an energy property so they must eat it to continue (this seems less probable as it wouldn't make sense to alter the record structures as the files may not work).

C#:

//Add to play game
case "eat":
                        EatItem(items, instruction, characters[0].CurrentLocation);
                        break;

 private static void EatItem(List<Item> items, string itemToEat, int currentLocation)
        {
            int indexOfItem = GetIndexOfItem(itemToEat, -1, items);

            if (indexOfItem == -1)
            {
                Console.WriteLine("You can't find " + itemToEat + " to eat.");
            }
            else if (items[indexOfItem].Location == Inventory && items[indexOfItem].Status.Contains("edible"))
            {
                currentLocation = GetPositionOfCommand(items[indexOfItem].Commands, "eat");
                items.RemoveAt(indexOfItem);
                Console.WriteLine("The item has been eaten");
            }
            else
            {
                Console.WriteLine("You cannot eat " + itemToEat);
            }
        }


{{CPTAnswerTabEnd}}

{{CPTAnswerTab|Delphi/Pascal}}
<syntaxhighlight lang="pascal">

Java:

Python:

def EatItem(Items,ItemToUse, CurrentLocation,Places):
   IndexOfItem = GetIndexOfItem(ItemToUse, -1, Items)
   if IndexOfItem != -1:
     if Items[IndexOfItem].Location == INVENTORY and "edible" in Items[IndexOfItem].Status:
       Items = ChangeLocationOfItem(Items,IndexOfItem, 0)
# the item needs to be completely discarded so moving it to location ID 0 is a guess as no other rooms are currently using this ID number
       print("You ate the " + Items[IndexOfItem].Name)
      #rather than printing this generic message, it could be specific to each item using
      #the say command in the results for property the item but this would require eat to be a command
      #that can be used by the item in it's commands property so you'd have to change the data already stored in the pickle file
      #or add it directly to the property
       return Items
     print("You can't eat that")
     return Items
  
#in PlayGame Function
elif Command == "eat":
      Items = EatItem(Items, Instruction, Characters[0].CurrentLocation,Places)

VB.NET:

'Add to play game under "Select Case Command"

Case "eat"
Console.WriteLine(Eat(Items, Instruction))

'New Function:

    Function Eat(ByVal Items, ByVal ItemToEat)
        Dim Edible As Boolean
        Dim IndexOfItem As Integer

        IndexOfItem = GetIndexOfItem(ItemToEat, -1, Items)
        If IndexOfItem = -1 Then
            Return ("You cant find the " + ItemToEat + " to eat!")
            Edible = False
        End If
        If Items(IndexOfItem).Status.Contains("edible") Then
            Edible = True
        Else
            Edible = False
        End If


        If Items(IndexOfItem).Location = Inventory And Edible = True Then
            ChangeLocationOfItem(Items, IndexOfItem, 0)
            Return ("You have eaten your " + ItemToEat)
        ElseIf Items(IndexOfItem).Location = Inventory And Edible = False Then
            Return ("You cant eat the " + ItemToEat)
        Else
            Return ("You can't eat what you don't have!")
        End If
    End Function

Add Drink Command[edit]

At start of game the character is carrying a flask. There is a barrel of water. Allow them to drink from the barrel.

C#:

Delphi/Pascal:

# Python is better than this

Java:

Python:

# Please add tea and cigs to drink commands
# add this in the PlayGame() subroutine
    elif Command == "drink":
        drinkFromBarrel(Characters, Items, Instruction)

# Only thing that can be drank from
def drinkFromBarrel(Characters, Items, ItemToDrink):
    canDrink = checkIfCanDrink(Characters, Items)
    if canDrink:
        # We should be dead now
        print("You drank cholera infested water you fool!")
    else:
        print("Cannot drink " + ItemToDrink)

# now to check if it is possible to drink
def checkIfCanDrink(Characters, Items):
    playerIsInSameRoom = False
    playerHasFlask = False
    # firstly check to see if the user has a flask in the inventory
    for item in Items:
        if item.Location == INVENTORY and "container" in item.Status:
            playerHasFlask = True
    # The barrel is only in location 8, cannot be moved at all
    if Characters[0].CurrentLocation == 8:
        playerIsInSameRoom = True
    # both have to be true to drink
    return playerIsInSameRoom and playerHasFlask
# Made by the Greenhead Gang
# Hello
# You wanna pot of tea and a cig?

VB.NET:

Modify Get Command so that the user can only get an item if they can carry it[edit]

Gettable items are either 'tiny, 'small' or 'medium'. Introduce a weighInventory sub-routine. Tiny = weight of 1, Small = weight of 2 and medium = weight of 3. Only allow an item to be collected if it wont take the inventory weight over 7.

C#:

//Create new WeighInventoryItems Subroutine.
private static int WeighInventoryItems(List<Item> items)
{
    int InventoryCount = 0;

    for (int i = 0; i < items.Count; i++)
    {
        if (items[i].Location == Inventory && items[i].Status.Contains("tiny"))
        {
            InventoryCount += 1; 
        }
        else if (items[i].Location == Inventory && items[i].Status.Contains("small"))
        {
            InventoryCount += 2;
        }
        else if (items[i].Location == Inventory && items[i].Status.Contains("medium"))
        {
            InventoryCount += 3;
        }
    }

    return InventoryCount;
}

//Call WeighInventoryItems in GetItems routine
//Add new 'else if' to GetItem routine
else if (inventoryCount > 7)
{
    Console.WriteLine("Inventory is too full to carry " + itemToGet + ".");
}

//Solution by Josh~Kb

Delphi/Pascal:

Java:

Python:

def GetWeight(Item):
  Weights = {"tiny": 1, "small": 2, "medium": 3}

  Weight = 0

  for attribute in item.Status.split(","):
    Weight += Weights[attribute] if attribute in Weights else 0

  return Weight

def WeighInventory(Items):
  InventoryWeight = 0

  for item in Items:
      if item.Location == INVENTORY:
          InventoryWeight += GetWeight(item)

  return InventoryWeight

def GetItem(Items, ItemToGet, CurrentLocation):
  SubCommand = ""
  SubCommandParameter = ""
  CanGet = False
  IndexOfItem = GetIndexOfItem(ItemToGet, -1, Items)
  if IndexOfItem == -1:
    print("You can't find " + ItemToGet + ".")
  elif Items[IndexOfItem].Location == INVENTORY:
    print("You have already got that!")
  elif not "get" in Items[IndexOfItem].Commands:
    print("You can't get " + ItemToGet + ".")
  elif Items[IndexOfItem].Location >= MINIMUM_ID_FOR_ITEM and Items[GetIndexOfItem("", Items[IndexOfItem].Location, Items)].Location != CurrentLocation:
    print("You can't find " + ItemToGet + ".")
  elif Items[IndexOfItem].Location < MINIMUM_ID_FOR_ITEM and Items[IndexOfItem].Location != CurrentLocation:
    print("You can't find " + ItemToGet + ".")
  elif WeightInventory(Items) + GetWeight(Items[IndexOfItem]) > 7:
    print("Inventory is too full to carry {}.".format(ItemToGet))
  else:
    CanGet = True
  if CanGet:
    Position = GetPositionOfCommand(Items[IndexOfItem].Commands, "get")
    ResultForCommand = GetResultForCommand(Items[IndexOfItem].Results, Position)
    SubCommand, SubCommandParameter = ExtractResultForCommand(SubCommand, SubCommandParameter, ResultForCommand)
    if SubCommand == "say":
      Say(SubCommandParameter)
    elif SubCommand == "win":
      Say("You have won the game")
      return True, Items
    if "gettable" in Items[IndexOfItem].Status:
      Items = ChangeLocationOfItem(Items, IndexOfItem, INVENTORY)
      print("You have got that now.")
  return False, Items

VB.NET:

If you are in the cellar you must be carrying a torch to see items[edit]

C#:

Delphi/Pascal:

Java:

Python:

def PlayGame(Characters, Items, Places):
  StopGame = False
  Moved = True
  while not StopGame:
    if Moved:
      print()
      print()
      hasTorch = False
      for item in Items:
          if item.Location == INVENTORY and item.Name == "torch":
              hasTorch = True
      if Places[Characters[0].CurrentLocation - 1].Description.find("cellar") != -1 and not hasTorch:
        print("You cannot see anything in the dark, maybe a torch would help...")
      else:
        print(Places[Characters[0].CurrentLocation - 1].Description)
        DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation)
      Moved = False
    Instruction = GetInstruction()
    Command, Instruction = ExtractCommand(Instruction)
    if Command == "get":
      StopGame, Items = GetItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "use":
      StopGame, Items = UseItem(Items, Instruction, Characters[0].CurrentLocation, Places)
    elif Command == "go":
      Characters[0], Moved = Go(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1])
    elif Command == "read":
      ReadItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "examine":
      Examine(Items, Characters, Instruction, Characters[0].CurrentLocation)
    elif Command == "open":
      ResultOfOpenClose, Items, Places = OpenClose(True, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, True)
    elif Command == "close":
      ResultOfOpenClose, Items, Places = OpenClose(False, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, False)
    elif Command == "move":
      MoveItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "say":
      Say(Instruction)
    elif Command == "playdice":
      Items = PlayDiceGame(Characters, Items, Instruction)
    elif Command == "quit":
      Say("You decide to give up, try again another time.")
      StopGame = True
    else:
      print("Sorry, you don't know how to " + Command + ".")
  input()

VB.NET:


If dice game is lost, allow last words[edit]

If user says certain thing for their last words they win instantly. Difficulty = Easy

Python:

#Sulaiman Maqsud HGS

def PlayDiceGame(Characters, Items, OtherCharacterName):
  PlayerScore = 0
  OtherCharacterScore = 0
  DiceGamePossible, IndexOfPlayerDie, IndexOfOtherCharacter, IndexOfOtherCharacterDie = CheckIfDiceGamePossible(Items, Characters, OtherCharacterName)
  if not DiceGamePossible:
    print("You can't play a dice game.")
  else:
    Position = GetPositionOfCommand(Items[IndexOfPlayerDie].Commands, "use")
    ResultForCommand = GetResultForCommand(Items[IndexOfPlayerDie].Results, Position)
    PlayerScore = RollDie(ResultForCommand[5], ResultForCommand[7])
    print("You rolled a " + str(PlayerScore) + ".")
    Position = GetPositionOfCommand(Items[IndexOfOtherCharacterDie].Commands, "use")
    ResultForCommand = GetResultForCommand(Items[IndexOfOtherCharacterDie].Results, Position)
    OtherCharacterScore = RollDie(ResultForCommand[5], ResultForCommand[7])
    print("They rolled a " + str(OtherCharacterScore) + ".")
    if PlayerScore > OtherCharacterScore:
      print("You win!")
      Items = TakeItemFromOtherCharacter(Items, Characters[IndexOfOtherCharacter].ID)
    elif PlayerScore < OtherCharacterScore:
      print("You lose!")
      pip = input("It's over Anakin, I have the high ground ")
      if pip == "You underestimate my power":
        print("Don't try it")
        exit()
      Items = TakeRandomItemFromPlayer(Items, Characters[IndexOfOtherCharacter].ID)
    else:
      print("Draw!")
  return Items

Delphi/Pascal:

Java:

C#:

VB.NET:

Add the ability to examine whether a door is open or closed[edit]

The user can type 'examine' and the status of the door they are examining will be returned

C#:

Delphi/Pascal:

Java:

Python:

VB.NET:

Container items can be used[edit]

Modify the program such that containers, such as the barrel and the jar, can have items placed inside them.

For example, use barrel would trigger the program to prompt for an item to be put into the barrel.

C#:

Delphi/Pascal:

Java:

Python:

Make Torch A Container[edit]

Make the torch a container and create batteries. The torch can only be turned on 'used' when it is powered. It is only powered when the batteries are in there.

C#:

Delphi/Pascal:

Java:

Python:

#in useItem()
if ItemToUse == "torch":
        if "powered" in Items[IndexOfItem].Status:
          Items[IndexOfItem].Status = Items[IndexOfItem].Status.replace("off","on")
        else:
          print("The torch is not powered. Please insert batteries")
          return StopGame, Items
      
      if SubCommand == "power":
        for items in Items:
          if (items.Name == "torch") and (("powered" in items.Status) == False) and (items.Location == INVENTORY or items.Location == CurrentLocation):
            items.Status += ",powered"
            Items[IndexOfItem].Location = items.ID
            print("Batteries inserted to the torch")
            return StopGame, Items
#in playGame()
     
   #sets the torch as a container and removes powered from it's statuses so it is initially unpowered.
    for item in Items:
      if item.ID == 2020:
        item.Status = "gettable,off,lightable,small,container"

    #creates batteries item    
    TempItem = Item()
    TempItem.ID = 2028
    TempItem.Description = "A collection of batteries"
    TempItem.Status = "gettable,small,usable"
    TempItem.Location = 1
    TempItem.Name = "batteries"
    TempItem.Commands = "get,use"
    TempItem.Results = ";power"
    Items.append(TempItem)


Create 'teleport item' command[edit]

Create a function to teleport any item to your location, even if it is another characters inventory

C#:

//Add to PlayGame()
case "teleportitem":
                        teleportitem(items, instruction, characters[0].CurrentLocation);
                        break;
//Add my snap fergus-rooney
//Add Function teleportitem()
private static void teleportitem(List<Item> items, string itemToTeleport, int currentLocation)
        {
            int position = currentLocation, indexOfItem;
            indexOfItem = GetIndexOfItem(itemToTeleport, -1, items);
            if (indexOfItem == -1)
            {
                Console.WriteLine("cannot find " + itemToTeleport+ " to teleport");
            }
            else
            {
                Console.WriteLine(itemToTeleport +" teleported to your location");
                position = GetPositionOfCommand(items[indexOfItem].Commands, "teleportitem");
                ChangeLocationOfItem(items, indexOfItem, currentLocation);
            }
        }

Delphi/Pascal:

Python:

def TeleportItem(Items, ItemToTeleport, CurrentLocation):
  IndexOfItem = GetIndexOfItem(ItemToTeleport, -1, Items)
  if IndexOfItem == -1:
    print("Cannot find {} in the game.".format(ItemToTeleport))
  else:
    ChangeLocationOfItem(Items, IndexOfItem, CurrentLocation)
    print("Successfully teleported {} to your location.".format(ItemToTeleport))

def PlayGame(Characters, Items, Places):
  StopGame = False
  Moved = True
  while not StopGame:
    if Moved:
      print()
      print()
      print(Places[Characters[0].CurrentLocation - 1].Description)
      DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation)
      Moved = False
    Instruction = GetInstruction()
    Command, Instruction = ExtractCommand(Instruction)
    if Command == "get":
      StopGame, Items = GetItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "use":
      StopGame, Items = UseItem(Items, Instruction, Characters[0].CurrentLocation, Places)
    elif Command == "go":
      Characters[0], Moved = Go(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1])
    elif Command == "read":
      ReadItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "examine":
      Examine(Items, Characters, Instruction, Characters[0].CurrentLocation)
    elif Command == "open":
      ResultOfOpenClose, Items, Places = OpenClose(True, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, True)
    elif Command == "close":
      ResultOfOpenClose, Items, Places = OpenClose(False, Items, Places, Instruction, Characters[0].CurrentLocation)
      DisplayOpenCloseMessage(ResultOfOpenClose, False)
    elif Command == "move":
      MoveItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "say":
      Say(Instruction)
    elif Command == "playdice":
      Items = PlayDiceGame(Characters, Items, Instruction)
    elif Command == "teleportitem":
      TeleportItem(Items, Instruction, Characters[0].CurrentLocation)
    elif Command == "quit":
      Say("You decide to give up, try again another time.")
      StopGame = True
    else:
      print("Sorry, you don't know how to " + Command + ".")
  input()


Create a 'move counter' and 'command history list'[edit]

Create a function to count the number of moves the user has made and display a history of those commands when requested.

// global varibles
moveCount = 0
commands = []

def GetInstruction():
	global moveCount
	global commands
	print(os.linesep)
	Instruction = input("> ").lower()
	commands.append(Instruction)
	moveCount +=1
	print("You have made", moveCount, "moves")
	return Instruction

// add to play game function	
elif Command == "history":
			print(commands)


Search/display the current directory for available games (to make the beginning less confusing for first time user[edit]

Searches and displays available games. Useful for making the beginning of the game obvious..

C#:

Delphi/Pascal:

Java:

Python:

import os

def listGameFiles():
  # Get the directory the program is being run from
  cwd = os.getcwd()

  # Loop over all files in the directory and print if they are a .gme file
  for file in os.listdir(cwd):
    if file.endswith(".gme"):
      print(file)

  print("\n")

def Main():
  Items = []
  Characters = []
  Places = []
  print("Games Available: ")
  listGameFiles()
  Filename = input("Enter filename> ") + ".gme"
  print()
  GameLoaded, Characters, Items, Places = LoadGame(Filename, Characters, Items, Places)
  if GameLoaded:
    PlayGame(Characters, Items, Places)
  else:
    print("Unable to load game.")
    input()

VB.NET:

Add at the top of the Sub Main subroutine:
Console.WriteLine("Type the name of the game that you wish to play.")
        ListExistingGames()

Add new subroutine ListExistingGames():
The subroutine searches for the files that end with the extension "gme".
***ASSUMES THAT THE GME FILES ARE SAVED INTO THE BIN/DEBUG (DEFAULT) FOLDER***
It the uses split to take the text to the left of the full stop.

Sub ListExistingGames()
        ' make a reference to a directory
        Dim di As New IO.DirectoryInfo(Directory.GetCurrentDirectory())
        Dim diar1 As IO.FileInfo() = di.GetFiles()
        Dim dra As IO.FileInfo
        Dim draT As String

        'list the names of all files in the specified directory
        For Each dra In diar1
            If dra.Extension = ".gme" Then
                draT = dra.ToString
                draT = draT.Split(".")(0)
                Console.WriteLine(draT)
            End If
        Next
    End Sub