A-level 計算機/AQA/試卷 1/骨架程式/2019
這是針對 AQA A-level 計算機科學規範的。
這裡可以對一些可能的問題以及解決方法提出建議。
請尊重他人,不要破壞或篡改此頁面,因為這會影響學生備考!
關於骨架程式碼的理論問題
- 骨架程式從二進位制檔案載入遊戲資料。請說明在骨架程式中使用二進位制檔案而不是文字檔案的兩個原因。[2 分]
GetIndexOfItem 子程式用於查詢 Items 中某一專案的索引。可以使用專案的名稱或 ID 來指定要查詢的專案。
- 解釋一下,如果 GetIndexOfItem 返回的值為 -1,這意味著什麼。[1 分]
- GetIndexOfItem 子程式如何知道是嘗試使用名稱還是 ID 來查詢作為引數傳遞給它的專案?[1 分]
- GetIndexOfItem 子程式中用於查詢專案的演算法的時間複雜度是多少?[1 分]
- 骨架程式程式碼中存在一個錯誤,在使用提供的遊戲檔案時不會導致問題,但可能會在使用其他遊戲檔案時導致問題。在什麼情況下,GetIndexOfItem 子程式會返回一個不是正在搜尋的專案的索引?[2 分]
- 如果骨架程式被設計為使用雜湊表來儲存專案,那麼當給出專案的 ID 時,它很可能比當前在 GetIndexOfItem 子程式中使用的演算法更快地找到專案的索引。[3 分]
- 解釋在雜湊表中查詢專案的步驟。您應該假設遊戲中所有可用的專案都已經成功地新增到雜湊表中。[4 分]
- 給出雜湊表不適合用作骨架程式中儲存專案的選項的一個原因。[1 分]
集合是一個無序的值集合,其中每個值最多出現一次。遊戲中專案的描述可以使用集合來表示。
- 集合 A 包含遊戲中的所有專案。
- 集合 B 包含所有在其 Commands 中包含“use”的專案。
- 集合 C 包含所有在其 Status 中包含“gettable”的專案。
- 集合 D 包含玩家庫存中的所有專案。
- 集合 E 包含所有 Location 等於玩家 CurrentLocation 且在其 Status 中包含“usable”的專案。
- 集合 F 包含所有 Location 等於 CurrentLocation 的專案。
對集合可以執行的四個操作是並集、差集、交集和成員資格。
- 解釋一下,如何使用集合 A 到 F 之間的某些集合進行操作,以生成玩家在當前遊戲狀態下可以使用的一組專案。[3 分]
- 上面專案中描述的集合是集合 A 到 F 之間某些集合的真子集。列出它屬於真子集的所有集合(A 到 F)。[1 分]
- 解釋一下,為什麼集合 F 和 C 的交集不包含玩家當前可以獲取的所有專案。[1 分]
- 解釋一下,子集和真子集的區別。[1 分]
關於骨架程式的程式設計問題
- 2018 年試卷 1 包含一個 2 分問題、一個 5 分問題、兩個 9 分問題和一個 12 分問題——這些分數包括螢幕截圖。相比之下,2017 年試卷 1 包含一個 5 分問題、三個 6 分問題和一個 12 分問題。
- 2019 年試卷 1 將包含 4 個問題:一個 5 分問題、一個 8 分問題、一個 9 分問題和一個 13 分問題——這些分數包括螢幕截圖,因此編碼部分的可能分數會低 1-2 分。
此列表是根據對標誌檔案的分析、ZigZag Education 的建議以及本 Wikibooks 頁面上的建議建立的。如果您能確定任何其他可能的 D 章節問題,請將其新增到此列表中。
最可能的預測
請注意,這些分數建議包括螢幕截圖的得分。
- Help 命令(2 分)
- 允許帶/不帶副檔名的檔名(2 分)
- 檢查房間(2 分以上)
- 如果門是開著的,檢視下一個房間的房間描述(5 分)
- 必須移動地毯才能開啟地窖門(5 分)
- 丟棄物品(5 分)
- 使用警棍(使用警棍命令)與守衛戰鬥(5 分)
- Eat 命令(5 分——包括恢復生命值可能會有 9 分)
- 使用 save 命令儲存遊戲(5 分)
- 玩家有 HP + 吃東西恢復生命值(9 分)
- 從容器中填充/飲用——例如,燒瓶和桶(9 分)
- 移動歷史(9 分以上)
- Go 命令會自動解鎖並開啟門,前提是您有鑰匙(9 分以上)
- 透過物品大小限制庫存空間——微型、小型和中型物品(9 分以上)
待程式設計的想法
- 開啟和關閉當前位置的所有門
- 建立一個新的位置/房間
- 將物品交給守衛,例如紅色骰子
- 往桶裡加水,然後可以放在燒瓶裡
- 根據百分比機率提供一個撬開門的選項,如果失敗,守衛會逮捕你
- 新增睡覺的好處,例如,提高贏得骰子的機會
- 儲存遊戲
- 當執行“use chair”時,它會說無法執行,但是檔案中寫著守衛不會讓你坐在他的腿上。需要修復嗎?
不太可能,.gme 檔案的椅子使用功能附帶了錯誤的指令。
gme 檔案應該包含“say,The guard won't let you sit on his lap”,而不是“use,The guard won't let you sit on his lap”。
這很可能只是一個遺留資料,因為程式碼的質量有待商榷,所以不足為奇。
r/iamverysmart
r/ihavereddit
r/computerscience
摘自 ZigZag 的示例問題。
歷史使用一個堆疊,允許玩家透過輸入“後退”來返回之前的位置,或者透過輸入“歷史”來顯示之前的位置。你需要兩個子程式:Push,用於新增一個新的訪問位置,和 Pop,用於從堆疊中移除最後一個位置並返回它。如果堆疊為空,則應返回 -1。
Java
//This class is the stack class that deals with
//all of the pushing and popping.
class History{
int pointer = -1;
int pastPlaces[] = new int[5];
void push(int newLocation)
{
if(pointer == 4)
{
for(int i = 0; i < 4; i++)
{
pastPlaces[i] = pastPlaces[i+1];
}
pastPlaces[4] = newLocation;
}
else
{
pastPlaces[pointer + 1] = newLocation;
pointer++;
}
}
int pop()
{
if(pointer == -1)
{
return-1;
}
else
{
int poppedValue = pastPlaces[pointer];
pastPlaces[pointer] = 0;
pointer--;
return poppedValue;
}
}
}
//These changes to 'playGame' allow for the
//use of the history stack
void playGame(ArrayList<Character> characters, ArrayList<Item> items, ArrayList<Place> places) {
History history = new History();
...
case "go":
moved = go(characters.get(0), instruction, places.get(characters.get(0).currentLocation - 1), history);
break;
...
}
//These changes to go add the past places to the history stack,
//and allow the user to travel 'back'
boolean go(Character you, String direction, Place currentPlace, History history) {
boolean moved = true;
switch (direction)
{
case "north":
if (currentPlace.north == 0) {
moved = false;
} else {
history.push(you.currentLocation);
you.currentLocation = currentPlace.north;
}
break;
case "east":
if (currentPlace.east == 0) {
moved = false;
} else {
history.push(you.currentLocation);
you.currentLocation = currentPlace.east;
}
break;
case "south":
if (currentPlace.south == 0) {
moved = false;
} else {
history.push(you.currentLocation);
you.currentLocation = currentPlace.south;
}
break;
case "west":
if (currentPlace.west == 0) {
moved = false;
} else {
history.push(you.currentLocation);
you.currentLocation = currentPlace.west;
}
break;
case "up":
if (currentPlace.up == 0) {
moved = false;
} else {
history.push(you.currentLocation);
you.currentLocation = currentPlace.up;
}
break;
case "down":
if (currentPlace.down == 0) {
moved = false;
} else {
history.push(you.currentLocation);
you.currentLocation = currentPlace.down;
}
break;
case "back":
int newLocation = history.pop();
if(newLocation == -1)
{
moved = false;
}
else
{
you.currentLocation = newLocation;
}
break;
default:
moved = false;
}
if (!moved) {
Console.writeLine("You are not able to go in that direction.");
}
return moved;
}
C#
//sc & ig olilcook
//create this class
public class History
{
public int pointer = -1;
public int[] pastPlaces = new int[5];
}
//create these two subroutines
private static void push(int newLocation, History history)
{
if (history.pointer == 4)
{
for (int i = 0; i < 4; i++)
{
history.pastPlaces[i] = history.pastPlaces[i + 1];
}
history.pastPlaces[4] = newLocation;
}
else
{
history.pastPlaces[history.pointer + 1] = newLocation;
history.pointer++;
}
}
public static int peek(int position, History history)
{
return history.pastPlaces[position];
}
//add this at the top of playgame
History history = new History();
//add this inside the while loop in playgame
if (moved)
{
push(places[characters[0].CurrentLocation -1].id, history);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(places[characters[0].CurrentLocation - 1].Description);
DisplayGettableItemsInLocation(items, characters[0].CurrentLocation);
moved = false;
}
//add this as a case in playgame
case "history":
int count = 6;
for (int i = 0; i < count - 1; i++)
{
int position = peek(i, history);
Console.WriteLine(decideHistoryRoom(position) + "\n");
}
break;
//create this subroutine
public static string decideHistoryRoom(int position)
{
string strtoreturn = "";
switch (position)
{
case 1:
strtoreturn = "Blue Room";
break;
case 2:
strtoreturn = "Cupboard";
break;
case 3:
strtoreturn = "Attic";
break;
case 4:
strtoreturn = "Corridoor";
break;
case 5:
strtoreturn = "Guardroom";
break;
case 6:
strtoreturn = "Gold Prison Cell";
break;
case 7:
strtoreturn = "Silver Prison Cell";
break;
case 8:
strtoreturn = "Cellar";
break;
default:
break;
}
return strtoreturn;
}
//once this has all completed, when the user types history it will display the last 5 locations that the character has been in. Hope this helped :)
VB.NET
Pascal/Delphi
unit History;
interface
Type THistoryStack = Class
private
Pointer: Integer;
Locations: Array[0..4] of Integer;
const MaxSize = 4;
public
Constructor Initialise;
procedure Push(Value:Integer);
function Pop: Integer;
End;
implementation
Constructor THistoryStack.Initialise;
begin
Pointer := -1;
Locations[0] := 0;
Locations[1] := 0;
Locations[2] := 0;
Locations[3] := 0;
Locations[4] := 0;
end;
procedure THistoryStack.Push(Value: Integer);
var
Counter: Integer;
begin
if(Pointer = MaxSize) then
begin
for Counter := 0 to MaxSize-1 do
begin
Locations[Counter] := Locations[Counter+1];
end;
Locations[MaxSize] := Value;
end
else
begin
Pointer := Pointer +1;
Locations[Pointer] := Value;
end;
end;
function THistoryStack.Pop: Integer;
begin
if Pointer >=0 then
begin
Pointer := Pointer -1;
Pop := Locations[Pointer+1];
end
else
Pop := -1;
end;
end.
//Update PlayGame so that it starts with:
procedure PlayGame(Characters: TCharacterArray; Items: TItemArray; Places: TPlaceArray);
var
StopGame: boolean;
Instruction: string;
Command: string;
Moved: boolean;
ResultOfOpenClose: integer;
LocationStack: THistoryStack;
begin
StopGame := false;
Moved := true;
LocationStack := THistoryStack.Initialise;
//And update Go so that it is now:
function Go(var You: TCharacter; Direction: string; CurrentPlace: TPlace; var LocationStack: THistoryStack): boolean;
var
Moved: boolean;
Back: boolean;
PreviousLocation: Integer;
begin
Moved := true;
PreviousLocation := You.CurrentLocation;
Back := False;
if Direction = 'north' then
if CurrentPlace.North = 0 then
Moved := false
else
You.CurrentLocation := CurrentPlace.North
else if Direction = 'east' then
if CurrentPlace.East = 0 then
Moved := false
else
You.CurrentLocation := CurrentPlace.East
else if Direction = 'south' then
if CurrentPlace.South = 0 then
Moved := false
else
You.CurrentLocation := CurrentPlace.South
else if Direction = 'west' then
if CurrentPlace.West = 0 then
Moved := false
else
You.CurrentLocation := CurrentPlace.West
else if Direction = 'up' then
if CurrentPlace.Up = 0 then
Moved := false
else
You.CurrentLocation := CurrentPlace.Up
else if Direction = 'down' then
if CurrentPlace.Down = 0 then
Moved := false
else
You.CurrentLocation := CurrentPlace.Down
else if Direction = 'back' then
begin
Back := True;
PreviousLocation := LocationStack.Pop();
if(PreviousLocation <> -1) then
You.CurrentLocation := PreviousLocation
else
Moved := False;
end
else
Moved := false;
if not Moved then
writeln('You are not able to go in that direction.');
if((Moved) and (not Back)) then
LocationStack.Push(PreviousLocation);
Go := Moved
end;
Python
class History():
def __init__(self):
self.Pointer=-1
self.Locations=[0,0,0,0,0]
def Push(self, NewLocation):
if self.Pointer==5:
self.Locations.pop(0)
self.Locations.append(NewLocation)
else:
self.Locations[self.Pointer]=NewLocation
self.Pointer+=1
def Pop(self):
if self.Pointer==-1:
return -1
else:
self.Pointer+=-1
return self.Locations[self.Pointer]
# add line to play game
past=History() #This instance needs to be passed into Go if the commad is 'go'
# indicates added or changed lines
def Go(You, Direction, CurrentPlace, past):#
pointer =-2#
Moved = True
if Direction == "north":
if CurrentPlace.North == 0:
Moved = False
else:
past.Push(You.CurrentLocation)#
You.CurrentLocation = CurrentPlace.North
elif Direction == "east":
if CurrentPlace.East == 0:
Moved = False
else:
past.Push(You.CurrentLocation)#
You.CurrentLocation = CurrentPlace.East
elif Direction == "south":
if CurrentPlace.South == 0:
Moved = False
else:
past.Push(You.CurrentLocation)#
You.CurrentLocation = CurrentPlace.South
elif Direction == "west":
if CurrentPlace.West == 0:
Moved = False
else:
past.Push(You.CurrentLocation)#
You.CurrentLocation = CurrentPlace.West
elif Direction == "up":
if CurrentPlace.Up == 0:
Moved = False
else:
past.Push(You.CurrentLocation)#
You.CurrentLocation = CurrentPlace.Up
elif Direction == "down":
if CurrentPlace.Down == 0:
Moved = False
else:
past.Push(You.CurrentLocation)#
You.CurrentLocation = CurrentPlace.Down
elif Direction=="back":#
pointer=past.Pop()#
if pointer == -1:#
print "You cannot go back"#
elif pointer != -2:#
You.CurrentLocation = pointer#
else:
Moved = False
if not Moved:
print "You are not able to go in that direction."
return You, Moved
SM HGS,難度:新遊戲 +
C#
private static void ChangeStatusOfDoor(List<Item> items, int currentLocation, int indexOfItemToLockUnlock, int indexOfOtherSideItemToLockUnlock, List<Place> places)
{
if (currentLocation == items[indexOfItemToLockUnlock].Location || currentLocation == items[indexOfOtherSideItemToLockUnlock].Location)
{
if (items[indexOfItemToLockUnlock].Status == "locked")
{
ChangeStatusOfItem(items, indexOfItemToLockUnlock, "close");
ChangeStatusOfItem(items, indexOfOtherSideItemToLockUnlock, "close");
Say(items[indexOfItemToLockUnlock].Name + " now unlocked.");
OpenClose(true, items, places, items[indexOfItemToLockUnlock].Name, currentLocation);
}
VB.NET
If Items(IndexOfItemToLockUnlock).Status = "locked" Then
ChangeStatusOfItem(Items, IndexOfItemToLockUnlock, "close")
ChangeStatusOfItem(Items, IndexOfOtherSideItemToLockUnlock, "close")
Say(Items(IndexOfItemToLockUnlock).Name & " now unlocked.")
OpenClose(True, Items, Places, Items(IndexOfItemsToLockUnlock).Name, CurrentLocation)
Pascal/Delphi
Python
##Oscar - WPS
Oscar from WPS why would this be in the exam?
def AutoUnlockOpenDoor(Items,Places,Characters,CurrentLocation):
Usables = list()
for Thing in Items:
if "key" in Thing.Name and Thing.Location == INVENTORY:
Usables.append(Thing)
for Thing in Usables:
ItemToUse = Thing.Name
try:
StopGame, Items = UseItem(Items, ItemToUse,CurrentLocation, Places)
except Exception as e:
print e
for door in Items:
if "door" in door.Name:
ToOpen = door.Name
try:
ResultOfOpenClose, Items, Places = OpenClose(True, Items, Places, ToOpen,CurrentLocation)
except Exception as e:
print e
return Items,Places,Characters
##In PlayGame
elif Command == "go":
Items , Places, Characters = AutoUnlockOpenDoor(Items,Places,Characters,Characters[0].CurrentLocation)
Characters[0], Moved = Go(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1])
#Less complicated way
def UnlockDoors(Items, CurrentLocation):
HasGoldKey = False
HasSilverKey = False
for Item in Items:
if "gold key" in Item.Name and Item.Location == INVENTORY:
HasGoldKey = True
elif "silver key" in Item.Name and Item.Location == INVENTORY:
HasSilverKey = True
if CurrentLocation == 5:
if HasGoldKey:
IndexOfGoldDoor = GetIndexOfItem("gold door", -1, Items)
Items = ChangeStatusOfItem(Items, IndexOfGoldDoor, "unlocked")
elif HasSilverKey:
IndexOfSilverDoor = GetIndexOfItem("silver door", -1, Items)
Items = ChangeStatusOfItem(Items, IndexOfSilverDoor, "unlocked")
return Items
# In PlayGame
elif Command == "open":
Items = UnlockDoors(Items, Characters[0].CurrentLocation)
ResultOfOpenClose, Items, Places = OpenClose(True, Items, Places, Instruction,
Characters[0].CurrentLocation)
DisplayOpenCloseMessage(ResultOfOpenClose, True)
#By your local anime cop, Ben R - Greenhead col
Java
//This function checks the list of items and finds and any doors blocking the direction specified by the user in the 'go' method. If it identifies a door, it checks if it is locked. If so, it checks the list of items to see if the user has a suitable key for the door (If a key is suitable for the door, the id of the door will be in the 'results' of the key). If the user has such a key, it will then unlock and subsequently open the door.
void checkDoor(int currentLocation, String direction, ArrayList<Item> items, ArrayList<Place> places)
{
for(Item item : items)
{
if(item.location == currentLocation && item.results.contains(direction))
{
if(item.status.equals("locked"))
{
for(Item otherItem : items)
{
if(otherItem.location == INVENTORY && otherItem.results.contains(Integer.toString(item.id)))
{
int indexOfItemToLockUnlock, indexOfOtherSideItemToLockUnlock;
indexOfItemToLockUnlock = getIndexOfItem("", item.id, items);
indexOfOtherSideItemToLockUnlock = getIndexOfItem("", item.id + ID_DIFFERENCE_FOR_OBJECT_IN_TWO_LOCATIONS, items);
changeStatusOfDoor(items, currentLocation, indexOfItemToLockUnlock, indexOfOtherSideItemToLockUnlock);
}
}
}
if(item.status.equals("close"))
{
openClose(true, items, places, item.name, currentLocation);
}
}
}
}
//Add to the start of 'go'
checkDoor(you.currentLocation, direction, items, places);
//Add the required parameters to the go case in 'playGame'
case "go":
moved = go(characters.get(0), instruction, places.get(characters.get(0).currentLocation - 1), items, places);
break;
修改原始碼,允許輸入帶/不帶副檔名(“.gme”)的檔名。
C#
static void Main(string[] args)
{
string filename;
List<Place> places = new List<Place>();
List<Item> items = new List<Item>();
List<Character> characters = new List<Character>();
Console.Write("Enter filename> ");
filename = Console.ReadLine();
if (!filename.EndsWith(".gme")) {
// you could also use .contains but do note that would mean file.gmejk would not append .gme to the end.
// learn both methods in case one is better suited for full marks?
filename = filename + ".gme";
}
if (LoadGame(filename, characters, items, places))
{
PlayGame(characters, items, places);
}
else
{
Console.WriteLine("Unable to load game.");
Console.ReadLine();
}
}
VB.NET
'Programmed by Samuel from Poole Grammar school.
Sub Main()
Dim Filename As String
Dim Items, Characters, Places As New ArrayList
Console.Write("Enter filename> ") 'Validate file name
'---------------------------------------------------------------------------
Filename = Console.ReadLine()
If Not Filename.EndsWith(".gme") Then
Filename = Filename & ".gme"
End If
'---------------------------------------------------------------------------
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
Pascal/Delphi
...
procedure Main;
...
write('Enter filename> ');
readln(Filename);
// Add this line
if not Filename.EndsWith('.gme') then Filename := Filename + '.gme';
writeln;
...
Python
##Rahmed HGS
##Inline conditional statements are the new (old) hip thing to do nowadays, and it's free!
def Main():
Items = []
Characters = []
Places = []
Filename = input("Enter filename> ")
Filename = Filename if Filename.endswith('.gme') else Filename + '.gme'
print()
...
Java
//Programmed by ya boy Arek from Kennet
//Add to Main()
filename = Console.readLine()
if (!filename.contains(".gme")){
filename = filename + ".gme";
}
修改原始碼,詢問使用者是否確定要退出遊戲。
VB.NET
'Programmed by Samuel from Poole Grammar school.
Edit the PlayGame subroutine under case "quit":
Case "quit"
'---------------------------------------------------------------------------
Console.WriteLine("Are you sure?") 'Are you sure quit
Dim Answer As String = Console.ReadLine().ToLower
If Answer = "y" Or Answer = "yes" Then
Say("You decide to give up, try again another time.")
StopGame = True
Else
Say("Keep going then...")
StopGame = False
End If
'---------------------------------------------------------------------------
Case Else
Console.WriteLine("Sorry, you don't know how to " & Command & ".")
End Select
End While
Console.ReadLine()
Pascal/Delphi
// Programmed by Liam Ray PSC
procedure PlayGame(Characters: TCharacterArray; Items: TItemArray; Places: TPlaceArray);
...
else if Command = 'quit' then
begin
writeln('Are you sure (y/n)?');
valid = getInstruction;
if (valid = 'y') or (valid = 'yes') then
begin
Say('You decide to give up, try again another time');
StopGame := true;
end;
end;
...
Python
##Rahmed HGS
##Modify PlayGame subroutine
def PlayGame(Characters, Items, Places):
...
elif Command == "quit":
Say('Are you sure? (y/n)')
response = GetInstruction()
if response == 'y' or ask == 'yes':
Say("You decide to give up, try again another time.")
StopGame = True
Java
//Programmed by ya boy Arek from Kennet
//Add to playGame()
case "quit":
say("Are you sure you want to quit?");
String input = Console.readLine().toLowerCase();
if ((input.equals("y")) || (input.equals("yes"))){
say("You decide to give up, try again another time.");
stopGame = true;
} else {
say("You decide to carry on.");
}
break;
C#
//Big J messed this up how are you gonna be using ||(or) and not and && deffo btec it
case "quit":
Say("Are you sure you want to stop this game? (Y/N)");
string reply = Console.ReadLine();
if (reply=="Y"||reply=="y")
{
Say("You decide to give up, try again another time.");
stopGame = true;
}
else if (reply == "N" && reply == "n")
{
stopGame = false;
}
break;
建立“幫助 <指令>”指令,它會列出有關單個指令的詳細資訊,
如果只輸入“幫助”,就會顯示現有命令列表。
C#
// Created By Dan
static void HeNeedSomeHelp(string itemToHelp)
{
IDictionary<string, string> helpDict = new Dictionary<string, string>();
helpDict.Add("get", "Allows the user to pick up an object.\nExample use: get torch");
helpDict.Add("use", "Allows the user to use an object.\nExample use: use torch");
helpDict.Add("go", "User can move in a specified direction.\nValid movements are:\n North\n South\n East\n West\n Up\n Down\nExample use: go north");
helpDict.Add("read", "Displays contents of readable objects. Valid if the item is either in the same location as the user or in their inventory.\nExample use: read book");
helpDict.Add("examine", "Provides the user with a detailed description of the specified item. Valid if the item is either in the same location as the user or in their inventory.\nExample use: examine torch");
helpDict.Add("open", "Allows the user to open an openable object.\nExample use: open window");
helpDict.Add("close", "Allows the user to close a closeable object.\nExample use: close window");
helpDict.Add("move", "User can move the specified object. Object must be in the same location as the user.\nExample use: move bed");
helpDict.Add("say", "The user will speak the input.\nExample use: say hello : returns 'hello'");
helpDict.Add("playdice", "Allows the user to play a dice game with another character\nShould the user win, they can select an item to obtain from the character.\nShould they lose, a random item is taken from your inventory.\nCommand needs to be followed by the name of the character to play with. They must be in the same location as the user and both must have a die to play with.\nExample use: playdice guard");
bool found = false;
if (itemToHelp == "help")
{
found = true;
Console.Write("\nAvailable commands:\n");
foreach (KeyValuePair<string, string> item in helpDict)
{
Console.Write("{0}, ", item.Key);
}
}
else
{
foreach (KeyValuePair<string, string> item in helpDict)
{
if (itemToHelp == item.Key)
{
Console.Write("\nHelp for '{0}'\n{1}", itemToHelp, item.Value);
}
}
}
}
Delphi/Pascal
//insert this into the playgame procedure
else if Command = 'help' then
begin
Writeln('Instructions help:');
Write('Get: 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');
Writeln(' no longer in its original location.');
Writeln;
Write('Use: 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.');
Writeln('using a key in a room with a locked door will unlock the door (if it is the right key for that door).');
Writeln;
Writeln('Go: 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.');
Writeln;
Writeln('Read: Will display the text of objects that can be read e.g. books, notes, signs.');
Writeln;
Write('Examine: 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');
Writeln(' wants to examine. Examine inventory will display a list of the items the player is currently carrying.');
Writeln;
Writeln('Open: 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.');
Writeln;
Writeln('Close: 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.');
Writeln;
Write('Move: 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');
Writeln(' displayed on the screen.');
Writeln;
Writeln('Say: The player will speak, saying the text that follows the say command.');
Writeln;
Write('Playdice: 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');
Writeln(' 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.');
Writeln;
Writeln('Quit: Ends the game, quitting the program.');
end
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','help','quit']
print('Commands:')
for i in cmds:
print(i)
# New answer:
# Previous answers didn't really do what the question asked in terms of only
# printing out all the instructions if the user only types help. Here's a couple
# of solutions I came up with, sorry I was too lazy to do all the commands:
# (I changed the indentation so that the code is actually readable)
# In the PlayGame function
elif Command == "help":
PrintHelp(Instruction)
# For the PrintHelp routine, you can either use a dictionary or an array,
# in my opinion the dictionary is more pythonic.
def PrintHelp(Instruction):
CommandDict = {
"get": "gets an item in the current location",
"use": "uses an item in the player's inventory",
"go": "moves the player in a given direction"
}
if Instruction == "help":
for Command in CommandDict:
print(Command, ": ", CommandDict[Command])
else:
try:
print(CommandDict[Instruction])
except KeyError:
print(Instruction, " is not in the list of commands")
def PrintHelp(Instruction):
Commands = ["use", "get", "go"]
Results = ["uses an item in the player's inventory",
"gets an item in the current location",
"moves the player in a given direction"]
if Instruction == "help":
for Command, Result in zip(Commands, Results):
print(Command, ": ", Result)
else:
for Command, Result in zip(Commands, Results):
if Command == Instruction:
print(Result)
break
else:
print(Instruction, " is not in the list of commands")
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
建立“傳送 <位置>”命令。這對測試遊戲很有用。
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;
}
SOLUTION BY YUNGEN
Delphi/Pascal
function Teleport(var You: TCharacter; CurrentPlace: integer): boolean;
var
Teleported, Moved : boolean;
TeleportToLocation : integer;
begin
writeln('Where do you want to go?' +
' 1 = Blue room,' +
' 2 = Store cupboard,' +
' 3 = Bare bed room,' +
' 4 = Empty corridor,' +
' 5 = Guardroom,' +
' 6 = Flag Jail cell,' +
' 7 = Skeleton Jail cell,' +
' 8 = Cellar');
readln(TeleportToLocation);
You.CurrentLocation := TeleportToLocation;
Teleport := True;
end;
//In the PlayGame procedure:
else if Command = 'teleport' then
Moved := Teleport(Characters[0], Characters[0].CurrentLocation)
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 方法 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
建立“儲存 <檔名>”命令。儲存遊戲的當前狀態。
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;
Console.WriteLine("please enter the filename you want to save");
//empty all the space in the file name
filename = Console.ReadLine();
filename = filename.Replace(" ", String.Empty);
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.write(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
//add this section to playgame
else if Command = 'save' then
begin
Save(Characters, Items, Places,Instruction);
end
//add this section anywhere else in the program
procedure WriteInteger32(Value: Integer; var Source: File);
begin
blockwrite(Source,Value,sizeof(Value));
end;
procedure WriteString(Value: string; var Source: File);
var
Counter: Integer;
Character: Char;
begin
WriteInteger32(length(Value),Source);
for Counter := 1 to length(Value) do
begin
blockwrite(Source, Value[Counter],1);
end;
end;
procedure Save(Characters: TCharacterArray; Items: TItemArray; Places: TPlaceArray; Instruction: String);
var
Writer: File;
Counter: Integer;
TempCharacter: TCharacter;
TempItem: TItem;
TempPlace: TPlace;
begin
Assign(Writer,Instruction+'.gme');
Rewrite(Writer, 1);
WriteInteger32(length(Characters),Writer);
for TempCharacter in Characters do
begin
WriteInteger32(TempCharacter.ID,Writer);
WriteString(TempCharacter.Name,Writer);
WriteString(TempCharacter.Description,Writer);
WriteInteger32(TempCharacter.CurrentLocation,Writer);
end;
WriteInteger32(length(Places),Writer);
for TempPlace in Places do
begin
WriteInteger32(TempPlace.ID,Writer);
WriteString(TempPlace.Description,Writer);
WriteInteger32(TempPlace.North,Writer);
WriteInteger32(TempPlace.East,Writer);
WriteInteger32(TempPlace.South,Writer);
WriteInteger32(TempPlace.West,Writer);
WriteInteger32(TempPlace.Up,Writer);
WriteInteger32(TempPlace.Down,Writer);
end;
WriteInteger32(length(Items),Writer);
for TempItem in Items do
begin
WriteInteger32(TempItem.ID,Writer);
WriteString(TempItem.Description,Writer);
WriteString(TempItem.Status,Writer);
WriteInteger32(TempItem.Location,Writer);
WriteString(TempItem.Name,Writer);
WriteString(TempItem.Commands,Writer);
WriteString(TempItem.Results,Writer);
end;
close(Writer);
Writeln('File saved');
end;
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.beansget(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 Character in Characters:
pickle.dump(Character.ID,f)
pickle.dump(Character.Name,f)
pickle.dump(Character.Description,f)
pickle.dump(Character.CurrentLocation,f)
pickle.dump(len(Places),f)
for Place in Places:
pickle.dump(Place.ID,f)
pickle.dump(Place.Description,f)
pickle.dump(Place.North,f)
pickle.dump(Place.East,f)
pickle.dump(Place.South,f)
pickle.dump(Place.West,f)
pickle.dump(Place.Up,f)
pickle.dump(Place.Down,f)
pickle.dump(len(Items),f)
for Item in Items:
pickle.dump(Item.ID,f)
pickle.dump(Item.Description,f)
pickle.dump(Item.Status,f)
pickle.dump(Item.Location,f)
pickle.dump(Item.Name,f)
pickle.dump(Item.Commands,f)
pickle.dump(Item.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
新增指令,向遊戲新增一個新角色。例如“新增角色 <名稱>”。
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
//Add new function:
function NewCharacterFunc(var Characters: TCharacterArray): TCharacterArray;
var
NewCharacter : TCharacter;
LengthOfCharacters:integer;
begin
writeln('Please write the new character''s name');
readln(NewCharacter.Name);
writeln('Please write the new character''s description');
readln(NewCharacter.Description);
LengthOfCharacters := length(Characters);
NewCharacter.ID := (LengthOfCharacters+1001);
writeln('Please input the new character''s location');
readln(NewCharacter.CurrentLocation);
setlength(Characters,(LengthOfCharacters+1));
LengthOfCharacters := length(Characters);
Characters[(LengthOfCharacters)] := NewCharacter;
NewCharacterFunc := Characters
end;
//Insert in PlayGame:
else if Command = 'newcharacter' then
NewCharacterFunc(Characters)
Java
// Addition to the switch statement
switch (command)
{
case "addcharacter":
addCharacter(characters);
break;
// Add character method
void addCharacter(ArrayList<Character> characters) {
Console.print("What would you like his name to be?");
String name = Console.readLine();
Console.print("His description?");
String description = Console.readLine();
Character characterToAdd = new Character();
characterToAdd.currentLocation = characters.get(0).currentLocation;
characterToAdd.description = description;
characterToAdd.id = characters.size() -1;
characterToAdd.name = name;
Console.println(name + " has been added!");
}
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
新增“檢查房間”選項,以便再次檢視房間的詳細資訊。這相當簡單,但在開發“新增角色”或“新增物品”時是一個有用的選項。
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
//replace the start of examine with this, and add places as a parameter when calling examine
procedure Examine(Items: TItemArray; Characters: TCharacterArray; ItemToExamine: string;
CurrentLocation: integer;Places: TPlaceArray);
var
Count: integer;
IndexOfItem: integer;
begin
if ItemToExamine = 'inventory' then
DisplayInventory(Items)
else if ItemToExamine = 'room' then
begin
writeln(Places[Characters[0].CurrentLocation - 1].Description);
DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation);
//As DisplayGettableItemsInLocation is defined lower down in the file, to not cause errors it has to be moved above Examine
end
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
透過“新增物品 <名稱>”命令建立遊戲的新物品。在建立“儲存 <檔名>”選項後,此功能很有用。
C#
Delphi/Pascal
Java
Python
#Mahtab Miah Aktar HA
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)
# in playgame()
elif Command == "add":
addItem(Items)
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)
建立“丟棄 <物品>”命令,該命令會從使用者的庫存中丟棄選定的物品。
C#
// Created by Ahmed Rahi
private static void Drop(List<Item> items,string itemtodrop,int currentlocation)
{
int pos = currentlocation;
int indexofitem = GetIndexOfItem(itemtodrop, -1, items);
if(items[indexofitem].Location!=Inventory)
{
Console.WriteLine("cant drop");
} else if (items[indexofitem].Location==Inventory)
{
pos = GetPositionOfCommand(items[indexofitem].Commands, "drop");
ChangeLocationOfItem(items, indexofitem, currentlocation);
Console.WriteLine("Dropped!");
}
}
//Add this into the playgame routine
case "drop":
Drop(items, instruction, characters[0].CurrentLocation);
break;
Delphi/Pascal
//add this to PlayGame
...
else if Command = 'drop' then
DropItem(Items, Instruction, Characters[0].CurrentLocation)
...
// add this anywhere in the file above PlayGame and below ChangeLocationOfItem (under GetItem is recommended)
procedure DropItem(Items: TItemArray; ItemToDrop: string; CurrentLocation: integer);
var
IndexOfItem: integer;
begin
IndexOfItem := GetIndexOfItem(ItemToDrop, -1, Items);
if IndexOfItem = -1 then // Doesn't exist
writeln('You don''t have ', ItemToDrop, '.')
else if Items[IndexOfItem].Location <> Inventory then // Not in your inv.
writeln('You have don''t have that!')
else
begin
ChangeLocationOfItem(Items, IndexOfItem, CurrentLocation);
writeln('You have dropped the', Items[IndexOfItem].Name, '.');
end;
end;
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 dropItem(ItemToRemove, Items, PlayerLocation):
for item in Items:
if item.Location == INVENTORY and item.Name == ItemToRemove:
item.Location = PlayerLocation
print("Dropped " + item.Name)
break
print("Cannot find " + ItemToRemove + " in your inventory")
return Items
#Add into PlayGame Function
elif Command == "drop":
Items = dropItem(Instruction, Items, 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
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
顯示玩家已經進行的移動次數。這可以用於確定高分,前提是找到了旗幟。可以將高分與儲存的高分進行比較,並在當前高分更高時更新。
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
//Make changes to GetItem
procedure GetItem(Items: TItemArray; ItemToGet: string; CurrentLocation: integer; NumOfTurns: integer;
SavedScore : string; var StopGame : boolean);
var
ResultForCommand: string;
SubCommand: string;
SubCommandParameter: string;
IndexOfItem: integer;
Position: integer;
CanGet: boolean;
strNumOfTurns : string;
Score : TextFile;
begin
SubCommand := '';
SubCommandParameter := '';
CanGet := false;
IndexOfItem := GetIndexOfItem(ItemToGet, -1, Items);
if IndexOfItem = -1 then
writeln('You can''t find ', ItemToGet, '.')
else if Items[IndexOfItem].Location = Inventory then
writeln('You have already got that!')
else if pos('get', Items[IndexOfItem].Commands) = 0 then
writeln('You can''t get ', ItemToGet, '.')
else if (Items[IndexOfItem].Location >= MinimumIDForItem) and (Items[GetIndexOfItem('', Items[
IndexOfItem].Location, Items)].Location <> CurrentLocation) then
writeln('You can''t find ', ItemToGet, '.')
else if (Items[IndexOfItem].Location < MinimumIDForItem) and (Items[IndexOfItem].Location <>
CurrentLocation) then
writeln('You can''t find ', ItemToGet, '.')
else
CanGet := true;
if CanGet then
begin
Position := GetPositionOfCommand(Items[IndexOfItem].Commands, 'get');
ResultForCommand := GetResultForCommand(Items[IndexOfItem].Results, Position);
ExtractResultForCommand(SubCommand, SubCommandParameter, ResultForCommand);
if SubCommand = 'say' then
Say(SubCommandParameter)
else if SubCommand = 'win' then
begin
say('You have won the game');
strNumOfTurns := inttostr(NumOfTurns);
writeln('Your score was '+strNumOfTurns);
StopGame := true;
if NumOfTurns < integer(SavedScore) then
begin
assignfile(Score,'score.txt');
rewrite(Score);
writeln(Score,NumOfTurns);
closefile(Score);
end;
exit;
end;
if pos('gettable', Items[IndexOfItem].Status) <> 0 then
begin
ChangeLocationOfItem(Items, IndexOfItem, Inventory);
writeln('You have got that now.');
end;
end;
end;
//Make changes to PlayGame
procedure PlayGame(Characters: TCharacterArray; Items: TItemArray; Places: TPlaceArray; NumOfTurns : integer);
var
StopGame: boolean;
Instruction: string;
Command: string;
SavedScore : string;
strNumOfTurns : string;
Moved: boolean;
ResultOfOpenClose : integer;
Score : Textfile;
begin
AssignFile(Score,'score.txt');
Reset(Score);
if Not EoF(Score) then
begin
read(Score,SavedScore);
writeln('The current High Score is '+SavedScore);
CloseFile(Score);
end;
StopGame := false;
Moved := true;
NumOfTurns := 0;
while not StopGame do
begin
if Moved then
begin
writeln;
writeln;
writeln(Places[Characters[0].CurrentLocation - 1].Description);
DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation);
Moved := false;
end;
strNumOfTurns := inttostr(NumOfTurns);
writeln('Turns = '+strNumOfTurns);
Instruction := GetInstruction;
Command := ExtractCommand(Instruction);
if Command = 'get' then
begin
GetItem(Items, Instruction, Characters[0].CurrentLocation, NumOfTurns, SavedScore, StopGame);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'use' then
begin
UseItem(Items, Instruction, Characters[0].CurrentLocation, StopGame, Places);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'go' then
begin
Moved := Go(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1]);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'read' then
begin
ReadItem(Items, Instruction, Characters[0].CurrentLocation);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'examine' then
begin
Examine(Items, Characters, Instruction, Characters[0].CurrentLocation);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'open' then
begin
ResultOfOpenClose := OpenClose(true, Items, Places, Instruction, Characters[0].CurrentLocation);
DisplayOpenCloseMessage(ResultOfOpenClose, true);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'close' then
begin
ResultOfOpenClose := OpenClose(false, Items, Places, Instruction, Characters[0].CurrentLocation);
DisplayOpenCloseMessage(ResultOfOpenClose, false);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'move' then
begin
MoveItem(Items, Instruction, Characters[0].CurrentLocation);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'say' then
begin
Say(Instruction);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'playdice' then
begin
PlayDiceGame(Characters, Items, Instruction);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'teleport' then
begin
Moved := Teleport(Characters[0], Characters[0].CurrentLocation);
NumOfTurns := NumOfTurns + 1;
end
else if Command = 'quit' then
begin
Say('You decide to give up, try again another time');
StopGame := true;
end
else
begin
writeln('Sorry, you don''t know how to ', Command, '.');
end;
end;
readln;
end;
//Make changes to Main
procedure Main;
var
Filename: string;
Items: TItemArray;
Characters: TCharacterArray;
Places: TPlaceArray;
NumOfTurns : integer;
begin
write('Enter filename> ');
readln(Filename);
Filename := Filename + '.gme';
writeln;
if LoadGame(Filename, Characters, Items, Places) then
PlayGame(Characters, Items, Places, NumOfTurns)
else
begin
writeln('Unable to load game.');
readln;
end;
end;
begin
randomize;
Main;
end.
Java
class GenerateUI<Integer>{
Integer information;
public GenerateUI(Integer input) {
information = input;
DisplayInfo();
}
public void DisplayInfo(){
Console.writeLine("Moves: " + information.toString() + System.lineSeparator());
}
}
Integer numMoves = 0;
while (!stopGame) {
if (moved) {
Console.writeLine();
Console.writeLine();
numMoves++;
GenerateUI<Integer> movesUI = new GenerateUI<Integer>(numMoves);
Console.writeLine(places.get(characters.get(0).currentLocation - 1).description);
displayGettableItemsInLocation(items, characters.get(0).currentLocation);
moved = false;
}
Python
#MS Maqsud HGS (edited by OGI)
#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()
# No need to create a text file, checks to see if one is there, if not games is played and one is made
def PlayGame(Characters, Items, Places):
try:
score = open("HighScore.txt")
currentHighScore = score.read()
except:
movesTaken = 0
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":
if Instruction == "torch":
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, Places)
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":
movesTaken -= 1
Say("You decide to give up, try again another time.")
StopGame = True
elif Command == "eat":
Items = eat(Instruction, Items)
elif Command == "additem":
Items = addItem(Items)
else:
movesTaken -= 1
print("Sorry, you don't know how to " + Command + ".")
movesTaken += 1
print("moves taken", str(movesTaken))
score = open("HighScore.txt", "w")
score.write(str(movesTaken))
score.close()
input()
# Made by the Greenhead Gang - Ben R
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
防止守衛在你輸掉時拿走骰子。或者重新開始遊戲。
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
//this requires StrUtils being included, so change the uses section to
uses
SysUtils,StrUtils;
//replace the current TakeRandomItemFromPlayer procedure with this
procedure TakeRandomItemFromPlayer(Items: TItemArray; OtherCharacterID: integer);
var
ListOfIndicesOfItemsInInventory: array of integer;
Count: integer;
rno: integer;
ArrayLength: integer;
begin
ArrayLength := 0;
Count := 0;
while Count < length(Items) do
begin
if Items[Count].Location = Inventory then
begin
if (not(ContainsText(Items[Count].Name,'die'))) then
begin
inc(ArrayLength);
SetLength(ListOfIndicesOfItemsInInventory, ArrayLength);
ListOfIndicesOfItemsInInventory[ArrayLength - 1] := Count;
end;
end;
inc(Count);
end;
if(length(ListOfIndicesOfItemsInInventory) > 0) then
begin
rno := GetRandomNumber(0, length(ListOfIndicesOfItemsInInventory) - 1);
writeln('They have taken your ', Items[ListOfIndicesOfItemsInInventory[rno]].Name, '.');
ChangeLocationOfItem(Items, ListOfIndicesOfItemsInInventory[rno], OtherCharacterID);
end
else
Writeln('You have no items for the guard to take');
end;
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
#by OllyGoodyIndustries
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
建立“時間”命令。它應該告訴你你已經玩了多少分鐘。或者,每次你從一個房間移動到另一個房間時,都會新增你在遊戲中的時間(例如多少分鐘)。**注意:**我懷疑他們會要求你這樣做,因為在某些語言中這很簡單,而在其他語言中則更難。更現實的是,它可能會要求你計算玩家在整個遊戲中輸入的指令數量。
C#
//add to top of playgame
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
//add the time and change the get cases switch
case "time":
Console.WriteLine("Time elapsed: {0:hh\\:mm\\:ss}", sw.Elapsed);
break;
case "get":
GetItem(items, instruction, characters[0].CurrentLocation, ref stopGame, sw);
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.");
}
}
}
//code was made by RSFC gang
Delphi/Pascal
procedure DisplayTime(Start:TDateTime);
var
Total :TDateTime;
begin
Total := TDateTime(Now) - Start;
writeln('Game Time: ' , TimeToStr(Total));
readln;
end;
procedure PlayGame(Characters: TCharacterArray; Items: TItemArray; Places: TPlaceArray);
var
StopGame: boolean;
Instruction: string;
Command: string;
Moved: boolean;
ResultOfOpenClose: integer;
Start:Tdatetime;
begin
Start:= tdatetime(now);
StopGame := false;
Moved := true;
while not StopGame do
begin
if Moved then
begin
writeln;
writeln;
writeln(Places[Characters[0].CurrentLocation - 1].Description);
DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation);
Moved := false;
end;
Instruction := GetInstruction;
Command := ExtractCommand(Instruction);
if Command = 'get' then
GetItem(Items, Instruction, Characters[0].CurrentLocation, StopGame,Start)
else if Command = 'use' then
UseItem(Items, Instruction, Characters[0].CurrentLocation, StopGame, Places)
else if Command = 'go' then
Moved := Go(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1],start)
else if Command = 'read' then
ReadItem(Items, Instruction, Characters[0].CurrentLocation)
else if Command = 'examine' then
Examine(Items, Characters, Instruction, Characters[0].CurrentLocation,Places)
else if Command = 'open' then
begin
ResultOfOpenClose := OpenClose(true, Items, Places, Instruction, Characters[0].CurrentLocation);
DisplayOpenCloseMessage(ResultOfOpenClose, true);
end
else if Command = 'close' then
begin
ResultOfOpenClose := OpenClose(false, Items, Places, Instruction, Characters[0].CurrentLocation);
DisplayOpenCloseMessage(ResultOfOpenClose, false);
end
else if Command = 'move' then
MoveItem(Items, Instruction, Characters[0].CurrentLocation)
else if Command = 'say' then
Say(Instruction)
else if Command = 'playdice' then
PlayDiceGame(Characters, Items, Instruction)
else if Command = 'quit' then
begin
Say('You decide to give up, try again another time');
StopGame := true;
DisplayTime(Start);
end
else
begin
writeln('Sorry, you don''t know how to ', Command, '.')
end;
end;
readln;
end;
// for it to work in Delphi 7 you need to put the DisplayTime procedure abit further up the page.
//Made by Jobless Programmmer :)
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
限制可以新增到庫存中的物品數量 SM HGS,難度:老手
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");
}
Delphi/Pascal
//replace the constants section at the start with this
const
Inventory: Integer = 1001;
MaxInventorySize: Integer = 6;
MinimumIDForItem: Integer = 2001;
IDDifferenceForObjectInTwoLocations: Integer = 10000;
//replace the GetItem procedure with this
procedure GetItem(Items: TItemArray; ItemToGet: string; CurrentLocation: integer; var StopGame:
boolean);
var
ResultForCommand: string;
SubCommand: string;
SubCommandParameter: string;
IndexOfItem: integer;
Position: integer;
CanGet: boolean;
NoOfItems: Integer;
TempItem: TItem;
begin
NoOfItems := 0;
for TempItem in Items do
begin
If(TempItem.Location = Inventory) then
NoOfItems := NoOfItems+1;
end;
if(NoOfItems < MaxInventorySize)then
begin
SubCommand := '';
SubCommandParameter := '';
CanGet := false;
IndexOfItem := GetIndexOfItem(ItemToGet, -1, Items);
if IndexOfItem = -1 then
writeln('You can''t find ', ItemToGet, '.')
else if Items[IndexOfItem].Location = Inventory then
writeln('You have already got that!')
else if pos('get', Items[IndexOfItem].Commands) = 0 then
writeln('You can''t get ', ItemToGet, '.')
else if (Items[IndexOfItem].Location >= MinimumIDForItem) and (Items[GetIndexOfItem('', Items[
IndexOfItem].Location, Items)].Location <> CurrentLocation) then
writeln('You can''t find ', ItemToGet, '.')
else if (Items[IndexOfItem].Location < MinimumIDForItem) and (Items[IndexOfItem].Location <>
CurrentLocation) then
writeln('You can''t find ', ItemToGet, '.')
else
CanGet := true;
if CanGet then
begin
Position := GetPositionOfCommand(Items[IndexOfItem].Commands, 'get');
ResultForCommand := GetResultForCommand(Items[IndexOfItem].Results, Position);
ExtractResultForCommand(SubCommand, SubCommandParameter, ResultForCommand);
if SubCommand = 'say' then
Say(SubCommandParameter)
else if SubCommand = 'win' then
begin
say('You have won the game');
StopGame := true;
exit;
end;
if pos('gettable', Items[IndexOfItem].Status) <> 0 then
begin
ChangeLocationOfItem(Items, IndexOfItem, Inventory);
writeln('You have got that now.');
end;
end;
end
else
Writeln('You are carrying too many items');
end;
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
man lyk 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
所有可獲取的物品都屬於“微型”、“小型”或“中型”。引入一個“稱重庫存”子程式。微型 = 重量 1,小型 = 重量 2,中型 = 重量 3。只有在物品不會使庫存重量超過 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
//---------------------- Inv. Size Mod Start ----------------------
function getItemWeight(Item: TItem): integer;
begin
if Item.Status.Contains('tiny') then getItemSize := 1
else if Item.Status.Contains('small') then getItemSize := 2
else if Item.Status.Contains('medium') then getItemSize := 3
else if Item.Status.Contains('large') then getItemSize := 5
else getItemSize := 0;
end;
function weighInventory(Items: TItemArray):boolean;
var
Item: TItem;
begin
result := 0;
for Item in Items do
if Item.Location = Inventory then
inc(result, getItemSize(Item));
end;
//---------------------- Inv. Size Mod End ----------------------
procedure GetItem(Items: TItemArray; ItemToGet: string; CurrentLocation: integer; var StopGame:
boolean);
...
else if (Items[IndexOfItem].Location < MinimumIDForItem) and (Items[IndexOfItem].Location <>
CurrentLocation) then
writeln('You can''t find ', ItemToGet, '.')
//---------------------- Inv. Size Mod Start ----------------------
else if (weighInventory(Items) + getItemSize(Items[IndexOfItem]) > MaxInventoryCapacity) then
writeln('Your inventory is too full')
//---------------------- Inv. Size Mod End ----------------------
else
CanGet := true;
...
Java
//This method takes an item and returns its weight
int itemWeight(Item item)
{
int weight = 0;
if(item.status.contains("tiny"))
{
weight = 1;
}
else if(item.status.contains("small"))
{
weight = 2;
}
else if(item.status.contains("medium"))
{
weight = 3;
}
else
{
weight = 4;
}
return weight;
}
//Iterates through the list of items, incrementing a weight variable each time an item in the inventory is found
boolean checkInventoryWeight(ArrayList<Item> items, Item thisItem)
{
int inventoryWeight = 0;
for(Item item : items)
{
if(item.location == INVENTORY)
{
inventoryWeight += itemWeight(item);
}
}
int itemWeight = itemWeight(thisItem);
//Checks if adding the new item to the inventory would raise the weight over the limit. 10 has been used rather than the 7 stated in the question since the initial weight of the inventory in the flag2 game is 10
if(itemWeight + inventoryWeight <= 10)
{
return true;
}
else
{
say("You can't take that item, your inventory is too heavy.");
return false;
}
}
//Alter the 'else' statement in 'getItem'
boolean getItem(ArrayList<Item> items, String itemToGet, int currentLocation) {
...
else
{
canGet = checkInventoryWeight(items, thisItem);
}
....
}
//Alter 'takeItemFromOtherCharacter' so that, if the dice game is won, an item can only be taken if the inventory has space
void takeItemFromOtherCharacter(ArrayList<Item> items, int otherCharacterID) {
...
if (listOfNamesOfItemsInInventory.contains(chosenItem)) {
int pos = listOfNamesOfItemsInInventory.indexOf(chosenItem);
boolean canGet = checkInventoryWeight(items,items.get(listOfIndicesOfItemsInInventory.get(pos)));
if(canGet)
{
changeLocationOfItem(items, listOfIndicesOfItemsInInventory.get(pos), INVENTORY);
Console.writeLine("You have that now.");
}
} else {
Console.writeLine("They don't have that item, so you don't take anything this time.");
}
}
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
用武器狀態的物品攻擊守衛(或房間中的任何角色),然後從他們身上拿走物品。
C#
#in the PlayGame function
case "hit":
UseWeapon(characters, items, instruction);
break;
#new UseWeapon function
private static void UseWeapon(List<Character> characters, List<Item> items, string CharacterToAttack)
{
bool PlayerHasWeapon = false;
bool PlayersInSameRoom = false;
int IndexOfPlayerWeapon = -1;
foreach (var Thing in items)
{
if ((Thing.Location == Inventory) && ( true == Thing.Status.Contains("weapon")))
{
PlayerHasWeapon = true;
IndexOfPlayerWeapon = GetIndexOfItem("", Thing.ID, items);
}
}
int count = 1;
while ((count < characters.Count) && (!PlayersInSameRoom))
{
if ((characters[0].CurrentLocation == characters[count].CurrentLocation) && (characters[count].Name == CharacterToAttack))
{
PlayersInSameRoom = true;
count++;
}
}
int indexOfOtherCharacter = 0;
count = 0;
while (count < characters.Count)
{
if (characters[count].Name == CharacterToAttack)
{
indexOfOtherCharacter = count;
}
count++;
}
if ((PlayerHasWeapon == true) && (PlayersInSameRoom == true))
{
Console.WriteLine("You hit " + CharacterToAttack);
TakeItemFromOtherCharacter(items, characters[indexOfOtherCharacter].ID);
}
else
{
Console.WriteLine("You can't hit");
}
}
Delphi/Pascal
function CheckIfAttackPossible(Items: TItemArray; Characters: TCharacterArray; var
IndexOfPlayerWeapon: integer; var IndexOfOtherCharacter: integer;
OtherCharacterName: string): boolean;
var
PlayerHasWeapon: boolean;
PlayersInSameRoom: boolean;
Count: Integer;
Thing: TItem;
begin
PlayerHasWeapon := false;
PlayersInSameRoom := false;
for Thing in Items do
begin
if (Thing.Location = Inventory) and (pos('weapon', Thing.Status) <> 0) then
begin
PlayerHasWeapon := true;
IndexOfPlayerWeapon := GetIndexOfItem('', Thing.ID, Items);
end;
end;
Count := 1;
while (Count < length(Characters)) and (not PlayersInSameRoom) do
begin
if (Characters[0].CurrentLocation = Characters[Count].CurrentLocation) and (Characters[Count].Name = OtherCharacterName) then
begin
PlayersInSameRoom := true;
IndexOfOtherCharacter := Count;
end;
inc(Count);
end;
CheckIfAttackPossible := (PlayerHasWeapon and PlayersInSameRoom);
end;
procedure Hit(Characters: TCharacterArray; Items: TItemArray; OtherCharacterName: string);
var
IndexOfPlayerWeapon: integer;
IndexOfOtherCharacter: integer;
AttackPossible: boolean;
begin
AttackPossible := CheckIfAttackPossible(Items, Characters, IndexOfPlayerWeapon,
IndexOfOtherCharacter, OtherCharacterName);
if not AttackPossible then
writeln('You can''t hit anyone.')
else
begin
writeln('You hit ' + OtherCharacterName + '!');
TakeItemFromOtherCharacter(Items, Characters[IndexOfOtherCharacter].ID);
end;
end;
...
// In PlayGame
else if Command = 'hit' then
Hit(Characters, Items, Instruction)
Java
void hitPlayer(ArrayList<Item> items, ArrayList<Character> characters, String victimName, int currentLocation)
{
boolean inSameRoom = false, hasWeapon = false;
Character victim = new Character();
Item weapon = new Item();
//Checks if the character you want to hit is in the same room as you
for(Character character: characters)
{
if(character.name.equals(victimName) && character.currentLocation == currentLocation)
{
inSameRoom = true;
victim = character;
}
}
if(inSameRoom)
{
for(Item item:items)
{
//Checks if you have a weapon in your inventory
if(item.status.contains("weapon") && item.location == INVENTORY)
{
hasWeapon = true;
weapon = item;
}
}
//If you have a weapon, you hit the victim and take an item from them
if(hasWeapon)
{
say("You have hit " + victimName + " with the " + weapon.name);
takeItemFromOtherCharacter(items, victim.id);
}
else
{
say("You don't have anything to hit " + victimName + " with.");
}
}
}
//Adds hit to the list of commands
void playGame(ArrayList<Character> characters, ArrayList<Item> items, ArrayList<Place> places) {
...
case "hit":
hitPlayer(items, characters, instruction, characters.get(0).currentLocation);
break;
...
}
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("Spank Me Harder Daddy!")
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
'New sub for using a weapon to take out another character
'using playdice sub as a template
Sub Attack(ByVal Characters As ArrayList, ByVal items As ArrayList, ByVal OtherCharacterName As String)
Dim IndexOfPlayerWeapon, IndexOfOtherCharacter, IndexOfOtherCharacterWeapon As Integer
Dim AttackPossible As Boolean = CheckIfAttackPossible(items, Characters, IndexOfPlayerWeapon, IndexOfOtherCharacter, IndexOfOtherCharacterWeapon, OtherCharacterName)
Dim Count As Integer = 1
While Count < Characters.Count
If Characters(0).CurrentLocation = Characters(Count).CurrentLocation And Characters(Count).Name = OtherCharacterName Then
IndexOfOtherCharacter = Count
End If
Count += 1
End While
If AttackPossible = True Then
Dim NewStatus As String = "unconscious"
ChangeStatusOfCharacter(Characters, IndexOfOtherCharacter, NewStatus)
Say("You knock the guard out!")
For Thing = 0 To items.Count - 1
If items(Thing).Location = Characters(IndexOfOtherCharacter).ID Then
ChangeLocationOfItem(items, Thing, Characters(IndexOfOtherCharacter).Currentlocation)
End If
Next
DisplayGettableItemsInLocation(items, Characters(0).CurrentLocation)
End If
End Sub
'Create this copy of change status of item then change all the variables to apply for characters instead
'This is because it doesnt like you changing single variables of objects once they are "made"
Sub ChangeStatusOfCharacter(ByVal Characters As ArrayList, ByVal IndexOfCharacter As Integer, ByVal NewStatus As String)
Dim ThisCharacter As Character = Characters(IndexOfCharacter)
ThisCharacter.Status = NewStatus
Characters(IndexOfCharacter) = ThisCharacter
End Sub
Function CheckIfAttackPossible(ByVal Items As ArrayList, ByVal Characters As ArrayList, ByRef IndexOfPlayerWeapon As Integer, ByRef IndexOfOtherCharacter As Integer, ByRef IndexOfOtherCharacterWeapon As Integer, ByVal OtherCharacterName As String) As Boolean
Dim PlayerHasWeapon As Boolean = False
Dim PlayersInSameRoom As Boolean = False
Dim OtherCharacterIsDefenceless As Boolean = True
For Each Thing In Items
If Thing.Location = Inventory And Thing.status.contains("weapon") Then
PlayerHasWeapon = True
IndexOfPlayerWeapon = GetIndexOfItem("", Thing.ID, Items)
End If
Next
Dim Count As Integer = 1
While Count < Characters.Count And Not PlayersInSameRoom
'Also need to add the check if the other character is unconscious to other subs so that it isnt possible to do all other things to an unconscious character
If Characters(0).CurrentLocation = Characters(Count).CurrentLocation And Characters(Count).Name = OtherCharacterName And Characters(Count).Status.contains("unconsious") = False Then
PlayersInSameRoom = True
For Each Thing In Items
If Thing.Location = Characters(Count).ID And Thing.status.contains("weapon") Then
OtherCharacterIsDefenceless = False
IndexOfOtherCharacterWeapon = GetIndexOfItem("", Thing.ID, Items)
IndexOfOtherCharacter = Count
End If
Next
End If
Count += 1
End While
'Adding specific messages or what is wrong if one of the conditions is false
If PlayersInSameRoom = False Then
Say("There is nobody to attack.")
ElseIf PlayerHasWeapon = False Then
Say("You dont have a weapon to attack them with.")
ElseIf OtherCharacterIsDefenceless = False Then
Say("They dont look like they'll go down without a fight...")
End If
Return PlayerHasWeapon And PlayersInSameRoom And OtherCharacterIsDefenceless
End Function
'Obviously this section also needs to be added to the playgame sub so attack can be called
'Attack command
Case "attack"
Attack(Characters, Items, Instruction)
'Changes to other subs so unconscious characters cant play dice etc.
Function CheckIfDiceGamePossible(ByVal Items As ArrayList, ByVal Characters As ArrayList, ByRef IndexOfPlayerDie As Integer, ByRef IndexOfOtherCharacter As Integer, ByRef IndexOfOtherCharacterDie As Integer, ByVal OtherCharacterName As String) As Boolean
Dim PlayerHasDie As Boolean = False
Dim PlayersInSameRoom As Boolean = False
Dim OtherCharacterHasDie As Boolean = False
For Each Thing In Items
If Thing.Location = Inventory And Thing.name.contains("die") Then
PlayerHasDie = True
IndexOfPlayerDie = GetIndexOfItem("", Thing.ID, Items)
End If
Next
Dim Count As Integer = 1
While Count < Characters.Count And Not PlayersInSameRoom
'added to check if guard is unconsious so they cant play dice with an unconsious guard lol
If Characters(0).CurrentLocation = Characters(Count).CurrentLocation And Characters(Count).Name = OtherCharacterName And Characters(Count).Status.contains("unconscious") = False Then
PlayersInSameRoom = True
For Each Thing In Items
If Thing.Location = Characters(Count).ID And Thing.name.contains("die") Then
OtherCharacterHasDie = True
IndexOfOtherCharacterDie = GetIndexOfItem("", Thing.ID, Items)
IndexOfOtherCharacter = Count
End If
Next
End If
Count += 1
End While
Return PlayerHasDie And PlayersInSameRoom And OtherCharacterHasDie
End Function
Sub Examine(ByVal Items As ArrayList, ByVal Places As ArrayList, ByVal Characters As ArrayList, ByVal ItemToExamine As String, ByVal CurrentLocation As Integer)
Dim Count As Integer = 0
If ItemToExamine = "inventory" Then
DisplayInventory(Items)
'not cleanest solution but will print a description of the room.
'didnt like using "moved" as they havent got moved and that would put code in playgame sub
ElseIf ItemToExamine = "room" Then
Console.WriteLine()
Console.WriteLine()
Console.WriteLine(Places(Characters(0).CurrentLocation - 1).Description)
DisplayGettableItemsInLocation(Items, Characters(0).CurrentLocation)
Else
Dim IndexOfItem As Integer = GetIndexOfItem(ItemToExamine, -1, Items)
If IndexOfItem <> -1 Then
If Items(IndexOfItem).Name = ItemToExamine And (Items(IndexOfItem).Location = Inventory Or Items(IndexOfItem).Location = CurrentLocation) Then
Console.WriteLine(Items(IndexOfItem).Description)
If Items(IndexOfItem).Name.Contains("door") Then
DisplayDoorStatus(Items(IndexOfItem).Status)
End If
If Items(IndexOfItem).Status.Contains("container") Then
DisplayContentsOfContainerItem(Items, Items(IndexOfItem).ID)
End If
Exit Sub
End If
End If
While Count < Characters.Count
If Characters(Count).Name = ItemToExamine And Characters(Count).CurrentLocation = CurrentLocation Then
Console.WriteLine(Characters(Count).Description)
'Adds flavour text / help text if the guard is unconsious
If Characters(Count).Status.contains("unconscious") = True Then
Console.WriteLine("The " & Characters(Count).name & " is unconscious")
End If
Exit Sub
End If
Count += 1
End While
Console.WriteLine("You cannot find " & ItemToExamine & " to look at.")
End If
End Sub
為角色新增一個“生命值”屬性,該屬性可以在程式碼中更改(或者可以新增一個命令供使用者更改它)。
建立一個攻擊系統,該系統會給玩家和角色一個百分比的機會,如果被擊中就會從他們的生命值中扣除一個。
如果玩家死亡,遊戲結束。如果其他角色死亡,他們的物品會掉落在戰鬥發生的房間裡。
C#
Delphi/Pascal
Java
Python
# Made by maxmontygom
# New subroutines
def Attack(Characters, Items, CharacterToHit):
StopGame = False
CharacterCanAttack = True
print()
AttackPossible = CheckIfAttackPossible(Items, Characters, CharacterToHit)
if not AttackPossible:
print("Maybe you can try another time...")
print()
if AttackPossible:
for Character in Characters:
if Character.Name == CharacterToHit:
CharacterToHit = Character
RandomNumber = GetRandomNumber(0, 10)
if RandomNumber <= 5:
CharacterToHit.Health -= 1
print("You hit the", CharacterToHit.Name, "and they lost 1 health!")
print("They now have", CharacterToHit.Health, "health")
if CharacterToHit.Health == 0:
CharacterCanAttack = False
print("You killed them!")
print("All their items scatter across the floor...")
Items, Characters = DeadCharacter(Items, Characters, Character)
else:
print("You missed!")
if CharacterCanAttack:
RandomNumber = GetRandomNumber(0, 10)
if RandomNumber <= 5:
Characters[0].Health -= 1
print("They hit you and you lost 1 health!")
print("You now have", Characters[0].Health, "health")
if Characters[0].Health == 0:
print("They killed you! So much for an easy game...")
print("Press enter to end the game")
StopGame = True
else:
print("They missed!")
return StopGame, Items, Characters
def CheckIfAttackPossible(Items, Characters, CharacterToHit):
PlayerHasWeapon = False
CharactersInSameRoom = False
for Item in Items:
if Item.Location == INVENTORY and "weapon" in Item.Status:
PlayerHasWeapon = True
Count = 1
while Count < len(Characters) and not CharactersInSameRoom:
if Characters[0].CurrentLocation == Characters[Count].CurrentLocation and Characters[Count].Name == CharacterToHit:
CharactersInSameRoom = True
Count += 1
if not PlayerHasWeapon:
print("You don't have a weapon to use!")
if not CharactersInSameRoom:
print("You're not even in the same room!")
return (PlayerHasWeapon and CharactersInSameRoom)
def DeadCharacter(Items, Characters, DeadCharacter):
for Item in Items:
if Item.Location == DeadCharacter.ID:
Item.Location = Characters[0].CurrentLocation
DeadCharacter.CurrentLocation = 9
return Items, Characters
# New addition to PlayGame()
elif Command == "hit":
StopGame, Items, Characters = Attack(Characters, Items, Instruction)
# New addition to LoadGame()
TempCharacter.CurrentLocation = pickle.load(f)
TempCharacter.Health = 3
Characters.append(TempCharacter)
VB.NET
== 建立一個動態地圖 == 真是太難了 建立一個地圖,顯示使用者的當前位置,以及他們相對於自己位置的已訪問區域。
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
在遊戲開始時,角色攜帶一個蘋果。允許他們吃掉它。也許引入一個能量屬性,這樣他們就必須吃掉它才能繼續(這似乎不太可能,因為修改記錄結構沒有任何意義,因為檔案可能無法正常工作)。
C#
//Add to play game
// Add Snap, jake-ormerod13
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);
}
}
Java
//Add a health attribute to the character class, so eating has a purpose
class Character {
String name, description;
int id, currentLocation, '''health = 10''';
}
void eatItem(ArrayList<Item> items,ArrayList<Character> characters, String itemToEat) {
int indexOfItem;
indexOfItem = getIndexOfItem(itemToEat, -1, items);
if (indexOfItem != -1) {
//If the user has an edible item, i.e. the apple, in their inventory, they eat it.
//If the player had less than full health, they regained full health.
if (items.get(indexOfItem).location == INVENTORY && items.get(indexOfItem).status.contains("edible"))
{
say("You have eaten the " + itemToEat + " and regained your health.");
characters.get(0).health = 10;
items.remove(indexOfItem);
}
else
{
say("You don't have that item to eat");
}
}
else
{
say("You don't have that item to eat");
}
}
void playGame(ArrayList<Character> characters, ArrayList<Item> items, ArrayList<Place> places) {
...
case "eat":
eatItem(items, characters, instruction);
break;
...
}
Delphi/Pascal
procedure EatItem(Items: TItemArray; ItemToEat: string);
var
IndexOfItem: integer;
Item: TItem;
begin
IndexOfItem := getIndexOfItem(ItemToEat, -1, Items);
if IndexOfItem = -1 then
writeln('You don''t have ', ItemToEat, '.')
else if Items[IndexOfItem].Location <> Inventory then // Not in inv.
writeln('You have don''t have that!')
else if not Items[IndexOfItem].Status.Contains('edible') then
writeln('You can''t eat that!')
else
begin
Items[IndexOfItem].Location := 0;
writeln('Eaten '+ItemToEat);
end;
end;
...
// Add to main
else if Command = 'eat' then
EatItem(Items, Instruction)
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
遊戲開始時,角色會攜帶一個燒瓶。有一個水桶。允許他們從水桶裡喝水。
C#
Delphi/Pascal
// add this to PlayGame
else if Command = 'drink' then
Drink(Instruction, Items, Characters[0])
//add this above the PlayGame procedure
procedure Drink(Instruction: string; Items: TItemArray; You: TCharacter);
var
Counter : Integer;
Drunk: Boolean;
Found : Boolean;
begin
Drunk := False;
Found := False;
for Counter := 0 to length(Items)-1 do
begin
if (lowercase(Items[Counter].Name) = Instruction) then
begin
if ((Items[Counter].Location = Inventory) or (Items[Counter].Location = You.CurrentLocation)) then
begin
Found := True;
if((Instruction = 'flask') or (Instruction = 'barrel')) then
Drunk := True;
end;
end;
end;
if(Drunk) then
Writeln('You drunk from the ', Instruction)
else if (Found) then
Writeln('You can''t drink from the ', Instruction)
else
Writeln('You couldn''t find the ', Instruction,' to drink from');
end;
Java
Python
# 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
Python [帶有“Fill <item>” 命令]
# The second Drink subroutine.
# Use this only if my Fill subroutine has been implemented
# Written by maxmontygom
# New subroutine
def Drink(Characters, Items, Places, ItemToDrink):
if ItemToDrink == "barrel":
if Characters[0].CurrentLocation == 8:
print("You drank from the barrel")
else:
print("You aren't near a barrel to drink from from.")
else:
PlayerHasItem = False
for Item in Items:
if Item.Name == ItemToDrink and "of water" in Item.Name and Item.Location == INVENTORY:
print("You drank from the", ItemToDrink)
Item.Name = ItemToDrink.replace(" of water", "")
PlayerHasItem = True
if PlayerHasItem == False:
print("You cannot drink from", ItemToDrink)
return Items
# New addition to PlayGame()
elif Command == "drink":
Drink(Characters, Items, Places, Instruction)
VB.NET
新增“Fill <item>” 命令
[edit | edit source]允許你用水裝滿燒瓶。
只能裝滿空的容器,你必須擁有該物品並在地下室才能裝滿它。
C#
//first alter the ChangeStatusOfItem subroutine slightly
private static void ChangeStatusOfItem(List<Item> items, int indexOfItem, string newStatus)
{
Item thisItem = items[indexOfItem];
//change this line to add the new status of the item after you fill it
thisItem.Status = thisItem.Status + "," + newStatus;
items[indexOfItem] = thisItem;
}
private static void FillItem(List<Item> items, string itemToFill, int currentLocation)
{
int indexOfItem = GetIndexOfItem(itemToFill, -1, items);
if (indexOfItem != -1)
{
if (items[indexOfItem].Location == Inventory)
{
if (items[indexOfItem].Status.Contains("container"))
{
if (!items[indexOfItem].Status.Contains("filled"))
{
if (currentLocation == 8)
{
ChangeStatusOfItem(items, indexOfItem, "filled");
Console.WriteLine("Your {0} is now filled.", itemToFill);
}
else
{
Console.WriteLine("You can't find anything to fill the {0} with.", itemToFill);
}
}
else
{
Console.WriteLine("That container is already filled.");
}
}
else
{
Console.WriteLine("You can't fill the {0}.", itemToFill);
}
}
else
{
Console.WriteLine("You don't have {0} to fill.", itemToFill);
}
}
else
{
Console.WriteLine("You can't find {0} to fill.", itemToFill);
}
}
//add a new case to the PlayGame subroutine
case "fill":
FillItem(items, instruction, characters[0].CurrentLocation);
break;
//Kacper Wojdyla
Delphi/Pascal
Java
// Method to fill the flask
boolean fillFlask (Character you, ArrayList<Item> items) {
int indexOfFlask = getIndexOfItem("flask", -1, items);
if (items.get(indexOfFlask).location > 1000 && items.get(indexOfFlask).location < 2000) {
System.out.println(items.get(indexOfFlask).status);
if (items.get(indexOfFlask).status.contains("full")) {
return false;
} else {
items.get(indexOfFlask).status += ",full";
return true;
}
} else {
return false;
}
}
// Addition to the switch statement
switch (command)
{
case "fill":
boolean filledOrNot = fillFlask(characters.get(0), items);
if(filledOrNot == true) {
System.out.println("Flask has been filled!");
} else {
System.out.println("Flask is full!");
}
break;
Python
# If using this subroutine, use the Drink subroutine I created in the section above.
# It adds functionality to filled items
# Made by maxmontygom
# New subroutine
def FillVessel(Characters, Items, Places, Vessel):
PlayerHasItem = False
PlayerIsInSameRoom = False
PlayerHasContainer = False
for Item in Items:
if Item.Name == Vessel:
PlayerHasItem = True
if Item.Location == INVENTORY and "container" in Item.Status:
PlayerHasContainer = True
if Characters[0].CurrentLocation == 8:
PlayerIsInSameRoom = True
if PlayerHasContainer and PlayerIsInSameRoom:
if "of water" in Vessel:
print(Vessel, "already full.")
else:
print("You have filled the", Vessel)
for Count in range(len(Items)):
if Items[Count].Name == Vessel:
Items[Count].Name += " of water"
else:
if PlayerHasItem == False:
print("You do not have this item")
elif PlayerHasContainer == False:
print(Vessel, "cannot hold water")
elif PlayerIsInSameRoom == False:
print("You cannot fill the", Vessel, "in here.")
return Items
# New addition to PlayGame()
elif Command == "fill":
FillVessel(Characters, Items, Places, Instruction)
VB.NET
如果你在地下室,你必須攜帶火把才能看到物品
[edit | edit source]C#
/*The following function contains a boolean statement determining if they are in the basement without a torch. If this is the case, it returns true. If this is not the case (either they are in there with the torch or they are in another room), it returns false;*/
private static bool basementValidation(int currentLocation, List<Item> items)
{
return currentLocation == 8 && items[GetIndexOfItem("torch", 2020, items)].Location != Inventory ? true : false;
}
/*For the purpose of this specific task, it needs only to be called in the 'DisplayContentsOfContainerItem(List<Item> items, int containerID)' procedure, however it can also be put in the 'DisplayGettableItemsInLocation(List<Item> items, int currentLocation)' procedure, in the event any items are placed on the floor in there. it's put in by placing a validating if statement around the original contents of the procedure;*/
if (basementValidation(currentLocation, items) == false)
{
//... original content goes here ...
}
else
{
Console.WriteLine("It is too dark to see any items");
}
/*Unfortunately I was unable to make it so that the torch had to be on for you to see, the trouble being I couldn't get the code to recognise if the torch status contained "off". If someone has a version that can do this, then by all means add it on. :-)*/
//JKW, Aquinas College
Delphi/Pascal
//replace the start of PlayGame with this
procedure PlayGame(Characters: TCharacterArray; Items: TItemArray; Places: TPlaceArray);
var
StopGame: boolean;
Instruction: string;
Command: string;
Moved: boolean;
ResultOfOpenClose: integer;
HasTorch: Boolean;
Counter: Integer;
begin
StopGame := false;
Moved := true;
while not StopGame do
begin
if Moved then
begin
writeln;
writeln;
HasTorch := False;
for Counter := 0 to length(Items)-1 do
begin
if((Items[Counter].Name = 'torch') and (Items[Counter].Location = Inventory)) then
HasTorch := True;
end;
if((Places[Characters[0].CurrentLocation-1].ID <> 8) or (HasTorch)) then
begin
writeln(Places[Characters[0].CurrentLocation - 1].Description);
DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation);
end
else
Writeln('It is too dark to see anything. Try getting a torch first');
Moved := false;
end;
//replace Examine with this
procedure Examine(Items: TItemArray; Characters: TCharacterArray; ItemToExamine: string;
CurrentLocation: integer);
var
Count: integer;
IndexOfItem: integer;
HasTorch : Boolean;
begin
HasTorch := False;
for Count := 0 to length(Items)-1 do
begin
if((Items[Count].Name = 'torch') and (Items[Count].Location = Inventory)) then
HasTorch := True;
end;
if((Characters[0].CurrentLocation = 8) and not(HasTorch)) then
Writeln('It is too dark to examine that')
else
begin
if ItemToExamine = 'inventory' then
DisplayInventory(Items)
else
begin
IndexOfItem := GetIndexOfItem(ItemToExamine, -1, Items);
if IndexOfItem <> -1 then
begin
if (Items[IndexOfItem].Location =
Inventory) or (Items[IndexOfItem].Location = CurrentLocation) then
begin
writeln(Items[IndexOfItem].Description);
if pos('door', Items[IndexOfItem].Name) <> 0 then
DisplayDoorStatus(Items[IndexOfItem].Status);
if pos('container', Items[IndexOfItem].Status) <> 0 then
DisplayContentsOfContainerItem(Items, Items[IndexOfItem].ID);
Exit
end;
end;
Count := 0;
while Count < length(Characters) do
begin
if (Characters[Count].Name = ItemToExamine) and (Characters[Count].CurrentLocation =
CurrentLocation) then
begin
writeln(Characters[Count].Description);
exit;
end;
inc(Count);
end;
writeln('You cannot find ' + ItemToExamine + ' to look at.');
end
end;
end;
Java
// Method to determine whether the location is cellar and whether the user has a torch or not.
boolean torchOrNot(int location, ArrayList<Item> items) {
int indexOfTorch = getIndexOfItem("torch", -1, items);
if (location == 8 && !(indexOfTorch < 2000 && indexOfTorch > 1000)) {
System.out.println("You cannot see any items without a torch!");
return false;
} else {
return true;
}
}
void displayGettableItemsInLocation(ArrayList<Item> items, int currentLocation) {
boolean containsGettableItems = false;
// If statement to determine whether the user is in the cellar with a torch or not, if user is in cellar with no torch it returns the method so nothing is printed.
if (torchOrNot(currentLocation, items) == false) {
return;
}
String listOfItems = "On the floor there is: ";
for (Item thing : items) {
if (thing.location == currentLocation && thing.status.contains("gettable")) {
if (containsGettableItems) {
listOfItems += ", ";
}
listOfItems += thing.name;
containsGettableItems = true;
}
}
if (containsGettableItems) {
Console.writeLine(listOfItems + ".");
}
}
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
'All the additions I used to hide items in the cellar
'Created by Joshua, Riddlesdown Collegiate
Sub Examine(ByVal Items As ArrayList, ByVal Characters As ArrayList, ByVal ItemToExamine As String, ByVal CurrentLocation As Integer)
Dim Count As Integer = 0
If ItemToExamine = "inventory" Then
DisplayInventory(Items)
Else
Dim IndexOfItem As Integer = GetIndexOfItem(ItemToExamine, -1, Items)
If IndexOfItem <> -1 Then
If Items(IndexOfItem).Name = ItemToExamine And (Items(IndexOfItem).Location = Inventory Or Items(IndexOfItem).Location = CurrentLocation) Then
Console.WriteLine(Items(IndexOfItem).Description)
If Items(IndexOfItem).Name.Contains("door") Then
DisplayDoorStatus(Items(IndexOfItem).Status)
End If
'This section needs to be added so containers are obscured in the cellar
If Items(IndexOfItem).Status.Contains("container") Then
If Characters(0).currentlocation = 8 Then
If CheckForTorch(Items) = True Then
DisplayContentsOfContainerItem(Items, Items(IndexOfItem).ID)
Else
Console.WriteLine("It is too dark to see anything.")
End If
Else
DisplayContentsOfContainerItem(Items, Items(IndexOfItem).ID)
End If
'
End If
Exit Sub
End If
End If
While Count < Characters.Count
If Characters(Count).Name = ItemToExamine And Characters(Count).CurrentLocation = CurrentLocation Then
Console.WriteLine(Characters(Count).Description)
Exit Sub
End If
Count += 1
End While
Console.WriteLine("You cannot find " & ItemToExamine & " to look at.")
End If
End Sub
Sub PlayGame(ByVal Characters As ArrayList, ByVal Items As ArrayList, ByVal Places As ArrayList)
Dim StopGame As Boolean = False
Dim Instruction, Command As String
Dim Moved As Boolean = True
Dim ResultOfOpenClose As Integer
Randomize()
While Not StopGame
If Moved Then
Console.WriteLine()
Console.WriteLine()
Console.WriteLine(Places(Characters(0).CurrentLocation - 1).Description)
'This section isnt really necessary but it will hide loose items in the cellar
'If any Then are dropped there for example
If Characters(0).currentlocation = 8 Then
If CheckForTorch(Items) = True Then
DisplayGettableItemsInLocation(Items, Characters(0).CurrentLocation)
Else
Console.WriteLine("It is too dark to see anything.")
End If
Else
DisplayGettableItemsInLocation(Items, Characters(0).CurrentLocation)
End If
Moved = False
End If
Instruction = GetInstruction()
Command = ExtractCommand(Instruction)
Select Case Command
Case "get"
GetItem(Items, Instruction, Characters(0).CurrentLocation, StopGame)
Case "use"
UseItem(Items, Instruction, Characters(0).CurrentLocation, StopGame, Places)
Case "go"
Moved = Go(Characters(0), Instruction, Places(Characters(0).CurrentLocation - 1))
Case "read"
ReadItem(Items, Instruction, Characters(0).CurrentLocation)
Case "examine"
Examine(Items, Characters, Instruction, Characters(0).CurrentLocation)
Case "open"
ResultOfOpenClose = OpenClose(True, Items, Places, Instruction, Characters(0).CurrentLocation)
DisplayOpenCloseMessage(ResultOfOpenClose, True)
Case "close"
ResultOfOpenClose = OpenClose(False, Items, Places, Instruction, Characters(0).CurrentLocation)
DisplayOpenCloseMessage(ResultOfOpenClose, False)
Case "move"
MoveItem(Items, Instruction, Characters(0).CurrentLocation)
Case "say"
Say(Instruction)
Case "playdice"
PlayDiceGame(Characters, Items, Instruction)
Case "quit"
Say("You decide to give up, try again another time.")
StopGame = True
Case Else
Console.WriteLine("Sorry, you don't know how to " & Command & ".")
End Select
End While
Console.ReadLine()
End Sub
Function CheckForTorch(ByVal Items As ArrayList)
For Each thing In Items
If thing.location = Inventory And thing.name.contains("torch") Then
Return True
End If
Next
Return False
End Function
如果骰子游戲輸了,允許最後的遺言
[edit | edit source]如果使用者在最後的遺言中說了某些話,他們就會立即獲勝。難度 = 瘋狂
Python
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("Hi")
if pip == "Hello":
print("Bye")
exit()
Items = TakeRandomItemFromPlayer(Items, Characters[IndexOfOtherCharacter].ID)
else:
print("Draw!")
return Items
Delphi/Pascal
Java
C#
VB.NET
'made by LUCAS BUTLER, HUSNAIN KHAWAJA, ROSHAN JHANGIANI, EUAN HUGHES, JUSTIN MENDON, NATHANIEL MACLEAN, LUKE CARUANA, JOSHUA FERRIMAN AND LASTLY MATTHEW HARMAN - JAMES HULATT HAS NO PARTICIPATION. from Riddlesdown Collegiate, CR81EX (posh tots)
'in the TakeRandomItemFromPlayer sub
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)
Console.WriteLine("What are your last words?")
Dim lastWords As String = Console.ReadLine
If lastWords = "Difficulty=Easy" Then
Console.WriteLine("You win the game")
Console.ReadLine()
End
End If
End If
容器物品可以使用,物品可以新增和移除容器
[edit | edit source]修改程式,使容器(如桶和罐子)可以放入物品。編輯:此處的 Python 程式碼無法正常工作!請有人修復。
例如,use barrel 會觸發程式提示要放入桶中的物品。
C#
// Add to PlayGame method.
case "fill":
FillContainer(items, instruction);
break;
case "empty":
EmptyContainer(items, instruction);
break;
//whip
private static void EmptyContainer(List<Item> items, string container)
{
string nameOfItemToMove;
int indexOfItemToMove;
Item containerItem;
int indexOfContainer = GetIndexOfItem(container, -1, items);
if (indexOfContainer != -1)
{
containerItem = items[indexOfContainer];
if (containerItem.Status.Contains("container"))
{
Say("What item would you like to remove from the " + containerItem.Name + "?");
nameOfItemToMove = Console.ReadLine();
indexOfItemToMove = GetIndexOfItem(nameOfItemToMove, -1, items);
if (indexOfItemToMove != -1)
{
if (items[indexOfItemToMove].Location == containerItem.ID)
{
ChangeLocationOfItem(items, indexOfItemToMove, Inventory);
Say("The " + nameOfItemToMove + " has been placed in your inventory");
}
else
{
Say("Not in the " + container);
}
}
else
{
Say("You can't do that");
}
}
else
{
Say("Not a container");
}
}
else
{
Say("You can't do that");
}
}
private static void FillContainer(List<Item> items, string container)
{
string nameOfItemToMove;
int indexOfItemToMove;
Item containerItem;
int indexOfContainer = GetIndexOfItem(container, -1, items);
if (indexOfContainer != -1)
{
containerItem = items[indexOfContainer];
if (containerItem.Status.Contains("container"))
{
Say("What item would you like to place inside of the " + containerItem.Name + "?");
nameOfItemToMove = Console.ReadLine();
indexOfItemToMove = GetIndexOfItem(nameOfItemToMove, -1, items);
if (indexOfItemToMove != -1)
{
if (!items[indexOfItemToMove].Status.Contains("container"))
{
if (items[indexOfItemToMove].Location == Inventory)
{
ChangeLocationOfItem(items, indexOfItemToMove, containerItem.ID);
Say("The " + nameOfItemToMove + " has been placed in the " + containerItem.Name);
}
else
{
Say("Not in your inventory");
}
}
else
{
Say("Cannot place a container inside of a container");
}
}
else
{
Say("You can't do that");
}
}
else
{
Say("Not a container");
}
}
else
{
Say("You can't do that");
}
}
Delphi/Pascal
Java
//Add a section to 'useItem' that checks if the item being used is a container
void useItem(ArrayList<Item> items, String itemToUse, int currentLocation, ArrayList<Place> places) {
...
if (indexOfItem != -1) {
if((items.get(indexOfItem).location == INVENTORY ||items.get(indexOfItem).location == currentLocation) && items.get(indexOfItem).status.contains("container"))
{
fillItem(items, items.get(indexOfItem));
return;
}
...
}
//New method for filling and emptying containers
void fillItem(ArrayList<Item> items, Item container)
{
say("Would you like to fill (f) or empty (e) the " + container.name + "?");
String response = Console.readLine().toLowerCase();
if(response.equals("f"))
{
say("What item would you like to put inside of the " + container.name +"?");
String itemToMove = Console.readLine().toLowerCase();
int indexOfItemToMove = getIndexOfItem(itemToMove, -1, items);
//Checks that the user has the item they want to move into the container
//And that they are not trying to put the container inside of itself
if(items.get(indexOfItemToMove).location == INVENTORY && !itemToMove.equals(container.name))
{
//Changes the location of the selected item from the inventory
//to the position defined by the ID of the container.
changeLocationOfItem(items, indexOfItemToMove, container.id);
say("The " + itemToMove + " has been placed in the " + container.name);
}
else if(itemToMove.equals(container.name))
{
say("You can't put an item inside itself");
}
else
{
say("You dont have that item");
}
}
else if(response.equals("e"))
{
say("What item would you like to remove from the " + container.name +"?");
String itemToRemove = Console.readLine().toLowerCase();
int indexOfItemToRemove = getIndexOfItem(itemToRemove, -1, items);
//Checks if the selected item is inside the container
if(items.get(indexOfItemToRemove).location == container.id)
{
//Changes the location of the selected item from the
//container to the players inventory.
changeLocationOfItem(items, indexOfItemToRemove, INVENTORY);
say("The " + itemToRemove + " has been placed in your inventory");
}
else
{
say("That item is not in the container");
}
}
else
{
say("You can't do that");
}
}
Python
def GetItem(Items, ItemToGet, CurrentLocation):
SubCommand = ""
SubCommandParameter = ""
CanGet = True
IndexOfItem = GetIndexOfItem(ItemToGet, -1, Items)
if IndexOfItem == -1: #if item is not valid
print("You can't find " + ItemToGet + ".")
CanGet = False
elif Items[IndexOfItem].Location == INVENTORY:#if item is in inventory
print("You have already got that!")
CanGet = False
elif Items[IndexOfItem].Location == CurrentLocation and "container" in Items[IndexOfItem].Status: #ADDED TO TAKE FROM CONTAINER ==STM==
ItemToTake = input("Enter the item you wish to remove from the container")
ItemToTakeIndex = GetIndexOfItem(ItemToTake, -1, Items)
if Items[ItemToTakeIndex].Location == Items[IndexOfItem].ID:
Items = ChangeLocationOfItem(Items, ItemToTakeIndex, INVENTORY)
print ("The item has been placed in your inventory")
return False,Items
if Items[ItemToTakeIndex].Location != Items[IndexOfItem].ID:
print ("This Item is not inside this container")
return False,Items
elif not "get" in Items[IndexOfItem].Commands:#if an item cannot be picked up
print("You can't get " + ItemToGet + ".")
CanGet = False
elif Items[IndexOfItem].Location >= MINIMUM_ID_FOR_ITEM and Items[GetIndexOfItem("", Items[IndexOfItem].Location, Items)].Location != CurrentLocation:#if item is not in current location
print("You can't find " + ItemToGet + ".")
CanGet = False
elif Items[IndexOfItem].Location < MINIMUM_ID_FOR_ITEM and Items[IndexOfItem].Location != CurrentLocation:
print("You can't find " + ItemToGet + ".")
CanGet = False
if CanGet:#gets item
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":#if item is grabbed is flag then the game is won
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
def UseItem(Items, ItemToUse, CurrentLocation, Places): #uses item in the given area
StopGame = False
SubCommand = ""
SubCommandParameter = ""
IndexOfItem = GetIndexOfItem(ItemToUse, -1, Items)
if IndexOfItem != -1: #ensures index is valid
if Items[IndexOfItem].Location == INVENTORY or (Items[IndexOfItem].Location == CurrentLocation and "usable" in Items[IndexOfItem].Status):#ensures item is in inventory or the room and is useable
Position = GetPositionOfCommand(Items[IndexOfItem].Commands, "use")
ResultForCommand = GetResultForCommand(Items[IndexOfItem].Results, Position)#gets what the command did
SubCommand, SubCommandParameter = ExtractResultForCommand(SubCommand, SubCommandParameter, ResultForCommand)
if SubCommand == "say": #prints the say
Say(SubCommandParameter)
elif SubCommand == "lockunlock":#door commands
IndexOfItemToLockUnlock = GetIndexOfItem("", int(SubCommandParameter), Items)
IndexOfOtherSideItemToLockUnlock = GetIndexOfItem("", int(SubCommandParameter) + ID_DIFFERENCE_FOR_OBJECT_IN_TWO_LOCATIONS, Items)
Items = ChangeStatusOfDoor(Items, CurrentLocation, IndexOfItemToLockUnlock, IndexOfOtherSideItemToLockUnlock)
elif SubCommand == "roll":#rolls the dice during playdice
Say("You have rolled a " + str(RollDie(ResultForCommand[5], ResultForCommand[7])))
return StopGame, Items
if Items[IndexOfItem].Location == CurrentLocation and "container" in Items[IndexOfItem].Status: #USED TO ADD AN ITEM INTO A CONTAINER ==STM==
#print ("Container Found")
StoredItem = input("Enter the item you want to store in the container ")
StoredItem = GetIndexOfItem(StoredItem,-1,Items)
if Items[StoredItem].Location == INVENTORY:
Items = ChangeLocationOfItem(Items, StoredItem, Items[IndexOfItem].ID)
print ("You have stored the item in the container!")
return StopGame, Items
print("You can't use that!")#for if an item cannot be used
return StopGame, Items
#AW :)
######################### alternative #####################################################
def UseItem(Items, ItemToUse, CurrentLocation, Places):
StopGame = False
SubCommand = ""
SubCommandParameter = ""
IndexOfItem = GetIndexOfItem(ItemToUse, -1, Items)
if "container" in Items[IndexOfItem].Status: # add this if statement to UseItem
FillItem(Items, ItemToUse, CurrentLocation)
else:
if IndexOfItem != -1:
if Items[IndexOfItem].Location == INVENTORY or (Items[IndexOfItem].Location == CurrentLocation and "usable" in Items[IndexOfItem].Status):
Position = GetPositionOfCommand(Items[IndexOfItem].Commands, "use")
ResultForCommand = GetResultForCommand(Items[IndexOfItem].Results, Position)
SubCommand, SubCommandParameter = ExtractResultForCommand(SubCommand, SubCommandParameter, ResultForCommand)
if SubCommand == "say":
Say(SubCommandParameter)
elif SubCommand == "lockunlock":
IndexOfItemToLockUnlock = GetIndexOfItem("", int(SubCommandParameter), Items)
IndexOfOtherSideItemToLockUnlock = GetIndexOfItem("", int(SubCommandParameter) + ID_DIFFERENCE_FOR_OBJECT_IN_TWO_LOCATIONS, Items)
Items = ChangeStatusOfDoor(Items, CurrentLocation, IndexOfItemToLockUnlock, IndexOfOtherSideItemToLockUnlock)
elif SubCommand == "roll":
Say("You have rolled a " + str(RollDie(ResultForCommand[5], ResultForCommand[7])))
return StopGame, Items
print("You can't use that!")
return StopGame, Items
#create two new functions, FillItem and PutItem
def FillItem(Items, ItemToFill, CurrentLocation):
SubCommand = ""
SubCommandParameter = ""
IndexOfItem = GetIndexOfItem(ItemToFill, -1, Items)
if Items[IndexOfItem].Location == CurrentLocation or Items[IndexOfItem].Location == INVENTORY and "container" in Items[IndexOfItem].Status:
FillerItem = input("What do you want to fill with? > ")
PutItem(Items, FillerItem, CurrentLocation, IndexOfItem, ItemToFill)
else:
print("you can't fill", ItemToFill)
return False, Items
def PutItem(Items, FillerItem, CurrentLocation, IndexOfItem, ItemToFill):
IndexOfFillerItem = GetIndexOfItem(FillerItem, -1, Items)
if Items[IndexOfFillerItem].Location == CurrentLocation or Items[IndexOfFillerItem].Location == INVENTORY:
Items[IndexOfFillerItem].Location = Items[IndexOfItem].Location
print(FillerItem, "is now inside", ItemToFill)
else:
print("you cant put", FillerItem, "inside", ItemToFill)
return False, Items
#############################################
使火把成為容器
[edit | edit source]使火把成為容器並建立電池。只有在供電時,火把才能被“使用”點亮。只有當電池在裡面時,它才會被供電。SM HGS,難度:狂暴
C#
Delphi/Pascal
Java
VB.NET
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)
建立“傳送物品”命令
[edit | edit source]建立一個函式,將任何物品傳送到你的位置,即使它是在另一個角色的物品欄中。SM HGS,難度:狂怒
C#
//Add to PlayGame()
case "teleportitem":
teleportitem(items, instruction, characters[0].CurrentLocation);
break;
//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()
VB. NET
'PlayGame sub
Case "tpitem"
tpItem(Items, Instruction, Characters(0).CurrentLocation)
'New subroutine
'made by Hus K.add my discord Cloud#0025
Sub tpItem(ByVal items As ArrayList, ByVal itemTp As String, ByVal currentLocation As Integer)
Dim position As String = currentLocation, indexOfItem
indexOfItem = GetIndexOfItem(itemTp, -1, items)
If indexOfItem = -1 Then
Console.WriteLine(itemTp + " can't be found")
Else
Console.WriteLine(itemTp + " was teleported to you")
position = GetPositionOfCommand(items(indexOfItem).Commands, "tpitem")
ChangeLocationOfItem(items, indexOfItem, currentLocation)
End If
End Sub
建立一個“移動計數器”和“命令歷史記錄列表”
[edit | edit source]SM HGS,難度:噩夢
Python
Create a function to count the number of moves the user has made and display a history of those commands when requested.<syntaxhighlight lang="python3">
// global variables
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)
Delphi/Pascal
procedure History(CommandHistory: Array of String);
Var
Counter: Integer;
begin
Writeln('Command history:');
for Counter := 0 to length(CommandHistory)-1 do
begin
Writeln(CommandHistory[Counter]);
end;
end;
procedure PlayGame(Characters: TCharacterArray; Items: TItemArray; Places: TPlaceArray);
var
StopGame: boolean;
Instruction: string;
Command: string;
Moved: boolean;
ResultOfOpenClose: integer;
CommandCounter: integer;
CommandHistory: Array of String;
ValidCommand: boolean;
begin
StopGame := false;
Moved := true;
CommandCounter:= 0;
SetLength(CommandHistory,0);
while not StopGame do
begin
ValidCommand := True;
if Moved then
begin
writeln;
writeln;
writeln(Places[Characters[0].CurrentLocation - 1].Description);
DisplayGettableItemsInLocation(Items, Characters[0].CurrentLocation);
Moved := false;
end;
Instruction := GetInstruction;
Command := ExtractCommand(Instruction);
if Command = 'get' then
GetItem(Items, Instruction, Characters[0].CurrentLocation, StopGame)
else if Command = 'use' then
UseItem(Items, Instruction, Characters[0].CurrentLocation, StopGame, Places)
else if Command = 'go' then
Moved := Go(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1])
else if Command = 'read' then
ReadItem(Items, Instruction, Characters[0].CurrentLocation)
else if Command = 'examine' then
Examine(Items, Characters, Instruction, Characters[0].CurrentLocation)
else if Command = 'open' then
begin
ResultOfOpenClose := OpenClose(true, Items, Places, Instruction, Characters[0].CurrentLocation);
DisplayOpenCloseMessage(ResultOfOpenClose, true);
end
else if Command = 'close' then
begin
ResultOfOpenClose := OpenClose(false, Items, Places, Instruction, Characters[0].CurrentLocation);
DisplayOpenCloseMessage(ResultOfOpenClose, false);
end
else if Command = 'move' then
MoveItem(Items, Instruction, Characters[0].CurrentLocation)
else if Command = 'say' then
Say(Instruction)
else if Command = 'playdice' then
PlayDiceGame(Characters, Items, Instruction)
else if Command = 'history' then
History(CommandHistory)
else if Command = 'quit' then
begin
Say('You decide to give up, try again another time');
ValidCommand := False;
StopGame := true;
end
else
begin
writeln('Sorry, you don''t know how to ', Command, '.');
ValidCommand := False;
end;
if(ValidCommand) then
begin
CommandCounter := CommandCounter +1;
SetLength(CommandHistory,CommandCounter);
CommandHistory[CommandCounter-1] := Command;
end;
end;
readln;
end;
VB.NET
'made by Hus K & Lucas from Riddlesdown Kenley
' code might be a bit suspect but tried my best
'global variables
Dim Moves As Integer
Dim commandhistory As New List(Of String)
' function GetInstruction() edited
Function GetInstruction() As String
Dim Instruction As String
Console.Write(Environment.NewLine & "> ")
Instruction = Console.ReadLine.ToLower
Moves = Moves + 1
commandhistory.Add(Instruction)
Console.WriteLine("You have made: " & Moves & " moves")
Return Instruction
End Function
'add to PlayGame
Case "history"
Console.WriteLine("history of instructions you have used:")
For i = 0 To commandhistory.Count - 1
Console.WriteLine(commandhistory.Item(i))
Next
搜尋/顯示當前目錄中的可用遊戲(為了使初次使用者更清楚地瞭解遊戲開頭)
[edit | edit source]搜尋並顯示可用的遊戲。有助於讓遊戲開頭變得清晰。SM HGS 難度:傳奇
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
如果使用者輸入無效命令 5 次,遊戲會告訴使用者並結束遊戲。
[edit | edit source]SM HGS,難度:非常簡單
C#
// Done at top of PlayGame()
int noOfIncorrectCommands = 0;
// This is inside of the switch statement
default:
Console.WriteLine("Sorry, you don't know how to " + Command + ".");
noOfIncorrectCommands++;
break;
}
if (noOfIncorrectCommands >= 5)
{
Console.WriteLine("You have entered 5 incorrect commands and will now die");
stopGame = true;
}
Delphi/Pascal
Java
Python
#SM Maqsud HGS
def PlayGame(Characters, Items, Places):
fails = 0
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 + ".")
fails += 1
if fails > 4:
print()
print("You need to learn the instructions!")
input("> ")
sys.exit()
#Used sys so window doesnt close
input()
VB.NET
'made by LUCAS BUTLER, HUSNAIN KHAWAJA, ROSHAN JHANGIANI, EUAN HUGHES, JUSTIN MENDON, LUKE CARUANA, JOSHUA FERRIMAN AND LASTLY MATTHEW HARMAN - JAMES HULATT HAS NO PARTICIPATION. from Riddlesdown Collegiate, CR81EX
'implement counter at top of PlayGame Sub
Dim invalidCommandCount As Integer
'at the end of the Select Case command:
Case Else
Console.WriteLine("Sorry, you don't know how to " & Command & ".")
invalidCommandCount = invalidCommandCount + 1
If invalidCommandCount = 5 Then
Console.WriteLine("You have entered an invalid command 5 times")
Console.WriteLine("Game Over")
Main()
End If
'I decided to just call the main subroutine, but could alternatively just exit the entire program
如果使用者輸了骰子游戲,他們可以選擇放棄哪件物品,而不是隨機物品
[edit | edit source]SM HGS,難度:中等,編輯:我剛剛釋出了 VB.net 部分的程式碼,但之前從未上傳到此網站,所以希望我做的一切都正確 :D
C#
Delphi/Pascal
Java
Python
#SM Maqsud
def TakeRandomItemFromPlayer(Items, OtherCharacterID):
ListOfIndicesOfItemsInInventory = []
ListOfNamesOfItemsInInventory = []
Count = 0
while Count < len(Items):
if Items[Count].Location == INVENTORY:
ListOfIndicesOfItemsInInventory.append(Count)
ListOfNamesOfItemsInInventory.append((str(Items[Count].Name)).upper())
Count += 1
rno = GetRandomNumber(0, len(ListOfIndicesOfItemsInInventory) - 1)
print(ListOfNamesOfItemsInInventory)
print()
choice = ((input("Input the name of the item you want: ")).upper())
print()
while choice not in ListOfNamesOfItemsInInventory:
print("Not available")
choice = ((input("Input the name of the item you want: ")).upper())
print()
print("They have taken your " + choice + ".")
Items = ChangeLocationOfItem(Items, ListOfIndicesOfItemsInInventory[ListOfNamesOfItemsInInventory.index(choice)], OtherCharacterID)
return Items
VB.NET
Sub TakeRandomItemFromPlayer(ByVal Items As ArrayList, ByVal OtherCharacterID As Integer)
Console.WriteLine("Choose an item to give up.")
DisplayInventory(Items)
Dim NotInInventory As Boolean = True
While NotInInventory = True
Dim ItemtoDiscard As String = Console.ReadLine()
For item = 0 To Items.Count - 1
If Items(item).location = Inventory And Items(item).name = ItemtoDiscard Then
Console.WriteLine("They have taken your " & Items(item).Name & ".")
ChangeLocationOfItem(Items, item, OtherCharacterID)
NotInInventory = False
End If
Next
If NotInInventory = True Then Console.WriteLine("You do not own this item, Choose a different item")
End While
End Sub
輸入“debugchar”以顯示遊戲中所有角色的詳細資訊
[edit | edit source]在列表中顯示每個角色的 ID、姓名、描述和當前位置。基於 ZigZag 教育問題。如果要嘗試將新角色新增到遊戲中,這很有用。SM HGS,難度:無情
C#
private static void DisplayCharacters(List<Character>characters)
{
//Written by Ahmed Rahi
foreach (var DC in characters)
{
Console.WriteLine("New Character");
Console.WriteLine(DC.ID);
Console.WriteLine(DC.Name);
Console.WriteLine(DC.Description);
Console.WriteLine(DC.CurrentLocation);
Console.WriteLine("End of a characters profile");
Console.WriteLine(" ");
}
}
//After creating that routine put this in the playgame routine
case "debugchar":
DisplayCharacters(characters);
break;
Delphi/Pascal
Java
Python [更新]
# I realized I made it in a really convoluted way so it's a bit cleaner now
# Written by maxmontygom
# New subroutines
LocationDict = {
"1":"Entry Room",
"2":"Store Cupboard",
"3":"Bedroom",
"4":"Empty Corridor",
"5":"Guardroom",
"6":"North Jail Cell",
"7":"South Jail Cell",
"8":"Cellar"
}
def DebugChar(Characters):
print("ID NAME DESCRIPTION LOCATION")
for Character in Characters:
TempId = Character.ID
IdSpace = ' ' * (5 - len(str(TempId)))
TempName = Character.Name
NameSpace = ' ' * (12 - len(TempName))
TempDesc = Character.Description
DescSpace = ' ' * (64 - len(TempDesc))
TempLocation = LocationDict[str(Character.CurrentLocation)]
TempCharacter = [TempId, IdSpace, TempName, NameSpace, TempDesc, DescSpace, TempLocation]
print(*TempCharacter, sep='')
# New addition to PlayGame()
elif Command == "debugchar":
DebugChar(Characters)
VB.NET
# add to playgame
Case "debugchar"
displaycharectars(Characters)
# create a new procedure
Sub displaycharectars(characters As ArrayList)
Dim header As String
header = header & "id "
header = header & "name "
header = header & "description".PadRight(64)
header = header & "currentlocation"
Console.WriteLine(header)
For Each c In characters
Dim line As String = " "
line = line & CType(c.id, String).PadRight(5)
line = line & c.name.padright(12)
line = line & c.description.padright(64)
line = line & c.currentlocation
Console.WriteLine(line)
Next
新增一個給予程式
[edit | edit source]此程式允許玩家將其中一件物品送給守衛。問題:你為什麼要給守衛任何東西?如果之後沒有任何事情發生,這毫無意義。
Python
#added to the Playgame function
elif Command == "give":
Items = GiveItem(Items, Instruction, Characters)
#new function
def GiveItem(Items, Instruction, Characters):
OtherCharacterID = Characters[1].ID
IndexOfItem = GetIndexOfItem(Instruction, -1, Items)
if Characters[0].CurrentLocation == Characters[1].CurrentLocation:
if Items[IndexOfItem].Location == INVENTORY:
Items = ChangeLocationOfItem(Items, IndexOfItem, OtherCharacterID)
print("You gave the guard", Items[IndexOfItem].Name)
return Items
將二進位制標記檔案轉換為文字檔案
[edit | edit source]
Python
#Ants
import json
def serialise(obj):
return obj.__dict__
def ConvertGmeToText(Filename, Characters, Items, Places):
GameLoaded, Characters, Items, Places = LoadGame(Filename, Characters, Items, Places)
if not GameLoaded:
print('Cant find game to load')
return
GameFile = {
'Characters': Characters,
'Items': Items,
'Places': Places
}
f = open(Filename+ '.txt', 'w')
#could also save to .json for better syntax highlighting - Spaceman George
f.write(json.dumps(GameFile, default=serialise, indent=4, sort_keys=True))
f.close()
def Main():
Items = []
Characters = []
Places = []
Filename = input("Enter filename to text> ") + ".gme"
ConvertGmeToText(Filename, Characters, Items, Places)
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()
新增“look”命令
[edit | edit source]加入一個額外的命令“look”,它可以用來代替“go”來預覽一個位置,假設“go”不會被關閉的門阻止(ZIGZAG 例題)。
Delphi/Pascal
// Based off Go
procedure Look(var You: TCharacter; Direction: string; CurrentPlace: TPlace; Places: TPlaceArray; Items: TItemArray);
var
Looked: boolean;
PlaceID: integer;
begin
Looked := true;
PlaceId := 0;
if Direction = 'north' then
if CurrentPlace.North = 0 then
Looked := false
else
PlaceID := CurrentPlace.North
else if Direction = 'east' then
if CurrentPlace.East = 0 then
Looked := false
else
PlaceID := CurrentPlace.East
else if Direction = 'south' then
if CurrentPlace.South = 0 then
Looked := false
else
PlaceID := CurrentPlace.South
else if Direction = 'west' then
if CurrentPlace.West = 0 then
Looked := false
else
PlaceID := CurrentPlace.West
else if Direction = 'up' then
if CurrentPlace.Up = 0 then
Looked := false
else
PlaceID := CurrentPlace.Up
else if Direction = 'down' then
if CurrentPlace.Down = 0 then
Looked := false
else
PlaceID := CurrentPlace.Down
else
Looked := false;
if not Looked then
writeln('You are not able to look in that direction.')
else
begin
writeln(Places[PlaceID].Description);
DisplayGettableItemsInLocation(Items, PlaceID);
end;
end;
...
procedure PlayGame(Characters: TCharacterArray; Items: TItemArray; Places: TPlaceArray);
... // In PlayGame
else if Command = 'look' then
Look(Characters[0], Instruction, Places[Characters[0].CurrentLocation - 1], Places, Items)
Java
//Very similar to the 'go' function.
void look(ArrayList<Place> places, String direction, Place currentPlace) {
boolean looked = true;
switch (direction)
{
case "north":
if (currentPlace.north == 0) {
looked = false;
} else {
//The first seven characters of a place description are "You are". This substring
//swaps those characters for "If you went DIRECTION, you would be" so that the
//output makes sense.
say("If you went north, you would be" + places.get(currentPlace.north-1).description.substring(7));
}
break;
case "east":
if (currentPlace.east == 0) {
looked = false;
} else {
say(places.get(currentPlace.east-1).description);
}
break;
case "south":
if (currentPlace.south == 0) {
looked = false;
} else {
say(places.get(currentPlace.south-1).description);
}
break;
case "west":
if (currentPlace.west == 0) {
looked = false;
} else {
say(places.get(currentPlace.west-1).description);
}
break;
case "up":
if (currentPlace.up == 0) {
looked = false;
} else {
say(places.get(currentPlace.up-1).description);
}
break;
case "down":
if (currentPlace.down == 0) {
looked = false;
} else {
say(places.get(currentPlace.down-1).description);
}
break;
default:
looked = false;
}
if (!looked) {
Console.writeLine("You are not able to look in that direction.");
}
}
//Also need to add the look command to the playGame function
Python
#WHY DID I TAKE A LEVEL COMPUTING?
def Look(Places, Characters, Direction):
CurrentPlace = Places[Characters[0].CurrentLocation - 1]
if Direction == "north":
if CurrentPlace.North == 0:
print("You can't see anything")
else:
print(Places[CurrentPlace.North - 1].Description[11::].capitalize())
elif Direction == "east":
if CurrentPlace.East == 0:
print("You can't see anything")
else:
print(Places[CurrentPlace.East - 1].Description[11::].capitalize())
elif Direction == "south":
if CurrentPlace.South == 0:
print("You can't see anything")
else:
print(Places[CurrentPlace.South - 1].Description[11::].capitalize())
elif Direction == "west":
if CurrentPlace.West == 0:
print("You can't see anything")
else:
print(Places[CurrentPlace.West - 1].Description[11::].capitalize())
elif Direction == "up":
if CurrentPlace.Up == 0:
print("You can't see anything")
else:
print(Places[CurrentPlace.Up - 1].Description[11::].capitalize())
elif Direction == "down":
if CurrentPlace.Down == 0:
print("You can't see anything")
else:
print(Places[CurrentPlace.Down - 1].Description[11::].capitalize())
else:
print("You can't look there")
return
#TO PLAYGAME
elif Command == "look":
Look(Places, Characters, Instruction)
VB.NET
Sub Look(ByRef You As Character, ByVal Direction As String,
ByVal CurrentPlace As Place, ByVal Places As ArrayList)
Select Case Direction
Case "north"
If CurrentPlace.North = 0 Then
Console.WriteLine("You can't see anything...")
Else
Console.WriteLine(Places(CurrentPlace.North - 1).Description)
End If
Case "east"
If CurrentPlace.East = 0 Then
Console.WriteLine("You can't see anything...")
Else
Console.WriteLine(Places(CurrentPlace.East - 1).Description)
End If
Case "south"
If CurrentPlace.South = 0 Then
Console.WriteLine("You can't see anything...")
Else
Console.WriteLine(Places(CurrentPlace.South - 1).Description)
End If
Case "west"
If CurrentPlace.West = 0 Then
Console.WriteLine("You can't see anything...")
Else
Console.WriteLine(Places(CurrentPlace.West - 1).Description)
End If
Case "up"
If CurrentPlace.Up = 0 Then
Console.WriteLine("You can't see anything...")
Else
Console.WriteLine(Places(CurrentPlace.Up - 1).Description)
End If
Case "down"
If CurrentPlace.Down = 0 Then
Console.WriteLine("You can't see anything...")
Else
Console.WriteLine(Places(CurrentPlace.Down - 1).Description)
End If
Case Else
Console.WriteLine("There's nothing there...")
End Select
End Sub
'At Sub PlayGame()
Case "look"
Look(Characters(0), Instruction, Places(Characters(0).CurrentLocation - 1), Places)
新增“put”功能
[edit | edit source]這意味著物品可以放置在容器中,目前物品只能從容器中取出。(將其新增到容器問題中)
VB.NET
Sub put(ByVal Items As ArrayList, ByVal ItemToPut As String, ByVal CurrentLocation As Integer)
Dim IndexOfItems As Integer
Dim Container As String
Dim ContainerID As Integer
IndexOfItems = GetIndexOfItem(ItemToPut, -1, Items)
If IndexOfItems = -1 Then
Console.WriteLine("You can't find this item")
End If
If Items(IndexOfItems).location = Inventory Then
Console.WriteLine("You can put your " & ItemToPut & " in these containers: ")
For Each thing In Items
If thing.status.contains("container") And thing.location = CurrentLocation Then
Console.WriteLine(thing.name)
End If
Next
Console.WriteLine("Which container would you like to put your item in?")
Try
Container = Console.ReadLine()
Catch ex As Exception
Console.WriteLine("Must be an actual contianer.")
End Try
Try
ContainerID = Items(GetIndexOfItem(Container, -1, Items)).ID
ChangeLocationOfItem(Items, IndexOfItems, ContainerID)
Catch ex As Exception
Console.WriteLine("You can't put this here")
End Try
Console.WriteLine("You have put the " & ItemToPut & " in the " & Container)
End If
End Sub
新增“pick”鎖功能
[edit | edit source]這允許使用者嘗試撬開其中一扇牢房門的鎖,但如果他們被抓到,他們會立即輸掉遊戲。
Python
#COMPLETE WITH LOCK PICK ANIMATION (MIGHT NOT BE NEEDED IN EXAM HOWEVER BUT YOU NEVER KNOW)
import time
def PickLock(Characters, Items, Places, DoorToBePicked):
Picked = False
StopGame = False
RandomPickChance = GetRandomNumber(0, 10)
if Characters[0].CurrentLocation == 5 and DoorToBePicked == "gold door" or DoorToBePicked == "silver door":
IndexOfDoor = GetIndexOfItem(DoorToBePicked, -1, Items)
if "unlocked" in Items[IndexOfDoor].Status:
print("The door is already unlocked silly.")
return StopGame, Items
for x in range (0,20):
print("\n" * 100)
print("""
.--------.
( .-------. )
| | | |
_| |________| |_
.' |_| |_| '.
'._____ ____ _____.'
| .'____'. |
'.__.'.' '.'.__.'""")
print("| |", " " * (20 - x), "\\_______________/========== ")
print("""| '.'.____.'.' |
'.____'.____.'____.'
'.________________.'
""")
time.sleep(0.1)
if RandomPickChance > 2: #Change number to increase or decrease chances of being caught
print("\n" * 100)
print("""
.----.
( .-----.)
| | | |
| | | |
| | | |
| | |_|
_| |____________
.' |_| |_|'.
'._____ ____ _____.'
| .'____'. |
'.__.'.' '.'.__.' *CLICK*
| | \\_______________/==========
| '.'.____.'.' |
'.____'.____.'____.'
'.________________.'
""")
print("\nYou hear the lock of the " +DoorToBePicked+ " open, the guard did not notice.")
ChangeStatusOfItem(Items, IndexOfDoor, "unlocked")
return StopGame, Items
else:
print("\n" * 100)
print("""
.--------.
( .-------. )
| | | |
_| |________| |_
.' |_| |_| '.
'._____ ____ _____.' |
| .'____'. | /
'.__.'.' '.'.__.' / ==
| | \\____________/_ *SNAP*
| '.'.____.'.' | \ ===
'.____'.____.'____.' |
'.________________.' |
""")
print("\nThe guard hears the pick break and sees you picking the door, you get arrested, its the cells for you, unlucky kid.")
print("\nYou lost, try again.")
StopGame = True
return StopGame, Items
else:
print("You can't find a " +DoorToBePicked+ " to pick")
return StopGame, Items
#ADD THIS TO PLAYGAME FUNCTION:
elif Command == "pick":
StopGame, Items = PickLock(Characters, Items, Places, Instruction)