Debian Codegraph @

terps/frankendrift/FrankenDrift.Adrift/clsUserSession.vb

raw
1 ' Everything specific to the user's session that isn't stored in Adventure needs to go here
2
3 Imports System.Xml
4
5 Imports FrankenDrift.Glue
6 Imports FrankenDrift.Glue.Util
7
8 Public Class RunnerSession
9
10 Public sIt, sHim, sHer, sThem As String
11 Public dtDebug As DateTime
12 Public iDebugIndent As Integer
13 Public bNoDebug As Boolean
14 Public iPrepProgress As Integer
15 Public States As New StateStack
16 Public iMarginWidth As Integer
17 Public bEXE As Boolean = False
18 Private listTaskKeys As New Generic.List(Of TaskKey)
19 Friend iMatchedTaskCommand As Integer
20 Friend dictMacros As New Generic.Dictionary(Of String, clsMacro)
21 Friend bSystemTask As Boolean = False
22 Public salCommands As New StringArrayList
23 Public bShowShortLocations As Boolean = True
24 Friend iPreviousOffset As Integer
25 Public sGameFolder As String
26 Public bGraphics As Boolean = True
27 Public WithEvents Map As FrankenDrift.Glue.Map
28 Friend bUseDefaultFont As Boolean = False
29 Friend sTurnOutput As String = ""
30 Friend bRequiresRestoreLayout As Boolean = False
31 Friend sRememberedVerb As String = ""
32 Friend bTestingOutput As Boolean = False
33
34 Public Property bSound As Boolean = True
35
36 Private Class TaskKey
37 Implements IComparable
38
39 Public sTaskKey As String
40 Public iPriority As Integer
41
42 Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
43 Return Me.iPriority.CompareTo(CType(obj, TaskKey).iPriority)
44 End Function
45 End Class
46
47 Friend NewReferences() As clsNewReference ' We should really keep a NewReferences collection PER parent task. So if we execute tasks within our actions, they have their own References set!!!
48
49 Private htblResponsesPass As New OrderedHashTable
50 Private htblResponsesFail As New OrderedHashTable
51 Public htblCompleteableGeneralTasks As New TaskHashTable
52 Public htblSecondChanceTasks As New TaskHashTable ' If we don't get a winner first time round, try again, matching against objects/characters that don't exist
53 Public htblVisibleObjects As New ObjectHashTable
54 Public htblSeenObjects As New ObjectHashTable
55 Public sInput, sLastProperInput As String
56 Friend iRestNum As Integer
57 Private sAmbTask As String
58 Public sOutputText As String
59 Public sRestrictionText, sRestrictionTextMulti As String
60
61 Friend Property sRouteError As String
62
63 Private ValidRefs As Hashtable
64
65 Friend PronounKeys As New PronounInfoList
66 Private Class SortByLength
67 Inherits Generic.Comparer(Of String)
68
69 Public Overrides Function Compare(ByVal x As String, ByVal y As String) As Integer
70 Return y.Length.CompareTo(x.Length)
71 End Function
72 End Class
73
74
75 Public Sub SaveMacros()
76
77 Try
78 Dim sMacrosFile As String = DataPath(True) & "ADRIFTMacros.xml"
79
80 Dim xmlWriter As New System.Xml.XmlTextWriter(sMacrosFile, System.Text.Encoding.UTF8)
81 With xmlWriter
82 .Indentation = 4
83 .IndentChar = " "c
84 .Formatting = Formatting.Indented
85
86 .WriteStartDocument()
87 .WriteComment("File created by ADRIFT v" & Application.ProductVersion)
88
89 .WriteStartElement("Macros")
90
91 For Each sTitle As String In dictMacros.Keys
92 .WriteStartElement("Macro")
93
94 Dim m As clsMacro = dictMacros(sTitle)
95
96 .WriteElementString("Key", m.Key)
97 .WriteElementString("Title", m.Title)
98 .WriteElementString("Shared", m.Shared.ToString)
99 .WriteElementString("IFID", m.IFID)
100 .WriteElementString("Commands", m.Commands)
101
102 .WriteEndElement() ' Macro
103 Next
104
105 .WriteEndElement() ' Macros
106
107 .WriteEndDocument()
108
109 .Flush()
110 .Close()
111
112 End With
113 Catch ex As Exception
114 ErrMsg("Error saving macros", ex)
115 End Try
116
117 End Sub
118
119
120 ' Load Macros from file
121 Public Sub LoadMacros()
122
123 Try
124 Dim sMacrosFile As String = DataPath(True) & "ADRIFTMacros.xml"
125 dictMacros.Clear()
126
127 If IO.File.Exists(sMacrosFile) Then
128 Dim xmlDoc As New System.Xml.XmlDocument
129 xmlDoc.Load(sMacrosFile)
130 Dim bFirst As Boolean = True
131
132 For Each nod As System.Xml.XmlNode In xmlDoc.SelectNodes("/Macros/Macro")
133
134 Dim sTitle As String = nod.SelectSingleNode("Title").InnerText
135 Dim sCommands As String = nod.SelectSingleNode("Commands").InnerText
136 Dim sKey As String = nod.SelectSingleNode("Key").InnerText
137
138 If sKey <> "" AndAlso sTitle <> "" AndAlso sCommands <> "" Then
139 Dim macro As New clsMacro(sKey)
140 macro.Title = sTitle
141 macro.Commands = sCommands
142
143 If nod.SelectSingleNode("Shared") IsNot Nothing Then macro.Shared = SafeBool(nod.SelectSingleNode("Shared").InnerText)
144 If nod.SelectSingleNode("IFID") IsNot Nothing Then macro.IFID = SafeString(nod.SelectSingleNode("IFID").InnerText)
145 dictMacros.Add(macro.Key, macro)
146 End If
147 Next
148 End If
149
150 Catch ex As Exception
151 ErrMsg("Error loading macros", ex)
152 End Try
153
154 End Sub
155
156
157 Public Function OpenAdventure(ByVal sFilename As String, Optional ByVal bSilentError As Boolean = False) As Boolean
158
159 Adventure = New clsAdventure
160
161 States.Clear()
162 salCommands.Clear()
163 #If Not Adravalon Then
164 salCommands.Add(fRunner.txtInput.Text)
165 #Else
166 salCommands.Add("")
167 #End If
168 iPreviousOffset = 0
169 Dim eFileType As FileIO.FileTypeEnum = FileTypeEnum.TextAdventure_TAF
170 If sFilename.ToLower.EndsWith(".blorb") Then eFileType = FileTypeEnum.Blorb
171 If sFilename.ToLower.EndsWith(".exe") Then eFileType = FileTypeEnum.Exe
172
173 If LoadFile(sFilename, eFileType, LoadWhatEnum.All, False, , , , bSilentError) Then
174 For eDirection As DirectionsEnum = DirectionsEnum.North To DirectionsEnum.NorthWest
175 Adventure.sDirectionsRE(eDirection) = Adventure.sDirectionsRE(eDirection).ToLower
176 Next
177 Glue.SetGameName(Adventure.Title)
178
179 'Sort tasks by priority
180 listTaskKeys.Clear()
181 For Each tas As clsTask In Adventure.htblTasks.Values
182 Dim tk As New TaskKey
183 tk.sTaskKey = tas.Key
184 tk.iPriority = tas.Priority
185 listTaskKeys.Add(tk)
186 Next
187 listTaskKeys.Sort()
188
189 Adventure.eGameState = clsAction.EndGameEnum.Running
190
191 ' Initialise any array values
192 For Each v As clsVariable In Adventure.htblVariables.Values
193 If v.Length > 1 Then
194 Dim sInitialValue() As String = v.StringValue.Split(Chr(10))
195 If sInitialValue.Length = v.Length Then
196 Dim i As Integer = 1
197 For Each sValue As String In sInitialValue
198 If v.Type = clsVariable.VariableTypeEnum.Numeric Then
199 v.IntValue(i) = SafeInt(sValue)
200 Else
201 v.StringValue(i) = sValue.Replace(Chr(13), "")
202 End If
203 i += 1
204 Next
205 End If
206 End If
207 Next
208
209 For Each t As clsTask In Adventure.htblTasks.Values
210 For i As Integer = 0 To t.arlCommands.Count - 1
211 t.arlCommands(i) = CorrectCommand(t.arlCommands(i))
212 Next
213 If t.TaskType = clsTask.TaskTypeEnum.System AndAlso t.RunImmediately Then
214 AttemptToExecuteTask(t.Key, True)
215 End If
216 Next
217
218 UpdateStatusBar()
219 InitialiseInputBox()
220 fRunner.SetBackgroundColour()
221
222 Adventure.Player.HasSeenLocation(Adventure.Player.Location.LocationKey) = True
223 UserSession.Map.RecalculateNode(Adventure.Map.FindNode(Adventure.Player.Location.LocationKey))
224 UserSession.Map.SelectNode(Adventure.Player.Location.LocationKey)
225 fRunner.txtOutput.Clear()
226 Display("<c>" & Adventure.Title & "</c>" & vbCrLf, True)
227 Display(Adventure.Introduction.ToString, True)
228
229 If Adventure.ShowFirstRoom AndAlso Adventure.htblLocations.ContainsKey(Adventure.Player.Location.LocationKey) Then Display(vbCrLf & pSpace(Adventure.htblLocations(Adventure.Player.Location.LocationKey).ViewLocation), True)
230
231 For Each e As clsEvent In Adventure.htblEvents.Values
232 Select Case e.WhenStart
233 Case clsEvent.WhenStartEnum.AfterATask
234 e.Status = clsEvent.StatusEnum.NotYetStarted
235 Case clsEvent.WhenStartEnum.BetweenXandYTurns
236 e.Status = clsEvent.StatusEnum.CountingDownToStart
237 e.TimerToEndOfEvent = e.StartDelay.Value + e.Length.Value
238 Case clsEvent.WhenStartEnum.Immediately
239 e.Start(True)
240 End Select
241 Next
242
243 ' Needs to be a separate loop in case a later event runs a task that starts an earlier event
244 For Each e As clsEvent In Adventure.htblEvents.Values
245 e.bJustStarted = False
246 Next
247
248 For Each c As clsCharacter In Adventure.htblCharacters.Values
249 For Each w As clsWalk In c.arlWalks
250 If w.StartActive Then w.Start(True)
251 Next
252 For Each w As clsWalk In c.arlWalks
253 w.bJustStarted = False
254 Next
255
256 ' Sort our topics by descending length
257 Dim topickeys As New Generic.SortedDictionary(Of String, Generic.List(Of String))(New SortByLength)
258 For Each t As clsTopic In c.htblTopics.Values
259 If t.bCommand Then t.Keywords = CorrectCommand(t.Keywords)
260 If Not topickeys.ContainsKey(t.Keywords) Then topickeys.Add(t.Keywords, New Generic.List(Of String))
261 topickeys(t.Keywords).Add(t.Key)
262 Next
263 Dim htblTopicsNew As New TopicHashTable
264 For Each sTopic As String In topickeys.Keys
265 For Each sKey As String In topickeys(sTopic)
266 htblTopicsNew.Add(c.htblTopics(sKey))
267 Next
268 Next
269 c.htblTopics = htblTopicsNew
270 Next
271
272 Display(vbCrLf & vbCrLf, True)
273
274 For Each task As clsTask In Adventure.htblTasks.Values
275 ReDim task.NewReferences(task.References.Count - 1)
276 Next
277
278 If Adventure.htblLocations.Count = 0 Then
279 ErrMsg("This adventure has no locations. Cannot continue.")
280 Return False
281 End If
282
283 PrepareForNextTurn()
284
285 Return True
286 Else
287 Return False
288 End If
289
290 End Function
291
292
293 Public Sub InitialiseInputBox(Optional ByVal sCursor As String = "Ø")
294 Glue.InitInput()
295 End Sub
296
297 Public bDisplaying As Boolean = False ' In case any output is once only - don't want it to trigger when we're just testing the text
298 Public Sub Display(ByVal sText As String, Optional ByVal bCommit As Boolean = False, Optional ByVal bAllowALR As Boolean = True, Optional ByVal bRecord As Boolean = True)
299
300 bDisplaying = True
301 Dim bAllowPSpace As Boolean = True
302
303 If Adventure IsNot Nothing AndAlso Adventure.dVersion < 5 Then
304 ' ViewRoom function used to always start at beginning of line, so no pspace
305 If sText.StartsWith("%DisplayLocation[") Then bAllowPSpace = False
306 End If
307
308 If Adventure IsNot Nothing AndAlso bAllowALR Then sText = ReplaceALRs(sText)
309 If bAllowPSpace AndAlso sText <> vbCrLf AndAlso sText <> "" Then
310 sOutputText = pSpace(sOutputText) & sText
311 Else
312 sOutputText = sOutputText & sText
313 End If
314
315 If bCommit Then
316 ' Ensure text doesn't get output more than once...
317 Dim theText As String = sOutputText
318 sOutputText = ""
319 Source2HTML(theText, fRunner.txtOutput, False)
320
321 If bRecord Then
322 While theText.EndsWith(vbCrLf)
323 theText = theText.Substring(0, theText.Length - 2)
324 End While
325 sTurnOutput &= theText
326 End If
327 End If
328
329 bDisplaying = False
330 End Sub
331
332 Public Sub LoadDefaults()
333 CreatePlayer()
334 CreateRequiredProperties()
335 End Sub
336
337
338 Private Sub CreatePlayer()
339 Dim Player As New clsCharacter
340 With Player
341 .ProperName = "Player"
342 .CharacterType = clsCharacter.CharacterTypeEnum.Player
343 .Key = "Player"
344 End With
345 Adventure.htblCharacters.Add(Player, Player.Key)
346 End Sub
347
348 Private Sub CreateRequiredProperties()
349
350 Dim pStaticDynamic As New clsProperty
351 With pStaticDynamic
352 .Key = "StaticOrDynamic"
353 .Description = "Object type"
354 .Type = clsProperty.PropertyTypeEnum.StateList
355 .arlStates.Add("Static")
356 .arlStates.Add("Dynamic")
357 .Mandatory = True
358 End With
359 Adventure.htblAllProperties.Add(pStaticDynamic)
360
361 Dim pSurface As New clsProperty
362 With pSurface
363 .Key = "Surface"
364 .Description = "This object has a surface"
365 .Type = clsProperty.PropertyTypeEnum.SelectionOnly
366 End With
367 Adventure.htblAllProperties.Add(pSurface)
368
369 Dim pSurfaceHold As New clsProperty
370 With pSurfaceHold
371 .Key = "SurfaceHold"
372 .Description = "Surface can hold"
373 .Type = clsProperty.PropertyTypeEnum.Integer
374 .DependentKey = "Surface"
375 End With
376 Adventure.htblAllProperties.Add(pSurfaceHold)
377
378 Dim pReadable As New clsProperty
379 With pReadable
380 .Key = "Readable"
381 .Description = "This object is readable"
382 .Type = clsProperty.PropertyTypeEnum.SelectionOnly
383 End With
384 Adventure.htblAllProperties.Add(pReadable)
385
386 Dim pReadText As New clsProperty
387 With pReadText
388 .Key = "ReadText"
389 .Description = "Description when read"
390 .Type = clsProperty.PropertyTypeEnum.Text
391 .DependentKey = "Readable"
392 End With
393 Adventure.htblAllProperties.Add(pReadText)
394
395 Dim pWearable As New clsProperty
396 With pWearable
397 .Key = "Wearable"
398 .Description = "Wearable"
399 .Type = clsProperty.PropertyTypeEnum.SelectionOnly
400 .DependentKey = "StaticOrDynamic"
401 .DependentValue = "Dynamic"
402 End With
403 Adventure.htblAllProperties.Add(pWearable)
404
405 Dim pContainer As New clsProperty
406 With pContainer
407 .Key = "Container"
408 .Description = "This object is a container"
409 .Type = clsProperty.PropertyTypeEnum.SelectionOnly
410 End With
411 Adventure.htblAllProperties.Add(pContainer)
412
413 Dim pContainerHold As New clsProperty
414 With pContainerHold
415 .Key = "ContainerHold"
416 .Description = "Container can hold"
417 .Type = clsProperty.PropertyTypeEnum.Integer
418 .DependentKey = "Container"
419 End With
420 Adventure.htblAllProperties.Add(pContainerHold)
421
422 Dim pOpenable As New clsProperty
423 With pOpenable
424 .Key = "Openable"
425 .Description = "Object can be opened and closed"
426 .Type = clsProperty.PropertyTypeEnum.StateList
427 .arlStates.Add("Open")
428 .arlStates.Add("Closed")
429 End With
430 Adventure.htblAllProperties.Add(pOpenable)
431
432 Dim pLockable As New clsProperty
433 With pLockable
434 .Key = "Lockable"
435 .Description = "And is lockable, with key"
436 .Type = clsProperty.PropertyTypeEnum.ObjectKey
437 .DependentKey = "Openable"
438 End With
439 Adventure.htblAllProperties.Add(pLockable)
440
441 Dim pSittable As New clsProperty
442 With pSittable
443 .Key = "Sittable"
444 .Description = "Characters can sit on this object"
445 .Type = clsProperty.PropertyTypeEnum.SelectionOnly
446 End With
447 Adventure.htblAllProperties.Add(pSittable)
448
449 Dim pStandable As New clsProperty
450 With pStandable
451 .Key = "Standable"
452 .Description = "Characters can stand on this object"
453 .Type = clsProperty.PropertyTypeEnum.SelectionOnly
454 End With
455 Adventure.htblAllProperties.Add(pStandable)
456
457 Dim pLieable As New clsProperty
458 With pLieable
459 .Key = "Lieable"
460 .Description = "Characters can lie on this object"
461 .Type = clsProperty.PropertyTypeEnum.SelectionOnly
462 End With
463 Adventure.htblAllProperties.Add(pLieable)
464
465 Dim pEdible As New clsProperty
466 With pEdible
467 .Key = "Edible"
468 .Description = "Object is edible"
469 .Type = clsProperty.PropertyTypeEnum.SelectionOnly
470 .DependentKey = "StaticOrDynamic"
471 .DependentValue = "Dynamic"
472 End With
473 Adventure.htblAllProperties.Add(pEdible)
474
475 End Sub
476
477
478 Public Sub Process(ByVal sCommand As String)
479
480 If Not Adventure Is Nothing Then
481 iPreviousOffset = fRunner.txtOutput.TextLength
482 If iPrepProgress = 0 Then iPrepProgress = 1
483 bNoDebug = False
484 dtDebug = Now
485 iDebugIndent = 0
486 bSystemTask = False
487 Dim dtStart As Date = Now
488 While iPrepProgress <> 2 AndAlso Now < dtStart.AddSeconds(10) ' Wait for the other thread to finish
489 Application.DoEvents()
490 Threading.Thread.Sleep(1)
491 End While
492 sInput = sCommand
493
494 If EvaluateInput(0, False) = "***SYSTEM***" Then
495 sOutputText = ""
496 Exit Sub
497 End If
498 bNoDebug = True
499
500 CheckEndOfGame()
501 If Adventure.eGameState <> clsAction.EndGameEnum.Running Then Exit Sub
502
503 iPrepProgress = 0
504 PrepareForNextTurn()
505
506 Adventure.Player.DoWalk()
507 End If
508 End Sub
509
510
511 Private Sub CheckEndOfGame()
512 If Not Adventure.bDisplayedWinLose Then
513 Select Case Adventure.eGameState
514 Case clsAction.EndGameEnum.Win
515 Display("<center><c><b>*** You have won ***</b></c></center>" & vbCrLf, True)
516 Case clsAction.EndGameEnum.Lose
517 Display("<center><c><b>*** You have lost ***</b></c></center>" & vbCrLf, True)
518 Case clsAction.EndGameEnum.Neutral
519 ' Don't display anything
520 Case clsAction.EndGameEnum.Running
521 ' Continue
522 End Select
523 If Adventure.eGameState <> clsAction.EndGameEnum.Running Then States.RecordState()
524 End If
525 If Adventure.eGameState <> clsAction.EndGameEnum.Running Then
526 Adventure.Player.WalkTo = ""
527 If Not Adventure.bDisplayedWinLose AndAlso Adventure.WinningText.ToString(True) <> "" Then
528 Display(Adventure.WinningText.ToString & vbCrLf)
529 End If
530 If Adventure.MaxScore > 0 AndAlso Not Adventure.bDisplayedWinLose Then
531 Display("In that game you scored " & Adventure.Score & " out of a possible " & Adventure.MaxScore & ", in " & Adventure.Turns & " turns." & vbCrLf & vbCrLf, True)
532 End If
533 Display("Would you like to <c>restart</c>, <c>restore</c> a saved game, <c>quit</c> or <c>undo</c> the last command?" & vbCrLf & vbCrLf, True)
534 Adventure.bDisplayedWinLose = True
535 End If
536 End Sub
537
538
539 Private Function KeyListsMatch(ByVal salSpecifics As StringArrayList, ByVal salReferences As ArrayList, ByVal bMultiple As Boolean) As Boolean
540 If salSpecifics.Count = salReferences.Count Then
541 For Each sSpecific As String In salSpecifics
542 Dim bFound As Boolean = False
543 For Each salRef As StringArrayList In salReferences
544 If salRef(0) = sSpecific Then
545 bFound = True
546 Exit For
547 End If
548 Next
549 If Not bFound Then Return False
550 Next
551 Else
552 Return False
553 End If
554
555 Return True
556 End Function
557
558
559 ' Ensures every Reference has at least one object assigned to it
560 Private Function AllRefsHaveAtLeastOne() As Boolean
561 If NewReferences Is Nothing Then Return False
562
563 For iRef As Integer = 0 To NewReferences.Length - 1
564 With NewReferences(iRef)
565 If .Items.Count > 0 Then
566 For Each itm As clsSingleItem In .Items
567 If itm.MatchingPossibilities.Count = 0 Then Return False
568 Next
569 Else
570 Return False
571 End If
572 End With
573 Next
574 Return True
575 End Function
576
577
578 ' If we have multiple commands, and we are matching on a different command, make sure we get the right ref
579 ' E.g. give %object% to %character%
580 ' give %character% %object%
581 Private Function GetAlternateRef(ByVal task As clsTask, ByVal iRef As Integer) As Integer
582 While task.TaskType = clsTask.TaskTypeEnum.Specific AndAlso task.Parent <> ""
583 task = Adventure.htblTasks(task.Parent)
584 End While
585
586 Dim sMatchingRef As String = task.References(iRef)
587 Dim iMatch As Integer = 0
588
589 For Each sOrigRef As String In task.RefsInCommand(task.TaskCommand(task, False, 0))
590 If sOrigRef = sMatchingRef Then Return iMatch
591 iMatch += 1
592 Next
593 Return iRef
594 End Function
595
596 ' Specifics are always defined in the order of the first command in the task
597 ' We may be matching on a different command, in which case Specifics will be
598 ' in a different order from the References
599 '
600 Private Function RefsMatchSpecifics(ByVal tasChild As clsTask) As Boolean
601 Dim aSpecifics() As clsTask.Specific = tasChild.Specifics
602 Dim alSpecs As New ArrayList
603 Dim salRefs As New StringArrayList
604
605 ' See if we have all the Specifics we need in the References
606 If NewReferences IsNot Nothing AndAlso aSpecifics.Length = NewReferences.Length Then
607 For iSpec As Integer = 0 To aSpecifics.Length - 1
608 ' Make sure References contains all Specifics
609 With aSpecifics(iSpec)
610 For Each sKey As String In .Keys ' We must find all of these in order for the task to match
611 Dim bKeyFoundInRefs As Boolean = False
612 If sKey = "" Then ' i.e. match any object/character etc...
613 bKeyFoundInRefs = True
614 Else
615 If sKey.Contains("%") Then sKey = ReplaceFunctions(sKey)
616
617 Dim iReference As Integer = iSpec
618 ' TODO - If this is matching on a second command in the task where the refs are the other way around, it fails to match the specifics
619 ' This is because Specific tasks always match on the first General task command
620 If UserSession.iMatchedTaskCommand > 0 Then
621 iReference = GetAlternateRef(tasChild, iReference)
622 End If
623
624 ' Grab the correct Reference
625 Dim NewRef As clsNewReference = NewReferences(iReference)
626 For Each Ref As clsNewReference In NewReferences
627 If Ref.Index = iSpec Then
628 NewRef = Ref
629 Exit For
630 End If
631 Next
632
633 For iRef As Integer = NewRef.Items.Count - 1 To 0 Step -1
634 If NewRef.Items(iRef).MatchingPossibilities(0).ToLower = sKey.ToLower Then
635 bKeyFoundInRefs = True
636 alSpecs.Add(iSpec)
637 salRefs.Add(sKey)
638 Exit For
639 End If
640 Next
641 End If
642 If Not bKeyFoundInRefs Then Return False
643 Next
644 End With
645 Next
646 Else
647 ' Not matching same amount
648 Return False
649 End If
650 Return True
651 End Function
652
653
654 Private Function RefsMatchSpecificsOld(ByVal tasChild As clsTask) As Boolean
655 Dim aSpecifics() As clsTask.Specific = tasChild.Specifics
656 Dim alSpecs As New ArrayList
657 Dim salRefs As New StringArrayList
658
659 ' See if we have all the Specifics we need in the References
660 If NewReferences IsNot Nothing AndAlso aSpecifics.Length = NewReferences.Length Then
661 For iSpec As Integer = 0 To aSpecifics.Length - 1
662 ' Make sure References contains all Specifics
663 With aSpecifics(iSpec)
664 For Each sKey As String In .Keys ' We must find all of these in order for the task to match
665 Dim bKeyFoundInRefs As Boolean = False
666 If sKey = "" Then
667 bKeyFoundInRefs = True
668 Else
669 If sKey = "%Player%" Then sKey = Adventure.Player.Key
670 For iRef As Integer = NewReferences(iSpec).Items.Count - 1 To 0 Step -1
671 If NewReferences(iSpec).Items(iRef).MatchingPossibilities(0) = sKey Then
672 bKeyFoundInRefs = True
673 alSpecs.Add(iSpec)
674 salRefs.Add(sKey)
675 Exit For
676 End If
677 Next
678 End If
679 If Not bKeyFoundInRefs Then Return False
680 Next
681 End With
682 Next
683 Else
684 ' Not matching same amount
685 Return False
686 End If
687 Return True
688 End Function
689
690
691 Friend Sub DebugPrint(ByVal eItemType As ItemEnum, ByVal sKey As String, ByVal eDetailLevel As DebugDetailLevelEnum, ByVal sMessage As String, Optional ByVal bNewLine As Boolean = True)
692 End Sub
693
694
695 Private Function ExecuteSubTasks(ByVal sTaskKey As String, ByVal bCalledFromEvent As Boolean, ByVal bChildTask As Boolean, ByVal InReferences() As clsNewReference, ByVal iRefIndex As Integer, ByVal sReferenceKeys() As String, ByVal sReferenceCommands() As String, ByRef bTaskHasOutputNew As Boolean, ByVal bPassingOnly As Boolean) As Boolean
696 If iRefIndex < InReferences.Length Then
697 If InReferences(iRefIndex) Is Nothing OrElse InReferences(iRefIndex).Items Is Nothing OrElse InReferences(iRefIndex).Items.Count = 0 Then
698 sReferenceKeys(iRefIndex) = ""
699 sReferenceCommands(iRefIndex) = ""
700 If ExecuteSubTasks(sTaskKey, bCalledFromEvent, bChildTask, InReferences, iRefIndex + 1, sReferenceKeys, sReferenceCommands, bTaskHasOutputNew, bPassingOnly) Then Return True
701 Else
702 For iItem As Integer = 0 To InReferences(iRefIndex).Items.Count - 1
703 If InReferences(iRefIndex).Items(iItem).MatchingPossibilities.Count > 0 Then
704 sReferenceKeys(iRefIndex) = InReferences(iRefIndex).Items(iItem).MatchingPossibilities(0)
705 Else
706 TODO("Check that this is intended...") ' Assume it's ok to leave this reference key as Nothing as there was no match
707 End If
708 sReferenceCommands(iRefIndex) = InReferences(iRefIndex).Items(iItem).sCommandReference
709 If ExecuteSubTasks(sTaskKey, bCalledFromEvent, bChildTask, InReferences, iRefIndex + 1, sReferenceKeys, sReferenceCommands, bTaskHasOutputNew, bPassingOnly) Then ExecuteSubTasks = True
710 Next
711 End If
712 Else
713 ' Ok, let's execute 'em
714 If AttemptToExecuteSubTask(sTaskKey, sReferenceKeys, bCalledFromEvent, bChildTask, sReferenceCommands, bTaskHasOutputNew, bPassingOnly) Then Return True
715 End If
716 End Function
717
718
719 ' EvaluateResponses - Should we replace functions for anything output by this task? We do this so that e.g. ViewRoom will be at the time the task was executed
720 ' bPassingOnly - Only do anything with the task if it passes. Means we already have a failing task with output, so don't need another
721 ' bAssignSpecificRefs - If we are attempting to run a specific task(e.g. from an event) then set the refs to those defined in the task
722 '
723 Public Function AttemptToExecuteTask(ByVal sTaskKey As String, Optional ByVal bCalledFromEvent As Boolean = False, Optional ByVal bSkipRestrictionsTest As Boolean = False, Optional ByVal bChildTask As Boolean = False, Optional ByRef bContinue As Boolean = False, Optional ByRef bTaskHasOutputNew As Boolean = False, Optional ByVal bEvaluateResponses As Boolean = False, Optional bPassingOnly As Boolean = False, Optional bAssignSpecificRefs As Boolean = False) As Boolean
724 ' E.g. if our task is "get red ball and blue ball from box", then subtasks are
725 ' "get red ball from box" and
726 ' "get blue ball from box"
727
728 Dim task As clsTask = Adventure.htblTasks(sTaskKey)
729
730 If task.Completed AndAlso Not task.Repeatable Then Return False
731 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.Low, "Attempting to execute task " & task.Description & "...")
732
733 Dim htblResponsesPassTemp As OrderedHashTable = Nothing
734 Dim htblResponsesFailTemp As OrderedHashTable = Nothing
735 If Not bChildTask Then
736 If htblResponsesPass.Count > 0 Then htblResponsesPassTemp = htblResponsesPass.Clone
737 If htblResponsesFail.Count > 0 Then htblResponsesFailTemp = htblResponsesFail.Clone
738 htblResponsesPass.Clear() ' Will this cause a problem, or do we just need to call it before events run tasks for example?
739 htblResponsesFail.Clear()
740 End If
741
742 ' This is really just in case anyone tries to run a specific task from an event - we need to know what the refs should be
743 If task.TaskType = clsTask.TaskTypeEnum.Specific AndAlso bAssignSpecificRefs Then
744 ReDim NewReferences(task.Specifics.Length - 1)
745 For i As Integer = 0 To NewReferences.Length - 1
746 NewReferences(i) = New clsNewReference(task.Specifics(i).Type)
747 With NewReferences(i)
748 For Each sKey As String In task.Specifics(i).Keys
749 .Items.Add(New clsSingleItem(sKey))
750 Next
751 End With
752 Next
753 End If
754
755 Dim bPass As Boolean = False
756 Dim InReferences() As clsNewReference = task.CopyNewRefs(NewReferences)
757 If InReferences Is Nothing Then ReDim InReferences(-1)
758
759 ' If we mention any characters on the command line, add them to the mentioned characters list (so we get "the" char rather than "a" char)
760 For Each ref As clsNewReference In InReferences
761 If ref IsNot Nothing Then
762 If ref.ReferenceType = ReferencesType.Character Then
763 For Each itm As clsSingleItem In ref.Items
764 If itm.MatchingPossibilities.Count = 1 Then
765 If Adventure.htblCharacters.ContainsKey(itm.MatchingPossibilities(0)) Then
766 Dim ch As clsCharacter = Adventure.htblCharacters(itm.MatchingPossibilities(0))
767 Adventure.lCharMentionedThisTurn(ch.Gender).Add(ch.Key)
768 End If
769 End If
770 Next
771 End If
772 End If
773 Next
774
775 Dim sReferenceKeys(InReferences.Length - 1) As String
776 Dim sReferenceCommands(InReferences.Length - 1) As String
777 bPass = ExecuteSubTasks(sTaskKey, bCalledFromEvent, bChildTask, InReferences, 0, sReferenceKeys, sReferenceCommands, bTaskHasOutputNew, bPassingOnly)
778
779 If bPassingOnly AndAlso Not bPass Then Return False
780
781 If Not bChildTask OrElse bEvaluateResponses Then
782 ' Create htblResponses from everything in htblResponsesPass, plus anything from ResponsesFail that isn't in ResponsesPass
783 Dim htblResponses As New OrderedHashTable
784 For Each sKey As String In htblResponsesPass.OrderedKeys
785 htblResponses.Add(sKey, htblResponsesPass(sKey))
786 Next
787
788 If htblResponsesPass.Count = 0 AndAlso htblResponsesFail.Count >= 0 AndAlso task.FailOverride.ToString <> "" AndAlso ContainsWord(sInput, "all") Then
789 Display(task.FailOverride.ToString)
790 Else
791
792 ' Get A, B, C from D
793 ' Pass: You pick up A, B from D
794 ' Fail: You can't get A from D
795 ' Fail: B, C is too heavy to pick up
796 ' Need: You pick up A, B from D. C is too heavy to pick up.
797
798 ' TODO - We could have responses from different tasks here. We need to only match references from the same parent task
799 ' So, for example, if we have an action that executes a different task with a different number of references, the different
800 ' tasks should not cancel each other out.
801 ' E.g. Stand on current object. Has no references, but executes task as action which has a parameter
802
803 ' So look at every reference combination in each failure message. If we don't have that combination in our pass set then add it
804 For Each sFailMessage As String In htblResponsesFail.OrderedKeys
805 Dim refsFail() As clsNewReference = CType(htblResponsesFail(sFailMessage), clsNewReference())
806 Dim bAllMatch As Boolean = False
807
808 For Each sPassMessage As String In htblResponsesPass.OrderedKeys
809 Dim refsPass() As clsNewReference = CType(htblResponsesPass(sPassMessage), clsNewReference())
810 bAllMatch = True
811
812 For iRef As Integer = 0 To refsFail.Length - 1
813 Dim refFail As clsNewReference = refsFail(iRef)
814 If refFail Is Nothing Then ' I think this is where our task could be executing a different task, with different references...
815 bAllMatch = False
816 Else
817 For iItm As Integer = 0 To refFail.Items.Count - 1
818 Dim itmFail As clsSingleItem = refFail.Items(iItm)
819 ' There should only be one matching possibility here, so no need to iterate them
820
821 ' resPass(iRef) Is Nothing - think this may also be different task/different refs issue...
822 ' Should only do this if it is for the same parent task. If we execute a sub-task, that should become the parent
823 If refsPass.Length <= iRef OrElse refsPass(iRef) Is Nothing OrElse refsPass(iRef).Items.Count <= iItm OrElse refsPass(iRef).Items(iItm).MatchingPossibilities(0) <> itmFail.MatchingPossibilities(0) Then
824 ' This fail is different from this pass
825 bAllMatch = False
826 GoTo NextPassMessage
827 End If
828
829 Next iItm
830 End If
831 Next iRef
832 NextPassMessage:
833 If bAllMatch Then Exit For
834 Next sPassMessage
835
836 If Not bAllMatch Then
837 ' We've found a failure message that didn't match any pass messages
838 If htblResponses.ContainsKey(sFailMessage) Then
839 ' Need to add refs for this message into the message
840 ' TODO
841 sFailMessage = sFailMessage
842 Else
843 ' Need to add this message
844 htblResponses.Add(sFailMessage, htblResponsesFail(sFailMessage))
845 End If
846 End If
847
848 Next sFailMessage
849
850 For Each sMessage As String In htblResponses.OrderedKeys
851 Dim refs As clsNewReference() = CType(htblResponses(sMessage), clsNewReference())
852
853 NewReferences = refs
854 Display(sMessage)
855 Next
856
857 End If
858
859 If bEvaluateResponses Then
860 htblResponsesPass.Clear()
861 htblResponsesFail.Clear()
862 End If
863 End If
864
865 If bPass Then
866 ' Check any walks/events to see if anything triggers on this task completing
867 For Each c As clsCharacter In Adventure.htblCharacters.Values
868 For Each w As clsWalk In c.arlWalks
869 For Each ctrl As EventOrWalkControl In w.WalkControls
870 If ctrl.eCompleteOrNot = EventOrWalkControl.CompleteOrNotEnum.Completion AndAlso ctrl.sTaskKey = task.Key Then
871 ' If a child task of the current task has affected the walk control, ignore this as a trigger
872 If w.sTriggeringTask = "" OrElse Not task.Children(True).Contains(w.sTriggeringTask) Then
873 Select Case ctrl.eControl
874 Case EventOrWalkControl.ControlEnum.Resume
875 w.Resume()
876 Case EventOrWalkControl.ControlEnum.Start
877 w.Start()
878 Case EventOrWalkControl.ControlEnum.Stop
879 w.Stop()
880 Case EventOrWalkControl.ControlEnum.Suspend
881 w.Pause()
882 End Select
883 w.sTriggeringTask = task.Key
884 End If
885 End If
886 Next
887 Next
888 Next
889 For Each e As clsEvent In Adventure.htblEvents.Values
890 For Each ctrl As EventOrWalkControl In e.EventControls
891 If ctrl.eCompleteOrNot = EventOrWalkControl.CompleteOrNotEnum.Completion AndAlso ctrl.sTaskKey = task.Key Then
892 ' If a child task of the current task has affected the walk control, ignore this as a trigger
893 If e.sTriggeringTask = "" OrElse Not task.Children(True).Contains(e.sTriggeringTask) Then
894 Select Case ctrl.eControl
895 Case EventOrWalkControl.ControlEnum.Resume
896 e.Resume()
897 Case EventOrWalkControl.ControlEnum.Start
898 e.Start()
899 Case EventOrWalkControl.ControlEnum.Stop
900 e.Stop()
901 Case EventOrWalkControl.ControlEnum.Suspend
902 e.Pause()
903 End Select
904 e.sTriggeringTask = task.Key
905 End If
906 End If
907 Next
908 Next
909 End If
910
911 If Not bCalledFromEvent Then
912 If task.ContinueToExecuteLowerPriority Then
913 bContinue = True
914 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Continuing trying to execute lower priority tasks (multiple matches)")
915 Else
916 If bPass Then
917 If bTaskHasOutputNew Then
918 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Task passes and has output. Will not execute lower priority tasks")
919 Else
920 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Task passes but has no output, therefore will continue to execute lower priority tasks")
921 bContinue = True
922 End If
923 Else
924 If Adventure.TaskExecution = clsAdventure.TaskExecutionEnum.HighestPriorityPassingTask Then
925 If bTaskHasOutputNew Then
926 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Task fails but has output. Will continue trying execute lower priority tasks")
927 ' Hmm, we actually want to execute lower priority tasks EXCEPT library ones...
928 bContinue = True
929 Else
930 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Task does not pass and also has no output, therefore will continue to execute lower priority tasks")
931 bContinue = True
932 End If
933 Else
934 If Not bTaskHasOutputNew Then
935 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Task does not pass and also has no output, therefore will continue to execute lower priority tasks")
936 bContinue = True
937 End If
938 End If
939 End If
940 End If
941
942 If bContinue AndAlso Not bChildTask Then
943 UpdateStatusBar()
944 EvaluateInput(task.Priority + 1, Not bPass AndAlso bTaskHasOutputNew)
945 End If
946 End If
947
948 If htblResponsesPassTemp IsNot Nothing Then htblResponsesPass = htblResponsesPassTemp.Clone
949 If htblResponsesFailTemp IsNot Nothing Then htblResponsesFail = htblResponsesFailTemp.Clone
950
951 Return bPass
952 End Function
953
954
955 ' Returns True if the SubTask was completed successfully
956 Public Function AttemptToExecuteSubTask(ByVal sTaskKey As String, ByVal sReferences() As String, ByVal bCalledFromEvent As Boolean, ByVal bChildTask As Boolean, ByVal sReferenceCommands() As String, ByRef bTaskHasOutputNew As Boolean, ByVal bPassingOnly As Boolean) As Boolean
957
958 Try
959 AttemptToExecuteSubTask = False
960
961 Dim task As clsTask = Adventure.htblTasks(sTaskKey)
962
963 ReDim NewReferences(sReferences.Length - 1)
964
965 If sReferences.Length = 0 Then
966 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.Medium, "Checking reference free task " & task.Description)
967 Else
968 Dim sSubTask As String = ParentTaskCommand(task)
969 For iRef As Integer = 0 To task.References.Count - 1
970 sSubTask = sSubTask.Replace(task.References(iRef), Adventure.GetNameFromKey(sReferences(iRef), False, False))
971 ' Set References to be ones from this particular subtask
972 Dim r As clsNewReference = Nothing
973 Select Case task.References(iRef)
974 Case "%object%", "%object1%", "%object2%", "%object3%", "%object4%", "%object5%", "%objects%"
975 r = New clsNewReference(ReferencesType.Object)
976 Case "%character%", "%character1%", "%character2%", "%character3%", "%character4%", "%character5%", "%characters%"
977 r = New clsNewReference(ReferencesType.Character)
978 Case "%location%", "%location1%", "%location2", "%location3", "%location4", "%location5"
979 r = New clsNewReference(ReferencesType.Location)
980 Case "%item%", "%item1%", "%item2%", "%item3%", "%item4%", "%item5%"
981 r = New clsNewReference(ReferencesType.Item)
982 Case "%direction%", "%direction1%", "%direction2%", "%direction3%", "%direction4%", "%direction5%"
983 r = New clsNewReference(ReferencesType.Direction)
984 Case "%text%", "%text1%", "%text2%", "%text3%", "%text4%", "%text5%"
985 r = New clsNewReference(ReferencesType.Text)
986 Case "%number%", "%number1%", "%number2%", "%number3%", "%number4%", "%number5%"
987 r = New clsNewReference(ReferencesType.Number)
988 Case Else
989 ErrMsg("To do")
990 End Select
991 r.sParentTask = sTaskKey
992 If sReferences(iRef) <> "" Then
993 Dim itm As New clsSingleItem
994 itm.MatchingPossibilities.Add(sReferences(iRef))
995 itm.sCommandReference = sReferenceCommands(iRef)
996 r.Items.Add(itm)
997 r.ReferenceMatch = task.References(iRef).Replace("%", "")
998 End If
999 If task.arlCommands.Count > 0 Then
1000 Dim sRefs As StringArrayList = task.RefsInCommand(task.arlCommands(0))
1001 Select Case task.References(iRef)
1002 Case "%objects%", "%object1%", "%object2%", "%object3%", "%object4%", "%object5%", "%characters%", "%character1%", "%character2%", "%character3%", "%character4%", "%character5%", "%direction1%", "%direction2%", "%direction3%", "%direction4%", "%direction5%", "%number1%", "%number2%", "%number3%", "%number4%", "%number5%", "%text1%", "%text2%", "%text3%", "%text4%", "%text5%", "%item1%", "%item2%", "%item3%", "%item4%", "%item5%"
1003 For iRef2 As Integer = 0 To sRefs.Count - 1
1004 If task.References(iRef) = sRefs(iRef2) Then
1005 r.Index = iRef2
1006 Exit For
1007 End If
1008 Next
1009 End Select
1010 End If
1011 NewReferences(iRef) = r
1012 Next
1013 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.Medium, "Checking " & CStr(IIf(sReferences.Length = 1, "single", IIf(sReferences.Length = 2, "double", "triple or more"))) & " reference task " & sSubTask)
1014 End If
1015
1016 Dim sMessage As String = ""
1017 Dim bPass As Boolean = PassRestrictions(task.arlRestrictions, , task)
1018 Dim bOutputMessages As Boolean = False
1019
1020 If bPass Then
1021 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.Medium, "Passed Restrictions")
1022
1023 ' Remove any failing refs if this ref passes
1024 For Each sFailMessage As String In htblResponsesFail.OrderedKeys
1025 Dim refsFail() As clsNewReference = CType(htblResponsesFail(sFailMessage), clsNewReference())
1026
1027 For iRef As Integer = 0 To refsFail.Length - 1
1028 Dim refFail As clsNewReference = refsFail(iRef)
1029 If refFail IsNot Nothing Then
1030 For iItm As Integer = 0 To refFail.Items.Count - 1
1031 Dim itmFail As clsSingleItem = refFail.Items(iItm)
1032 ' There should only be one matching possibility here, so no need to iterate them
1033 If NewReferences(iRef) Is Nothing OrElse NewReferences(iRef).Items(iItm).MatchingPossibilities(0) <> itmFail.MatchingPossibilities(0) Then
1034 ' This fail is different from this pass
1035 GoTo NextMessage
1036 End If
1037 Next iItm
1038 End If
1039 Next iRef
1040
1041 ' Ok, lets remove the failed one
1042 htblResponsesFail.Remove(sFailMessage)
1043 Exit For ' There should only be one matching the refs, so bomb out so we don't cause problem iterating loop
1044 NextMessage:
1045 Next sFailMessage
1046
1047 ' If this task contains references, see if we have a specific task
1048 If task.Children.Count > 0 Then DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Checking whether any of our child tasks should override...")
1049
1050 Dim bShouldParentOutputText As Boolean = True
1051 Dim bShouldParentExecuteTasks As Boolean = True
1052 Dim bAnyChildHasOutput As Boolean = False
1053 Dim lAfterChildren As New List(Of String)
1054
1055
1056 For Each sChildTask As String In task.Children ' in order or priority...
1057 Dim tasChild As clsTask = Adventure.htblTasks(sChildTask)
1058 If task.TaskType = clsTask.TaskTypeEnum.Specific Then
1059 ' If our parent is a Specific task, we may need to pad our Specifics out with any that have been dropped
1060 If task.Specifics.Length <> tasChild.Specifics.Length Then
1061 ' TODO - These may be in the wrong order if we're matching on a secondary command!
1062 Dim newSpecs(task.Specifics.Length - 1) As clsTask.Specific
1063 Dim iChild As Integer = 0
1064 For i As Integer = 0 To task.Specifics.Length - 1
1065 newSpecs(i) = task.Specifics(i)
1066 If newSpecs(i).Keys.Count = 0 OrElse (newSpecs(i).Keys.Count = 1 AndAlso newSpecs(i).Keys(0) = "") Then
1067 newSpecs(i) = tasChild.Specifics(iChild)
1068 iChild += 1
1069 End If
1070 Next
1071 tasChild.Specifics = newSpecs
1072 End If
1073 End If
1074 Dim iMatchCount As Integer = 0
1075
1076 If RefsMatchSpecifics(tasChild) Then ' This should remove the ref so it doesn't get processed when we execute the main task
1077 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.Medium, "Overriding child task found: " & tasChild.Description)
1078
1079 Select Case tasChild.SpecificOverrideType
1080 Case clsTask.SpecificOverrideTypeEnum.BeforeActionsOnly, clsTask.SpecificOverrideTypeEnum.BeforeTextAndActions, clsTask.SpecificOverrideTypeEnum.BeforeTextOnly, clsTask.SpecificOverrideTypeEnum.Override
1081 iDebugIndent += 1
1082 Dim bContinueExecutingTasks As Boolean = False
1083
1084 If tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.Override Then
1085 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.High, "Override Parent")
1086 Else
1087 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.High, "Run Before Parent")
1088 End If
1089
1090 ' Make a note of how many failing responses we have, so we know if this task has failing output
1091 Dim iFailRefsBefore As Integer = 0
1092 If task.References.Count = 0 Then
1093 iFailRefsBefore += htblResponsesFail.Count
1094 Else
1095 For Each responses() As clsNewReference In htblResponsesFail.Values
1096 For Each response As clsNewReference In responses
1097 iFailRefsBefore += response.Items.Count
1098 Next
1099 Next
1100 End If
1101
1102
1103 Dim bChildTaskHasOutput As Boolean = False
1104 If AttemptToExecuteTask(tasChild.Key, bCalledFromEvent, , True, bContinueExecutingTasks, bChildTaskHasOutput, , bAnyChildHasOutput) Then
1105 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.High, "Child task passes")
1106 If tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.BeforeActionsOnly OrElse tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.BeforeTextAndActions Then
1107 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.Medium, "Execute Parent actions...")
1108 Else
1109 bShouldParentExecuteTasks = False
1110 End If
1111 If tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.BeforeTextAndActions OrElse tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.BeforeTextOnly Then
1112 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.Medium, "Output Parent text...")
1113 Else
1114 bShouldParentOutputText = False
1115 End If
1116 AttemptToExecuteSubTask = True
1117 Else
1118 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.High, "Child task fails")
1119 ' Ok, compare failing output vs what it was before - if we have failing output, this takes precedence over parent if set
1120 Dim iFailRefsAfter As Integer = 0
1121 If task.References.Count = 0 Then
1122 iFailRefsAfter += htblResponsesFail.Count
1123 Else
1124 For Each responses() As clsNewReference In htblResponsesFail.Values
1125 For Each response As clsNewReference In responses
1126 iFailRefsAfter += response.Items.Count
1127 Next
1128 Next
1129 End If
1130
1131 If iFailRefsAfter > iFailRefsBefore Then
1132 If tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.BeforeTextAndActions OrElse tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.BeforeTextOnly OrElse tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.Override Then
1133 bShouldParentOutputText = False
1134 End If
1135 If tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.BeforeTextAndActions OrElse tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.BeforeActionsOnly OrElse tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.Override Then
1136 bShouldParentExecuteTasks = False
1137 End If
1138 bAnyChildHasOutput = True
1139 End If
1140 End If
1141
1142
1143 bTaskHasOutputNew = bTaskHasOutputNew OrElse bChildTaskHasOutput ' If the child task has output, ensure we are aware of it
1144 iDebugIndent -= 1
1145
1146 If Not bContinueExecutingTasks Then
1147 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.Medium, "Do not continue executing other child tasks.")
1148 Exit For
1149 Else
1150 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.Medium, "Continue executing other child tasks.")
1151 End If
1152
1153 Case Else
1154 lAfterChildren.Add(tasChild.Key)
1155 If tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.AfterActionsOnly OrElse tasChild.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.AfterTextOnly Then
1156 ' TODO - Need to check PassRestrictions to see if we need to suppress parent Text or Actions
1157 End If
1158 End Select
1159 End If
1160 Next
1161
1162 Dim sBeforeActionsMessage As String = ""
1163 Dim iResponsePosition As Integer = -1
1164 If task.eDisplayCompletion = clsTask.BeforeAfterEnum.Before AndAlso bShouldParentOutputText Then
1165 ' We may have already printed these refs out in a child task, so only print them here if we haven't done that
1166 If NewReferences.Length > 0 Then PrintOutReferences()
1167 sMessage = task.CompletionMessage.ToString
1168 If sMessage Is Nothing Then sMessage = ""
1169 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, sMessage)
1170 ' Replace any functions that could be affected by our actions...
1171 ' Can't do this, because %TheObject[%objects%]% will interpret so we get multiple entries if do get all
1172 ' But then it means that %ParentOf[%objects%]% will be incorrect if action moves it
1173 'sMessage = sMessage.Replace("%ParentOf[", "%PrevParentOf[").Replace("%ListObjectsOn[", "%PrevListObjectsOn[").Replace(".Parent.", ".PrevParent.")
1174
1175 ' If we do this then drop all gives us: Ok, I drop X. Ok, I drop Y. Ok, I drop Z.
1176 UserSession.bDisplaying = True
1177 bTestingOutput = True ' Ensure any DisplayOnce descriptions aren't marked as displayed, as we'll mark them in final output (Display)
1178 sBeforeActionsMessage = ReplaceExpressions(ReplaceFunctions(sMessage))
1179 bTestingOutput = False
1180 If sBeforeActionsMessage = sMessage Then sBeforeActionsMessage = ""
1181 UserSession.bDisplaying = False
1182 If sBeforeActionsMessage = "" Then
1183 ' It is safe to add the response now
1184 If Not task.AggregateOutput Then sMessage = ReplaceExpressions(ReplaceFunctions(sMessage))
1185 If AddResponse(bOutputMessages, sMessage, sReferences, True) Then bTaskHasOutputNew = True
1186 Else
1187 ' The response changes with functions, so we can't add yet until we know whether the actions affect the output
1188 Dim htblResponses As OrderedHashTable = CType(IIf(bPass, htblResponsesPass, htblResponsesFail), OrderedHashTable)
1189 iResponsePosition = htblResponses.Count
1190 End If
1191 End If
1192
1193 task.Completed = True
1194 If bShouldParentExecuteTasks Then ExecuteActions(task, bCalledFromEvent, bTaskHasOutputNew)
1195
1196 If sBeforeActionsMessage <> "" Then
1197 ' Check to see if the actions had any effect on the message. If so, add the replaced message. If not, add the unreplaced message
1198 UserSession.bDisplaying = True
1199 bTestingOutput = True
1200 If sBeforeActionsMessage <> ReplaceExpressions(ReplaceFunctions(sMessage)) Then sMessage = sBeforeActionsMessage
1201 bTestingOutput = False
1202 UserSession.bDisplaying = False
1203 If Not task.AggregateOutput Then sMessage = ReplaceExpressions(ReplaceFunctions(sMessage))
1204 If AddResponse(bOutputMessages, sMessage, sReferences, True, iResponsePosition) Then bTaskHasOutputNew = True
1205 End If
1206
1207 If task.eDisplayCompletion = clsTask.BeforeAfterEnum.After AndAlso bShouldParentOutputText Then
1208 sMessage = task.CompletionMessage.ToString
1209 If sMessage Is Nothing Then sMessage = ""
1210 If Not task.AggregateOutput Then sMessage = ReplaceExpressions(ReplaceFunctions(sMessage))
1211 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, sMessage)
1212 If AddResponse(bOutputMessages, sMessage, sReferences, True) Then bTaskHasOutputNew = True
1213 End If
1214
1215
1216 For Each sChildTask As String In lAfterChildren
1217 iDebugIndent += 1
1218
1219 Dim tasChild As clsTask = Adventure.htblTasks(sChildTask)
1220 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.High, "Run After Parent")
1221
1222 Dim bChildTaskHasOutput As Boolean = False
1223 Dim bContinueExecutingTasks As Boolean = False
1224 If AttemptToExecuteTask(tasChild.Key, bCalledFromEvent, , True, bContinueExecutingTasks, bChildTaskHasOutput) Then
1225 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.High, "Child task passes")
1226 AttemptToExecuteSubTask = True
1227 Else
1228 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.High, "Child task fails")
1229 End If
1230
1231
1232 bTaskHasOutputNew = bTaskHasOutputNew OrElse bChildTaskHasOutput ' If the child task has output, ensure we are aware of it
1233 iDebugIndent -= 1
1234 If Not bContinueExecutingTasks Then
1235 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.Medium, "Do not continue executing other child tasks.")
1236 Exit For
1237 Else
1238 DebugPrint(ItemEnum.Task, tasChild.Key, DebugDetailLevelEnum.Medium, "Continue executing other child tasks.")
1239 End If
1240 Next
1241
1242 AttemptToExecuteSubTask = True
1243 Else
1244 If Not bPassingOnly Then
1245 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.Medium, "Failed Restrictions")
1246 sMessage = sRestrictionText
1247
1248 If sMessage Is Nothing Then sMessage = ""
1249 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, sMessage)
1250 If NewReferences.Length > 0 Then PrintOutReferences()
1251
1252 If task.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.AfterTextAndActions OrElse task.SpecificOverrideType = clsTask.SpecificOverrideTypeEnum.AfterTextOnly Then
1253 ' Although this is a failing restriction, it is being output _after_ a successful task, so we need to append to the success list :-/
1254 If sMessage <> "" Then bPass = True
1255 End If
1256 End If
1257 End If
1258
1259 If AddResponse(bOutputMessages, sMessage, sReferences, bPass) Then bTaskHasOutputNew = True
1260
1261 Catch ex As Exception
1262 ErrMsg("Error executing subtask " & sTaskKey, ex)
1263 End Try
1264 End Function
1265
1266 Private Class clsReponse
1267 Public sReferences() As String
1268 Public bPass As Boolean
1269 End Class
1270
1271 ' Determines whether tags in a message correspond to actual output
1272 Private Function bHasOutput(ByVal sText As String) As Boolean
1273 If sText = "" Then
1274 Return False
1275 Else
1276 If StripCarats(sText) = "" Then
1277 Dim sTextLower As String = sText.ToLower
1278 For Each sValid As String In New String() {"<br>", "<center>", "<centre>", "<i>", "</i>", "<b>", "</b>", "<u>", "</u>", "<c>", "</c>", "<font", "</font>", "<right>", "</right>", "<left>", "</left>", "<del>", "<wait", "<cls>", "<img "}
1279 If sTextLower.Contains(sValid) Then Return True
1280 Next
1281 ' Ok, so we have an unknown tag. But the user may be text replacing it, so check for that
1282 If Adventure.htblALRs.ContainsKey(sText) Then
1283 Return True
1284 Else
1285 Return False
1286 End If
1287 Else
1288 Return True
1289 End If
1290 End If
1291 End Function
1292
1293
1294 ' Returns True if a response was added, or False otherwise
1295 Private Function AddResponse(ByRef bOutputMessages As Boolean, ByVal sMessage As String, ByVal sReferences() As String, ByVal bPass As Boolean, Optional iPosition As Integer = -1) As Boolean
1296
1297 If bOutputMessages OrElse Not bHasOutput(sMessage) Then Return False
1298
1299 Dim htblResponses As OrderedHashTable = CType(IIf(bPass, htblResponsesPass, htblResponsesFail), OrderedHashTable)
1300
1301 If htblResponses.ContainsKey(sMessage) Then
1302 ' Add our new references to the ones already there
1303 For iRef As Integer = 0 To sReferences.Length - 1
1304 If CType(htblResponses(sMessage), clsNewReference()).Length > iRef AndAlso CType(htblResponses(sMessage), clsNewReference())(iRef) IsNot Nothing AndAlso Not CType(htblResponses(sMessage), clsNewReference())(iRef).ContainsKey(sReferences(iRef)) Then
1305 CType(htblResponses(sMessage), clsNewReference())(iRef).Items.Add(New clsSingleItem(sReferences(iRef)))
1306 End If
1307 Next
1308 Else
1309 ' Store our references
1310 If iPosition > -1 Then
1311 htblResponses.Insert(sMessage, NewReferences, iPosition)
1312 Else
1313 htblResponses.Add(sMessage, NewReferences)
1314 End If
1315 End If
1316
1317 bOutputMessages = True
1318 Return True
1319
1320 End Function
1321
1322 Public Sub UncompleteTask(ByVal sTaskKey As String)
1323
1324 Adventure.htblTasks(sTaskKey).Completed = False
1325 For Each c As clsCharacter In Adventure.htblCharacters.Values
1326 For Each w As clsWalk In c.arlWalks
1327 For Each wc As EventOrWalkControl In w.WalkControls
1328 If wc.sTaskKey = sTaskKey AndAlso wc.eCompleteOrNot = EventOrWalkControl.CompleteOrNotEnum.UnCompletion Then
1329 Select Case wc.eControl
1330 Case EventOrWalkControl.ControlEnum.Start
1331 If w.Status = clsEvent.StatusEnum.NotYetStarted Then w.Start()
1332 Case EventOrWalkControl.ControlEnum.Stop
1333 If w.Status = clsEvent.StatusEnum.Running Then w.Stop()
1334 Case EventOrWalkControl.ControlEnum.Suspend
1335 If w.Status = clsEvent.StatusEnum.Running Then w.Pause()
1336 Case EventOrWalkControl.ControlEnum.Resume
1337 If w.Status = clsEvent.StatusEnum.Paused Then w.Resume()
1338 End Select
1339 End If
1340 Next
1341 Next
1342 Next
1343 For Each e As clsEvent In Adventure.htblEvents.Values
1344 For Each ec As EventOrWalkControl In e.EventControls
1345 If ec.sTaskKey = sTaskKey AndAlso ec.eCompleteOrNot = EventOrWalkControl.CompleteOrNotEnum.UnCompletion Then
1346 Select Case ec.eControl
1347 Case EventOrWalkControl.ControlEnum.Start
1348 If e.Status = clsEvent.StatusEnum.NotYetStarted Then e.Start()
1349 Case EventOrWalkControl.ControlEnum.Stop
1350 If e.Status = clsEvent.StatusEnum.Running Then e.Stop()
1351 Case EventOrWalkControl.ControlEnum.Suspend
1352 If e.Status = clsEvent.StatusEnum.Running Then e.Pause()
1353 Case EventOrWalkControl.ControlEnum.Resume
1354 If e.Status = clsEvent.StatusEnum.Paused Then e.Resume()
1355 End Select
1356 End If
1357 Next
1358 Next
1359
1360 End Sub
1361
1362
1363 ' Return the token that the reference we're looking at is
1364 Private Function GetReferenceKey(ByVal sTaskCommand As String, ByVal iRefNum As Integer) As String
1365
1366 Dim sTokens() As String = sTaskCommand.Split(" "c)
1367 Dim iWhichRef As Integer = 0
1368 For Each sToken As String In sTokens
1369 Select Case sToken
1370 Case "%character1%", "%character2%", "%character3%", "%character4%", "%character5%", "%characters%", "%direction%", "%number%", "%numbers%", "%object1%", "%object2%", "%object3%", "%object4%", "%object5%", "%objects%", "%text%"
1371 iWhichRef += 1
1372 End Select
1373 If iWhichRef = iRefNum Then
1374 Return sToken.Replace("%object", "ReferencedObject").Replace("%direction", "ReferencedDirection").Replace("%", "")
1375 Exit For
1376 End If
1377 Next
1378
1379 Return ""
1380
1381 End Function
1382
1383 Private Sub ExecuteSingleAction(ByVal actx As clsAction, ByVal sTaskCommand As String, ByVal task As clsTask, Optional ByVal bCalledFromEvent As Boolean = False, Optional ByRef bTaskHasOutputNew As Boolean = False)
1384 Try
1385 Dim act As clsAction = actx.Copy
1386
1387 ' Replace references
1388 Select Case act.sKey1
1389 Case "ReferencedObject", "ReferencedObject1", "ReferencedObject2", "ReferencedObject3", "ReferencedObject4", "ReferencedObject5"
1390 act.sKey1 = GetReference(act.sKey1)
1391 Case "ReferencedObjects"
1392 For iRef As Integer = 0 To NewReferences.Length - 1
1393 With NewReferences(iRef)
1394 If .Items.Count > 0 AndAlso .ReferenceType = ReferencesType.Object AndAlso GetReferenceKey(sTaskCommand, iRef + 1) = "ReferencedObjects" Then
1395 For iOb As Integer = 0 To .Items.Count - 1
1396 If .Items(iOb).MatchingPossibilities.Count > 0 Then
1397 act.sKey1 = .Items(iOb).MatchingPossibilities(0)
1398 ExecuteSingleAction(act, sTaskCommand, task, bTaskHasOutputNew)
1399 End If
1400 Next
1401 End If
1402 End With
1403 Next
1404 Exit Sub
1405 Case "ReferencedDirection", "ReferencedDirection1", "ReferencedDirection2", "ReferencedDirection3", "ReferencedDirection4", "ReferencedDirection5"
1406 act.sKey1 = GetReference(act.sKey1)
1407 Case "ReferencedCharacter", "ReferencedCharacter1", "ReferencedCharacter2", "ReferencedCharacter3", "ReferencedCharacter4", "ReferencedCharacter5"
1408 act.sKey1 = GetReference(act.sKey1)
1409 Case "ReferencedLocation", "ReferencedLocation1", "ReferencedLocation2", "ReferencedLocation3", "ReferencedLocation4", "ReferencedLocation5"
1410 act.sKey1 = GetReference(act.sKey1)
1411 Case "ReferencedItem", "ReferencedItem1", "ReferencedItem2", "ReferencedItem3", "ReferencedItem4", "ReferencedItem5"
1412 act.sKey1 = GetReference(act.sKey1)
1413 Case "ReferencedNumber", "ReferencedNumber1", "ReferencedNumber2", "ReferencedNumber3", "ReferencedNumber4", "ReferencedNumber5"
1414 act.sKey1 = GetReference(act.sKey1)
1415 Case "%Player%"
1416 act.sKey1 = Adventure.Player.Key
1417
1418 End Select
1419 Select Case act.sKey2
1420 Case "ReferencedObject", "ReferencedObject1", "ReferencedObject2", "ReferencedObject3", "ReferencedObject4", "ReferencedObject5"
1421 act.sKey2 = GetReference(act.sKey2)
1422 Case "ReferencedObjects"
1423 For iRef As Integer = 0 To NewReferences.Length - 1
1424 With NewReferences(iRef)
1425 If .Items.Count > 0 AndAlso .ReferenceType = ReferencesType.Object AndAlso GetReferenceKey(sTaskCommand, iRef) = "ReferencedObjects" Then
1426 For iOb As Integer = 0 To .Items.Count - 1
1427 If .Items(iOb).MatchingPossibilities.Count > 0 Then
1428 act.sKey2 = .Items(iOb).MatchingPossibilities(0)
1429 ExecuteSingleAction(act, sTaskCommand, task, bTaskHasOutputNew)
1430 End If
1431 Next
1432 End If
1433 End With
1434 Next
1435 Exit Sub
1436 Case "ReferencedDirection", "ReferencedDirection1", "ReferencedDirection2", "ReferencedDirection3", "ReferencedDirection4", "ReferencedDirection5"
1437 act.sKey2 = GetReference(act.sKey2)
1438 Case "ReferencedCharacter", "ReferencedCharacter1", "ReferencedCharacter2", "ReferencedCharacter3", "ReferencedCharacter4", "ReferencedCharacter5"
1439 act.sKey2 = GetReference(act.sKey2)
1440 Case "ReferencedLocation", "ReferencedLocation1", "ReferencedLocation2", "ReferencedLocation3", "ReferencedLocation4", "ReferencedLocation5"
1441 act.sKey2 = GetReference(act.sKey2)
1442 Case "ReferencedItem", "ReferencedItem1", "ReferencedItem2", "ReferencedItem3", "ReferencedItem4", "ReferencedItem5"
1443 act.sKey2 = GetReference(act.sKey2)
1444 Case "ReferencedNumber", "ReferencedNumber1", "ReferencedNumber2", "ReferencedNumber3", "ReferencedNumber4", "ReferencedNumber5"
1445 act.sKey2 = GetReference(act.sKey2)
1446 Case "%Player%"
1447 act.sKey2 = Adventure.Player.Key
1448
1449 End Select
1450
1451 For i As Integer = 0 To 5
1452 Dim iRef As Integer = i
1453 If iRef > 0 Then iRef -= 1
1454
1455 Dim sRefText As String = "%text" & If(i > 0, i.ToString, "").ToString & "%"
1456 If act.eItem = clsAction.ItemEnum.Conversation AndAlso act.StringValue = sRefText Then
1457 act.StringValue = Adventure.sReferencedText(iRef)
1458 End If
1459 Next
1460
1461
1462 Dim bBadKeys As Boolean = False
1463 Select Case act.eItem
1464 Case clsAction.ItemEnum.EndGame, clsAction.ItemEnum.Time
1465 Case clsAction.ItemEnum.SetVariable, clsAction.ItemEnum.IncreaseVariable, clsAction.ItemEnum.DecreaseVariable, clsAction.ItemEnum.SetTasks, clsAction.ItemEnum.Conversation
1466 If act.sKey1 Is Nothing Then bBadKeys = True
1467 Case Else
1468 If act.sKey1 Is Nothing OrElse act.sKey2 Is Nothing Then bBadKeys = True
1469 End Select
1470 If bBadKeys Then
1471 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.High, "Bad key(s) for action ")
1472 Exit Sub
1473 End If
1474
1475 Select Case act.eItem
1476 Case clsAction.ItemEnum.MoveObject, clsAction.ItemEnum.AddObjectToGroup, clsAction.ItemEnum.RemoveObjectFromGroup
1477 Dim obs As ObjectHashTable = Nothing
1478
1479 Select Case act.eMoveObjectWhat
1480 Case clsAction.MoveObjectWhatEnum.Object
1481 obs = New ObjectHashTable
1482 obs.Add(Adventure.htblObjects(act.sKey1), act.sKey1)
1483 Case clsAction.MoveObjectWhatEnum.EverythingAtLocation
1484 obs = New ObjectHashTable
1485 For Each ob As clsObject In Adventure.htblObjects.Values
1486 If Not ob.IsStatic AndAlso ob.Location.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InLocation AndAlso ob.Location.Key = act.sKey1 Then
1487 obs.Add(ob, ob.Key)
1488 End If
1489 Next
1490 Case clsAction.MoveObjectWhatEnum.EverythingHeldBy
1491 obs = Adventure.htblCharacters(act.sKey1).HeldObjects
1492 Case clsAction.MoveObjectWhatEnum.EverythingInGroup
1493 obs = New ObjectHashTable
1494 For Each sKey As String In Adventure.htblGroups(act.sKey1).arlMembers
1495 obs.Add(Adventure.htblObjects(sKey), sKey)
1496 Next
1497 Case clsAction.MoveObjectWhatEnum.EverythingInside
1498 obs = Adventure.htblObjects(act.sKey1).Children(clsObject.WhereChildrenEnum.InsideObject)
1499 Case clsAction.MoveObjectWhatEnum.EverythingOn
1500 obs = Adventure.htblObjects(act.sKey1).Children(clsObject.WhereChildrenEnum.OnObject)
1501 Case clsAction.MoveObjectWhatEnum.EverythingWithProperty
1502 obs = New ObjectHashTable
1503 Dim prop As clsProperty = Adventure.htblObjectProperties(act.sKey1)
1504 For Each ob As clsObject In Adventure.htblObjects.Values
1505 If ob.HasProperty(prop.Key) Then
1506 If prop.Type = clsProperty.PropertyTypeEnum.SelectionOnly Then
1507 obs.Add(ob, ob.Key)
1508 Else
1509 If ob.GetPropertyValue(prop.Key) = act.sPropertyValue Then obs.Add(ob, ob.Key)
1510 End If
1511 End If
1512 Next
1513 Case clsAction.MoveObjectWhatEnum.EverythingWornBy
1514 obs = Adventure.htblCharacters(act.sKey1).WornObjects
1515 End Select
1516
1517 If obs IsNot Nothing Then
1518 For Each ob As clsObject In obs.Values
1519
1520 Select Case act.eItem
1521 Case clsAction.ItemEnum.MoveObject
1522 Dim dest As New clsObjectLocation
1523 Select Case act.eMoveObjectTo
1524 Case clsAction.MoveObjectToEnum.InsideObject
1525 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InObject
1526 dest.Key = act.sKey2
1527 Case clsAction.MoveObjectToEnum.OntoObject
1528 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.OnObject
1529 dest.Key = act.sKey2
1530 Case clsAction.MoveObjectToEnum.ToCarriedBy
1531 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.HeldByCharacter
1532 dest.Key = act.sKey2
1533
1534 Case clsAction.MoveObjectToEnum.ToLocation
1535 If ob.IsStatic Then
1536 If act.sKey2 = "Hidden" Then ' i.e. Nowhere
1537 dest.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.NoRooms
1538 Else
1539 dest.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.SingleLocation
1540 dest.Key = act.sKey2
1541 End If
1542 Else
1543 If act.sKey2 = "Hidden" Then
1544 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.Hidden
1545 Else
1546 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InLocation
1547 dest.Key = act.sKey2
1548 End If
1549 End If
1550
1551 Case clsAction.MoveObjectToEnum.ToPartOfCharacter
1552 dest.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.PartOfCharacter
1553 dest.Key = act.sKey2
1554
1555 Case clsAction.MoveObjectToEnum.ToPartOfObject
1556 dest.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.PartOfObject
1557 dest.Key = act.sKey2
1558
1559 Case clsAction.MoveObjectToEnum.ToLocationGroup
1560 If ob.IsStatic Then
1561 dest.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.LocationGroup
1562 dest.Key = act.sKey2
1563 Else
1564 ' Need to select one room at random
1565 Dim group As clsGroup = Adventure.htblGroups(act.sKey2)
1566 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InLocation
1567 dest.Key = group.RandomKey
1568 End If
1569
1570 Case clsAction.MoveObjectToEnum.ToSameLocationAs
1571 If ob.IsStatic Then
1572 If Adventure.htblCharacters.ContainsKey(act.sKey2) Then
1573 ' Move Static ob to same location as a character
1574 Dim chDest As clsCharacter = Adventure.htblCharacters(act.sKey2)
1575 If chDest.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation Then
1576 dest.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.SingleLocation
1577 dest.Key = chDest.Location.Key
1578 ElseIf chDest.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.Hidden Then
1579 dest.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.NoRooms
1580 End If
1581 ElseIf Adventure.htblObjects.ContainsKey(act.sKey2) Then
1582 ' Move Static ob to same location as an object
1583 Dim obDest As clsObject = Adventure.htblObjects(act.sKey2)
1584 If obDest.IsStatic Then
1585 dest = obDest.Location.Copy
1586 Else
1587 If obDest.Location.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.Hidden Then
1588 dest.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.NoRooms
1589 Else
1590 dest.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.SingleLocation
1591 For Each loc As clsLocation In obDest.LocationRoots.Values
1592 dest.Key = loc.Key
1593 Exit For
1594 Next
1595 End If
1596 End If
1597 Else
1598 ErrMsg("Cannot move object to same location as " & act.sKey2 & " - key not found!")
1599 End If
1600
1601 Else
1602 If Adventure.htblCharacters.ContainsKey(act.sKey2) Then
1603 ' Move dynamic ob to same location as a character
1604 Dim chDest As clsCharacter = Adventure.htblCharacters(act.sKey2)
1605
1606 Select Case chDest.Location.ExistWhere
1607 Case clsCharacterLocation.ExistsWhereEnum.AtLocation
1608 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InLocation
1609 dest.Key = chDest.Location.Key
1610 Case clsCharacterLocation.ExistsWhereEnum.Hidden
1611 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.Hidden
1612 Case clsCharacterLocation.ExistsWhereEnum.InObject
1613 ' Move the object inside the object we're in - but only if it allows dynamic objects
1614 Dim obDest As clsObject = Adventure.htblObjects(chDest.Location.Key)
1615 If obDest.IsContainer Then
1616 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InObject
1617 dest.Key = chDest.Location.Key
1618 Else
1619 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InLocation
1620 dest.Key = chDest.Location.LocationKey
1621 End If
1622 Case clsCharacterLocation.ExistsWhereEnum.OnCharacter
1623 ' Move to the location that the character is at
1624 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InLocation
1625 dest.Key = chDest.Location.LocationKey
1626 Case clsCharacterLocation.ExistsWhereEnum.OnObject
1627 ' Move the object onto the object we're on - but only if it allows dynamic objects
1628 Dim obDest As clsObject = Adventure.htblObjects(chDest.Location.Key)
1629 If obDest.HasSurface Then
1630 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.OnObject
1631 dest.Key = chDest.Location.Key
1632 Else
1633 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InLocation
1634 dest.Key = chDest.Location.LocationKey
1635 End If
1636 End Select
1637
1638 ElseIf Adventure.htblObjects.ContainsKey(act.sKey2) Then
1639 Dim obDest As clsObject = Adventure.htblObjects(act.sKey2)
1640
1641 If obDest.IsStatic Then
1642 ' If the static object exists in more than one place, pick a random location
1643 Select Case obDest.Location.StaticExistWhere
1644 Case clsObjectLocation.StaticExistsWhereEnum.AllRooms
1645 TODO("Move dynamic object to one of all rooms")
1646 Case clsObjectLocation.StaticExistsWhereEnum.LocationGroup
1647 TODO("Move dynamic object to one of a location group")
1648 Case clsObjectLocation.StaticExistsWhereEnum.NoRooms
1649 obDest.Location.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.Hidden
1650 Case clsObjectLocation.StaticExistsWhereEnum.PartOfCharacter
1651 TODO("Move dynamic object to same room as character")
1652 Case clsObjectLocation.StaticExistsWhereEnum.PartOfObject
1653 TODO("Move dynamic object to same room as part of object")
1654 Case clsObjectLocation.StaticExistsWhereEnum.SingleLocation
1655 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InLocation
1656 dest.Key = obDest.Location.Key
1657 End Select
1658 Else
1659 If obDest.Location.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.Hidden Then
1660 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.Hidden
1661 Else
1662 dest = obDest.Location.Copy
1663 End If
1664 End If
1665 Else
1666 ErrMsg("Cannot move object to same location as " & act.sKey2 & " - key not found!")
1667 End If
1668
1669 End If
1670 Case clsAction.MoveObjectToEnum.ToWornBy
1671 dest.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.WornByCharacter
1672 dest.Key = act.sKey2
1673 End Select
1674 ob.Move(dest)
1675
1676 Case clsAction.ItemEnum.AddObjectToGroup
1677 If Not Adventure.htblGroups(act.sKey2).arlMembers.Contains(ob.Key) Then Adventure.htblGroups(act.sKey2).arlMembers.Add(ob.Key)
1678 ob.ResetInherited()
1679 Case clsAction.ItemEnum.RemoveObjectFromGroup
1680 If Adventure.htblGroups(act.sKey2).arlMembers.Contains(ob.Key) Then Adventure.htblGroups(act.sKey2).arlMembers.Remove(ob.Key)
1681 ob.ResetInherited()
1682 End Select
1683 Next
1684 End If
1685
1686 Case clsAction.ItemEnum.MoveCharacter, clsAction.ItemEnum.AddCharacterToGroup, clsAction.ItemEnum.RemoveCharacterFromGroup
1687 Dim chars As CharacterHashTable = Nothing
1688
1689 Select Case act.eMoveCharacterWho
1690 Case clsAction.MoveCharacterWhoEnum.Character
1691 chars = New CharacterHashTable
1692 chars.Add(Adventure.htblCharacters(act.sKey1), act.sKey1)
1693 Case clsAction.MoveCharacterWhoEnum.EveryoneAtLocation
1694 chars = Adventure.htblLocations(act.sKey1).CharactersDirectlyInLocation(True)
1695 Case clsAction.MoveCharacterWhoEnum.EveryoneInGroup
1696 chars = New CharacterHashTable
1697 For Each sKey As String In Adventure.htblGroups(act.sKey1).arlMembers
1698 chars.Add(Adventure.htblCharacters(sKey), sKey)
1699 Next
1700 Case clsAction.MoveCharacterWhoEnum.EveryoneInside
1701 chars = Adventure.htblObjects(act.sKey1).ChildrenCharacters(clsObject.WhereChildrenEnum.InsideObject)
1702 Case clsAction.MoveCharacterWhoEnum.EveryoneOn
1703 chars = Adventure.htblObjects(act.sKey1).ChildrenCharacters(clsObject.WhereChildrenEnum.OnObject)
1704 Case clsAction.MoveCharacterWhoEnum.EveryoneWithProperty
1705 chars = New CharacterHashTable
1706 Dim prop As clsProperty = Adventure.htblCharacterProperties(act.sKey1)
1707 For Each ch As clsCharacter In Adventure.htblCharacters.Values
1708 If ch.HasProperty(prop.Key) Then
1709 If prop.Type = clsProperty.PropertyTypeEnum.SelectionOnly Then
1710 chars.Add(ch, ch.Key)
1711 Else
1712 If ch.GetPropertyValue(prop.Key) = act.sPropertyValue Then chars.Add(ch, ch.Key)
1713 End If
1714 End If
1715 Next
1716 End Select
1717
1718 If chars IsNot Nothing Then
1719 For Each ch As clsCharacter In chars.Values
1720
1721 Select Case act.eItem
1722 Case clsAction.ItemEnum.MoveCharacter
1723 Dim dest As New clsCharacterLocation(ch)
1724
1725 ' Default new destination to current location
1726 dest.ExistWhere = ch.Location.ExistWhere
1727 dest.Key = ch.Location.Key
1728 dest.Position = ch.Location.Position
1729
1730 Select Case act.eMoveCharacterTo
1731 Case clsAction.MoveCharacterToEnum.InDirection
1732 Dim d As DirectionsEnum = CType([Enum].Parse(GetType(DirectionsEnum), act.sKey2), DirectionsEnum)
1733 Dim dDetails As clsDirection = Nothing
1734 If Adventure.htblLocations.ContainsKey(ch.Location.LocationKey) Then dDetails = Adventure.htblLocations(ch.Location.LocationKey).arlDirections(d)
1735 Dim sRouteErrorTask As String = sRouteError ' because sRouteError gets overwritten by checking route restrictions
1736 Dim sRestrictionTextTemp As String = sRestrictionText
1737 sRestrictionText = ""
1738
1739 If dDetails IsNot Nothing AndAlso ch.HasRouteInDirection(d, False) Then
1740 If Adventure.htblLocations.ContainsKey(dDetails.LocationKey) Then
1741 dest.Key = dDetails.LocationKey
1742 ElseIf Adventure.htblGroups.ContainsKey(dDetails.LocationKey) Then
1743 dest.Key = Adventure.htblGroups(dDetails.LocationKey).RandomKey
1744 End If
1745 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1746 Else
1747 If sRestrictionText <> "" Then
1748 Display(sRestrictionText)
1749 Else
1750 ' Need to grab out the restriction text from the movement task
1751 If sRouteErrorTask <> "" Then Display(sRouteErrorTask)
1752 End If
1753 dest = Nothing
1754 End If
1755 sRestrictionText = sRestrictionText
1756
1757 Case clsAction.MoveCharacterToEnum.ToLocation
1758 If act.sKey2 = "Hidden" Then
1759 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.Hidden
1760 dest.Key = ""
1761 Else
1762 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1763 dest.Key = act.sKey2
1764 End If
1765 Case clsAction.MoveCharacterToEnum.ToLocationGroup
1766 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1767 dest.Key = Adventure.htblGroups(act.sKey2).RandomKey
1768 Case clsAction.MoveCharacterToEnum.ToLyingOn
1769 dest.Position = clsCharacterLocation.PositionEnum.Lying
1770 If act.sKey2 = THEFLOOR Then
1771 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1772 dest.Key = ch.Location.LocationKey
1773 Else
1774 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject
1775 dest.Key = act.sKey2
1776 End If
1777 Case clsAction.MoveCharacterToEnum.ToSameLocationAs
1778 If Adventure.htblCharacters.ContainsKey(act.sKey2) Then
1779 dest.ExistWhere = Adventure.htblCharacters(act.sKey2).Location.ExistWhere
1780 dest.Key = Adventure.htblCharacters(act.sKey2).Location.Key
1781 ElseIf Adventure.htblObjects.ContainsKey(act.sKey2) Then
1782 With Adventure.htblObjects(act.sKey2)
1783 If .IsStatic Then
1784 Select Case .Location.StaticExistWhere
1785 Case clsObjectLocation.StaticExistsWhereEnum.AllRooms, clsObjectLocation.StaticExistsWhereEnum.LocationGroup
1786 ' Doesn't make sense to map
1787 Case clsObjectLocation.StaticExistsWhereEnum.NoRooms
1788 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.Hidden
1789 Case clsObjectLocation.StaticExistsWhereEnum.PartOfCharacter
1790 TODO("Move Char to same location as object that is part of a character")
1791 Case clsObjectLocation.StaticExistsWhereEnum.PartOfObject
1792 TODO("Move Char to same location as object that is part of an object")
1793 Case clsObjectLocation.StaticExistsWhereEnum.SingleLocation
1794 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1795 dest.Key = .Location.Key
1796 End Select
1797 Else
1798 Select Case .Location.DynamicExistWhere
1799 Case clsObjectLocation.DynamicExistsWhereEnum.HeldByCharacter, clsObjectLocation.DynamicExistsWhereEnum.WornByCharacter
1800 dest.ExistWhere = Adventure.htblCharacters(.Key).Location.ExistWhere
1801 dest.Key = Adventure.htblCharacters(.Key).Location.Key
1802 Case clsObjectLocation.DynamicExistsWhereEnum.Hidden
1803 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.Hidden
1804 Case clsObjectLocation.DynamicExistsWhereEnum.InLocation
1805 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1806 dest.Key = .Location.Key
1807 Case clsObjectLocation.DynamicExistsWhereEnum.InObject, clsObjectLocation.DynamicExistsWhereEnum.OnObject
1808 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1809 For Each l As clsLocation In Adventure.htblObjects(.Key).LocationRoots.Values
1810 dest.Key = l.Key
1811 Exit For
1812 Next
1813 End Select
1814 End If
1815
1816 End With
1817 End If
1818 Case clsAction.MoveCharacterToEnum.ToSittingOn
1819 dest.Position = clsCharacterLocation.PositionEnum.Sitting
1820 If act.sKey2 = THEFLOOR Then
1821 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1822 dest.Key = ch.Location.LocationKey
1823 Else
1824 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject
1825 dest.Key = act.sKey2
1826 End If
1827 Case clsAction.MoveCharacterToEnum.ToStandingOn
1828 dest.Position = clsCharacterLocation.PositionEnum.Standing
1829 If act.sKey2 = THEFLOOR Then
1830 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1831 dest.Key = ch.Location.LocationKey
1832 Else
1833 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject
1834 dest.Key = act.sKey2
1835 End If
1836 Case clsAction.MoveCharacterToEnum.ToSwitchWith
1837 If ch.Key = Adventure.Player.Key OrElse act.sKey2 = Adventure.Player.Key Then
1838 ' Don't move the characters, but change which one is the player
1839 Dim eCurrentPerspective As PerspectiveEnum = Adventure.Player.Perspective
1840 Dim sOldPlayerKey As String = Adventure.Player.Key
1841 Adventure.Player.CharacterType = clsCharacter.CharacterTypeEnum.NonPlayer
1842 If ch.Key = Adventure.Player.Key Then
1843 Adventure.Player = Adventure.htblCharacters(act.sKey2)
1844 Else
1845 Adventure.Player = Adventure.htblCharacters(ch.Key)
1846 End If
1847 Adventure.Player.CharacterType = clsCharacter.CharacterTypeEnum.Player
1848 Adventure.Player.Perspective = eCurrentPerspective
1849 ' If the old Player character has any descriptors that match any pronouns for the player perspective, move them to the new Player
1850 ' TODO - Change this to configurable pronouns
1851 With Adventure.htblCharacters(sOldPlayerKey)
1852 For iDescriptor As Integer = .arlDescriptors.Count - 1 To 0 Step -1
1853 Dim sDescriptor As String = .arlDescriptors(iDescriptor)
1854 Dim sPronouns As String() = {}
1855 Select Case eCurrentPerspective
1856 Case PerspectiveEnum.FirstPerson
1857 sPronouns = New String() {"I", "me", "myself"}
1858 Case PerspectiveEnum.SecondPerson
1859 sPronouns = New String() {"I", "me", "myself", "you", "yourself"} ' include 1st in 2nd
1860 Case PerspectiveEnum.ThirdPerson
1861
1862 End Select
1863 For Each sPronoun As String In sPronouns
1864 If sPronoun.ToLower = sDescriptor.ToLower Then
1865 .arlDescriptors.RemoveAt(iDescriptor)
1866 If Not Adventure.Player.arlDescriptors.Contains(sPronoun) Then Adventure.Player.arlDescriptors.Add(sPronoun)
1867 End If
1868 Next
1869 Next
1870 End With
1871 Else
1872 ' Move the characters about
1873 Dim loc As clsCharacterLocation = ch.Location
1874 ch.Location = Adventure.htblCharacters(act.sKey2).Location
1875 Adventure.htblCharacters(act.sKey2).Location = loc
1876 End If
1877 Case clsAction.MoveCharacterToEnum.InsideObject
1878 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.InObject
1879 dest.Key = act.sKey2
1880 Case clsAction.MoveCharacterToEnum.OntoCharacter
1881 If Adventure.htblCharacters.ContainsKey(act.sKey2) Then
1882 If ch.Key = act.sKey2 OrElse ch.Children(True).ContainsKey(act.sKey2) Then
1883 DisplayError("Recursive character relationship")
1884 Else
1885 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnCharacter
1886 dest.Key = act.sKey2
1887 End If
1888 End If
1889 Case clsAction.MoveCharacterToEnum.ToParentLocation
1890 dest.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
1891 Dim sCurrent As String = ch.Location.Key
1892 If Adventure.htblObjects.ContainsKey(sCurrent) Then
1893 For Each sKey As String In Adventure.htblObjects(sCurrent).LocationRoots.Keys
1894 dest.Key = sKey
1895 Exit For
1896 Next
1897 ElseIf Adventure.htblCharacters.ContainsKey(sCurrent) Then
1898 dest.Key = Adventure.htblCharacters(sCurrent).Location.LocationKey
1899 End If
1900 Case Else
1901 TODO("Move Character to " & act.eMoveCharacterTo.ToString)
1902 End Select
1903 If dest IsNot Nothing Then ch.Move(dest)
1904
1905 Case clsAction.ItemEnum.AddCharacterToGroup
1906 If Not Adventure.htblGroups(act.sKey2).arlMembers.Contains(ch.Key) Then Adventure.htblGroups(act.sKey2).arlMembers.Add(ch.Key)
1907 ch.ResetInherited()
1908 Case clsAction.ItemEnum.RemoveCharacterFromGroup
1909 If Adventure.htblGroups(act.sKey2).arlMembers.Contains(ch.Key) Then Adventure.htblGroups(act.sKey2).arlMembers.Remove(ch.Key)
1910 ch.ResetInherited()
1911 End Select
1912
1913 Next
1914 End If
1915
1916
1917 Case clsAction.ItemEnum.AddLocationToGroup, clsAction.ItemEnum.RemoveLocationFromGroup
1918 Dim locs As LocationHashTable = Nothing
1919
1920 Select Case act.eMoveLocationWhat
1921 Case clsAction.MoveLocationWhatEnum.Location
1922 locs = New LocationHashTable
1923 locs.Add(Adventure.htblLocations(act.sKey1), act.sKey1)
1924 Case clsAction.MoveLocationWhatEnum.LocationOf
1925 If Adventure.htblCharacters.ContainsKey(act.sKey1) Then
1926 locs = New LocationHashTable
1927 Dim sLocKey As String = Adventure.htblCharacters(act.sKey1).Location.LocationKey
1928 If sLocKey <> HIDDEN Then locs.Add(Adventure.htblLocations(sLocKey), act.sKey1)
1929 ElseIf Adventure.htblObjects.ContainsKey(act.sKey1) Then
1930 locs = Adventure.htblObjects(act.sKey1).LocationRoots
1931 End If
1932 Case clsAction.MoveLocationWhatEnum.EverywhereInGroup
1933 locs = New LocationHashTable
1934 For Each sKey As String In Adventure.htblGroups(act.sKey1).arlMembers
1935 locs.Add(Adventure.htblLocations(sKey), sKey)
1936 Next
1937 Case clsAction.MoveLocationWhatEnum.EverywhereWithProperty
1938 locs = New LocationHashTable
1939 Dim prop As clsProperty = Adventure.htblLocationProperties(act.sKey1)
1940 For Each loc As clsLocation In Adventure.htblLocations.Values
1941 If loc.HasProperty(prop.Key) Then
1942 If prop.Type = clsProperty.PropertyTypeEnum.SelectionOnly Then
1943 locs.Add(loc, loc.Key)
1944 Else
1945 If loc.GetPropertyValue(prop.Key) = act.sPropertyValue Then locs.Add(loc, loc.Key)
1946 End If
1947 End If
1948 Next
1949 End Select
1950
1951 If locs IsNot Nothing Then
1952 For Each loc As clsLocation In locs.Values
1953
1954 Select Case act.eItem
1955 Case clsAction.ItemEnum.AddLocationToGroup
1956 If Not Adventure.htblGroups(act.sKey2).arlMembers.Contains(loc.Key) Then Adventure.htblGroups(act.sKey2).arlMembers.Add(loc.Key)
1957 loc.ResetInherited()
1958 Case clsAction.ItemEnum.RemoveLocationFromGroup
1959 If Adventure.htblGroups(act.sKey2).arlMembers.Contains(loc.Key) Then Adventure.htblGroups(act.sKey2).arlMembers.Remove(loc.Key)
1960 loc.ResetInherited()
1961 End Select
1962
1963 Next
1964 End If
1965
1966
1967 Case clsAction.ItemEnum.SetProperties
1968 If Adventure.htblObjects.ContainsKey(act.sKey1) Then
1969 Dim ob As clsObject = Adventure.htblObjects(act.sKey1)
1970
1971 Select Case act.sKey2
1972 Case OBJECTARTICLE
1973 Dim sResult As String = EvaluateExpression(act.sPropertyValue)
1974 If sResult Is Nothing AndAlso act.sPropertyValue <> "" Then sResult = act.sPropertyValue
1975 ob.Article = sResult
1976 Case OBJECTPREFIX
1977 Dim sResult As String = EvaluateExpression(act.sPropertyValue)
1978 If sResult Is Nothing AndAlso act.sPropertyValue <> "" Then sResult = act.sPropertyValue
1979 ob.Prefix = sResult
1980 Case OBJECTNOUN
1981 Dim sResult As String = EvaluateExpression(act.sPropertyValue)
1982 If sResult Is Nothing AndAlso act.sPropertyValue <> "" Then sResult = act.sPropertyValue
1983 ob.arlNames(0) = sResult
1984 Case Else
1985 Dim prop As clsProperty = Nothing
1986 If ob.HasProperty(act.sKey2) Then prop = ob.GetProperty(act.sKey2)
1987
1988 If prop Is Nothing Then
1989 ' We're trying to add this as a property
1990 If Adventure.htblObjectProperties.ContainsKey(act.sKey2) Then
1991 prop = CType(Adventure.htblObjectProperties(act.sKey2).Clone, clsProperty)
1992 prop.Selected = True
1993 ob.AddProperty(prop)
1994
1995 Select Case prop.Type
1996 Case clsProperty.PropertyTypeEnum.SelectionOnly
1997 ' Nothing more to do
1998 Case clsProperty.PropertyTypeEnum.ObjectKey
1999 Dim sObKey As String = act.sPropertyValue
2000 If sObKey.StartsWith("Referenced") Then sObKey = GetReference(sObKey)
2001 ob.SetPropertyValue(prop.Key, sObKey)
2002 End Select
2003 Else
2004 DebugPrint(ItemEnum.Task, act.sKey1, DebugDetailLevelEnum.Error, "Property " & act.sKey2 & " not found.")
2005 End If
2006 Else
2007 If act.StringValue = sUNSELECTED Then
2008 ' We're trying to remove this property
2009 ob.RemoveProperty(act.sKey2)
2010 Else
2011 Select Case prop.Type
2012 Case clsProperty.PropertyTypeEnum.Integer, clsProperty.PropertyTypeEnum.Text, clsProperty.PropertyTypeEnum.StateList, clsProperty.PropertyTypeEnum.ValueList
2013 ' Could be dropdown or expression
2014 Dim sResult As String = EvaluateExpression(act.sPropertyValue)
2015 If sResult Is Nothing AndAlso act.sPropertyValue <> "" Then sResult = act.sPropertyValue
2016 prop.Value = sResult
2017 Case clsProperty.PropertyTypeEnum.ObjectKey, clsProperty.PropertyTypeEnum.CharacterKey, clsProperty.PropertyTypeEnum.LocationKey
2018 Dim sObKey As String = act.sPropertyValue
2019 If sObKey.StartsWith("Referenced") Then sObKey = GetReference(sObKey)
2020 prop.Value = sObKey
2021 Case Else
2022 prop.Value = act.sPropertyValue
2023 End Select
2024 End If
2025 End If
2026 End Select
2027
2028 ElseIf Adventure.htblCharacters.ContainsKey(act.sKey1) Then
2029 Dim prop As clsProperty = Nothing
2030 Dim ch As clsCharacter = Adventure.htblCharacters(act.sKey1)
2031 If ch.HasProperty(act.sKey2) Then prop = ch.GetProperty(act.sKey2)
2032
2033 If prop Is Nothing Then
2034 Select Case act.sKey2
2035 Case CHARACTERPROPERNAME
2036 prop = New clsProperty
2037 prop.Key = act.sKey2
2038 prop.Type = clsProperty.PropertyTypeEnum.Text
2039 End Select
2040 End If
2041
2042 If prop Is Nothing Then
2043 If act.StringValue = sSELECTED Then
2044 ' We're trying to add this as a property
2045 If Adventure.htblCharacterProperties.ContainsKey(act.sKey2) Then
2046 prop = CType(Adventure.htblCharacterProperties(act.sKey2).Clone, clsProperty)
2047 If prop.Type = clsProperty.PropertyTypeEnum.SelectionOnly Then
2048 prop.Selected = True
2049 ch.AddProperty(prop)
2050 End If
2051 Else
2052 DebugPrint(ItemEnum.Task, act.sKey1, DebugDetailLevelEnum.Error, "Property " & act.sKey2 & " not found.")
2053 End If
2054 Else
2055 DebugPrint(ItemEnum.Task, act.sKey1, DebugDetailLevelEnum.Error, "Property " & act.sKey2 & " not found.")
2056 End If
2057 Else
2058 If act.StringValue = sUNSELECTED Then
2059 ' We're trying to remove this property
2060 ch.RemoveProperty(act.sKey2)
2061 Else
2062 Select Case prop.Type
2063 Case clsProperty.PropertyTypeEnum.Integer, clsProperty.PropertyTypeEnum.Text, clsProperty.PropertyTypeEnum.StateList, clsProperty.PropertyTypeEnum.ValueList
2064 ' Could be dropdown or expression
2065 Dim sResult As String = EvaluateExpression(act.sPropertyValue)
2066 If sResult Is Nothing AndAlso act.sPropertyValue <> "" Then sResult = act.sPropertyValue
2067 prop.Value = sResult
2068 Case clsProperty.PropertyTypeEnum.ObjectKey, clsProperty.PropertyTypeEnum.CharacterKey, clsProperty.PropertyTypeEnum.LocationKey
2069 Dim sObKey As String = act.sPropertyValue
2070 If sObKey.StartsWith("Referenced") Then sObKey = GetReference(sObKey)
2071 prop.Value = sObKey
2072 Case Else
2073 prop.Value = act.sPropertyValue
2074 End Select
2075 End If
2076 End If
2077
2078 Select Case act.sKey2
2079 Case CHARACTERPROPERNAME
2080 ch.ProperName = prop.Value
2081 Case "CharacterPosition"
2082 ch.Location.ResetPosition()
2083 End Select
2084
2085 ElseIf Adventure.htblLocations.ContainsKey(act.sKey1) Then
2086 Dim prop As clsProperty = Nothing
2087 If Adventure.htblLocations(act.sKey1).HasProperty(act.sKey2) Then prop = Adventure.htblLocations(act.sKey1).GetProperty(act.sKey2)
2088
2089 If prop Is Nothing Then
2090 If act.StringValue = sSELECTED Then
2091 ' We're trying to add this as a property
2092 If Adventure.htblLocationProperties.ContainsKey(act.sKey2) Then
2093 prop = CType(Adventure.htblLocationProperties(act.sKey2).Clone, clsProperty)
2094 If prop.Type = clsProperty.PropertyTypeEnum.SelectionOnly Then
2095 prop.Selected = True
2096 Adventure.htblLocations(act.sKey1).AddProperty(prop)
2097 End If
2098 Else
2099 DebugPrint(ItemEnum.Task, act.sKey1, DebugDetailLevelEnum.Error, "Property " & act.sKey2 & " not found.")
2100 End If
2101 Else
2102 DebugPrint(ItemEnum.Task, act.sKey1, DebugDetailLevelEnum.Error, "Property " & act.sKey2 & " not found.")
2103 End If
2104 Else
2105 If act.StringValue = sUNSELECTED Then
2106 ' We're trying to remove this property
2107 Adventure.htblLocations(act.sKey1).RemoveProperty(act.sKey2)
2108 Else
2109 Select Case prop.Type
2110 Case clsProperty.PropertyTypeEnum.Integer, clsProperty.PropertyTypeEnum.Text, clsProperty.PropertyTypeEnum.StateList, clsProperty.PropertyTypeEnum.ValueList
2111 ' Could be dropdown or expression
2112 Dim sResult As String = EvaluateExpression(act.sPropertyValue)
2113 If sResult Is Nothing AndAlso act.sPropertyValue <> "" Then sResult = act.sPropertyValue
2114 prop.Value = sResult
2115 Case clsProperty.PropertyTypeEnum.ObjectKey, clsProperty.PropertyTypeEnum.CharacterKey, clsProperty.PropertyTypeEnum.LocationKey
2116 Dim sObKey As String = act.sPropertyValue
2117 If sObKey.StartsWith("Referenced") Then sObKey = GetReference(sObKey)
2118 prop.Value = sObKey
2119 Case Else
2120 prop.Value = act.sPropertyValue
2121 End Select
2122 If prop.Key = "CharacterPosition" Then Adventure.htblCharacters(act.sKey1).Location.ResetPosition()
2123 End If
2124 End If
2125 End If
2126
2127 Case clsAction.ItemEnum.SetVariable, clsAction.ItemEnum.IncreaseVariable, clsAction.ItemEnum.DecreaseVariable
2128 Dim var As clsVariable = Adventure.htblVariables(act.sKey1)
2129 Dim sExpr As String = act.StringValue
2130 If act.eItem = clsAction.ItemEnum.IncreaseVariable Then sExpr = "%" & var.Name & "% + " & sExpr
2131 If act.eItem = clsAction.ItemEnum.DecreaseVariable Then sExpr = "%" & var.Name & "% - " & sExpr
2132
2133 If act.eVariables = clsAction.VariablesEnum.Assignment Then
2134 Dim iIndex As Integer = 1
2135 If var.Length > 1 AndAlso Not act.sKey2 Is Nothing Then
2136 If act.sKey2.StartsWith("ReferencedNumber") Then
2137 iIndex = SafeInt(GetReference(act.sKey2))
2138 ElseIf IsNumeric(act.sKey2) Then
2139 iIndex = CInt(Val(act.sKey2))
2140 Else
2141 iIndex = Adventure.htblVariables(act.sKey2).IntValue
2142 End If
2143 End If
2144 If var.Key <> "Score" OrElse (task IsNot Nothing AndAlso Not task.Scored) Then
2145 var.SetToExpression(sExpr, iIndex)
2146 If var.Key = "Score" Then
2147 task.Scored = True
2148 Adventure.Score = var.IntValue
2149 End If
2150 End If
2151 Else
2152 For iLoop As Integer = act.IntValue To CInt(act.sKey2)
2153 var.SetToExpression(sExpr, iLoop)
2154 Next
2155 End If
2156
2157 Case clsAction.ItemEnum.SetTasks
2158 Dim tas2X As clsTask = Adventure.htblTasks(act.sKey1)
2159
2160 Dim iFrom As Integer = 1
2161 Dim iTo As Integer = 1
2162
2163 If act.sPropertyValue <> "" Then
2164 iFrom = act.IntValue
2165 iTo = SafeInt(act.sPropertyValue)
2166 End If
2167
2168 For iLoop As Integer = iFrom To iTo
2169 If act.eSetTasks = clsAction.SetTasksEnum.Execute Then
2170 ' Store the existing refs
2171 Dim oExistingRefs() As clsNewReference = NewReferences
2172
2173 DebugPrint(ItemEnum.Task, act.sKey1, DebugDetailLevelEnum.High, "Executing task '" & tas2X.Description & "'.")
2174 If act.StringValue <> "" Then
2175 ' Rewrite the references based on our parameters
2176 Dim sParams() As String = act.StringValue.Split("|"c)
2177 Dim iWhichNewRefAreWeLookingAt As Integer = -1
2178 Dim ReferencesNew(sParams.Length - 1) As clsNewReference
2179 For Each sParam As String In sParams
2180 iWhichNewRefAreWeLookingAt += 1
2181
2182 ' Find each ref in the new task that our parameter corresponds to
2183 Dim bFoundMatchingRef As Boolean = False
2184 Dim iWhichOldRefAreWeLookingAt As Integer = -1
2185 For Each sRef As String In tas2X.References
2186 iWhichOldRefAreWeLookingAt += 1
2187 ' Again, we may be looking outside NewRefs if we're looking at subtask with different refs... :-/
2188 If sParam = sRef AndAlso iWhichOldRefAreWeLookingAt < NewReferences.Length Then ' Ok, found same ref, so we just pass the ref thru
2189 ReferencesNew(iWhichNewRefAreWeLookingAt) = NewReferences(iWhichOldRefAreWeLookingAt)
2190 bFoundMatchingRef = True
2191 End If
2192 Next
2193 If Not bFoundMatchingRef Then
2194 ' Need to work this out on our own...
2195 Dim UserDefinedRef As clsNewReference = Nothing
2196
2197 If sParam.Contains(".") Then
2198 ' Hmm, let's see if this is an OO function
2199 For Each sProp As String In Adventure.htblAllProperties.Keys
2200 If sParam.EndsWith("." & sProp) Then
2201 Dim prop As clsProperty = Adventure.htblAllProperties(sProp)
2202 Select Case prop.Type
2203 Case clsProperty.PropertyTypeEnum.CharacterKey
2204 UserDefinedRef = New clsNewReference(ReferencesType.Character)
2205 Case clsProperty.PropertyTypeEnum.Integer
2206 UserDefinedRef = New clsNewReference(ReferencesType.Number)
2207 Case clsProperty.PropertyTypeEnum.LocationGroupKey
2208 UserDefinedRef = New clsNewReference(ReferencesType.Text)
2209 Case clsProperty.PropertyTypeEnum.LocationKey
2210 UserDefinedRef = New clsNewReference(ReferencesType.Location)
2211 Case clsProperty.PropertyTypeEnum.ObjectKey
2212 UserDefinedRef = New clsNewReference(ReferencesType.Object)
2213 Case clsProperty.PropertyTypeEnum.SelectionOnly
2214 Select Case prop.PropertyOf
2215 Case clsProperty.PropertyOfEnum.AnyItem
2216 UserDefinedRef = New clsNewReference(ReferencesType.Item)
2217 Case clsProperty.PropertyOfEnum.Characters
2218 UserDefinedRef = New clsNewReference(ReferencesType.Character)
2219 Case clsProperty.PropertyOfEnum.Locations
2220 UserDefinedRef = New clsNewReference(ReferencesType.Location)
2221 Case clsProperty.PropertyOfEnum.Objects
2222 UserDefinedRef = New clsNewReference(ReferencesType.Object)
2223 End Select
2224 Case clsProperty.PropertyTypeEnum.StateList
2225 UserDefinedRef = New clsNewReference(ReferencesType.Text)
2226 Case clsProperty.PropertyTypeEnum.Text
2227 UserDefinedRef = New clsNewReference(ReferencesType.Text)
2228 Case clsProperty.PropertyTypeEnum.ValueList
2229 UserDefinedRef = New clsNewReference(ReferencesType.Number)
2230 End Select
2231 Exit For
2232 End If
2233 Next
2234 If UserDefinedRef Is Nothing Then
2235 If sParam.EndsWith(".Worn") Then
2236 UserDefinedRef = New clsNewReference(ReferencesType.Object)
2237 ElseIf sParam.EndsWith(".List") Then
2238 TODO()
2239 ElseIf sParam.EndsWith(".Count") Then
2240 UserDefinedRef = New clsNewReference(ReferencesType.Number)
2241 ElseIf sParam.EndsWith(".Exits") Then
2242 UserDefinedRef = New clsNewReference(ReferencesType.Direction)
2243 End If
2244 End If
2245 End If
2246 If UserDefinedRef Is Nothing Then
2247 ' Gotta guess the type of ref...
2248 Select Case sLeft(sParam, 6).ToLower
2249 Case "%convc"
2250 UserDefinedRef = New clsNewReference(ReferencesType.Character)
2251 Case "%paren"
2252 UserDefinedRef = New clsNewReference(ReferencesType.Object)
2253 Case "%text%"
2254 UserDefinedRef = New clsNewReference(ReferencesType.Text)
2255 Case "%loop%", "%numbe"
2256 UserDefinedRef = New clsNewReference(ReferencesType.Number)
2257 Case Else
2258 If IsNumeric(sLeft(sParam, 6).ToLower) Then
2259 UserDefinedRef = New clsNewReference(ReferencesType.Number)
2260 Else
2261 UserDefinedRef = New clsNewReference(ReferencesType.Object)
2262 End If
2263 End Select
2264 End If
2265 UserDefinedRef.sParentTask = tas2X.Key
2266
2267 ' Now work out, e.g. %ParentOf[%objects%]% ...
2268 Dim sFunctionRef As String = ReplaceFunctions(sParam)
2269 If sFunctionRef.ToLower = "%loop%" Then sFunctionRef = iLoop.ToString
2270
2271 If Not sFunctionRef.Contains("***") Then
2272 Dim listRefs As New List(Of String)
2273 If sFunctionRef.Contains("|") Then
2274 For Each sRef As String In sFunctionRef.Split("|"c)
2275 listRefs.Add(sRef)
2276 Next
2277 Else
2278 listRefs.Add(sFunctionRef)
2279 End If
2280
2281 For Each sRef As String In listRefs
2282 Dim itm As New clsSingleItem
2283 If sRef = "nothing" Then sRef = Nothing ' List function
2284 itm.MatchingPossibilities.Add(sRef)
2285 UserDefinedRef.Items.Add(itm)
2286 Next
2287 If sParam.StartsWith("%ParentOf") Then
2288 UserDefinedRef.ReferenceType = ReferencesType.Object
2289 End If
2290 Else
2291 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.High, "Error calculating parameter " & sParam)
2292 End If
2293 ReferencesNew(iWhichNewRefAreWeLookingAt) = UserDefinedRef
2294 End If
2295 Next
2296 NewReferences = ReferencesNew
2297 PrintOutReferences()
2298 Else
2299 ' Explicitly clear the refs for this task being called
2300 NewReferences = Nothing
2301 End If
2302 ' was True in ChildTask. But it's not a child, it's a seperate task call...
2303 ' was bCalledFromEvent in second param - but think this should be set if calling from task
2304 ' Re the above, a reason why would be good. Means later we don't do the continue? check
2305 Dim bSubTaskHasOutput As Boolean = False
2306 ' Did have EvaluateResponses = True, but we need to evaluate at the end in case we are inserting responses before ones in actions
2307 AttemptToExecuteTask(act.sKey1, bCalledFromEvent, , True, , bSubTaskHasOutput, False) 'True)
2308 If bSubTaskHasOutput Then bTaskHasOutputNew = True
2309 NewReferences = oExistingRefs
2310 Else
2311 If tas2X.Completed Then
2312 DebugPrint(ItemEnum.Task, act.sKey1, DebugDetailLevelEnum.High, "Task '" & tas2X.Description & "' being uncompleted.")
2313
2314 If tas2X.Completed Then
2315 ' Check any walks/events to see if anything triggers on this task completing
2316 For Each c As clsCharacter In Adventure.htblCharacters.Values
2317 For Each w As clsWalk In c.arlWalks
2318 For Each ctrl As EventOrWalkControl In w.WalkControls
2319 If ctrl.eCompleteOrNot = EventOrWalkControl.CompleteOrNotEnum.UnCompletion AndAlso ctrl.sTaskKey = tas2X.Key Then
2320 Select Case ctrl.eControl
2321 Case EventOrWalkControl.ControlEnum.Resume
2322 If w.Status = clsWalk.StatusEnum.Paused Then w.Resume()
2323 Case EventOrWalkControl.ControlEnum.Start
2324 If w.Status <> clsWalk.StatusEnum.Running Then w.Start()
2325 Case EventOrWalkControl.ControlEnum.Stop
2326 If w.Status = clsWalk.StatusEnum.Running Then w.Stop()
2327 Case EventOrWalkControl.ControlEnum.Suspend
2328 If w.Status = clsWalk.StatusEnum.Running Then w.Pause()
2329 End Select
2330 End If
2331 Next
2332 Next
2333 Next
2334 For Each e As clsEvent In Adventure.htblEvents.Values
2335 For Each ctrl As EventOrWalkControl In e.EventControls
2336 If ctrl.eCompleteOrNot = EventOrWalkControl.CompleteOrNotEnum.UnCompletion AndAlso ctrl.sTaskKey = tas2X.Key Then
2337 Select Case ctrl.eControl
2338 Case EventOrWalkControl.ControlEnum.Resume
2339 If e.Status = clsWalk.StatusEnum.Paused Then e.Resume()
2340 Case EventOrWalkControl.ControlEnum.Start
2341 If e.Status <> clsWalk.StatusEnum.Running Then e.Start()
2342 Case EventOrWalkControl.ControlEnum.Stop
2343 If e.Status = clsWalk.StatusEnum.Running Then e.Stop()
2344 Case EventOrWalkControl.ControlEnum.Suspend
2345 If e.Status = clsWalk.StatusEnum.Running Then e.Pause()
2346 End Select
2347 End If
2348 Next
2349 Next
2350 End If
2351
2352 tas2X.Completed = False
2353 End If
2354 End If
2355 Next
2356
2357 Case clsAction.ItemEnum.Time
2358 ' This isn't perfect - not sure what'll happen with any fail messages
2359 For Each sMessage As String In htblResponsesPass.OrderedKeys
2360 Dim refs As clsNewReference() = CType(htblResponsesPass(sMessage), clsNewReference())
2361
2362 NewReferences = refs
2363 Display(sMessage)
2364 Next
2365 htblResponsesPass.Clear()
2366 For i As Integer = 0 To EvaluateExpression(act.StringValue, True) - 1
2367 TurnBasedStuff()
2368 Next
2369 htblResponsesPass.Clear()
2370
2371 Case clsAction.ItemEnum.EndGame
2372 Adventure.eGameState = act.eEndgame
2373
2374 Case clsAction.ItemEnum.Conversation
2375 Select Case act.eConversation
2376 Case clsAction.ConversationEnum.EnterConversation
2377 Adventure.sConversationCharKey = act.sKey1
2378 Case clsAction.ConversationEnum.LeaveConversation
2379 If Adventure.sConversationCharKey = act.sKey1 Then Adventure.sConversationCharKey = ""
2380 Case Else
2381 ExecuteConversation(act.sKey1, act.eConversation, act.StringValue, bTaskHasOutputNew)
2382 'bTaskHasOutput = True
2383 End Select
2384
2385 End Select
2386
2387 Catch ex As Exception
2388 ErrMsg("Error executing action " & actx.Summary, ex)
2389 End Try
2390
2391 End Sub
2392
2393 Private Sub ExecuteConversation(ByVal sCharKey As String, ByVal ConvType As clsAction.ConversationEnum, ByVal sCommandOrSubject As String, ByRef bTaskHasOutputNew As Boolean)
2394
2395 DebugPrint(ItemEnum.Character, sCharKey, DebugDetailLevelEnum.Medium, "Execute Conversation " & ConvType.ToString & ": " & sCommandOrSubject)
2396
2397 ' If currently in a conversation with a different character, search for an Implicit Farewell for other char
2398 If Adventure.sConversationCharKey <> "" AndAlso Adventure.sConversationCharKey <> sCharKey Then
2399 Dim farewell As clsTopic = FindConversationNode(Adventure.htblCharacters(Adventure.sConversationCharKey), ConvType, "")
2400 If farewell IsNot Nothing Then
2401 If AddResponse(False, farewell.oConversation.ToString, New String() {}, True) Then bTaskHasOutputNew = True
2402 End If
2403
2404 Adventure.sConversationCharKey = ""
2405 Adventure.sConversationNode = ""
2406 End If
2407
2408 Dim ConvChar As clsCharacter = Adventure.htblCharacters(sCharKey)
2409
2410 ' If not currently in conversation and ConvType != Intro, then search for an Implicit Intro for that char
2411 If Adventure.sConversationCharKey = "" Then ' AndAlso ConvType <> clsAction.ConversationEnum.Greet Then
2412 ' Try to find an explicit intro
2413 Dim intro As clsTopic = FindConversationNode(ConvChar, ConvType Or clsAction.ConversationEnum.Greet, sCommandOrSubject)
2414 ' If not, look for an implicit one
2415 If intro Is Nothing Then intro = FindConversationNode(ConvChar, clsAction.ConversationEnum.Greet, "")
2416 If intro IsNot Nothing Then
2417 If AddResponse(False, intro.oConversation.ToString, New String() {}, True) Then bTaskHasOutputNew = True
2418 Adventure.sConversationNode = intro.Key
2419 If intro.bAsk OrElse intro.bTell OrElse intro.bCommand Then ' We matched an explicit intro, so no need to look further
2420 Adventure.sConversationCharKey = sCharKey
2421 If intro.arlActions.Count > 0 Then ExecuteActions(intro.arlActions, bTaskHasOutputNew)
2422 Exit Sub
2423 End If
2424 ' TODO - Run the implicit actions if we didn't find an explict match later.
2425 End If
2426 End If
2427
2428 ' Enter conversation with character
2429 Adventure.sConversationCharKey = sCharKey
2430
2431 ' Find conversation node (try to match on Farewell commands first)
2432 Dim topic As clsTopic = Nothing
2433 Dim sRestrictionTextTemp As String = sRestrictionText
2434 sRestrictionText = ""
2435 If ConvType = clsAction.ConversationEnum.Command Then topic = FindConversationNode(ConvChar, ConvType Or clsAction.ConversationEnum.Farewell, sCommandOrSubject)
2436 If topic Is Nothing Then
2437 topic = FindConversationNode(ConvChar, ConvType, sCommandOrSubject)
2438 Else
2439 Adventure.sConversationCharKey = ""
2440 Adventure.sConversationNode = ""
2441 End If
2442
2443 If topic IsNot Nothing Then
2444 If AddResponse(False, topic.oConversation.ToString, New String() {}, True) Then bTaskHasOutputNew = True
2445 ' If topic has children, set the conversation node
2446 If ConvChar.htblTopics.DoesTopicHaveChildren(topic.Key) Then
2447 Adventure.sConversationNode = topic.Key
2448 Else
2449 If Not topic.bStayInNode Then Adventure.sConversationNode = ""
2450 End If
2451 If topic.arlActions.Count > 0 Then ExecuteActions(topic.arlActions, bTaskHasOutputNew)
2452 Else
2453 ' Hmm, no conversation found. Need to give a default response back...
2454 Adventure.sConversationNode = ""
2455 Dim sMessage As String = ""
2456 If sRestrictionText <> "" Then
2457 sMessage = sRestrictionText
2458 Else
2459 ' TODO: Need to make this configurable within Generator
2460 Select Case ConvType
2461 Case clsAction.ConversationEnum.Ask
2462 If Adventure.dVersion < 5 Then
2463 sMessage = "%CharacterName[" & ConvChar.Key & "]% does not respond to your question."
2464 Else
2465 sMessage = "%CharacterName[" & ConvChar.Key & "]% doesn't appear to understand you."
2466 End If
2467 Case clsAction.ConversationEnum.Farewell
2468 sMessage = "%CharacterName[" & ConvChar.Key & "]% doesn't appear to understand you."
2469 Case clsAction.ConversationEnum.Greet
2470 sMessage = "%CharacterName[" & ConvChar.Key & "]% doesn't appear to understand you."
2471 Case clsAction.ConversationEnum.Tell
2472 sMessage = "%CharacterName[" & ConvChar.Key & "]% doesn't appear to understand you."
2473 Case clsAction.ConversationEnum.Command
2474 sMessage = "%CharacterName[" & ConvChar.Key & "]% ignores you."
2475 'AddResponse(bOutputMessages, ConvChar.Name & " ignores you.", sReferences, bPass)
2476 End Select
2477 End If
2478
2479 If AddResponse(False, sMessage, New String() {}, True) Then bTaskHasOutputNew = True
2480 End If
2481 sRestrictionText = sRestrictionTextTemp ' Dunno if we really need to do this, but may as well to be safe
2482 End Sub
2483
2484
2485 Friend Sub TriggerTimerEvent(ByVal sEventKey As String, ByVal se As clsEvent.SubEvent)
2486 With Adventure.htblEvents(sEventKey)
2487 .RunSubEvent(se)
2488 End With
2489 Display(vbCrLf & vbCrLf, True)
2490 CheckEndOfGame()
2491 End Sub
2492
2493 Friend Function FindConversationNode(ByVal ConvChar As clsCharacter, ByVal ConvType As clsAction.ConversationEnum, ByVal sCommandOrSubject As String) As clsTopic
2494 Dim iConvType As Integer = CInt(ConvType)
2495 Dim bFarewell As Boolean = False
2496 If iConvType >= CInt(clsAction.ConversationEnum.Farewell) Then
2497 bFarewell = True
2498 iConvType -= CInt(clsAction.ConversationEnum.Farewell)
2499 End If
2500 Dim bCommand As Boolean = False
2501 If iConvType >= CInt(clsAction.ConversationEnum.Command) Then
2502 bCommand = True
2503 iConvType -= CInt(clsAction.ConversationEnum.Command)
2504 End If
2505 Dim bTell As Boolean = False
2506 If iConvType >= CInt(clsAction.ConversationEnum.Tell) Then
2507 bTell = True
2508 iConvType -= CInt(clsAction.ConversationEnum.Tell)
2509 End If
2510 Dim bAsk As Boolean = False
2511 If iConvType >= CInt(clsAction.ConversationEnum.Ask) Then
2512 bAsk = True
2513 iConvType -= CInt(clsAction.ConversationEnum.Ask)
2514 End If
2515 Dim bIntro As Boolean = False
2516 If iConvType >= CInt(clsAction.ConversationEnum.Greet) Then
2517 bIntro = True
2518 iConvType -= CInt(clsAction.ConversationEnum.Greet)
2519 End If
2520
2521 ' Iterate thru all the leaves of the current node
2522 With ConvChar
2523 ' Should we sort our topics, perhaps by length?
2524 Dim dfHighestPercent As Double = 0
2525 Dim iMostMatches As Integer = 0
2526 Dim topicBest As clsTopic = Nothing
2527
2528 For Each topic As clsTopic In .htblTopics.Values
2529 Dim iMatchedKeywords As Integer = 0
2530
2531 If (topic.ParentKey = "" OrElse topic.ParentKey = Adventure.sConversationNode) AndAlso (Not bIntro OrElse topic.bIntroduction) AndAlso (Not bFarewell OrElse topic.bFarewell) AndAlso (bCommand = topic.bCommand) AndAlso (Not bAsk OrElse topic.bAsk) AndAlso (Not bTell OrElse topic.bTell) Then
2532
2533 If bAsk OrElse bTell Then
2534 ' Keyword matching
2535 ' Find the node that matches the most keywords
2536 ' Then if there are more than one, pick the one that matches most as a percentage
2537 Dim sKeywords As String() = topic.Keywords.Split(","c)
2538 Dim bLowPriority As Boolean = False
2539
2540 For Each sKeyword As String In sKeywords
2541 If ContainsWord(sCommandOrSubject, sKeyword.ToLower.Trim) OrElse sKeyword = "*" Then
2542 If PassRestrictions(topic.arlRestrictions) Then iMatchedKeywords += 1 ' Return topic
2543 If sKeyword = "*" Then bLowPriority = True
2544 End If
2545 Next
2546 Dim dfPercentMatched As Double = iMatchedKeywords / sKeywords.Length
2547 If bLowPriority AndAlso dfPercentMatched = 1 Then dfPercentMatched = 0.001
2548
2549 If iMatchedKeywords > iMostMatches OrElse (iMatchedKeywords = iMostMatches AndAlso dfPercentMatched > dfHighestPercent) Then
2550 topicBest = topic
2551 dfHighestPercent = dfPercentMatched
2552 iMostMatches = iMatchedKeywords
2553 End If
2554 End If
2555
2556 If bCommand Then
2557 ' RE matching
2558 For Each re As System.Text.RegularExpressions.Regex In GetRegularExpression(topic.Keywords.Trim.Replace("?", "\?"), sCommandOrSubject, False)
2559 If re IsNot Nothing AndAlso re.IsMatch(sCommandOrSubject) Then
2560 If PassRestrictions(topic.arlRestrictions) Then
2561 For i As Integer = 0 To 4
2562 Dim iRef As Integer = i + 1
2563 Dim sNumber As String = "%number" & iRef.ToString & "%"
2564 Dim sRefText As String = "%text" & iRef.ToString & "%"
2565
2566 If topic.Keywords.Contains(sRefText) Then ' Needs full parsing really...
2567 Adventure.sReferencedText(i) = re.Match(sCommandOrSubject).Groups("text" & iRef.ToString).Value.Trim
2568 ' Update Refs
2569 For Each ref As clsNewReference In NewReferences
2570 If ref.ReferenceType = ReferencesType.Text AndAlso ref.ReferenceMatch = sRefText.Replace("%", "") Then
2571 ref.Items.Clear()
2572 Dim refItem As New clsSingleItem
2573 refItem.bExplicitlyMentioned = True
2574 refItem.MatchingPossibilities.Add(Adventure.sReferencedText(i))
2575 refItem.sCommandReference = sCommandOrSubject
2576 ref.Items.Add(refItem)
2577 ref.sParentTask = "Topic"
2578 End If
2579 Next
2580 End If
2581 Next
2582
2583 Return topic
2584 End If
2585 End If
2586 Next
2587 End If
2588 If Not bAsk AndAlso Not bTell AndAlso Not bCommand Then
2589 ' No matching whatsoever
2590 If PassRestrictions(topic.arlRestrictions) Then Return topic
2591 End If
2592 End If
2593 Next
2594 If topicBest IsNot Nothing Then Return topicBest
2595 End With
2596 Return Nothing
2597 End Function
2598
2599
2600 Private Sub ExecuteActions(ByVal Actions As ActionArrayList, Optional ByRef bTaskHasOutputNew As Boolean = False)
2601
2602 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.High, "Executing Actions...")
2603 iDebugIndent += 1
2604 For Each act As clsAction In Actions
2605 ExecuteSingleAction(act, "", Nothing, bTaskHasOutputNew)
2606 Next
2607 iDebugIndent -= 1
2608
2609 End Sub
2610 Private Sub ExecuteActions(ByVal task As clsTask, Optional ByVal bCalledFromEvent As Boolean = False, Optional ByRef bTaskHasOutputNew As Boolean = False)
2611 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Executing Actions...")
2612 iDebugIndent += 1
2613 For Each act As clsAction In task.arlActions
2614 ExecuteSingleAction(act, ParentTaskCommand(task), task, bCalledFromEvent, bTaskHasOutputNew)
2615 Next
2616 iDebugIndent -= 1
2617 End Sub
2618
2619 Public Sub ShowUserSplash()
2620 If clsBlorb.Frontispiece > -1 Then
2621 Dim imgSplash As Byte() = Blorb.GetImage(clsBlorb.Frontispiece)
2622 If imgSplash IsNot Nothing Then
2623 Glue.ShowCoverArt(imgSplash)
2624 End If
2625 End If
2626 End Sub
2627
2628 ' Returns the command from the parent task if we're a specific task. Does this recursively in case we're specific of a specific etc.
2629 Public Function ParentTaskCommand(ByVal task As clsTask) As String
2630 While task.TaskType = clsTask.TaskTypeEnum.Specific
2631 task = Adventure.htblTasks(task.GeneralKey)
2632 End While
2633 If task.arlCommands.Count > 0 Then
2634 If task.arlCommands.Count > iMatchedTaskCommand Then
2635 Return task.arlCommands(iMatchedTaskCommand)
2636 Else
2637 Return task.arlCommands(0)
2638 End If
2639 Else
2640 Return ""
2641 End If
2642 End Function
2643
2644 Private Function ToProper(ByVal sText As String, Optional ByVal bStrict As Boolean = False) As String
2645 Dim sReturn As String = Nothing
2646
2647 If sText.Length > 0 Then sReturn = sText.Substring(0, 1).ToUpper
2648 If sText.Length > 1 Then
2649 If bStrict Then sReturn &= sText.Substring(1).ToLower Else sReturn &= sText.Substring(1)
2650 End If
2651
2652 Return sReturn
2653 End Function
2654
2655
2656 Private Function AmbWord(ByVal sKeys As StringArrayList, ByVal RefType As ReferencesType) As String
2657 Dim bFoundInAllItemsSoFar As Boolean
2658 Dim bFoundInThisItem As Boolean
2659
2660 AmbWord = Nothing
2661
2662 ' Work out a common word that's in all the object names, and is also in the input
2663 For Each sWord As String In Split(sLastProperInput, " ")
2664 bFoundInAllItemsSoFar = True
2665 For Each sKey As String In sKeys
2666 bFoundInThisItem = False
2667 Select Case RefType
2668 Case ReferencesType.Object
2669 If Adventure.htblObjects.ContainsKey(sKey) Then
2670 For Each sName As String In Adventure.htblObjects(sKey).arlNames
2671 If sWord = sName Then
2672 bFoundInThisItem = True
2673 GoTo NextItem
2674 End If
2675 Next sName
2676 End If
2677 Case ReferencesType.Character
2678 If Adventure.htblCharacters.ContainsKey(sKey) Then
2679 If sWord = Adventure.htblCharacters(sKey).ProperName Then
2680 bFoundInThisItem = True
2681 GoTo NextItem
2682 End If
2683 For Each sName As String In Adventure.htblCharacters(sKey).arlDescriptors
2684 If sWord = sName Then
2685 bFoundInThisItem = True
2686 GoTo NextItem
2687 End If
2688 Next sName
2689 End If
2690 Case ReferencesType.Location
2691 If Adventure.htblLocations.ContainsKey(sKey) Then
2692 For Each sName As String In Adventure.htblLocations(sKey).ShortDescription.ToString.ToLower.Split(" "c)
2693 If sWord = sName Then
2694 bFoundInThisItem = True
2695 GoTo NextItem
2696 End If
2697 Next sName
2698 End If
2699 End Select
2700
2701 If Not bFoundInThisItem Then
2702 bFoundInAllItemsSoFar = False
2703 GoTo NextWord
2704 End If
2705 NextItem:
2706 Next sKey
2707 If bFoundInAllItemsSoFar Then Return sWord
2708 NextWord:
2709 Next sWord
2710 End Function
2711
2712 Private Sub DisplayAmbiguityQuestion()
2713 NewReferences = Adventure.htblTasks(sAmbTask).NewReferencesWorking
2714 If NewReferences Is Nothing Then Exit Sub
2715
2716 For iRef As Integer = 0 To NewReferences.Length - 1
2717 Debug.WriteLine("Reference " & iRef)
2718 With NewReferences(iRef)
2719 Debug.WriteLine("Number of Items in this Reference: " & .Items.Count)
2720 For Each itm As clsSingleItem In .Items
2721 If itm.MatchingPossibilities.Count > 1 Then
2722 Select Case .ReferenceType
2723 Case ReferencesType.Object
2724 Dim htblObs As New ObjectHashTable
2725 For Each sKey As String In itm.MatchingPossibilities
2726 If Not htblObs.ContainsKey(sKey) Then htblObs.Add(Adventure.htblObjects(sKey), sKey)
2727 Next
2728 Dim bCanSeeAny As Boolean = False
2729 For Each sKey As String In htblObs.Keys
2730 If Not bCanSeeAny AndAlso Adventure.Player.CanSeeObject(sKey) Then bCanSeeAny = True
2731 Next
2732 If Not bCanSeeAny Then ' Want to try to move this into the library at some point, as we _may_ want to resolve ambiguous items that aren't visible to the player
2733 Dim bAnyPlural As Boolean = False
2734 For Each ob As clsObject In htblObs.Values
2735 If ob.IsPlural Then
2736 bAnyPlural = True
2737 Exit For
2738 End If
2739 Next
2740 If bAnyPlural Then
2741 Display("You can't see any " & AmbWord(itm.MatchingPossibilities, .ReferenceType) & "!" & vbCrLf)
2742 Else
2743 Display("You can't see any " & (New clsObject).GuessPluralFromNoun(AmbWord(itm.MatchingPossibilities, .ReferenceType)) & "!" & vbCrLf)
2744 End If
2745 sAmbTask = Nothing
2746 Else
2747 Display("Which " & AmbWord(itm.MatchingPossibilities, .ReferenceType) & "?")
2748 Display(ToProper(htblObs.List("or")) & "." & vbCrLf)
2749 End If
2750 Exit Sub
2751 Case ReferencesType.Character
2752 Dim htblChars As New CharacterHashTable
2753 For Each sKey As String In itm.MatchingPossibilities
2754 htblChars.Add(Adventure.htblCharacters(sKey), sKey)
2755 Next
2756 Dim bCanSeeAny As Boolean = False
2757 For Each sKey As String In htblChars.Keys
2758 If Not bCanSeeAny AndAlso Adventure.Player.CanSeeCharacter(sKey) Then bCanSeeAny = True
2759 Next
2760 If Not bCanSeeAny Then
2761 Display("You can't see any " & AmbWord(itm.MatchingPossibilities, .ReferenceType) & "!" & vbCrLf)
2762 sAmbTask = Nothing
2763 Else
2764 Display("Which " & AmbWord(itm.MatchingPossibilities, .ReferenceType) & "?")
2765 Display(ToProper(htblChars.List("or")) & "." & vbCrLf)
2766 End If
2767 Exit Sub
2768 Case ReferencesType.Location
2769 Dim htblLocs As New LocationHashTable
2770 For Each sKey As String In itm.MatchingPossibilities
2771 htblLocs.Add(Adventure.htblLocations(sKey), sKey)
2772 Next
2773 Display("Which " & AmbWord(itm.MatchingPossibilities, .ReferenceType) & "?")
2774 Display(ToProper(htblLocs.List("or")) & "." & vbCrLf)
2775 Exit Sub
2776 Case Else
2777 ErrMsg("Unable to disambiguate reference types " & .ReferenceType.ToString)
2778 End Select
2779 ElseIf itm.MatchingPossibilities.Count = 0 Then
2780 Display("Sorry, that does not clarify the ambiguity." & vbCrLf)
2781 sAmbTask = Nothing
2782 Exit Sub
2783 End If
2784 Next
2785 End With
2786 Next
2787 End Sub
2788
2789 Private Sub PrintOutReferences()
2790
2791 If NewReferences Is Nothing Then Exit Sub
2792 For iRef As Integer = 0 To NewReferences.Length - 1
2793 Select Case iRef
2794 Case 0
2795 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, "First Reference: ", False)
2796 Case 1
2797 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, "Second Reference: ", False)
2798 Case 2
2799 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, "Third Reference: ", False)
2800 Case 3
2801 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, "Fourth Reference: ", False)
2802 Case Else
2803 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, "Reference " & iRef & ": ", False)
2804 End Select
2805
2806 Dim iCount As Integer = 0
2807 If NewReferences(iRef) IsNot Nothing Then
2808 For Each itm As clsSingleItem In NewReferences(iRef).Items
2809 For Each sKey As String In itm.MatchingPossibilities
2810 If sKey IsNot Nothing Then
2811 Select Case NewReferences(iRef).ReferenceType
2812 Case ReferencesType.Object
2813 If Adventure.htblObjects.ContainsKey(sKey) Then DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, Adventure.htblObjects(sKey).FullName, False)
2814 Case ReferencesType.Direction
2815 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, sKey, False)
2816 Case ReferencesType.Character
2817 If Adventure.htblCharacters.ContainsKey(sKey) Then DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, Adventure.htblCharacters(sKey).ProperName, False)
2818 Case ReferencesType.Number
2819
2820 Case ReferencesType.Text
2821
2822 End Select
2823 iCount += 1
2824 If iCount < NewReferences(iRef).Items.Count Then DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, ", ", False)
2825 Else
2826 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, "NULL reference", False)
2827 End If
2828 Next
2829 Next
2830 Else
2831 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, "Nothing", False)
2832 End If
2833 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, "")
2834 Next
2835 End Sub
2836
2837 Private Sub GrabIt()
2838
2839 Try
2840 Dim sNewIt As String = ""
2841 Dim sNewThem As String = ""
2842 Dim sNewHim As String = ""
2843 Dim sNewHer As String = ""
2844 Dim sWords() As String = sInput.Split(" "c)
2845 Dim PossibleItKeys As New StringArrayList
2846 Dim PossibleThemKeys As New StringArrayList
2847 Dim PossibleHimKeys As New StringArrayList
2848 Dim PossibleHerKeys As New StringArrayList
2849
2850 ' First, look at anything visible, then seen
2851 For iScope As eScope = eScope.Visible To eScope.Seen
2852 For Each sWord As String In sWords
2853
2854 Dim htblObs As ObjectHashTable = Nothing
2855 Dim htblChars As CharacterHashTable = Nothing
2856 If iScope = eScope.Visible Then
2857 htblObs = Adventure.htblObjects.VisibleTo(Adventure.Player.Key)
2858 htblChars = Adventure.htblCharacters.VisibleTo(Adventure.Player.Key)
2859 Else
2860 htblObs = Adventure.htblObjects.SeenBy(Adventure.Player.Key)
2861 htblChars = Adventure.htblCharacters.SeenBy(Adventure.Player.Key)
2862 End If
2863
2864 If sNewIt = "" Then
2865 For Each ob As clsObject In htblObs.Values
2866 For Each sName As String In ob.arlNames
2867 If sWord = sName Then
2868 If Not PossibleItKeys.Contains(ob.Key) Then PossibleItKeys.Add(ob.Key)
2869 End If
2870 Next
2871 Next ob
2872 End If
2873 If sNewThem = "" Then
2874 For Each ob As clsObject In htblObs.Values
2875 If ob.IsPlural Then
2876 For Each sName As String In ob.arlNames
2877 If sWord = sName Then
2878 If Not PossibleThemKeys.Contains(ob.Key) Then PossibleThemKeys.Add(ob.Key)
2879 End If
2880 Next
2881 End If
2882 Next ob
2883 End If
2884 For Each ch As clsCharacter In htblChars.Values
2885 Dim bMatch As Boolean = False
2886 If sWord = ch.ProperName.ToLower Then bMatch = True
2887 For Each sName As String In ch.arlDescriptors
2888 If sWord = sName Then
2889 bMatch = True
2890 Exit For
2891 End If
2892 Next
2893 If bMatch Then
2894 Select Case ch.Gender
2895 Case clsCharacter.GenderEnum.Male
2896 If Not PossibleItKeys.Contains(ch.Key) Then PossibleHimKeys.Add(ch.Key)
2897 Case clsCharacter.GenderEnum.Female
2898 If Not PossibleItKeys.Contains(ch.Key) Then PossibleHerKeys.Add(ch.Key)
2899 Case clsCharacter.GenderEnum.Unknown
2900 If Not PossibleItKeys.Contains(ch.Key) Then PossibleItKeys.Add(ch.Key)
2901 End Select
2902 End If
2903 Next
2904 Next sWord
2905
2906 If sNewIt = "" Then
2907 If PossibleItKeys.Count = 1 Then
2908 If Adventure.htblObjects.ContainsKey(PossibleItKeys(0)) Then
2909 sNewIt = Adventure.htblObjects(PossibleItKeys(0)).FullName(ArticleTypeEnum.Definite)
2910 Else
2911 sNewIt = Adventure.htblCharacters(PossibleItKeys(0)).Name
2912 End If
2913 ElseIf PossibleItKeys.Count > 1 Then
2914 Dim arlKeys As New StringArrayList
2915
2916 For Each sKey As String In PossibleItKeys
2917 If Adventure.htblObjects.ContainsKey(sKey) Then
2918 Dim ob As clsObject = Adventure.htblObjects(sKey)
2919 For Each sPrefixWord As String In ob.Prefix.Split(" "c)
2920 For Each sWord As String In sWords
2921 If sPrefixWord = sWord Then
2922 arlKeys.Add(sKey)
2923 GoTo NextOb
2924 End If
2925 Next
2926 Next
2927 End If
2928 NextOb:
2929 If Adventure.htblCharacters.ContainsKey(sKey) Then
2930 Dim ch As clsCharacter = Adventure.htblCharacters(sKey)
2931 For Each sPrefixWord As String In ch.Prefix.Split(" "c)
2932 For Each sWord As String In sWords
2933 If sPrefixWord = sWord Then
2934 arlKeys.Add(sKey)
2935 GoTo NextChar
2936 End If
2937 Next
2938 Next
2939 End If
2940 NextChar:
2941 Next
2942
2943 If arlKeys.Count = 1 Then
2944 If Adventure.htblObjects.ContainsKey(arlKeys(0)) Then
2945 sNewIt = Adventure.htblObjects(arlKeys(0)).FullName(ArticleTypeEnum.Definite)
2946 ElseIf Adventure.htblCharacters.ContainsKey(arlKeys(0)) Then
2947 sNewIt = Adventure.htblCharacters(arlKeys(0)).Name
2948 End If
2949 End If
2950 End If
2951 End If
2952
2953 If sNewThem = "" Then
2954 If PossibleThemKeys.Count = 1 Then
2955 If Adventure.htblObjects.ContainsKey(PossibleThemKeys(0)) Then
2956 sNewThem = Adventure.htblObjects(PossibleThemKeys(0)).FullName(ArticleTypeEnum.Definite)
2957 Else
2958 sNewThem = Adventure.htblCharacters(PossibleThemKeys(0)).Name
2959 End If
2960 ElseIf PossibleThemKeys.Count > 1 Then
2961 Dim arlKeys As New StringArrayList
2962
2963 For Each sKey As String In PossibleThemKeys
2964 If Adventure.htblObjects.ContainsKey(sKey) Then
2965 Dim ob As clsObject = Adventure.htblObjects(sKey)
2966 If ob.IsPlural Then
2967 For Each sPrefixWord As String In ob.Prefix.Split(" "c)
2968 For Each sWord As String In sWords
2969 If sPrefixWord = sWord Then
2970 arlKeys.Add(sKey)
2971 GoTo NextObT
2972 End If
2973 Next
2974 Next
2975 End If
2976 End If
2977 NextObT:
2978 If Adventure.htblCharacters.ContainsKey(sKey) Then
2979 Dim ch As clsCharacter = Adventure.htblCharacters(sKey)
2980 For Each sPrefixWord As String In ch.Prefix.Split(" "c)
2981 For Each sWord As String In sWords
2982 If sPrefixWord = sWord Then
2983 arlKeys.Add(sKey)
2984 GoTo NextCharT
2985 End If
2986 Next
2987 Next
2988 End If
2989 NextCharT:
2990 Next
2991
2992 If arlKeys.Count = 1 Then
2993 If Adventure.htblObjects.ContainsKey(arlKeys(0)) Then
2994 sNewThem = Adventure.htblObjects(arlKeys(0)).FullName(ArticleTypeEnum.Definite)
2995 ElseIf Adventure.htblCharacters.ContainsKey(arlKeys(0)) Then
2996 sNewThem = Adventure.htblCharacters(arlKeys(0)).Name
2997 End If
2998 End If
2999 End If
3000 End If
3001
3002 If sNewHim = "" Then
3003 If PossibleHimKeys.Count = 1 Then
3004 If Adventure.htblCharacters.ContainsKey(PossibleHimKeys(0)) Then
3005 sNewHim = Adventure.htblCharacters(PossibleHimKeys(0)).Name(, False, False, ArticleTypeEnum.Definite)
3006 End If
3007 ElseIf PossibleHimKeys.Count > 1 Then
3008 Dim arlKeys As New StringArrayList
3009
3010 For Each sKey As String In PossibleHimKeys
3011 If Adventure.htblCharacters.ContainsKey(sKey) Then
3012 Dim ch As clsCharacter = Adventure.htblCharacters(sKey)
3013 For Each sPrefixWord As String In ch.Prefix.Split(" "c)
3014 For Each sWord As String In sWords
3015 If sPrefixWord = sWord Then
3016 arlKeys.Add(sKey)
3017 GoTo NextChar1
3018 End If
3019 Next
3020 Next
3021 End If
3022 NextChar1:
3023 Next
3024
3025 If arlKeys.Count = 1 Then
3026 If Adventure.htblCharacters.ContainsKey(arlKeys(0)) Then
3027 sNewHim = Adventure.htblCharacters(arlKeys(0)).Name(, False, False, ArticleTypeEnum.Definite)
3028 End If
3029 End If
3030 End If
3031 End If
3032
3033 If sNewHer = "" Then
3034 If PossibleHerKeys.Count = 1 Then
3035 If Adventure.htblCharacters.ContainsKey(PossibleHerKeys(0)) Then
3036 sNewHer = Adventure.htblCharacters(PossibleHerKeys(0)).Name(, False, False, ArticleTypeEnum.Definite)
3037 End If
3038 ElseIf PossibleHerKeys.Count > 1 Then
3039 Dim arlKeys As New StringArrayList
3040
3041 For Each sKey As String In PossibleHerKeys
3042 If Adventure.htblCharacters.ContainsKey(sKey) Then
3043 Dim ch As clsCharacter = Adventure.htblCharacters(sKey)
3044 For Each sPrefixWord As String In ch.Prefix.Split(" "c)
3045 For Each sWord As String In sWords
3046 If sPrefixWord = sWord Then
3047 arlKeys.Add(sKey)
3048 GoTo NextChar2
3049 End If
3050 Next
3051 Next
3052 End If
3053 NextChar2:
3054 Next
3055
3056 If arlKeys.Count = 1 Then
3057 If Adventure.htblCharacters.ContainsKey(arlKeys(0)) Then
3058 sNewHer = Adventure.htblCharacters(arlKeys(0)).Name(, False, False, ArticleTypeEnum.Definite)
3059 End If
3060 End If
3061 End If
3062 End If
3063
3064 Next
3065
3066 If sNewIt <> "" Then sIt = sNewIt
3067 If sNewThem <> "" Then sThem = sNewThem
3068 If sNewHim <> "" Then sHim = sNewHim
3069 If sNewHer <> "" Then sHer = sNewHer
3070
3071 If sIt = "" Then sIt = "Absolutely Nothing"
3072 If sThem = "" Then sThem = "Absolutely Nothing"
3073 If sHim = "" Then sHim = "No male"
3074 If sHer = "" Then sHer = "No female"
3075
3076 Catch ex As Exception
3077 ErrMsg("Error grabbing ""it""", ex)
3078 sIt = "Absolutely Nothing"
3079 End Try
3080
3081 End Sub
3082
3083 Private Sub ReplaceWord(ByRef sText As String, ByVal sFind As String, ByVal sReplace As String)
3084 sText = sText.Replace(" " & sFind & " ", " " & sReplace & " ")
3085 If sText.StartsWith(sFind & " ") Then sText = sReplace & " " & sRight(sText, sText.Length - (sFind.Length + 1))
3086 If sText.EndsWith(" " & sFind) Then sText = sLeft(sText, sText.Length - (sFind.Length + 1)) & " " & sReplace
3087 If sText = sFind Then sText = sReplace
3088 End Sub
3089
3090
3091 Friend Sub Restart()
3092 OpenAdventure(Adventure.FullPath)
3093 End Sub
3094
3095
3096 Friend Function SaveGame(Optional ByVal bSaveAs As Boolean = False) As Boolean
3097 Try
3098 Dim sFilename As String = Glue.QuerySavePath()
3099
3100 If sFilename <> "" Then
3101 If Not sFilename.ToLower.EndsWith(".tas") Then sFilename &= ".tas"
3102 Adventure.sGameFilename = sFilename
3103 Dim ss As New StateStack
3104 If SaveState(ss.GetState, sFilename) Then
3105 Display("Game """ & IO.Path.GetFileNameWithoutExtension(sFilename) & """ saved")
3106 SaveSetting("ADRIFT", "Runner", "Game Path", IO.Path.GetDirectoryName(sFilename))
3107 Adventure.Changed = False
3108 Return True
3109 Else
3110 Display("Error saving game")
3111 Return False
3112 End If
3113 End If
3114 Catch ex As Exception
3115 Display("Error saving game: " & ex.Message)
3116 Return False
3117 End Try
3118 Return False
3119 End Function
3120
3121 Friend Sub Restore(Optional sFilename As String = "")
3122 If sFilename <> "" Then
3123 If Not sFilename.ToLower.EndsWith(".tas") Then sFilename &= ".tas"
3124 Else
3125 sFilename = Glue.QueryRestorePath()
3126 End If
3127
3128 If sFilename <> "" Then
3129 If IO.File.Exists(sFilename) Then
3130 States.Clear()
3131 For Each t As clsTask In Adventure.htblTasks.Values
3132 t.Completed = False ' Just in case the save file doesn't cover that task
3133 Next
3134 Dim ss As New StateStack
3135 ss.LoadState(sFilename)
3136 Display("Game """ & IO.Path.GetFileNameWithoutExtension(sFilename) & """ restored" & vbCrLf, True)
3137 Adventure.sGameFilename = sFilename
3138 Adventure.eGameState = clsAction.EndGameEnum.Running
3139 Adventure.bDisplayedWinLose = False
3140 UpdateStatusBar()
3141 Display(Adventure.htblLocations(Adventure.Player.Location.LocationKey).ViewLocation, True)
3142 'If States.Count = 0 Then States.RecordState() ' So we're able to Undo immediately after a restore
3143 bSystemTask = False ' Allow events to run
3144 PrepareForNextTurn()
3145 UserSession.Map.RecalculateNode(Adventure.Map.FindNode(Adventure.Player.Location.LocationKey))
3146 UserSession.Map.SelectNode(Adventure.Player.Location.LocationKey)
3147 Else
3148 Display("Save file not found.", True)
3149 End If
3150 End If
3151 End Sub
3152
3153
3154 Friend bQuitting As Boolean = False
3155 Friend Function Quit(Optional ByVal bJustGame As Boolean = False) As Boolean
3156 If Adventure IsNot Nothing AndAlso Adventure.eGameState = clsAction.EndGameEnum.Running Then
3157 If Adventure.Changed Then
3158 Select Case Glue.QuerySaveBeforeQuit()
3159 Case QueryResult.YES
3160 SaveGame(True)
3161 Case QueryResult.NO
3162 ' Continue
3163 Case QueryResult.CANCEL
3164 Return False
3165 End Select
3166 End If
3167 End If
3168
3169 If bJustGame Then
3170 Adventure.eGameState = clsAction.EndGameEnum.Neutral
3171 Else
3172 If Not bQuitting Then fRunner.Close()
3173 End If
3174 Return True
3175 End Function
3176
3177 Friend Sub Undo()
3178 If States.SetLastState Then
3179 Adventure.bDisplayedWinLose = False
3180 UserSession.Map.RecalculateNode(Adventure.Map.FindNode(Adventure.Player.Location.LocationKey))
3181 UserSession.Map.SelectNode(Adventure.Player.Location.LocationKey)
3182 UpdateStatusBar()
3183 Dim sText As String = sTurnOutput
3184 Display("Undone.", , , False)
3185 If sText <> "" Then Display(sText)
3186 Else
3187 Display("Sorry, <c>undo</c> is not currently available.")
3188 End If
3189 bSystemTask = True
3190 End Sub
3191
3192 Private Function GetBlock(ByVal sText As String) As String
3193 Dim cText() As Char = sText.ToCharArray
3194 Dim sOut As String = ""
3195 Dim iLevel As Integer = 0
3196
3197 For Each c As Char In cText
3198 Select Case c
3199 Case "{"c, "["c
3200 iLevel += 1
3201 Case "}"c, "]"c
3202 iLevel -= 1
3203 End Select
3204 sOut &= c
3205 If iLevel = 0 Then Return sOut
3206 Next
3207 Return sText
3208 End Function
3209
3210 Private Function MySplit(ByVal sText As String, ByRef iMinLength As Integer) As StringArrayList
3211
3212 Dim sSplits() As String = Split(sText, "/")
3213 Dim sal As New StringArrayList
3214 Dim iLevel As Integer = 0
3215 Dim s As String = ""
3216
3217 For Each sSplit As String In sSplits
3218 If iLevel > 0 Then s &= "/"
3219 s &= sSplit
3220 For i As Integer = 0 To sSplit.Length - 1
3221 Select Case sSplit(i)
3222 Case "["c, "{"c
3223 iLevel += 1
3224 Case "]"c, "}"c
3225 iLevel -= 1
3226 End Select
3227 Next
3228 If iLevel = 0 Then
3229 sal.Add(s)
3230 If s.Length < iMinLength Then iMinLength = s.Length
3231 s = ""
3232 End If
3233 Next
3234 Return sal
3235 End Function
3236
3237
3238 ' This should split any block, e.g. [examine/ex/x/look {at/in/under}] %object%
3239 ' into:
3240 ' examine %object%
3241 ' ex %object%
3242 ' x %object%
3243 ' look %object%
3244 ' look at %object%
3245 ' look in %object%
3246 ' look under %object%
3247 '
3248 ' [get/take/pick {up}] {the} hat {from Grandad}
3249 Private Function ExpandBlock(ByVal sBlock As String) As StringArrayList
3250 Dim sal As New StringArrayList
3251
3252 If sBlock = "" Then
3253 sal.Add("")
3254 Return sal
3255 End If
3256
3257 Dim sPre As String = System.Text.RegularExpressions.Regex.Replace(sBlock, "({|\[).*$", "")
3258 Dim sMid As String = GetBlock(sRight(sBlock, sBlock.Length - sPre.Length))
3259 Dim salPost As StringArrayList = Nothing
3260
3261 If sMid <> "" Then
3262 Dim bOptional As Boolean = False
3263 If sLeft(sMid, 1) = "{" Then
3264 salPost = ExpandBlock(sRight(sBlock, sBlock.Length - sMid.Length - sPre.Length))
3265 For Each sPost As String In salPost
3266 sal.Add(sPre & sPost)
3267 Next
3268 bOptional = True
3269 End If
3270 sMid = Mid(sMid, 2, sMid.Length - 2)
3271
3272 Dim iMinLength As Integer = Integer.MaxValue
3273 Dim sSplits As StringArrayList = MySplit(sMid, iMinLength)
3274 If salPost Is Nothing AndAlso sPre.Length + iMinLength <= fRunner.txtInput.TextLength - 2 Then
3275 salPost = ExpandBlock(sRight(sBlock, sBlock.Length - (sMid.Length + 2) - sPre.Length))
3276 End If
3277
3278 For Each sSplit As String In sSplits
3279 Dim salSplit As StringArrayList = ExpandBlock(sSplit)
3280 For Each s As String In salSplit
3281 If bOptional Then s = "@@@" & s
3282 If salPost IsNot Nothing Then
3283 For Each sPost As String In salPost
3284 If s <> "" AndAlso sPost <> "" AndAlso Not s.EndsWith(" ") AndAlso Not sPost.StartsWith(" ") Then sPost = " " & sPost
3285 sal.Add(sPre & s & sPost)
3286 If sal.Count > 1000 Then Return sal ' PK Girl can return millions of possibilities - Yikes, need to redesign!
3287 Next
3288 Else
3289 sal.Add(sPre & s)
3290 End If
3291 Next
3292 Next
3293 Else
3294 salPost = ExpandBlock(sRight(sBlock, sBlock.Length - sMid.Length - sPre.Length))
3295 For Each sPost As String In salPost
3296 sal.Add(sPre & sPost)
3297 If sal.Count > 1000 Then Return sal
3298 Next
3299 End If
3300 Return sal
3301 End Function
3302
3303 Private Function EvaluateInput(ByVal iMinimumPriority As Integer, ByVal bPassingOnly As Boolean) As String
3304 Dim cCursor As Char = "Ø"c
3305 Dim cCommentCursor As Char = "@"c
3306 Dim sCursorFont As String = "Wingdings"
3307 Dim bComment As Boolean = False
3308 bComment = (fRunner.txtInput.Text.Length > 0 AndAlso fRunner.txtInput.Text(0) = cCommentCursor)
3309
3310 InitialiseInputBox()
3311 If bComment Then
3312 Display("<c><font face=""" & sCursorFont & """ size=18>" & cCommentCursor & "</font> " & sInput & "</c>" & vbCrLf, True, False)
3313 Return ""
3314 End If
3315
3316 If iMinimumPriority = 0 Then
3317 Display("<c><font face=""" & sCursorFont & """ size=14>" & cCursor & "</font> " & sInput & "</c>" & vbCrLf, True, False, False)
3318 sInput = sInput.ToLower
3319 If ContainsWord(sInput, "it") Then
3320 Display("<c>(" & sIt & ")</c>" & vbCrLf, True)
3321 ReplaceWord(sInput, "it", sIt)
3322 End If
3323 If ContainsWord(sInput, "them") Then
3324 Display("<c>(" & sThem & ")</c>" & vbCrLf, True)
3325 ReplaceWord(sInput, "them", sThem)
3326 End If
3327 If ContainsWord(sInput, "him") Then
3328 Display("<c>(" & sHim & ")</c>" & vbCrLf, True)
3329 ReplaceWord(sInput, "him", sHim)
3330 End If
3331 If ContainsWord(sInput, "her") Then
3332 Display("<c>(" & sHer & ")</c>" & vbCrLf, True)
3333 ReplaceWord(sInput, "her", sHer)
3334 End If
3335 If (sInput = "again" OrElse sInput = "g") AndAlso salCommands.Count > 2 Then
3336 Display("<c>(" & salCommands(salCommands.Count - 3) & ")</c>" & vbCrLf, True)
3337 sInput = salCommands(salCommands.Count - 3)
3338 salCommands.RemoveAt(salCommands.Count - 2) ' Don't store 'again'
3339 End If
3340 GrabIt()
3341
3342 Dim sPreSyn As String = sInput
3343 For Each syn As clsSynonym In Adventure.htblSynonyms.Values
3344 For Each sFrom As String In syn.ChangeFrom
3345 If ContainsWord(sInput, sFrom) Then
3346 ReplaceWord(sInput, sFrom, syn.ChangeTo)
3347 End If
3348 Next
3349 Next
3350 If sInput <> sPreSyn Then
3351 DebugPrint(ItemEnum.General, "", DebugDetailLevelEnum.Medium, "Synonyms changed input """ & sPreSyn & """ to """ & sInput & """")
3352 End If
3353 If CBool(GetSetting("ADRIFT", "Runner", "BlankLine", "0")) Then Display(vbCrLf)
3354 End If
3355
3356 sInput = sInput.ToLower
3357
3358 ' Don't actually respond to the tasks here, in case the user has created a task to override the system one.
3359 If Adventure.eGameState <> clsAction.EndGameEnum.Running OrElse Adventure.dVersion < 5 Then
3360 If SystemTasks(True) Then
3361 Return ""
3362 Else
3363 If Adventure.eGameState <> clsAction.EndGameEnum.Running Then
3364 Display("Please give one of the answers above." & vbCrLf)
3365 Return ""
3366 End If
3367 End If
3368 End If
3369
3370 Dim sTaskKey As String = Nothing
3371
3372 If sAmbTask IsNot Nothing Then
3373 sTaskKey = ResolveAmbiguity(sInput)
3374
3375 If Not sTaskKey Is Nothing Then
3376 sRestrictionTextMulti = ""
3377 sRestrictionText = sRestrictionTextMulti
3378 End If
3379 Else
3380 sLastProperInput = sInput
3381 Erase NewReferences
3382 End If
3383
3384 ' only run this if we're not resolving an ambiguity or it left no tasks
3385 If sTaskKey Is Nothing Then
3386 Dim cRefCopy(-1) As clsNewReference
3387 Dim bCopied As Boolean = False
3388 Dim sRememberAmbTask As String = Nothing
3389 For i As Integer = 0 To 4
3390 Adventure.sReferencedText(i) = ""
3391 Next
3392 ' If Not sAmbTask Is Nothing Then remember References, so we can reapply them if we don't get a new command
3393 If Not sAmbTask Is Nothing Then
3394 ReDim cRefCopy(NewReferences.Length - 1)
3395 Array.Copy(NewReferences, cRefCopy, NewReferences.Length)
3396 bCopied = True
3397 sRememberAmbTask = sAmbTask
3398 End If
3399 sTaskKey = GetGeneralTask(sInput, iMinimumPriority, False)
3400 If Adventure.sReferencedText(0) = "" Then Adventure.sReferencedText(0) = sInput
3401 If sTaskKey Is Nothing AndAlso sAmbTask IsNot Nothing AndAlso iMinimumPriority > 0 AndAlso sOutputText <> "" Then sAmbTask = Nothing ' Suppress ambiguity question if we're running further down task list and we already have a failure response
3402 If sTaskKey Is Nothing AndAlso sAmbTask Is Nothing AndAlso Not sRememberAmbTask Is Nothing Then sAmbTask = sRememberAmbTask
3403 If sTaskKey Is Nothing AndAlso Not sAmbTask Is Nothing AndAlso bCopied Then
3404 ReDim NewReferences(cRefCopy.Length - 1)
3405 Array.Copy(cRefCopy, NewReferences, cRefCopy.Length)
3406 End If
3407
3408 End If
3409
3410 If Not sAmbTask Is Nothing AndAlso sTaskKey Is Nothing Then
3411 ' Display ambiguity question
3412 DisplayAmbiguityQuestion()
3413 Else
3414 sAmbTask = Nothing
3415 If sTaskKey IsNot Nothing Then
3416 Dim taskRun As clsTask = Adventure.htblTasks(sTaskKey)
3417 NewReferences = taskRun.NewReferencesWorking
3418 AttemptToExecuteTask(sTaskKey, , , , , , , bPassingOnly)
3419 If taskRun.bSystemTask Then bSystemTask = True
3420
3421 While Adventure.qTasksToRun.Count > 0
3422 Dim sKey As String = Adventure.qTasksToRun.Dequeue
3423 AttemptToExecuteTask(sKey, True)
3424 End While
3425
3426 If iMinimumPriority = 0 Then
3427 If sOutputText = "" Then
3428 NotUnderstood()
3429 Else
3430 ' Ok, successful task. So long as we didn't execute a system task
3431 If Not bSystemTask Then TurnBasedStuff()
3432 Adventure.Changed = True
3433 sRememberedVerb = ""
3434 End If
3435 End If
3436 Else
3437 If iMinimumPriority = 0 Then
3438 If Adventure.eGameState = clsAction.EndGameEnum.Running Then
3439 If Not SystemTasks() Then NotUnderstood()
3440 bSystemTask = True
3441 End If
3442 End If
3443 End If
3444 If iMinimumPriority = 0 AndAlso sOutputText <> "***SYSTEM***" Then Display(vbCrLf)
3445 End If
3446
3447 If sOutputText <> "***SYSTEM***" Then
3448 If iMinimumPriority = 0 Then
3449 Display(vbCrLf, True)
3450 DebugPrint(ItemEnum.General, "", DebugDetailLevelEnum.Low, "ENDOFTURN")
3451 End If
3452 Debug.WriteLine(Now.Subtract(dtDebug).ToString())
3453
3454 UpdateStatusBar()
3455 End If
3456
3457 Return sOutputText
3458 End Function
3459
3460
3461 Private Class TaskSorter
3462 Implements System.Collections.Generic.IComparer(Of clsTask)
3463
3464 Public Function Compare(x As clsTask, y As clsTask) As Integer Implements System.Collections.Generic.IComparer(Of clsTask).Compare
3465 Return x.Priority.CompareTo(y.Priority)
3466 End Function
3467 End Class
3468
3469 Private Sub NotUnderstood()
3470
3471 If sRememberedVerb <> "" Then
3472 sInput = sRememberedVerb & " " & sInput
3473 sRememberedVerb = ""
3474 EvaluateInput(-1, False)
3475 If sOutputText <> "" Then Exit Sub
3476 End If
3477
3478 With Adventure
3479 If .lstTasks Is Nothing Then
3480 .lstTasks = New List(Of clsTask)
3481 For Each tas As clsTask In .htblTasks.Values
3482 .lstTasks.Add(tas)
3483 Next
3484 .lstTasks.Sort(New TaskSorter)
3485 End If
3486 If .listKnownWords Is Nothing Then
3487 .listKnownWords = New List(Of String)
3488 ' Verbs
3489 For Each tas As clsTask In .lstTasks
3490 If tas.TaskType = clsTask.TaskTypeEnum.General Then
3491 For Each sCommand As String In tas.arlCommands
3492 sCommand = sCommand.Replace("[", " ").Replace("]", " ").Replace("{", " ").Replace("}", " ").Replace("/", " ")
3493 While sCommand.Contains(" ")
3494 sCommand = sCommand.Replace(" ", " ")
3495 End While
3496 For Each sWord As String In sCommand.Split(" "c)
3497 If Not .listKnownWords.Contains(sWord) Then .listKnownWords.Add(sWord)
3498 Next
3499 Next
3500 End If
3501 Next
3502 ' Nouns
3503 For Each ob As clsObject In .htblObjects.Values
3504 If Not .listKnownWords.Contains(ob.Article) Then .listKnownWords.Add(ob.Article)
3505 For Each sWord As String In ob.Prefix.Split(" "c)
3506 If Not .listKnownWords.Contains(sWord) Then .listKnownWords.Add(sWord)
3507 Next
3508 For Each sWord As String In ob.arlNames
3509 If Not .listKnownWords.Contains(sWord) Then .listKnownWords.Add(sWord)
3510 Next
3511 Next
3512 For Each ch As clsCharacter In .htblCharacters.Values
3513 If Not .listKnownWords.Contains(ch.Article) Then .listKnownWords.Add(ch.Article)
3514 If ch.Prefix IsNot Nothing Then
3515 For Each sWord As String In ch.Prefix.Split(" "c)
3516 If Not .listKnownWords.Contains(sWord) Then .listKnownWords.Add(sWord)
3517 Next
3518 End If
3519 For Each sWord As String In ch.arlDescriptors
3520 If Not .listKnownWords.Contains(sWord) Then .listKnownWords.Add(sWord)
3521 Next
3522 If Not .listKnownWords.Contains(ch.ProperName) Then .listKnownWords.Add(ch.ProperName.ToLower)
3523 Next
3524 ' Adverbs
3525 For Each sWord As String In sDirectionsRE.Split("|"c)
3526 If Not .listKnownWords.Contains(sWord) Then .listKnownWords.Add(sWord)
3527 Next
3528 ' Additional words
3529 For Each sWord As String In New String() {"and"}
3530 If Not .listKnownWords.Contains(sWord) Then .listKnownWords.Add(sWord)
3531 Next
3532 End If
3533
3534 ' Check all words typed, to ensure they are valid
3535 For Each sWord As String In sInput.Split(" "c)
3536 If Not .listKnownWords.Contains(sWord) Then
3537 Display("I did not understand the word """ & sWord & """.")
3538 Exit Sub
3539 End If
3540 Next
3541
3542 ' If the user just entered a verb, check to see if we understand verb noun
3543 If Not sInput.Contains(" ") Then
3544 For Each tas As clsTask In .lstTasks 'Adventure.htblTasks.Values
3545 If tas.TaskType = clsTask.TaskTypeEnum.General Then
3546 If tas.arlCommands(0).Contains(sInput) AndAlso tas.arlCommands(0).Contains(" ") Then
3547 If tas.arlCommands(0).Contains("%object") Then
3548 For Each lRegEx As List(Of System.Text.RegularExpressions.Regex) In tas.RegExs
3549 For Each RegEx As System.Text.RegularExpressions.Regex In lRegEx
3550 If RegEx.IsMatch(sInput & " sdkfjdslkj") Then
3551 sRememberedVerb = sInput
3552 Display(PCase(sInput) & " what?")
3553 Exit Sub
3554 End If
3555 Next
3556 Next
3557 ElseIf tas.arlCommands(0).Contains("%character") Then
3558 For Each lRegEx As List(Of System.Text.RegularExpressions.Regex) In tas.RegExs
3559 For Each RegEx As System.Text.RegularExpressions.Regex In lRegEx
3560 If RegEx.IsMatch(sInput & " sdkfjdslkj") Then
3561 sRememberedVerb = sInput
3562 Display(PCase(sInput) & " who?")
3563 Exit Sub
3564 End If
3565 Next
3566 Next
3567 ElseIf tas.arlCommands(0).Contains("%direction%") Then
3568 For Each lRegEx As List(Of System.Text.RegularExpressions.Regex) In tas.RegExs
3569 For Each RegEx As System.Text.RegularExpressions.Regex In lRegEx
3570 If RegEx.IsMatch(sInput & " " & DirectionName(DirectionsEnum.North)) Then
3571 sRememberedVerb = sInput
3572 Display(PCase(sInput) & " where?")
3573 Exit Sub
3574 End If
3575 Next
3576 Next
3577 End If
3578 End If
3579 End If
3580 Next
3581 End If
3582
3583 ' If the user just entered a noun, give a default message
3584 For Each ob As clsObject In Adventure.htblObjects.Values
3585 If Adventure.Player.HasSeenObject(ob.Key) Then
3586 If Adventure.Player.CanSeeObject(ob.Key) Then
3587 Dim re As New System.Text.RegularExpressions.Regex(ob.sRegularExpressionString)
3588 If re.IsMatch(sInput) Then
3589 Display("I don't understand what you want to do with " & ob.FullName(ArticleTypeEnum.Definite) & ".")
3590 Exit Sub
3591 End If
3592 Else
3593 ' Hmm, should we give a response when mentioning objects seen but not visible
3594 End If
3595 End If
3596 Next
3597 For Each ch As clsCharacter In Adventure.htblCharacters.Values
3598 If Adventure.Player.HasSeenCharacter(ch.Key) Then
3599 If Adventure.Player.CanSeeCharacter(ch.Key) Then
3600 Dim re As New System.Text.RegularExpressions.Regex(ch.sRegularExpressionString)
3601 If re.IsMatch(sInput) Then
3602 Display("I don't understand what you want to do with " & ch.Name & ".")
3603 Exit Sub
3604 End If
3605 Else
3606 ' Hmm, should we give a response when mentioning characters seen but not visible
3607 End If
3608 End If
3609 Next
3610 End With
3611
3612 Display(Adventure.NotUnderstood)
3613 End Sub
3614
3615 Private Function SystemTasks(Optional ByVal bEarly As Boolean = False) As Boolean
3616 SystemTasks = True
3617 Select Case sInput
3618 Case "restart"
3619 Restart()
3620 If Not bEarly Then sOutputText = "***SYSTEM***"
3621 Case "restore"
3622 Restore()
3623 Display(vbCrLf & vbCrLf, True)
3624 If Not bEarly Then sOutputText = "***SYSTEM***"
3625 Case "save"
3626 If bEarly Then Return False Else SaveGame()
3627 Case "save as", "saveas"
3628 If bEarly Then Return False Else SaveGame(True)
3629 Case "quit"
3630 Quit(Not bEarly)
3631 Case "undo"
3632 Undo()
3633 If bEarly Then Display(vbCrLf & vbCrLf, True)
3634 Case "wait", "z"
3635 If bEarly Then
3636 Return False
3637 Else
3638 sOutputText = ReplaceALRs("Time passes...") ' TODO - Bring this into Developer as a task
3639 For i As Integer = 0 To Adventure.WaitTurns - 1
3640 TurnBasedStuff()
3641 Next
3642 End If
3643 Case Else
3644 If bEarly Then Return False
3645 If sInput.StartsWith("save ") AndAlso CharacterCount(sInput, " "c) = 1 Then
3646 Dim sFilename As String = sInput.Replace("save ", "")
3647 If sFilename.StartsWith("""") AndAlso sFilename.EndsWith("""") Then sFilename = sFilename.Substring(1, sFilename.Length - 2)
3648 For Each c As Char In IO.Path.GetInvalidPathChars
3649 If sFilename.Contains(c) Then
3650 Display("Bad Filename")
3651 Return True
3652 End If
3653 Next
3654 If Not sFilename.Contains(IO.Path.DirectorySeparatorChar) Then
3655 If Adventure.sGameFilename <> "" Then
3656 Dim sPath As String = IO.Path.GetDirectoryName(Adventure.sGameFilename)
3657 sFilename = sPath & IO.Path.DirectorySeparatorChar & sFilename
3658 Else
3659 sFilename = GetSetting("ADRIFT", "Runner", "Game Path", System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) & "\" & sFilename
3660 End If
3661 End If
3662 Adventure.sGameFilename = sFilename
3663 SaveGame()
3664 Return True
3665 End If
3666
3667 If sInput.StartsWith("restore ") AndAlso CharacterCount(sInput, " "c) = 1 Then
3668 Dim sFilename As String = sInput.Replace("restore ", "")
3669 If sFilename.StartsWith("""") AndAlso sFilename.EndsWith("""") Then sFilename = sFilename.Substring(1, sFilename.Length - 2)
3670 For Each c As Char In IO.Path.GetInvalidPathChars
3671 If sFilename.Contains(c) Then
3672 Display("Bad Filename")
3673 Return True
3674 End If
3675 Next
3676 If Not sFilename.Contains(IO.Path.DirectorySeparatorChar) Then
3677 If Adventure.sGameFilename <> "" Then
3678 Dim sPath As String = IO.Path.GetDirectoryName(Adventure.sGameFilename)
3679 sFilename = sPath & IO.Path.DirectorySeparatorChar & sFilename
3680 Else
3681 sFilename = GetSetting("ADRIFT", "Runner", "Game Path", System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) & "\" & sFilename
3682 End If
3683 End If
3684 Restore(sFilename)
3685 Return True
3686 End If
3687 Return False
3688 End Select
3689
3690 End Function
3691
3692 Public Sub UpdateStatusBar()
3693 If Adventure Is Nothing Then Exit Sub
3694
3695 Try
3696 Dim sDescription As String = ""
3697 Dim sScore As String = ""
3698 Dim sUserStatus As String = ""
3699
3700 If Adventure.eGameState = clsAction.EndGameEnum.Running Then
3701 If Adventure.Player IsNot Nothing Then
3702 If Adventure.Player.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.Hidden OrElse Adventure.Player.Location.LocationKey = "" Then
3703 sDescription = "(Nowhere)"
3704 Else
3705 sDescription = Adventure.htblLocations(Adventure.Player.Location.LocationKey).ShortDescriptionSafe
3706 If Adventure.Player.Location.ExistWhere <> clsCharacterLocation.ExistsWhereEnum.AtLocation Then
3707 sDescription &= " (" & Adventure.Player.Location.ToString & ")"
3708 End If
3709 End If
3710 End If
3711 sUserStatus = Adventure.sUserStatus
3712 Else
3713 sDescription = "Game Over"
3714 End If
3715
3716 If Adventure.MaxScore > 0 Then sScore = "Score: " & Adventure.Score
3717
3718 If Not Adventure.Enabled(clsAdventure.EnabledOptionEnum.Score) Then sScore = ""
3719 fRunner.UpdateStatusBar(sDescription, sScore, sUserStatus)
3720 Catch exOD As ObjectDisposedException
3721 ' Fail silently
3722 Catch ex As Exception
3723 ErrMsg("UpdateStatusBar error", ex)
3724 End Try
3725
3726 End Sub
3727
3728 Friend bEventsRunning As Boolean = False
3729 Private Sub TurnBasedStuff()
3730
3731 If Adventure.eGameState <> clsAction.EndGameEnum.Running Then Exit Sub
3732
3733 For Each c As clsCharacter In Adventure.htblCharacters.Values
3734 For Each w As clsWalk In c.arlWalks
3735 If Adventure.eGameState <> clsAction.EndGameEnum.Running Then Exit Sub
3736 w.IncrementTimer()
3737 Next
3738 Next
3739 bEventsRunning = True
3740 For Each e As clsEvent In Adventure.htblEvents.Values
3741 If Adventure.eGameState <> clsAction.EndGameEnum.Running Then Exit Sub
3742 If e.EventType = clsEvent.EventTypeEnum.TurnBased Then e.IncrementTimer()
3743 Next
3744 ' Needs to be a separate loop in case a later event runs a task that starts an earlier event
3745 For Each e As clsEvent In Adventure.htblEvents.Values
3746 If e.EventType = clsEvent.EventTypeEnum.TurnBased Then e.bJustStarted = False
3747 Next
3748 bEventsRunning = False
3749
3750 End Sub
3751
3752 Public Sub TimeBasedStuff()
3753 If Adventure.eGameState <> clsAction.EndGameEnum.Running OrElse fRunner.Locked Then Exit Sub
3754
3755 bEventsRunning = True
3756
3757 For Each e As clsEvent In Adventure.htblEvents.Values
3758 If Adventure.eGameState <> clsAction.EndGameEnum.Running Then Exit For
3759 If e.EventType = clsEvent.EventTypeEnum.TimeBased Then e.IncrementTimer()
3760 Next
3761 ' Needs to be a separate loop in case a later event runs a task that starts an earlier event
3762 For Each e As clsEvent In Adventure.htblEvents.Values
3763 If e.EventType = clsEvent.EventTypeEnum.TimeBased Then e.bJustStarted = False
3764 Next
3765 bEventsRunning = False
3766 If sOutputText <> "" Then Display("", True)
3767
3768 CheckEndOfGame()
3769 End Sub
3770
3771 Private Sub PrepareForNextTurn()
3772 If Not bSystemTask AndAlso Adventure.eGameState = clsAction.EndGameEnum.Running Then States.RecordState()
3773 sTurnOutput = ""
3774
3775 ' Mark objects as seen for all the characters
3776 For Each ch As clsCharacter In Adventure.htblCharacters.Values
3777 For Each ob As clsObject In Adventure.htblObjects.Values
3778 If ch.CanSeeObject(ob.Key) Then ob.SeenBy(ch.Key) = True
3779 Next
3780 Dim sLocKey As String = ch.Location.LocationKey
3781 If sLocKey <> HIDDEN AndAlso sLocKey <> "" Then
3782 Dim locChar As clsLocation = Adventure.htblLocations(sLocKey)
3783 If locChar IsNot Nothing Then locChar.SeenBy(ch.Key) = True
3784 End If
3785
3786 For Each ch2 As clsCharacter In Adventure.htblCharacters.Values
3787 If Not ch.SeenBy(ch2.Key) AndAlso ch.CanSeeCharacter(ch2.Key) Then
3788 ch.SeenBy(ch2.Key) = True
3789 End If
3790 Next
3791 ch.dictHasRouteCache.Clear()
3792 ch.dictRouteErrors.Clear()
3793 If ch.Introduced Then
3794 If ch IsNot Adventure.Player AndAlso Not Adventure.Player.CanSeeCharacter(ch.Key) Then
3795 ch.Introduced = False
3796 End If
3797 End If
3798 Next
3799 For Each eGen As clsCharacter.GenderEnum In New clsCharacter.GenderEnum() {clsCharacter.GenderEnum.Male, clsCharacter.GenderEnum.Female, clsCharacter.GenderEnum.Unknown}
3800 Adventure.lCharMentionedThisTurn(eGen) = New Generic.List(Of String)
3801 Next
3802
3803 htblCompleteableGeneralTasks.Clear()
3804 For Each tas As clsTask In Adventure.Tasks(clsAdventure.TasksListEnum.GeneralTasks).Values
3805 If tas.TaskType = clsTask.TaskTypeEnum.General AndAlso (Not tas.Completed OrElse tas.Repeatable) Then
3806 htblCompleteableGeneralTasks.Add(tas, tas.Key)
3807 End If
3808 Next
3809
3810 iPrepProgress = 2
3811
3812 htblVisibleObjects.Clear()
3813 htblSeenObjects.Clear()
3814 For Each ob As clsObject In Adventure.htblObjects.Values
3815 If ob.SeenBy(Adventure.Player.Key) Then htblSeenObjects.Add(ob, ob.Key)
3816 If ob.IsVisibleTo(Adventure.Player.Key) Then htblVisibleObjects.Add(ob, ob.Key)
3817 ob.PrevParent = ob.Parent
3818 Next
3819 For Each ch As clsCharacter In Adventure.htblCharacters.Values
3820 ch.PrevParent = ch.Parent
3821 Next
3822
3823 PronounKeys.Clear()
3824 End Sub
3825
3826 ' Runs this on a background thread so if user types a command we just resume where we are
3827 Private Sub CalculateCompleteableTasks()
3828 Dim htblTasks As New TaskHashTable
3829
3830 Try
3831 ' TODO: This should only add if completeable in current room, i.e. pass all restrictions ignoring ones regarding references.
3832 For Each sKey As String In htblCompleteableGeneralTasks.Keys
3833 Dim task As clsTask = Adventure.htblTasks(sKey)
3834 If iPrepProgress = 1 OrElse task.HasReferences OrElse task.IsCompleteable Then htblTasks.Add(task, sKey)
3835 Next
3836 Catch
3837 htblTasks = htblCompleteableGeneralTasks
3838 End Try
3839
3840 htblCompleteableGeneralTasks = htblTasks
3841 iPrepProgress = 2
3842 End Sub
3843
3844
3845 Private Function ResolveAmbiguity(ByVal sInput As String) As String
3846 Dim bResolved As Boolean = False
3847
3848 ResolveAmbiguity = sAmbTask ' the default unless we're still ambiguous
3849
3850 For iRef As Integer = 0 To NewReferences.Length - 1
3851 Debug.WriteLine("Reference " & iRef)
3852 If NewReferences(iRef) IsNot Nothing Then
3853 With NewReferences(iRef)
3854 Debug.WriteLine("Number of Refs in this Reference: " & .Items.Count)
3855 For i As Integer = 0 To .Items.Count - 1
3856 Dim salRefs As StringArrayList = .Items(i).MatchingPossibilities
3857 Debug.WriteLine("Number of matching references: " & salRefs.Count)
3858 If salRefs.Count <> 1 Then
3859 If Not bResolved Then
3860 .Items(i).MatchingPossibilities = PossibleKeys(salRefs, sInput, .ReferenceType)
3861 End If
3862 If .Items(i).MatchingPossibilities.Count <> 1 Then Return Nothing
3863 If .ReferenceType = ReferencesType.Object Then sIt = Adventure.htblObjects(.Items(i).MatchingPossibilities(0)).FullName(ArticleTypeEnum.Definite)
3864 If .ReferenceType = ReferencesType.Object AndAlso Adventure.htblObjects(.Items(i).MatchingPossibilities(0)).IsPlural Then sThem = Adventure.htblObjects(.Items(i).MatchingPossibilities(0)).FullName(ArticleTypeEnum.Definite)
3865 If .ReferenceType = ReferencesType.Character Then
3866 With Adventure.htblCharacters(.Items(i).MatchingPossibilities(0))
3867 Select Case .Gender
3868 Case clsCharacter.GenderEnum.Male
3869 sHim = .Name
3870 Case clsCharacter.GenderEnum.Female
3871 sHer = .Name
3872 Case clsCharacter.GenderEnum.Unknown
3873 sIt = .Name
3874 End Select
3875 End With
3876 End If
3877 bResolved = True
3878 End If
3879 Next
3880 End With
3881 End If
3882 Next
3883 End Function
3884
3885 Private Function ContainsWord(ByVal sSentence As String, ByVal sCheckWord As String) As Boolean
3886 Dim sChecks() As String = Split(sCheckWord, " ")
3887 Dim sWords() As String = Split(sSentence.ToLower, " ")
3888
3889 For Each sCheck As String In sChecks
3890 Dim bFound As Boolean = False
3891 For Each sWord As String In sWords
3892 If sWord = sCheck Then
3893 bFound = True
3894 Exit For
3895 End If
3896 Next
3897 If Not bFound Then Return False
3898 Next
3899
3900 Return True
3901 End Function
3902
3903 ' This takes a list of possible refs, then narrows the field (hopefully to 1) given the input
3904 Private Function PossibleKeys(ByVal salKeys As StringArrayList, ByVal sInput As String, ByVal sRefType As ReferencesType) As StringArrayList
3905 Dim salReturn As New StringArrayList
3906 ' Check each word in the refined text to ensure they all match
3907
3908 Select Case sRefType
3909 Case ReferencesType.Object
3910 For Each sKey As String In salKeys
3911 Dim ob As clsObject = Adventure.htblObjects(sKey)
3912 Dim bMatchAll As Boolean = True
3913 For Each sWord As String In sInput.Split(" "c)
3914 Dim bWordInObject As Boolean = False
3915 If sWord = "the" OrElse sWord = ob.Article OrElse ContainsWord(ob.Prefix, sWord) Then
3916 bWordInObject = True
3917 Else
3918 For Each sName As String In ob.arlNames
3919 If ContainsWord(sName, sWord) Then
3920 bWordInObject = True
3921 Exit For
3922 End If
3923 Next
3924 End If
3925 If Not bWordInObject Then
3926 bMatchAll = False
3927 Exit For
3928 End If
3929 Next
3930 If bMatchAll Then salReturn.Add(sKey)
3931 Next
3932
3933 Case ReferencesType.Character
3934 For Each sKey As String In salKeys
3935 Dim ch As clsCharacter = Adventure.htblCharacters(sKey)
3936 Dim bMatchAll As Boolean = True
3937 For Each sWord As String In sInput.Split(" "c)
3938 Dim bWordInChar As Boolean = False
3939 If ContainsWord(ch.Prefix, sWord) OrElse ContainsWord(ch.ProperName, sWord) Then
3940 bWordInChar = True
3941 Else
3942 For Each sName As String In ch.arlDescriptors
3943 If ContainsWord(sName, sWord) Then
3944 bWordInChar = True
3945 Exit For
3946 End If
3947 Next
3948 End If
3949 If Not bWordInChar Then
3950 bMatchAll = False
3951 Exit For
3952 End If
3953 Next
3954 If bMatchAll Then salReturn.Add(sKey)
3955 Next
3956
3957 Case ReferencesType.Location
3958 For Each sKey As String In salKeys
3959 Dim loc As clsLocation = Adventure.htblLocations(sKey)
3960 Dim bMatchAll As Boolean = True
3961 For Each sWord As String In sInput.Split(" "c)
3962 Dim bWordInLoc As Boolean = False
3963 If ContainsWord(loc.ShortDescription.ToString(True), sWord) Then
3964 bWordInLoc = True
3965 End If
3966 If Not bWordInLoc Then
3967 bMatchAll = False
3968 Exit For
3969 End If
3970 Next
3971 If bMatchAll Then salReturn.Add(sKey)
3972 Next
3973
3974 End Select
3975
3976 Return salReturn
3977 End Function
3978
3979
3980 Private Function GetReference(ByVal sReference As String) As String
3981 If NewReferences Is Nothing Then Return Nothing
3982
3983 For iRef As Integer = 0 To NewReferences.Length - 1
3984 With NewReferences(iRef)
3985 If NewReferences(iRef) IsNot Nothing AndAlso .Items IsNot Nothing Then 'AndAlso .Items.Count > 0 AndAlso .Items(0).MatchingPossibilities.Count > 0 Then
3986
3987 Select Case sReference
3988 Case "ReferencedObject", "ReferencedObject1", "ReferencedObject2", "ReferencedObject3", "ReferencedObject4", "ReferencedObject5", "ReferencedObjects"
3989 If .ReferenceType = ReferencesType.Object Then
3990 If sReference = "ReferencedObjects" _
3991 OrElse (.ReferenceMatch = "object1" AndAlso (sReference = "ReferencedObject" OrElse sReference = "ReferencedObject1")) _
3992 OrElse (.ReferenceMatch = "object2" AndAlso sReference = "ReferencedObject2") _
3993 OrElse (.ReferenceMatch = "object3" AndAlso sReference = "ReferencedObject3") _
3994 OrElse (.ReferenceMatch = "object4" AndAlso sReference = "ReferencedObject4") _
3995 OrElse (.ReferenceMatch = "object5" AndAlso sReference = "ReferencedObject5") Then
3996 If .Items.Count > 0 AndAlso .Items(0).MatchingPossibilities.Count > 0 Then
3997 Return .Items(0).MatchingPossibilities(0)
3998 Else
3999 Return Nothing
4000 End If
4001 End If
4002 End If
4003 Case "ReferencedDirection", "ReferencedDirection1", "ReferencedDirection2", "ReferencedDirection3", "ReferencedDirection4", "ReferencedDirection5"
4004 If .ReferenceType = ReferencesType.Direction Then
4005 If (.ReferenceMatch = "direction1" AndAlso (sReference = "ReferencedDirection" OrElse sReference = "ReferencedDirection1")) _
4006 OrElse (.ReferenceMatch = "direction2" AndAlso sReference = "ReferencedDirection2") _
4007 OrElse (.ReferenceMatch = "direction3" AndAlso sReference = "ReferencedDirection3") _
4008 OrElse (.ReferenceMatch = "direction4" AndAlso sReference = "ReferencedDirection4") _
4009 OrElse (.ReferenceMatch = "direction5" AndAlso sReference = "ReferencedDirection5") Then
4010 If .Items.Count > 0 AndAlso .Items(0).MatchingPossibilities.Count > 0 Then
4011 Return .Items(0).MatchingPossibilities(0)
4012 Else
4013 Return Nothing
4014 End If
4015 End If
4016 End If
4017 Case "ReferencedCharacter", "ReferencedCharacter1", "ReferencedCharacter2", "ReferencedCharacter3", "ReferencedCharacter4", "ReferencedCharacter5"
4018 If .ReferenceType = ReferencesType.Character Then
4019 If sReference = "ReferencedCharacters" _
4020 OrElse (.ReferenceMatch = "character1" AndAlso (sReference = "ReferencedCharacter" OrElse sReference = "ReferencedCharacter1")) _
4021 OrElse (.ReferenceMatch = "character2" AndAlso sReference = "ReferencedCharacter2") _
4022 OrElse (.ReferenceMatch = "character3" AndAlso sReference = "ReferencedCharacter3") _
4023 OrElse (.ReferenceMatch = "character4" AndAlso sReference = "ReferencedCharacter4") _
4024 OrElse (.ReferenceMatch = "character5" AndAlso sReference = "ReferencedCharacter5") Then
4025 If .Items.Count > 0 AndAlso .Items(0).MatchingPossibilities.Count > 0 Then
4026 Return .Items(0).MatchingPossibilities(0)
4027 Else
4028 Return Nothing
4029 End If
4030 End If
4031 End If
4032 Case "ReferencedLocation", "ReferencedLocation1", "ReferencedLocation2", "ReferencedLocation3", "ReferencedLocation4", "ReferencedLocation5"
4033 If .ReferenceType = ReferencesType.Location Then
4034 If (.ReferenceMatch = "location1" AndAlso (sReference = "ReferencedLocation" OrElse sReference = "ReferencedLocation1")) _
4035 OrElse (.ReferenceMatch = "location2" AndAlso sReference = "ReferencedLocation2") _
4036 OrElse (.ReferenceMatch = "location3" AndAlso sReference = "ReferencedLocation3") _
4037 OrElse (.ReferenceMatch = "location4" AndAlso sReference = "ReferencedLocation4") _
4038 OrElse (.ReferenceMatch = "location5" AndAlso sReference = "ReferencedLocation5") Then
4039 If .Items.Count > 0 AndAlso .Items(0).MatchingPossibilities.Count > 0 Then
4040 Return .Items(0).MatchingPossibilities(0)
4041 Else
4042 Return Nothing
4043 End If
4044 End If
4045 End If
4046 Case "ReferencedItem", "ReferencedItem1", "ReferencedItem2", "ReferencedItem3", "ReferencedItem4", "ReferencedItem5"
4047 If .ReferenceType = ReferencesType.Item Then
4048 If (.ReferenceMatch = "item1" AndAlso (sReference = "ReferencedItem" OrElse sReference = "ReferencedItem1")) _
4049 OrElse (.ReferenceMatch = "item2" AndAlso sReference = "ReferencedItem2") _
4050 OrElse (.ReferenceMatch = "item3" AndAlso sReference = "ReferencedItem3") _
4051 OrElse (.ReferenceMatch = "item4" AndAlso sReference = "ReferencedItem4") _
4052 OrElse (.ReferenceMatch = "item5" AndAlso sReference = "ReferencedItem5") Then
4053 If .Items.Count > 0 AndAlso .Items(0).MatchingPossibilities.Count > 0 Then
4054 Return .Items(0).MatchingPossibilities(0)
4055 Else
4056 Return Nothing
4057 End If
4058 End If
4059 End If
4060 Case "ReferencedNumber", "ReferencedNumber1", "ReferencedNumber2", "ReferencedNumber3", "ReferencedNumber4", "ReferencedNumber5"
4061 If .ReferenceType = ReferencesType.Number Then
4062 If (.ReferenceMatch = "number1" AndAlso (sReference = "ReferencedNumber" OrElse sReference = "ReferencedNumber1")) _
4063 OrElse (.ReferenceMatch = "number2" AndAlso sReference = "ReferencedNumber2") _
4064 OrElse (.ReferenceMatch = "number3" AndAlso sReference = "ReferencedNumber3") _
4065 OrElse (.ReferenceMatch = "number4" AndAlso sReference = "ReferencedNumber4") _
4066 OrElse (.ReferenceMatch = "number5" AndAlso sReference = "ReferencedNumber5") Then
4067 If .Items.Count > 0 AndAlso .Items(0).MatchingPossibilities.Count > 0 Then
4068 Return .Items(0).MatchingPossibilities(0)
4069 Else
4070 Return Nothing
4071 End If
4072 End If
4073 End If
4074 End Select
4075
4076 End If
4077 End With
4078 Next
4079 Return Nothing
4080 End Function
4081
4082 Private Function PassSingleRestriction(ByVal restx As clsRestriction, Optional ByVal bIgnoreReferences As Boolean = False) As Boolean
4083
4084 Try
4085 Dim rest As New clsRestriction
4086 rest = restx.Copy
4087 Dim r As Boolean = False
4088 ' Replace references
4089 Select Case rest.sKey1
4090 Case "ReferencedObject", "ReferencedObject1", "ReferencedObject2", "ReferencedObject3", "ReferencedObject4", "ReferencedObject5", "ReferencedObjects", "ReferencedDirection", "ReferencedCharacter", "ReferencedCharacter1", "ReferencedCharacter2", "ReferencedCharacter3", "ReferencedCharacter4", "ReferencedCharacter5", "ReferencedLocation", "ReferencedItem"
4091 rest.sKey1 = GetReference(rest.sKey1)
4092 If bIgnoreReferences AndAlso rest.sKey1 Is Nothing Then Return True
4093 End Select
4094 Select Case rest.sKey2
4095 Case "ReferencedObject", "ReferencedObject1", "ReferencedObject2", "ReferencedObject3", "ReferencedObject4", "ReferencedObject5", "ReferencedObjects", "ReferencedDirection", "ReferencedCharacter", "ReferencedCharacter1", "ReferencedCharacter2", "ReferencedCharacter3", "ReferencedCharacter4", "ReferencedCharacter5", "ReferencedLocation", "ReferencedItem"
4096 rest.sKey2 = GetReference(rest.sKey2)
4097 If bIgnoreReferences AndAlso rest.sKey2 Is Nothing Then Return True
4098 End Select
4099
4100 If rest.sKey1 = "%Player%" AndAlso Adventure.Player IsNot Nothing Then rest.sKey1 = Adventure.Player.Key
4101 If rest.sKey2 = "%Player%" AndAlso Adventure.Player IsNot Nothing Then rest.sKey2 = Adventure.Player.Key
4102
4103 If Not rest.eType = clsRestriction.RestrictionTypeEnum.Expression AndAlso (rest.sKey1 Is Nothing OrElse (rest.sKey2 Is Nothing AndAlso rest.eType <> clsRestriction.RestrictionTypeEnum.Task AndAlso rest.eType <> clsRestriction.RestrictionTypeEnum.Variable AndAlso rest.eType <> clsRestriction.RestrictionTypeEnum.Direction AndAlso Not (rest.eType = clsRestriction.RestrictionTypeEnum.Object AndAlso rest.eObject = clsRestriction.ObjectEnum.BeHidden))) Then
4104 r = False
4105 GoTo SkipTest
4106 End If
4107
4108 Select Case rest.eType
4109 Case clsRestriction.RestrictionTypeEnum.Location
4110 Dim loc As clsLocation = Nothing
4111 Select Case rest.sKey1
4112 Case PLAYERLOCATION
4113 loc = Adventure.htblLocations(Adventure.Player.Location.LocationKey)
4114 Case Else
4115 If Adventure.htblLocations.ContainsKey(rest.sKey1) Then loc = Adventure.htblLocations(rest.sKey1)
4116 End Select
4117 If loc IsNot Nothing Then
4118 Select Case rest.eLocation
4119 Case clsRestriction.LocationEnum.HaveBeenSeenByCharacter
4120 r = loc.SeenBy(rest.sKey2)
4121 Case clsRestriction.LocationEnum.BeInGroup
4122 Select Case rest.sKey1
4123 Case PLAYERLOCATION
4124 r = Adventure.htblGroups(rest.sKey2).arlMembers.Contains(Adventure.Player.Location.LocationKey)
4125 Case Else
4126 r = Adventure.htblGroups(rest.sKey2).arlMembers.Contains(rest.sKey1)
4127 End Select
4128 Case clsRestriction.LocationEnum.HaveProperty
4129 r = loc.HasProperty(rest.sKey2)
4130 Case clsRestriction.LocationEnum.BeLocation
4131 Select Case rest.sKey1
4132 Case PLAYERLOCATION
4133 r = (Adventure.Player.Location.LocationKey = rest.sKey2)
4134 Case Else
4135 r = (rest.sKey1 = rest.sKey2)
4136 End Select
4137 Case clsRestriction.LocationEnum.Exist
4138 r = True
4139 End Select
4140 End If
4141
4142 Case clsRestriction.RestrictionTypeEnum.Object
4143 Select Case rest.eObject
4144 Case clsRestriction.ObjectEnum.BeAtLocation
4145 Select Case rest.sKey1
4146 Case NOOBJECT
4147 r = Adventure.htblLocations(rest.sKey2).ObjectsInLocation(clsLocation.WhichObjectsToListEnum.AllObjects, False).Count = 0
4148 Case ANYOBJECT
4149 r = Adventure.htblLocations(rest.sKey2).ObjectsInLocation(clsLocation.WhichObjectsToListEnum.AllObjects, False).Count > 0
4150 Case Else
4151 r = Adventure.htblObjects(rest.sKey1).ExistsAtLocation(rest.sKey2)
4152 End Select
4153 Case clsRestriction.ObjectEnum.BeHeldByCharacter
4154 Select Case rest.sKey1
4155 Case NOOBJECT
4156 Select Case rest.sKey2
4157 Case ANYCHARACTER
4158 TODO("No object held by any character test")
4159 Case Else
4160 r = Adventure.htblCharacters(rest.sKey2).HeldObjects.Count = 0
4161 End Select
4162 Case ANYOBJECT
4163 Select Case rest.sKey2
4164 Case ANYCHARACTER
4165 TODO("Any object held by any character test")
4166 Case Else
4167 r = Adventure.htblCharacters(rest.sKey2).HeldObjects.Count > 0
4168 End Select
4169 Case Else
4170 Select Case rest.sKey2
4171 Case ANYCHARACTER
4172 r = Adventure.htblObjects(rest.sKey1).IsHeldByAnyone
4173 Case Else
4174 r = Adventure.htblCharacters(rest.sKey2).IsHoldingObject(rest.sKey1)
4175 End Select
4176 End Select
4177 Case clsRestriction.ObjectEnum.BeHidden
4178 Select Case rest.sKey1
4179 Case NOOBJECT
4180 TODO("No object hidden")
4181 Case ANYOBJECT
4182 TODO("Any object hidden")
4183 Case Else
4184 With Adventure.htblObjects(rest.sKey1)
4185 If .IsStatic Then
4186 r = .Location.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.NoRooms
4187 Else
4188 r = .Location.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.Hidden
4189 End If
4190 End With
4191 End Select
4192 Case clsRestriction.ObjectEnum.BeInGroup
4193 Select Case rest.sKey1
4194 Case NOOBJECT
4195 r = Adventure.htblGroups(rest.sKey2).arlMembers.Count = 0
4196 Case ANYOBJECT
4197 r = Adventure.htblGroups(rest.sKey2).arlMembers.Count > 0
4198 Case Else
4199 r = Adventure.htblGroups(rest.sKey2).arlMembers.Contains(rest.sKey1)
4200 End Select
4201 Case clsRestriction.ObjectEnum.BeInsideObject
4202 Select Case rest.sKey1
4203 Case NOOBJECT
4204 Select Case rest.sKey2
4205 Case NOOBJECT
4206 TODO("No object in no object test")
4207 Case ANYOBJECT
4208 TODO("No object in any object test")
4209 Case Else
4210 r = Adventure.htblObjects(rest.sKey2).Children(clsObject.WhereChildrenEnum.InsideObject).Count = 0
4211 End Select
4212 Case ANYOBJECT
4213 Select Case rest.sKey2
4214 Case NOOBJECT
4215 TODO("Any object in no object test")
4216 Case ANYOBJECT
4217 TODO("Any object in any object test")
4218 Case Else
4219 r = Adventure.htblObjects(rest.sKey2).Children(clsObject.WhereChildrenEnum.InsideObject).Count > 0
4220 End Select
4221 Case Else
4222 Select Case rest.sKey2
4223 Case NOOBJECT
4224 TODO("Object inside no object test")
4225 Case ANYOBJECT
4226 r = (Adventure.htblObjects(rest.sKey1).Location.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.InObject)
4227 Case Else
4228 r = Adventure.htblObjects(rest.sKey1).IsInside(rest.sKey2)
4229 End Select
4230 End Select
4231 Case clsRestriction.ObjectEnum.BeInState
4232 Select Case rest.sKey1
4233 Case NOOBJECT
4234 For Each ob As clsObject In Adventure.htblObjects.Values
4235 For Each prop As clsProperty In ob.htblProperties.Values
4236 If prop.Type = clsProperty.PropertyTypeEnum.StateList AndAlso prop.Value = rest.sKey2 AndAlso prop.AppendToProperty = "" Then
4237 r = False
4238 GoTo SkipTest
4239 End If
4240 Next
4241 Next
4242 r = True
4243 Case ANYOBJECT
4244 For Each ob As clsObject In Adventure.htblObjects.Values
4245 For Each prop As clsProperty In ob.htblProperties.Values
4246 If prop.Type = clsProperty.PropertyTypeEnum.StateList AndAlso prop.Value = rest.sKey2 AndAlso prop.AppendToProperty = "" Then
4247 r = True
4248 GoTo SkipTest
4249 End If
4250 Next
4251 Next
4252 Case Else
4253 ' Ok, this is a fudge option
4254 For Each prop As clsProperty In Adventure.htblObjects(rest.sKey1).htblProperties.Values
4255 If prop.Type = clsProperty.PropertyTypeEnum.StateList AndAlso prop.Value = rest.sKey2 AndAlso prop.AppendToProperty = "" Then
4256 r = True
4257 GoTo SkipTest
4258 End If
4259 Next
4260 End Select
4261 Case clsRestriction.ObjectEnum.BeOnObject
4262 Select Case rest.sKey1
4263 Case NOOBJECT
4264 Select Case rest.sKey2
4265 Case NOOBJECT
4266 TODO("No Object must be on No Object test")
4267 Case ANYOBJECT
4268 TODO("No Object must be on Any Object test")
4269 Case Else
4270 r = Adventure.htblObjects(rest.sKey2).Children(clsObject.WhereChildrenEnum.OnObject).Count = 0
4271 End Select
4272 Case ANYOBJECT
4273 Select Case rest.sKey2
4274 Case NOOBJECT
4275 TODO("Any Object must be on No Object test")
4276 Case ANYOBJECT
4277 TODO("Any Object must be on Any Object test")
4278 Case Else
4279 r = Adventure.htblObjects(rest.sKey2).Children(clsObject.WhereChildrenEnum.OnObject).Count > 0
4280 End Select
4281 Case Else
4282 Select Case rest.sKey2
4283 Case NOOBJECT
4284 TODO("Object must be on No Object test")
4285 Case ANYOBJECT
4286 r = (Adventure.htblObjects(rest.sKey1).Location.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.OnObject)
4287 Case Else
4288 r = Adventure.htblObjects(rest.sKey1).IsOn(rest.sKey2)
4289 End Select
4290 End Select
4291 Case clsRestriction.ObjectEnum.BePartOfCharacter
4292 Select Case rest.sKey1
4293 Case NOOBJECT
4294 TODO("No Object is part of character test")
4295 Case ANYOBJECT
4296 TODO("Any Object is part of character test")
4297 Case Else
4298 Select Case rest.sKey2
4299 Case ANYCHARACTER
4300 TODO("Object is part of any character test")
4301 Case Else
4302 r = Adventure.htblObjects(rest.sKey1).Location.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.PartOfCharacter _
4303 AndAlso Adventure.htblObjects(rest.sKey1).Location.Key = rest.sKey2
4304 End Select
4305 End Select
4306 Case clsRestriction.ObjectEnum.BePartOfObject
4307 Select Case rest.sKey1
4308 Case NOOBJECT
4309 TODO("No Object is part of object test")
4310 Case ANYOBJECT
4311 TODO("Any Object is part of object test")
4312 Case Else
4313 Select Case rest.sKey2
4314 Case NOOBJECT
4315 TODO("Object is part of No object test")
4316 Case ANYOBJECT
4317 r = Adventure.htblObjects(rest.sKey1).Location.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.PartOfObject
4318 Case Else
4319 r = Adventure.htblObjects(rest.sKey1).Location.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.PartOfObject _
4320 AndAlso Adventure.htblObjects(rest.sKey1).Location.Key = rest.sKey2
4321 End Select
4322 End Select
4323 Case clsRestriction.ObjectEnum.HaveBeenSeenByCharacter
4324 Select Case rest.sKey1
4325 Case NOOBJECT
4326 TODO("No Object has been seen by character test")
4327 Case ANYOBJECT
4328 TODO("Any Object has been seen by character test")
4329 Case Else
4330 Select Case rest.sKey2
4331 Case ANYCHARACTER
4332 TODO("Object has been seen by any character test")
4333 Case Else
4334 r = Adventure.htblCharacters(rest.sKey2).HasSeenObject(rest.sKey1)
4335 End Select
4336 End Select
4337 Case clsRestriction.ObjectEnum.BeVisibleToCharacter
4338 Dim ch As clsCharacter = Adventure.htblCharacters(rest.sKey2)
4339 Select Case rest.sKey1
4340 Case NOOBJECT
4341 Select Case rest.sKey2
4342 Case ANYCHARACTER
4343 TODO("No Object visible to any character test")
4344 Case Else
4345 r = True
4346 For Each ob As clsObject In Adventure.htblObjects.Values
4347 If ch.CanSeeObject(ob.Key) Then
4348 r = False
4349 Exit For
4350 End If
4351 Next
4352 End Select
4353 Case ANYOBJECT
4354 Select Case rest.sKey2
4355 Case ANYCHARACTER
4356 TODO("Any Object visible to any character test")
4357 Case Else
4358 r = False
4359 For Each ob As clsObject In Adventure.htblObjects.Values
4360 If ch.CanSeeObject(ob.Key) Then
4361 r = True
4362 Exit For
4363 End If
4364 Next
4365 End Select
4366 Case Else
4367 Select Case rest.sKey2
4368 Case ANYCHARACTER
4369 TODO("Object visible to any character test")
4370 Case Else
4371 r = ch.CanSeeObject(rest.sKey1)
4372 End Select
4373 End Select
4374 Case clsRestriction.ObjectEnum.BeWornByCharacter
4375 Select Case rest.sKey1
4376 Case NOOBJECT
4377 Select Case rest.sKey2
4378 Case ANYCHARACTER
4379 TODO("No Object worn by any character test")
4380 Case Else
4381 r = Adventure.htblCharacters(rest.sKey2).WornObjects.Count = 0
4382 End Select
4383 Case ANYOBJECT
4384 Select Case rest.sKey2
4385 Case ANYCHARACTER
4386 TODO("Any Object worn by any character test")
4387 Case Else
4388 r = Adventure.htblCharacters(rest.sKey2).WornObjects.Count > 0
4389 End Select
4390 Case Else
4391 If Adventure.htblObjects.ContainsKey(rest.sKey1) Then
4392 Select Case rest.sKey2
4393 Case ANYCHARACTER
4394 r = Adventure.htblObjects(rest.sKey1).Location.DynamicExistWhere = clsObjectLocation.DynamicExistsWhereEnum.WornByCharacter
4395 Case Else
4396 r = Adventure.htblCharacters(rest.sKey2).IsWearingObject(rest.sKey1)
4397 End Select
4398 End If
4399 End Select
4400
4401 Case clsRestriction.ObjectEnum.Exist
4402 Select Case rest.sKey1
4403 Case NOOBJECT
4404 r = Adventure.htblObjects.Count = 0
4405 Case ANYOBJECT
4406 r = Adventure.htblObjects.Count > 0
4407 Case Else
4408 r = Adventure.htblObjects.ContainsKey(rest.sKey1)
4409 End Select
4410 Case clsRestriction.ObjectEnum.HaveProperty
4411 Select Case rest.sKey1
4412 Case NOOBJECT
4413 For Each ob As clsObject In Adventure.htblObjects.Values
4414 If ob.HasProperty(rest.sKey2) Then
4415 r = False
4416 GoTo SkipTest
4417 End If
4418 Next
4419 r = True
4420 Case ANYOBJECT
4421 For Each ob As clsObject In Adventure.htblObjects.Values
4422 If ob.HasProperty(rest.sKey2) Then
4423 r = True
4424 GoTo SkipTest
4425 End If
4426 Next
4427 Case Else
4428 r = Adventure.htblObjects.ContainsKey(rest.sKey1) AndAlso Adventure.htblObjects(rest.sKey1).HasProperty(rest.sKey2)
4429 End Select
4430 Case clsRestriction.ObjectEnum.BeExactText
4431 Select Case rest.sKey1
4432 Case NOOBJECT
4433 TODO("No Object be exact text test")
4434 Case ANYOBJECT
4435 TODO("Any Object be exact text test")
4436 Case Else
4437 r = restx.sKey1 = "ReferencedObjects" AndAlso NewReferences IsNot Nothing AndAlso (NewReferences(0).Items(0).sCommandReference = "all" OrElse (NewReferences.Length > 1 AndAlso NewReferences(1).Items(0).sCommandReference = "all")) ' Should probably verify that %objects% was actually reference 0
4438 End Select
4439 Case clsRestriction.ObjectEnum.BeObject
4440 Select Case rest.sKey1
4441 Case NOOBJECT
4442 TODO("No Object be specific object test")
4443 Case ANYOBJECT
4444 TODO("Any Object be specific object test")
4445 Case Else
4446 r = (rest.sKey1 = rest.sKey2)
4447 End Select
4448 End Select
4449
4450 Case clsRestriction.RestrictionTypeEnum.Task
4451 Select Case rest.eTask
4452 Case clsRestriction.TaskEnum.Complete
4453 If Adventure.htblTasks.ContainsKey(rest.sKey1) Then r = Adventure.htblTasks(rest.sKey1).Completed
4454 End Select
4455
4456 Case clsRestriction.RestrictionTypeEnum.Variable
4457 Dim var As clsVariable
4458 Dim iIndex As Integer = 1
4459 If rest.sKey1.StartsWith("ReferencedNumber") Then
4460 Dim iRef As Integer = Math.Max(SafeInt(rest.sKey1.Replace("ReferencedNumber", "")) - 1, 0)
4461 var = New clsVariable
4462 var.Type = clsVariable.VariableTypeEnum.Numeric
4463 var.IntValue = SafeInt(GetReference(rest.sKey1))
4464 ElseIf rest.sKey1.StartsWith("ReferencedText") Then
4465 Dim iRef As Integer = Math.Max(SafeInt(rest.sKey1.Replace("ReferencedText", "")) - 1, 0)
4466 var = New clsVariable
4467 var.Type = clsVariable.VariableTypeEnum.Text
4468 var.StringValue = Adventure.sReferencedText(iRef)
4469 Else
4470 var = Adventure.htblVariables(rest.sKey1)
4471 If rest.sKey2 <> "" Then
4472 If Adventure.htblVariables.ContainsKey(rest.sKey2) Then
4473 iIndex = Adventure.htblVariables(rest.sKey2).IntValue
4474 Else
4475 iIndex = SafeInt(EvaluateExpression(rest.sKey2))
4476 End If
4477 End If
4478 End If
4479
4480 Dim iIntVal As Integer
4481 Dim sStringVal As String = ""
4482 If var.Type = clsVariable.VariableTypeEnum.Numeric Then
4483 If rest.IntValue = Integer.MinValue AndAlso rest.StringValue <> "" Then
4484 iIntVal = Adventure.htblVariables(rest.StringValue).IntValue ' Variable value
4485 Else
4486 If rest.StringValue <> "" AndAlso rest.StringValue <> rest.IntValue.ToString Then
4487 iIntVal = SafeInt(EvaluateExpression(rest.StringValue)) ' Expression
4488 Else
4489 iIntVal = rest.IntValue ' Integer value
4490 End If
4491 End If
4492 Else
4493 If rest.IntValue = Integer.MinValue AndAlso rest.StringValue <> "" Then
4494 sStringVal = Adventure.htblVariables(rest.StringValue).StringValue
4495 Else
4496 sStringVal = EvaluateExpression(rest.StringValue)
4497 End If
4498 End If
4499
4500 Select Case rest.eVariable
4501 Case clsRestriction.VariableEnum.EqualTo
4502 If var.Type = clsVariable.VariableTypeEnum.Numeric Then
4503 r = (var.IntValue(iIndex) = iIntVal)
4504 Else
4505 r = (var.StringValue(iIndex) = sStringVal)
4506 End If
4507 Case clsRestriction.VariableEnum.GreaterThan
4508 If var.Type = clsVariable.VariableTypeEnum.Numeric Then
4509 r = (var.IntValue(iIndex) > iIntVal)
4510 Else
4511 r = (var.StringValue(iIndex) > sStringVal)
4512 End If
4513 Case clsRestriction.VariableEnum.GreaterThanOrEqualTo
4514 If var.Type = clsVariable.VariableTypeEnum.Numeric Then
4515 r = (var.IntValue(iIndex) >= iIntVal)
4516 Else
4517 r = (var.StringValue(iIndex) >= sStringVal)
4518 End If
4519 Case clsRestriction.VariableEnum.LessThan
4520 If var.Type = clsVariable.VariableTypeEnum.Numeric Then
4521 r = (var.IntValue(iIndex) < iIntVal)
4522 Else
4523 r = (var.StringValue(iIndex) < sStringVal)
4524 End If
4525 Case clsRestriction.VariableEnum.LessThanOrEqualTo
4526 If var.Type = clsVariable.VariableTypeEnum.Numeric Then
4527 r = (var.IntValue(iIndex) <= iIntVal)
4528 Else
4529 r = (var.StringValue(iIndex) <= sStringVal)
4530 End If
4531 Case clsRestriction.VariableEnum.Contain
4532 If var.Type = clsVariable.VariableTypeEnum.Text Then
4533 r = var.StringValue(iIndex) IsNot Nothing AndAlso var.StringValue(iIndex).Contains(sStringVal)
4534 End If
4535 End Select
4536
4537 Case clsRestriction.RestrictionTypeEnum.Character
4538 Select Case rest.eCharacter
4539 Case clsRestriction.CharacterEnum.BeAlone
4540 Select Case rest.sKey1
4541 Case ANYCHARACTER
4542 For Each ch As clsCharacter In Adventure.htblCharacters.Values
4543 If ch.IsAlone Then
4544 r = True
4545 Exit For
4546 End If
4547 Next
4548 r = False
4549 Case Else
4550 r = Adventure.htblCharacters(rest.sKey1).IsAlone
4551 End Select
4552
4553 Case clsRestriction.CharacterEnum.BeAloneWith
4554 Select Case rest.sKey1
4555 Case ANYCHARACTER
4556 TODO("Any Character be alone")
4557 Case Else
4558 If rest.sKey2 = ANYCHARACTER Then
4559 r = Adventure.htblCharacters(rest.sKey1).AloneWithChar IsNot Nothing
4560 Else
4561 r = Adventure.htblCharacters(rest.sKey1).AloneWithChar = rest.sKey2
4562 End If
4563 End Select
4564
4565 Case clsRestriction.CharacterEnum.BeAtLocation
4566 Select Case rest.sKey1
4567 Case ANYCHARACTER
4568 r = False
4569 For Each c As clsCharacter In Adventure.htblCharacters.Values
4570 If c.Location.LocationKey = rest.sKey2 Then
4571 r = True
4572 Exit For
4573 End If
4574 Next
4575 Case Else
4576 r = Adventure.htblCharacters(rest.sKey1).Location.LocationKey = rest.sKey2
4577 End Select
4578
4579 Case clsRestriction.CharacterEnum.BeCharacter
4580 Select Case rest.sKey1
4581 Case ANYCHARACTER
4582 r = True ' Bit pointless
4583 Case Else
4584 r = (rest.sKey1 = rest.sKey2)
4585 End Select
4586
4587 Case clsRestriction.CharacterEnum.BeInConversationWith
4588 Select Case rest.sKey1
4589 Case ANYCHARACTER
4590 TODO("Any Character be in conversation with")
4591 Case Else
4592 If rest.sKey2 = ANYCHARACTER Then
4593 r = (Adventure.sConversationCharKey <> "")
4594 Else
4595 r = (Adventure.sConversationCharKey = rest.sKey2)
4596 End If
4597 End Select
4598
4599 Case clsRestriction.CharacterEnum.Exist
4600 Select Case rest.sKey1
4601 Case ANYCHARACTER
4602 r = Adventure.htblCharacters.Count > 0
4603 Case Else
4604 r = Adventure.htblCharacters.ContainsKey(rest.sKey1)
4605 End Select
4606
4607 Case clsRestriction.CharacterEnum.HaveRouteInDirection
4608 sRouteError = rest.oMessage.ToString
4609 Dim sSpecificError As String = ""
4610 Select Case rest.sKey1
4611 Case ANYCHARACTER
4612 r = False
4613 Select Case rest.sKey2
4614 Case ANYDIRECTION
4615 For Each c As clsCharacter In Adventure.htblCharacters.Values
4616 For Each d As DirectionsEnum In [Enum].GetValues(GetType(DirectionsEnum))
4617 If c.HasRouteInDirection(d, False, , sSpecificError) Then
4618 r = True
4619 GoTo DoneAnyCharAnyDir
4620 End If
4621 Next
4622 Next
4623 DoneAnyCharAnyDir:
4624 Case Else
4625 For Each c As clsCharacter In Adventure.htblCharacters.Values
4626 If c.HasRouteInDirection(CType([Enum].Parse(GetType(DirectionsEnum), rest.sKey2), DirectionsEnum), False, , sSpecificError) Then
4627 r = True
4628 Exit For
4629 End If
4630 Next
4631 End Select
4632 Case Else
4633 Dim ch As clsCharacter = Adventure.htblCharacters(rest.sKey1)
4634 Select Case rest.sKey2
4635 Case ANYDIRECTION
4636 r = False
4637 For Each d As DirectionsEnum In [Enum].GetValues(GetType(DirectionsEnum))
4638 If ch.HasRouteInDirection(d, False, , sSpecificError) Then
4639 r = True
4640 Exit For
4641 End If
4642 Next
4643 Case Else
4644 r = ch.HasRouteInDirection(CType([Enum].Parse(GetType(DirectionsEnum), rest.sKey2), DirectionsEnum), False, , sSpecificError)
4645 End Select
4646 End Select
4647 If sSpecificError <> "" Then sRouteError = sSpecificError
4648
4649 Case clsRestriction.CharacterEnum.HaveSeenCharacter
4650 Select Case rest.sKey1
4651 Case ANYCHARACTER
4652 TODO("Any Character seen character")
4653 Case Else
4654 r = Adventure.htblCharacters(rest.sKey1).HasSeenCharacter(rest.sKey2)
4655 End Select
4656
4657 Case clsRestriction.CharacterEnum.HaveSeenLocation
4658 Select Case rest.sKey1
4659 Case ANYCHARACTER
4660 TODO("Any Character seen location")
4661 Case Else
4662 r = Adventure.htblCharacters(rest.sKey1).HasSeenLocation(rest.sKey2)
4663 End Select
4664
4665 Case clsRestriction.CharacterEnum.HaveSeenObject
4666 Select Case rest.sKey1
4667 Case ANYCHARACTER
4668 TODO("Any Character seen object")
4669 Case Else
4670 r = Adventure.htblCharacters(rest.sKey1).HasSeenObject(rest.sKey2)
4671 End Select
4672
4673 Case clsRestriction.CharacterEnum.BeHoldingObject
4674 Select Case rest.sKey1
4675 Case ANYCHARACTER
4676 r = Adventure.htblObjects(rest.sKey2).IsHeldByAnyone
4677 Case Else
4678 r = Adventure.htblCharacters(rest.sKey1).IsHoldingObject(rest.sKey2)
4679 End Select
4680
4681 Case clsRestriction.CharacterEnum.BeInSameLocationAsCharacter
4682 Select Case rest.sKey1
4683 Case ANYCHARACTER
4684 r = Not Adventure.htblCharacters(rest.sKey2).IsAlone
4685 Case Else
4686 Dim ch As clsCharacter = Adventure.htblCharacters(rest.sKey1)
4687 If rest.sKey2 = ANYCHARACTER Then
4688 r = False
4689 For Each c As clsCharacter In Adventure.htblCharacters.Values
4690 If c.Key <> rest.sKey1 AndAlso c.Location.LocationKey = ch.Location.LocationKey Then
4691 r = True
4692 Exit For
4693 End If
4694 Next
4695 Else
4696 r = ch.Location.LocationKey = Adventure.htblCharacters(rest.sKey2).Location.LocationKey
4697 End If
4698 End Select
4699
4700 Case clsRestriction.CharacterEnum.BeVisibleToCharacter
4701 Dim lChars As New List(Of clsCharacter)
4702
4703 Select Case rest.sKey1
4704 Case ANYCHARACTER
4705 For Each c As clsCharacter In Adventure.htblCharacters.Values
4706 lChars.Add(c)
4707 Next
4708 Case Else
4709 lChars.Add(Adventure.htblCharacters(rest.sKey1))
4710 End Select
4711
4712 r = False
4713 For Each c As clsCharacter In lChars
4714 If rest.sKey2 = ANYCHARACTER Then
4715 For Each c2 As clsCharacter In Adventure.htblCharacters.Values
4716 If c.Key <> c2.Key Then
4717 If c.CanSeeCharacter(c2.Key) Then
4718 r = True
4719 Exit For
4720 End If
4721 End If
4722 Next
4723 Else
4724 If c.CanSeeCharacter(rest.sKey2) Then
4725 r = True
4726 Exit For
4727 End If
4728 End If
4729 Next
4730
4731 Case clsRestriction.CharacterEnum.BeInSameLocationAsObject
4732 Select Case rest.sKey1
4733 Case ANYCHARACTER
4734 For Each c As clsCharacter In Adventure.htblCharacters.Values
4735 If c.CanSeeObject(rest.sKey2) Then
4736 r = True
4737 Exit For
4738 End If
4739 Next
4740 Case Else
4741 r = Adventure.htblCharacters(rest.sKey1).CanSeeObject(rest.sKey2)
4742 End Select
4743
4744 Case clsRestriction.CharacterEnum.BeLyingOnObject
4745 Select Case rest.sKey1
4746 Case ANYCHARACTER
4747 For Each c As clsCharacter In Adventure.htblCharacters.Values
4748 If c.Location.Position = clsCharacterLocation.PositionEnum.Lying Then
4749 If rest.sKey2 = ANYOBJECT Then
4750 If c.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject Then
4751 r = True
4752 Exit For
4753 End If
4754 ElseIf rest.sKey2 = THEFLOOR Then
4755 If c.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation Then
4756 r = True
4757 Exit For
4758 End If
4759 Else
4760 If c.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject AndAlso c.Location.Key = rest.sKey2 Then
4761 r = True
4762 Exit For
4763 End If
4764 End If
4765 End If
4766 Next
4767 Case Else
4768 Dim ch As clsCharacter = Adventure.htblCharacters(rest.sKey1)
4769 If rest.sKey2 = ANYOBJECT Then
4770 r = ch.Location.Position = clsCharacterLocation.PositionEnum.Lying AndAlso ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject
4771 ElseIf rest.sKey2 = THEFLOOR Then
4772 r = ch.Location.Position = clsCharacterLocation.PositionEnum.Lying AndAlso ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
4773 Else
4774 r = (ch.Location.Position = clsCharacterLocation.PositionEnum.Lying AndAlso ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject AndAlso ch.Location.Key = rest.sKey2)
4775 End If
4776 End Select
4777
4778 Case clsRestriction.CharacterEnum.BeInGroup
4779 Select Case rest.sKey1
4780 Case ANYCHARACTER
4781 For Each c As clsCharacter In Adventure.htblCharacters.Values
4782 If Adventure.htblGroups(rest.sKey2).arlMembers.Contains(c.Key) Then
4783 r = True
4784 Exit For
4785 End If
4786 Next
4787 Case Else
4788 r = Adventure.htblGroups(rest.sKey2).arlMembers.Contains(rest.sKey1)
4789 End Select
4790
4791 Case clsRestriction.CharacterEnum.BeOfGender
4792 Select Case rest.sKey1
4793 Case ANYCHARACTER
4794 TODO("Any Character be of gender")
4795 Case Else
4796 r = Adventure.htblCharacters(rest.sKey1).Gender = CType([Enum].Parse(GetType(clsCharacter.GenderEnum), rest.sKey2), clsCharacter.GenderEnum)
4797 End Select
4798
4799 Case clsRestriction.CharacterEnum.BeSittingOnObject
4800 Select Case rest.sKey1
4801 Case ANYCHARACTER
4802 For Each c As clsCharacter In Adventure.htblCharacters.Values
4803 If c.Location.Position = clsCharacterLocation.PositionEnum.Sitting Then
4804 If rest.sKey2 = ANYOBJECT Then
4805 If c.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject Then
4806 r = True
4807 Exit For
4808 End If
4809 ElseIf rest.sKey2 = THEFLOOR Then
4810 If c.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation Then
4811 r = True
4812 Exit For
4813 End If
4814 Else
4815 If c.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject AndAlso c.Location.Key = rest.sKey2 Then
4816 r = True
4817 Exit For
4818 End If
4819 End If
4820 End If
4821 Next
4822 Case Else
4823 Dim ch As clsCharacter = Adventure.htblCharacters(rest.sKey1)
4824 If rest.sKey2 = ANYOBJECT Then
4825 r = ch.Location.Position = clsCharacterLocation.PositionEnum.Sitting AndAlso ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject
4826 ElseIf rest.sKey2 = THEFLOOR Then
4827 r = ch.Location.Position = clsCharacterLocation.PositionEnum.Sitting AndAlso ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
4828 Else
4829 r = (ch.Location.Position = clsCharacterLocation.PositionEnum.Sitting AndAlso ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject AndAlso ch.Location.Key = rest.sKey2)
4830 End If
4831 End Select
4832
4833 Case clsRestriction.CharacterEnum.BeStandingOnObject
4834 Select Case rest.sKey1
4835 Case ANYCHARACTER
4836 For Each c As clsCharacter In Adventure.htblCharacters.Values
4837 If c.Location.Position = clsCharacterLocation.PositionEnum.Standing Then
4838 If rest.sKey2 = ANYOBJECT Then
4839 If c.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject Then
4840 r = True
4841 Exit For
4842 End If
4843 ElseIf rest.sKey2 = THEFLOOR Then
4844 If c.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation Then
4845 r = True
4846 Exit For
4847 End If
4848 Else
4849 If c.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject AndAlso c.Location.Key = rest.sKey2 Then
4850 r = True
4851 Exit For
4852 End If
4853 End If
4854 End If
4855 Next
4856 Case Else
4857 Dim ch As clsCharacter = Adventure.htblCharacters(rest.sKey1)
4858 If rest.sKey2 = ANYOBJECT Then
4859 r = ch.Location.Position = clsCharacterLocation.PositionEnum.Standing AndAlso ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject
4860 ElseIf rest.sKey2 = THEFLOOR Then
4861 r = ch.Location.Position = clsCharacterLocation.PositionEnum.Standing AndAlso ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.AtLocation
4862 Else
4863 r = (ch.Location.Position = clsCharacterLocation.PositionEnum.Standing AndAlso ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject AndAlso ch.Location.Key = rest.sKey2)
4864 End If
4865 End Select
4866
4867 Case clsRestriction.CharacterEnum.BeWearingObject
4868 Select Case rest.sKey1
4869 Case ANYCHARACTER
4870 r = Adventure.htblObjects(rest.sKey2).IsWornByAnyone
4871 Case Else
4872 r = Adventure.htblCharacters(rest.sKey1).IsWearingObject(rest.sKey2)
4873 End Select
4874
4875 Case clsRestriction.CharacterEnum.BeWithinLocationGroup
4876 Select Case rest.sKey1
4877 Case ANYCHARACTER
4878 For Each c As clsCharacter In Adventure.htblCharacters.Values
4879 If Adventure.htblGroups(rest.sKey2).arlMembers.Contains(c.Location.LocationKey) Then
4880 r = True
4881 Exit For
4882 End If
4883 Next
4884 Case Else
4885 r = Adventure.htblGroups(rest.sKey2).arlMembers.Contains(Adventure.htblCharacters(rest.sKey1).Location.LocationKey)
4886 End Select
4887
4888 Case clsRestriction.CharacterEnum.HaveProperty
4889 Select Case rest.sKey1
4890 Case ANYCHARACTER
4891 For Each c As clsCharacter In Adventure.htblCharacters.Values
4892 If c.HasProperty(rest.sKey2) Then
4893 r = True
4894 Exit For
4895 End If
4896 Next
4897 Case Else
4898 r = Adventure.htblCharacters.ContainsKey(rest.sKey1) AndAlso Adventure.htblCharacters(rest.sKey1).HasProperty(rest.sKey2)
4899 End Select
4900
4901 Case clsRestriction.CharacterEnum.BeInPosition
4902 Select Case rest.sKey1
4903 Case ANYCHARACTER
4904 For Each c As clsCharacter In Adventure.htblCharacters.Values
4905 If c.HasProperty("CharacterPosition") AndAlso c.GetPropertyValue("CharacterPosition") = rest.sKey2 Then
4906 r = True
4907 Exit For
4908 End If
4909 Next
4910 Case Else
4911 If Adventure.htblCharacters(rest.sKey1).HasProperty("CharacterPosition") Then
4912 r = Adventure.htblCharacters(rest.sKey1).GetPropertyValue("CharacterPosition") = rest.sKey2
4913 End If
4914 End Select
4915
4916 Case clsRestriction.CharacterEnum.BeInsideObject
4917 Select Case rest.sKey1
4918 Case ANYCHARACTER
4919 Select Case rest.sKey2
4920 Case ANYOBJECT
4921 TODO("Any Character be inside any object")
4922 Case Else
4923 r = Adventure.htblObjects(rest.sKey2).ChildrenCharacters(clsObject.WhereChildrenEnum.InsideObject).Count > 0
4924 End Select
4925 Case Else
4926 If rest.sKey2 = ANYOBJECT Then
4927 r = (Adventure.htblCharacters(rest.sKey1).Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.InObject)
4928 Else
4929 If rest.sKey1 = ANYOBJECT Then
4930 r = Adventure.htblObjects(rest.sKey2).Children(clsObject.WhereChildrenEnum.InsideObject).Count > 0
4931 ElseIf rest.sKey1 = ANYCHARACTER Then
4932 r = Adventure.htblObjects(rest.sKey2).ChildrenCharacters(clsObject.WhereChildrenEnum.InsideObject).Count > 0
4933 Else
4934 r = Adventure.htblCharacters(rest.sKey1).Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.InObject AndAlso Adventure.htblCharacters(rest.sKey1).Location.Key = rest.sKey2
4935 End If
4936 End If
4937 End Select
4938
4939 Case clsRestriction.CharacterEnum.BeOnObject
4940 Select Case rest.sKey1
4941 Case ANYCHARACTER
4942 If rest.sKey2 = ANYOBJECT Then
4943 TODO("Any Character on Any Object")
4944 Else
4945 r = Adventure.htblObjects(rest.sKey2).ChildrenCharacters(clsObject.WhereChildrenEnum.OnObject).Count > 0
4946 End If
4947 Case Else
4948 If rest.sKey2 = ANYOBJECT Then
4949 r = (Adventure.htblCharacters(rest.sKey1).Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject)
4950 Else
4951 Dim ch As clsCharacter = Adventure.htblCharacters(rest.sKey1)
4952 r = ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnObject AndAlso ch.Location.Key = rest.sKey2 ' Adventure.htblObjects(rest.sKey1).IsOn(rest.sKey2)
4953 End If
4954 End Select
4955
4956 Case clsRestriction.CharacterEnum.BeOnCharacter
4957 Select Case rest.sKey1
4958 Case ANYCHARACTER
4959 TODO("Any Character be on character")
4960 Case Else
4961 Dim ch As clsCharacter = Adventure.htblCharacters(rest.sKey1)
4962 If rest.sKey2 = ANYCHARACTER Then
4963 r = (ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnCharacter)
4964 Else
4965 r = ch.Location.ExistWhere = clsCharacterLocation.ExistsWhereEnum.OnCharacter AndAlso ch.Location.Key = rest.sKey2
4966 End If
4967 End Select
4968
4969 End Select
4970
4971 Case clsRestriction.RestrictionTypeEnum.Item
4972
4973 Dim obItem As clsObject = Nothing
4974 Dim chItem As clsCharacter = Nothing
4975 Dim locItem As clsLocation = Nothing
4976
4977 If Not Adventure.htblObjects.TryGetValue(rest.sKey1, obItem) AndAlso Not Adventure.htblCharacters.TryGetValue(rest.sKey1, chItem) AndAlso Not Adventure.htblLocations.TryGetValue(rest.sKey1, locItem) Then
4978 r = False
4979 GoTo SkipTest
4980 End If
4981
4982 Select Case rest.eItem
4983 Case clsRestriction.ItemEnum.BeAtLocation
4984 If obItem IsNot Nothing Then
4985 r = obItem.IsVisibleAtLocation(rest.sKey2)
4986 ElseIf chItem IsNot Nothing Then
4987 r = chItem.Location.LocationKey = rest.sKey2
4988 Else
4989 r = locItem.Key = rest.sKey2
4990 End If
4991 Case clsRestriction.ItemEnum.BeCharacter
4992 r = chItem IsNot Nothing AndAlso chItem.Key = rest.sKey2
4993 Case clsRestriction.ItemEnum.BeInGroup
4994 Dim grp As clsGroup = Nothing
4995 If Adventure.htblGroups.TryGetValue(rest.sKey2, grp) Then
4996 r = grp.arlMembers.Contains(rest.sKey1)
4997 End If
4998 Case clsRestriction.ItemEnum.BeInSameLocationAsCharacter
4999 Dim chKey2 As clsCharacter = Nothing
5000 If Adventure.htblCharacters.TryGetValue(rest.sKey2, chKey2) Then
5001 If obItem IsNot Nothing Then
5002 r = chKey2.CanSeeObject(obItem.Key)
5003 ElseIf chItem IsNot Nothing Then
5004 r = chKey2.CanSeeCharacter(chItem.Key)
5005 Else
5006 r = chKey2.Location.LocationKey = locItem.Key
5007 End If
5008 End If
5009 Case clsRestriction.ItemEnum.BeInSameLocationAsObject
5010 Dim obKey2 As clsObject = Nothing
5011 If Adventure.htblObjects.TryGetValue(rest.sKey2, obKey2) Then
5012 r = False
5013 If obItem IsNot Nothing Then
5014 For Each sOb1Loc As String In obItem.LocationRoots.Keys
5015 For Each sOb2Loc As String In obKey2.LocationRoots.Keys
5016 If sOb1Loc = sOb2Loc Then r = True
5017 Exit For
5018 Next
5019 Next
5020 ElseIf chItem IsNot Nothing Then
5021 r = chItem.CanSeeObject(obKey2.Key)
5022 Else
5023 r = obKey2.LocationRoots.ContainsKey(locItem.Key)
5024 End If
5025 End If
5026 Case clsRestriction.ItemEnum.BeInsideObject
5027 Dim obKey2 As clsObject = Nothing
5028 If Adventure.htblObjects.TryGetValue(rest.sKey2, obKey2) Then
5029 r = obKey2.Children(clsObject.WhereChildrenEnum.InsideObject, True).ContainsKey(rest.sKey1)
5030 End If
5031 Case clsRestriction.ItemEnum.BeLocation
5032 r = locItem IsNot Nothing AndAlso locItem.Key = rest.sKey2
5033 Case clsRestriction.ItemEnum.BeObject
5034 r = obItem IsNot Nothing AndAlso obItem.Key = rest.sKey2
5035 Case clsRestriction.ItemEnum.BeOnCharacter
5036 Dim chKey2 As clsCharacter = Nothing
5037 If Adventure.htblCharacters.TryGetValue(rest.sKey2, chKey2) Then
5038 If obItem IsNot Nothing Then
5039 r = obItem.Location.StaticExistWhere = clsObjectLocation.StaticExistsWhereEnum.PartOfCharacter AndAlso obItem.Location.Key = chKey2.Key
5040 ElseIf chItem IsNot Nothing Then
5041 r = chKey2.Children(True).ContainsKey(chItem.Key)
5042 Else
5043 r = False
5044 End If
5045 End If
5046 Case clsRestriction.ItemEnum.BeType
5047 r = (rest.sKey2 = "Object" AndAlso obItem IsNot Nothing) OrElse (rest.sKey2 = "Character" AndAlso chItem IsNot Nothing) OrElse (rest.sKey2 = "Location" AndAlso locItem IsNot Nothing)
5048 Case clsRestriction.ItemEnum.Exist
5049 r = obItem IsNot Nothing OrElse chItem IsNot Nothing OrElse locItem IsNot Nothing
5050 Case clsRestriction.ItemEnum.HaveProperty
5051 If obItem IsNot Nothing Then
5052 r = obItem.HasProperty(rest.sKey2)
5053 ElseIf chItem IsNot Nothing Then
5054 r = chItem.HasProperty(rest.sKey2)
5055 Else
5056 r = locItem.HasProperty(rest.sKey2)
5057 End If
5058 End Select
5059
5060 Case clsRestriction.RestrictionTypeEnum.Property
5061 Dim item As clsItem = Nothing
5062 Dim bItemContainsProperty As Boolean = False
5063 If Adventure.htblObjects.ContainsKey(rest.sKey2) Then
5064 item = Adventure.htblObjects(rest.sKey2)
5065 bItemContainsProperty = CType(item, clsObject).HasProperty(rest.sKey1)
5066 ElseIf Adventure.htblCharacters.ContainsKey(rest.sKey2) Then
5067 item = Adventure.htblCharacters(rest.sKey2)
5068 bItemContainsProperty = CType(item, clsCharacter).HasProperty(rest.sKey1)
5069 ElseIf Adventure.htblLocations.ContainsKey(rest.sKey2) Then
5070 item = Adventure.htblLocations(rest.sKey2)
5071 bItemContainsProperty = CType(item, clsLocation).HasProperty(rest.sKey1)
5072 End If
5073
5074 If Not bItemContainsProperty Then
5075 r = False
5076 Else
5077 Dim prop As clsProperty
5078 If TypeOf item Is clsObject Then
5079 prop = CType(item, clsObject).GetProperty(rest.sKey1)
5080 ElseIf TypeOf item Is clsCharacter Then
5081 prop = CType(item, clsCharacter).GetProperty(rest.sKey1)
5082 Else
5083 prop = CType(item, clsLocation).GetProperty(rest.sKey1)
5084 End If
5085
5086 Select Case prop.Type
5087 Case clsProperty.PropertyTypeEnum.CharacterKey, clsProperty.PropertyTypeEnum.LocationGroupKey, clsProperty.PropertyTypeEnum.LocationKey, clsProperty.PropertyTypeEnum.ObjectKey
5088 Dim sKey As String = GetReference(rest.StringValue)
5089 If sKey Is Nothing Then sKey = rest.StringValue
5090 r = (prop.Value = sKey)
5091 Case clsProperty.PropertyTypeEnum.Integer
5092 Dim iCompareValue As Integer = 0
5093 If Adventure.htblVariables.ContainsKey(rest.StringValue) Then
5094 iCompareValue = Adventure.htblVariables(rest.StringValue).IntValue
5095 Else
5096 If bIgnoreReferences Then
5097 For Each sRef As String In ReferenceNames()
5098 If rest.StringValue.Contains(sRef) Then
5099 r = True
5100 GoTo SkipTest
5101 End If
5102 Next
5103 End If
5104 iCompareValue = EvaluateExpression(rest.StringValue, True)
5105 End If
5106 Select Case CType(rest.IntValue, clsRestriction.VariableEnum)
5107 Case clsRestriction.VariableEnum.LessThan
5108 r = (SafeInt(prop.Value) < iCompareValue)
5109 Case clsRestriction.VariableEnum.LessThanOrEqualTo
5110 r = (SafeInt(prop.Value) <= iCompareValue)
5111 Case clsRestriction.VariableEnum.EqualTo, CType(-1, clsRestriction.VariableEnum)
5112 r = (SafeInt(prop.Value) = iCompareValue)
5113 Case clsRestriction.VariableEnum.GreaterThanOrEqualTo
5114 r = (SafeInt(prop.Value) >= iCompareValue)
5115 Case clsRestriction.VariableEnum.GreaterThan
5116 r = (SafeInt(prop.Value) > iCompareValue)
5117 End Select
5118 Case clsProperty.PropertyTypeEnum.SelectionOnly
5119 r = True
5120 Case clsProperty.PropertyTypeEnum.StateList
5121 r = prop.Value = rest.StringValue
5122 Case clsProperty.PropertyTypeEnum.Text
5123 Dim sStringVal As String
5124 ' Could be an expression or simple text
5125 If rest.StringValue.Contains("""") Then
5126 sStringVal = EvaluateExpression(rest.StringValue)
5127 Else
5128 sStringVal = ReplaceFunctions(rest.StringValue)
5129 End If
5130 r = (prop.Value = sStringVal)
5131 Case clsProperty.PropertyTypeEnum.ValueList
5132 Dim iCompareValue As Integer = 0
5133 If IsNumeric(rest.StringValue) Then
5134 iCompareValue = SafeInt(rest.StringValue)
5135 Else
5136 If bIgnoreReferences Then
5137 For Each sRef As String In ReferenceNames()
5138 If rest.StringValue.Contains(sRef) Then
5139 r = True
5140 GoTo SkipTest
5141 End If
5142 Next
5143 End If
5144 iCompareValue = EvaluateExpression(rest.StringValue, True)
5145 End If
5146 Select Case CType(rest.IntValue, clsRestriction.VariableEnum)
5147 Case clsRestriction.VariableEnum.LessThan
5148 r = (SafeInt(prop.Value) < iCompareValue)
5149 Case clsRestriction.VariableEnum.LessThanOrEqualTo
5150 r = (SafeInt(prop.Value) <= iCompareValue)
5151 Case clsRestriction.VariableEnum.EqualTo, CType(-1, clsRestriction.VariableEnum)
5152 r = (SafeInt(prop.Value) = iCompareValue)
5153 Case clsRestriction.VariableEnum.GreaterThanOrEqualTo
5154 r = (SafeInt(prop.Value) >= iCompareValue)
5155 Case clsRestriction.VariableEnum.GreaterThan
5156 r = (SafeInt(prop.Value) > iCompareValue)
5157 End Select
5158 End Select
5159 End If
5160
5161 Case clsRestriction.RestrictionTypeEnum.Direction
5162 Dim sRefDirection As String = GetReference("ReferencedDirection")
5163 r = rest.sKey1 = sRefDirection
5164
5165 Case clsRestriction.RestrictionTypeEnum.Expression
5166 r = SafeBool(EvaluateExpression(rest.StringValue))
5167
5168 End Select
5169
5170 SkipTest:
5171 If r = (rest.eMust = clsRestriction.MustEnum.Must) Then
5172 sRestrictionText = ""
5173 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, restx.Summary & ": Passed")
5174 Return True
5175 Else
5176 sRestrictionText = restx.oMessage.ToString ' Use original, so we mark any Display Once as seen
5177 If rest.eType = clsRestriction.RestrictionTypeEnum.Character AndAlso rest.eCharacter = clsRestriction.CharacterEnum.HaveRouteInDirection Then
5178 If sRouteError <> sRestrictionText AndAlso sRouteError <> "" Then sRestrictionText = sRouteError
5179 End If
5180 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, restx.Summary & ": Failed")
5181 End If
5182
5183 Catch ex As Exception
5184 ErrMsg("Error evaluating PassSingleRestriction for restriction """ & restx.ToString & """", ex)
5185 End Try
5186
5187 End Function
5188
5189
5190 Private Function EvaluateRestrictionBlock(ByVal arlRestrictions As RestrictionArrayList, ByVal sBlock As String, Optional ByVal bIgnoreReferences As Boolean = False, Optional tas As clsTask = Nothing) As Boolean
5191
5192 While sBlock.Contains("A#O")
5193 ' #A#O# => (#A#)O#
5194 ' #A#A#O# => (#A#A#)O#
5195 '(#O#)A#O# => ((#O#)A#)O#
5196 '#A(#A#O#) => #A((#A#)O#)
5197 ' Insert a ( at beginning, or after previous (
5198 Dim i As Integer = sBlock.IndexOf("A#O")
5199 Dim j As Integer = sBlock.Substring(0, i).LastIndexOf("(") + 1
5200 sBlock = sLeft(sBlock, j) & "(" & sBlock.Substring(j, i - j) & "A#)O" & sBlock.Substring(i + 3)
5201 End While
5202
5203 Select Case Left(sBlock, 1)
5204 Case "("
5205 ' Get block
5206 Dim iBrackDepth As Integer = 1
5207 Dim sSubBlock As String = "("
5208 Dim iOffset As Integer = 1
5209 While iBrackDepth > 0
5210 Dim s As String = sBlock.Substring(iOffset, 1)
5211 Select Case s
5212 Case "("
5213 iBrackDepth += 1
5214 Case ")"
5215 iBrackDepth -= 1
5216 Case Else
5217 ' Do nothing
5218 End Select
5219 sSubBlock &= s
5220 iOffset += 1
5221 End While
5222 sSubBlock = sSubBlock.Substring(1, sSubBlock.Length - 2)
5223 If sBlock.Length - 2 = sSubBlock.Length Then
5224 Return EvaluateRestrictionBlock(arlRestrictions, sSubBlock, bIgnoreReferences)
5225 Else
5226 Select Case sBlock.Substring(sSubBlock.Length + 2, 1)
5227 Case "A"
5228 Dim bFirst As Boolean = EvaluateRestrictionBlock(arlRestrictions, sSubBlock, bIgnoreReferences)
5229 If Not bFirst Then
5230 iRestNum += CharacterCount(sBlock.Substring(sSubBlock.Length + 3), "#"c)
5231 Return False
5232 Else
5233 Return EvaluateRestrictionBlock(arlRestrictions, sBlock.Substring(sSubBlock.Length + 3), bIgnoreReferences)
5234 End If
5235 Case "O"
5236 Dim bFirst As Boolean = EvaluateRestrictionBlock(arlRestrictions, sSubBlock, bIgnoreReferences)
5237 If bFirst Then
5238 iRestNum += CharacterCount(sBlock.Substring(sSubBlock.Length + 3), "#"c)
5239 Return True
5240 Else
5241 Return EvaluateRestrictionBlock(arlRestrictions, sBlock.Substring(sSubBlock.Length + 3), bIgnoreReferences)
5242 End If
5243 Case Else
5244 ' Error
5245 End Select
5246 End If
5247 Case "#"
5248 iRestNum += 1
5249 If sBlock.Length = 1 Then
5250 Return PassSingleRestriction(arlRestrictions(iRestNum - 1), bIgnoreReferences)
5251 Else
5252 Select Case sBlock.Substring(1, 1)
5253 Case "A"
5254 Dim bFirst As Boolean = PassSingleRestriction(arlRestrictions(iRestNum - 1), bIgnoreReferences)
5255 If Not bFirst Then
5256 iRestNum += CharacterCount(sBlock.Substring(2), "#"c)
5257 Return False
5258 Else
5259 Return EvaluateRestrictionBlock(arlRestrictions, sBlock.Substring(2), bIgnoreReferences)
5260 End If
5261 Case "O"
5262 Dim bFirst As Boolean = PassSingleRestriction(arlRestrictions(iRestNum - 1), bIgnoreReferences)
5263 If bFirst Then
5264 iRestNum += CharacterCount(sBlock.Substring(2), "#"c)
5265 Return True
5266 Else
5267 Return EvaluateRestrictionBlock(arlRestrictions, sBlock.Substring(2), bIgnoreReferences)
5268 End If
5269 Case Else
5270 ' Error
5271 End Select
5272 End If
5273 Case Else
5274 If tas IsNot Nothing Then
5275 ErrMsg("Bad Bracket Sequence in task """ & tas.Description & """")
5276 Else
5277 ErrMsg("Bad Bracket Sequence")
5278 End If
5279
5280 End Select
5281
5282 End Function
5283
5284
5285 ' IgnoreReferences is for when we are evaluating whether the task is completable or not, but we don't have any refs yet
5286 Public Function PassRestrictions(ByVal arlRestrictions As RestrictionArrayList, Optional ByVal bIgnoreReferences As Boolean = False, Optional tas As clsTask = Nothing) As Boolean
5287
5288 iRestNum = 0
5289 sRouteError = ""
5290
5291 If arlRestrictions.Count = 0 Then
5292 Return True
5293 Else
5294 ' We have to check each combination of objects from our task
5295 ' e.g. "get %objects% from %object2%
5296 ' "get red ball and blue ball from box"
5297 ' get red ball from box
5298 ' get blue ball from box
5299 Return EvaluateRestrictionBlock(arlRestrictions, arlRestrictions.BracketSequence, bIgnoreReferences, tas)
5300 End If
5301
5302 End Function
5303
5304
5305 Private Function InputMatchesObjects(ByVal task As clsTask, ByVal sInput As String, ByVal iNewRef As Integer, Optional ByVal bExcepts As Boolean = False, Optional ByVal bPlural As Boolean = False, Optional ByVal bSecondChance As Boolean = False) As Boolean
5306
5307 Dim re As System.Text.RegularExpressions.Regex
5308
5309 If Not bPlural Then
5310 re = New System.Text.RegularExpressions.Regex("^((?<all>all( .+)?)|(?<objects1>.+))( (except|but|apart from) (?<objects2>.+))?$", System.Text.RegularExpressions.RegexOptions.RightToLeft Or System.Text.RegularExpressions.RegexOptions.IgnoreCase)
5311 If re.IsMatch(sInput) Then
5312 For Each sGroupName As String In re.GetGroupNames
5313 Select Case sGroupName
5314
5315 Case "all"
5316 Dim sAll As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5317 If sAll <> "" Then
5318 If sAll = "all" Then
5319 ' User isn't refining 'all', so we need to populate list with all objects
5320 Dim iItemNum As Integer = 0
5321 For Each ob As clsObject In Adventure.htblObjects.SeenBy.Values
5322 task.NewReferences(iNewRef).Items.Add(New clsSingleItem)
5323 task.NewReferences(iNewRef).Items(iItemNum).MatchingPossibilities.Add(ob.Key)
5324 task.NewReferences(iNewRef).Items(iItemNum).bExplicitlyMentioned = False
5325 task.NewReferences(iNewRef).Items(iItemNum).sCommandReference = "all"
5326 iItemNum += 1
5327 Next
5328 Else
5329 ' i.e. all balls
5330 ' object1 should be plural here, in which case we want to match any object with that as the plural, i.e. balls, cactii, sheep
5331 If Not InputMatchesObjects(task, sAll.Substring(4), iNewRef, , True) Then GoTo NextCheck ' Return False
5332 End If
5333 End If
5334
5335 Case "objects1"
5336 Dim sObs As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5337 If sObs <> "" AndAlso Not sObs.StartsWith("all ") Then
5338 ' i.e. balls
5339 ' object1 should be plural here, in which case we want to match any object with that as the plural, i.e. balls, cactii, sheep
5340 If Not InputMatchesObjects(task, sObs, iNewRef, bExcepts, True) Then GoTo NextCheck
5341 End If
5342
5343 Case "objects2"
5344 Dim sExcepts As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5345 If sExcepts <> "" Then
5346 ' Need to go thru and remove any matching ref
5347 InputMatchesObjects(task, sExcepts, iNewRef, True)
5348 End If
5349
5350 End Select
5351 Next
5352 Return True
5353 End If
5354
5355 NextCheck:
5356 re = New System.Text.RegularExpressions.Regex("^(?<commaseparatedobjects>(.+), )*(?<object2>.+) and (?<object3>.+)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
5357 If re.IsMatch(sInput) Then
5358 Dim m As System.Text.RegularExpressions.Match = re.Match(sInput)
5359 Dim iItemNum As Integer = 0
5360 If m.Groups("commaseparatedobjects").Length > 0 Then
5361 For Each sObject As String In m.Groups("commaseparatedobjects").Value.TrimEnd(New Char() {","c, " "c}).Split(","c)
5362 sObject = sObject.Trim
5363 If Not InputMatchesObject(task, sObject, iNewRef, iItemNum, bExcepts) Then Return False
5364 iItemNum += 1
5365 Next
5366 End If
5367 If Not InputMatchesObject(task, m.Groups("object2").Value, iNewRef, iItemNum, bExcepts) Then Return False
5368 iItemNum += 1
5369 If Not InputMatchesObject(task, m.Groups("object3").Value, iNewRef, iItemNum, bExcepts) Then Return False
5370 Return True
5371 End If
5372
5373 End If
5374 Return InputMatchesObject(task, sInput, iNewRef, 0, bExcepts, bPlural, bSecondChance)
5375 End Function
5376
5377
5378 Private Function InputMatchesObject(ByVal task As clsTask, ByVal sInput As String, ByVal iReferenceNum As Integer, ByVal iItemNum As Integer, Optional ByVal bExcepts As Boolean = False, Optional ByVal bPlural As Boolean = False, Optional ByVal bSecondChance As Boolean = False) As Boolean
5379 Dim bResult As Boolean = False
5380 Dim bAddedItem As Boolean = False
5381
5382 If iItemNum = 0 AndAlso bPlural Then iItemNum = -1
5383 For Each ob As clsObject In Adventure.htblObjects.Values
5384 If System.Text.RegularExpressions.Regex.IsMatch(sInput, "^" & ob.sRegularExpressionString(, bPlural) & "$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) Then
5385 bResult = True
5386 If Not bExcepts Then
5387 If bPlural Then iItemNum += 1
5388 If bPlural OrElse Not bAddedItem Then task.NewReferences(iReferenceNum).Items.Add(New clsSingleItem)
5389 bAddedItem = True
5390
5391 task.NewReferences(iReferenceNum).Items(iItemNum).MatchingPossibilities.Add(ob.Key)
5392 task.NewReferences(iReferenceNum).Items(iItemNum).bExplicitlyMentioned = True
5393 task.NewReferences(iReferenceNum).Items(iItemNum).sCommandReference = sInput
5394 Else
5395 For iItem As Integer = task.NewReferences(iReferenceNum).Items.Count - 1 To 0 Step -1
5396 Dim itm As clsSingleItem = task.NewReferences(iReferenceNum).Items(iItem)
5397 If itm.MatchingPossibilities.Contains(ob.Key) Then itm.MatchingPossibilities.Remove(ob.Key)
5398 If itm.MatchingPossibilities.Count = 0 Then task.NewReferences(iReferenceNum).Items.RemoveAt(iItem)
5399 Next
5400 End If
5401 End If
5402 Next
5403
5404 If Not bResult AndAlso bSecondChance AndAlso task.HasObjectExistRestriction Then
5405 ' TODO - This needs to check that it is the correct 'must exist' check, rather than just any
5406 ' If our task has a check that objects should exist, return True as a match so the task can deal with that in it's restrictions
5407 'task.NewReferences(iReferenceNum).Items.Add(New clsSingleItem)
5408 'task.NewReferences(iReferenceNum).Items(0).MatchingPossibilities.Add("NonExistingObject")
5409 'task.NewReferences(iReferenceNum).Items(0).bExplicitlyMentioned = False
5410 'task.NewReferences(iReferenceNum).Items(0).sCommandReference = sInput
5411 Return True
5412 End If
5413
5414 Return bResult
5415
5416 End Function
5417
5418
5419 Private Function InputMatchesCharacters(ByVal task As clsTask, ByVal sInput As String, ByVal iNewRef As Integer, Optional ByVal bExcepts As Boolean = False, Optional ByVal bSecondChance As Boolean = False) As Boolean
5420 Dim re As System.Text.RegularExpressions.Regex
5421
5422 NextCheck:
5423 re = New System.Text.RegularExpressions.Regex("^(?<commaseparatedcharacters>(.+), )*(?<character2>.+) and (?<character3>.+)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
5424 If re.IsMatch(sInput) Then
5425 Dim m As System.Text.RegularExpressions.Match = re.Match(sInput)
5426 Dim iItemNum As Integer = 0
5427 If m.Groups("commaseparatedcharacters").Length > 0 Then
5428 For Each sCharacter As String In m.Groups("commaseparatedcharacters").Value.TrimEnd(New Char() {","c, " "c}).Split(","c)
5429 sCharacter = sCharacter.Trim
5430 If Not InputMatchesCharacter(task, sCharacter, iNewRef, iItemNum, bExcepts) Then Return False
5431 iItemNum += 1
5432 Next
5433 End If
5434 If Not InputMatchesCharacter(task, m.Groups("character2").Value, iNewRef, iItemNum, bExcepts) Then Return False
5435 iItemNum += 1
5436 If Not InputMatchesCharacter(task, m.Groups("character3").Value, iNewRef, iItemNum, bExcepts) Then Return False
5437 Return True
5438 End If
5439
5440 Return InputMatchesCharacter(task, sInput, iNewRef, 0, bExcepts, bSecondChance)
5441
5442 End Function
5443
5444
5445 Private Function InputMatchesLocation(ByVal task As clsTask, ByVal sInput As String, ByVal iReferenceNum As Integer, ByVal iItemNum As Integer, Optional ByVal bExcepts As Boolean = False, Optional ByVal bSecondChance As Boolean = False) As Boolean
5446 Dim bResult As Boolean = False
5447 Dim bAddedLoc As Boolean = False
5448
5449 For Each l As clsLocation In Adventure.htblLocations.Values
5450 If System.Text.RegularExpressions.Regex.IsMatch(sInput, "^" & l.sRegularExpressionString() & "$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) Then
5451 bResult = True
5452 If Not bExcepts Then
5453 If Not bAddedLoc Then task.NewReferences(iReferenceNum).Items.Add(New clsSingleItem)
5454 bAddedLoc = True
5455
5456 task.NewReferences(iReferenceNum).Items(iItemNum).MatchingPossibilities.Add(l.Key)
5457 task.NewReferences(iReferenceNum).Items(iItemNum).bExplicitlyMentioned = True
5458 task.NewReferences(iReferenceNum).Items(iItemNum).sCommandReference = sInput
5459 Else
5460 For iItem As Integer = task.NewReferences(iReferenceNum).Items.Count - 1 To 0 Step -1
5461 Dim itm As clsSingleItem = task.NewReferences(iReferenceNum).Items(iItem)
5462 If itm.MatchingPossibilities.Contains(l.Key) Then itm.MatchingPossibilities.Remove(l.Key)
5463 If itm.MatchingPossibilities.Count = 0 Then task.NewReferences(iReferenceNum).Items.RemoveAt(iItem)
5464 Next
5465 End If
5466 End If
5467 Next
5468
5469 If Not bResult AndAlso bSecondChance AndAlso task.HasLocationExistRestriction Then
5470 ' TODO - This needs to check that it is the correct 'must exist' check, rather than just any
5471 ' If our task has a check that objects should exist, return True as a match so the task can deal with that in it's restrictions
5472 'task.NewReferences(iReferenceNum).Items.Add(New clsSingleItem)
5473 'task.NewReferences(iReferenceNum).Items(0).MatchingPossibilities.Add("NonExistingObject")
5474 'task.NewReferences(iReferenceNum).Items(0).bExplicitlyMentioned = False
5475 'task.NewReferences(iReferenceNum).Items(0).sCommandReference = sInput
5476 Return True
5477 End If
5478
5479 Return bResult
5480 End Function
5481
5482
5483 Private Function InputMatchesCharacter(ByVal task As clsTask, ByVal sInput As String, ByVal iReferenceNum As Integer, ByVal iItemNum As Integer, Optional ByVal bExcepts As Boolean = False, Optional ByVal bSecondChance As Boolean = False) As Boolean
5484 Dim bResult As Boolean = False
5485 Dim bAddedChar As Boolean = False
5486
5487 For Each ch As clsCharacter In Adventure.htblCharacters.Values
5488 If System.Text.RegularExpressions.Regex.IsMatch(sInput, "^" & ch.sRegularExpressionString() & "$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) Then
5489 bResult = True
5490 If Not bExcepts Then
5491 If Not bAddedChar Then task.NewReferences(iReferenceNum).Items.Add(New clsSingleItem)
5492 bAddedChar = True
5493
5494 task.NewReferences(iReferenceNum).Items(iItemNum).MatchingPossibilities.Add(ch.Key)
5495 task.NewReferences(iReferenceNum).Items(iItemNum).bExplicitlyMentioned = True
5496 task.NewReferences(iReferenceNum).Items(iItemNum).sCommandReference = sInput
5497 Else
5498 For iItem As Integer = task.NewReferences(iReferenceNum).Items.Count - 1 To 0 Step -1
5499 Dim itm As clsSingleItem = task.NewReferences(iReferenceNum).Items(iItem)
5500 If itm.MatchingPossibilities.Contains(ch.Key) Then itm.MatchingPossibilities.Remove(ch.Key)
5501 If itm.MatchingPossibilities.Count = 0 Then task.NewReferences(iReferenceNum).Items.RemoveAt(iItem)
5502 Next
5503 End If
5504 End If
5505 Next
5506
5507 If Not bResult AndAlso bSecondChance AndAlso task.HasCharacterExistRestriction Then
5508 ' TODO - This needs to check that it is the correct 'must exist' check, rather than just any
5509 ' If our task has a check that objects should exist, return True as a match so the task can deal with that in it's restrictions
5510 'task.NewReferences(iReferenceNum).Items.Add(New clsSingleItem)
5511 'task.NewReferences(iReferenceNum).Items(0).MatchingPossibilities.Add("NonExistingObject")
5512 'task.NewReferences(iReferenceNum).Items(0).bExplicitlyMentioned = False
5513 'task.NewReferences(iReferenceNum).Items(0).sCommandReference = sInput
5514 Return True
5515 End If
5516
5517 Return bResult
5518 End Function
5519
5520
5521 ' If the command contains asterixes, strip them out, then add them in one by one until we (possibly) get a match
5522 Friend Function GetRegularExpression(ByVal sCommand As String, ByVal sInput As String, ByVal bRightToLeft As Boolean) As List(Of System.Text.RegularExpressions.Regex)
5523 Dim lRegExs As New List(Of System.Text.RegularExpressions.Regex)
5524
5525 Try
5526 Dim options As System.Text.RegularExpressions.RegexOptions = System.Text.RegularExpressions.RegexOptions.IgnoreCase
5527 If bRightToLeft Then options = options Or System.Text.RegularExpressions.RegexOptions.RightToLeft
5528
5529 If sCommand.Contains("*") Then
5530 sCommand = sCommand.Replace("**", "*")
5531 Dim iAsterixCount As Integer = 0
5532 Dim sTestCommand As String = sCommand
5533
5534 While sTestCommand.Contains("*")
5535 sTestCommand = Replace(sTestCommand, "*", "", , 1)
5536 iAsterixCount += 1
5537 End While
5538
5539 ' We should really try all combinations of wildcard removal.
5540 ' E.g. " * %object * " should give us " * %object% " and " %object% * "
5541 ' otherwise we may always end up matching the object name in *
5542
5543 ' For * # * # * we want
5544 ' _ # _ # _
5545 ' * # _ # _
5546 ' _ # * # _
5547 ' _ # _ # *
5548 ' * # * # _
5549 ' * # _ # *
5550 ' _ # * # *
5551 ' * # * # *
5552
5553 For iAsterix As Integer = iAsterixCount - 1 To -1 Step -1
5554 sTestCommand = sCommand
5555 For i As Integer = 0 To iAsterix
5556 sTestCommand = Replace(sTestCommand, "*", "", , 1)
5557 Next
5558 Dim sPattern As String = ConvertToRE(sTestCommand)
5559 Dim re As New System.Text.RegularExpressions.Regex(sPattern, options)
5560 If sInput = "" OrElse re.IsMatch(sInput) Then lRegExs.Add(re) ' Return re
5561 Next
5562
5563 Return lRegExs ' Nothing
5564 Else
5565 Dim sPattern As String = ConvertToRE(sCommand)
5566 lRegExs.Add(New System.Text.RegularExpressions.Regex(sPattern, options))
5567 Return lRegExs
5568 End If
5569 Catch ex As Exception
5570 ErrMsg("Error in command """ & sCommand & """", ex)
5571 Return lRegExs
5572 End Try
5573 End Function
5574
5575 Private Function InputMatchesCommand(ByVal task As clsTask, ByVal sInput As String, ByVal sCommand As String, ByVal bSecondChance As Boolean, ByVal bRightToLeft As Boolean, Optional ByVal RegExs As List(Of System.Text.RegularExpressions.Regex) = Nothing) As Boolean
5576
5577 If RegExs Is Nothing Then RegExs = GetRegularExpression(sCommand, sInput, bRightToLeft)
5578
5579 For Each re As System.Text.RegularExpressions.Regex In RegExs
5580 Dim iNewReferences As Integer = 0
5581
5582 ' Clear the references
5583 If task.NewReferences IsNot Nothing Then
5584 For i As Integer = 0 To task.NewReferences.Length - 1
5585 task.NewReferences(i) = Nothing
5586 Next
5587 End If
5588
5589 If Not re.IsMatch(sInput) Then GoTo DoesntMatch
5590
5591 Dim sRefs As StringArrayList = task.References
5592
5593 For Each sGroupName As String In re.GetGroupNames
5594 Select Case sGroupName
5595 Case "objects"
5596 iNewReferences += 1
5597 task.NewReferences(iNewReferences - 1) = New clsNewReference(ReferencesType.Object)
5598 task.NewReferences(iNewReferences - 1).ReferenceMatch = sGroupName
5599
5600 Dim sObjectsInput As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5601 If Not InputMatchesObjects(task, sObjectsInput, iNewReferences - 1, , , bSecondChance) Then GoTo DoesntMatch ' Return False
5602
5603 Case "object1", "object2", "object3", "object4", "object5"
5604 iNewReferences += 1
5605 task.NewReferences(iNewReferences - 1) = New clsNewReference(ReferencesType.Object)
5606 task.NewReferences(iNewReferences - 1).ReferenceMatch = sGroupName
5607
5608 Dim sObjectInput As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5609 If Not InputMatchesObject(task, sObjectInput, iNewReferences - 1, 0, , , bSecondChance) Then GoTo DoesntMatch ' Return False
5610
5611 Case "characters"
5612 iNewReferences += 1
5613 task.NewReferences(iNewReferences - 1) = New clsNewReference(ReferencesType.Character)
5614 task.NewReferences(iNewReferences - 1).ReferenceMatch = sGroupName
5615
5616 Dim sCharactersInput As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5617 If Not InputMatchesCharacters(task, sCharactersInput, iNewReferences - 1, , bSecondChance) Then GoTo DoesntMatch
5618
5619 Case "character1", "character2", "character3", "character4", "character5"
5620 iNewReferences += 1
5621 task.NewReferences(iNewReferences - 1) = New clsNewReference(ReferencesType.Character)
5622 task.NewReferences(iNewReferences - 1).ReferenceMatch = sGroupName
5623
5624 Dim sCharacterInput As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5625 If Not InputMatchesCharacter(task, sCharacterInput, iNewReferences - 1, 0, , bSecondChance) Then GoTo DoesntMatch
5626
5627 Case "location1", "location2", "location3", "location4", "location5"
5628 iNewReferences += 1
5629 task.NewReferences(iNewReferences - 1) = New clsNewReference(ReferencesType.Location)
5630 task.NewReferences(iNewReferences - 1).ReferenceMatch = sGroupName
5631
5632 Dim sLocationInput As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5633 If Not InputMatchesLocation(task, sLocationInput, iNewReferences - 1, 0, , bSecondChance) Then GoTo DoesntMatch
5634
5635 Case "item1", "item2", "item3", "item4", "item5"
5636 iNewReferences += 1
5637 task.NewReferences(iNewReferences - 1) = New clsNewReference(ReferencesType.Item)
5638 task.NewReferences(iNewReferences - 1).ReferenceMatch = sGroupName
5639
5640 Dim sItemInput As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5641 If Not (InputMatchesObjects(task, sItemInput, iNewReferences - 1, , , bSecondChance) OrElse InputMatchesCharacter(task, sItemInput, iNewReferences - 1, 0, , bSecondChance) OrElse InputMatchesLocation(task, sItemInput, iNewReferences - 1, 0, , bSecondChance)) Then GoTo DoesntMatch
5642
5643 Case "direction1", "direction2", "direction3", "direction4", "direction5"
5644 iNewReferences += 1
5645 task.NewReferences(iNewReferences - 1) = New clsNewReference(ReferencesType.Direction)
5646 task.NewReferences(iNewReferences - 1).ReferenceMatch = sGroupName
5647
5648 Dim sDirInput As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5649 With task.NewReferences(iNewReferences - 1)
5650 Dim sDirTest As String = ""
5651 For dr As DirectionsEnum = DirectionsEnum.North To DirectionsEnum.NorthWest
5652 sDirTest = DirectionRE(dr, True, True)
5653 If System.Text.RegularExpressions.Regex.IsMatch(sDirInput, "^" & sDirTest & "$") Then
5654 .Items.Add(New clsSingleItem)
5655 .Items(0).MatchingPossibilities.Add(dr.ToString)
5656 .Items(0).sCommandReference = sDirInput
5657 Exit For
5658 End If
5659 Next
5660 End With
5661
5662 Case "number1", "number2", "number3", "number4", "number5"
5663 iNewReferences += 1
5664 task.NewReferences(iNewReferences - 1) = New clsNewReference(ReferencesType.Number)
5665 task.NewReferences(iNewReferences - 1).ReferenceMatch = sGroupName
5666
5667 Dim sNumber As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5668 With task.NewReferences(iNewReferences - 1)
5669 If System.Text.RegularExpressions.Regex.IsMatch(sNumber, "^-?[0-9]+$") Then
5670 Dim iRef As Integer = Math.Max(SafeInt(sGroupName.Replace("number", "")) - 1, 0)
5671 .Items.Add(New clsSingleItem)
5672 .Items(0).MatchingPossibilities.Add(sNumber)
5673 .Items(0).sCommandReference = sNumber
5674 End If
5675 End With
5676
5677 Case "text1", "text2", "text3", "text4", "text5"
5678 iNewReferences += 1
5679 task.NewReferences(iNewReferences - 1) = New clsNewReference(ReferencesType.Text)
5680 task.NewReferences(iNewReferences - 1).ReferenceMatch = sGroupName
5681
5682 Dim sText As String = re.Match(sInput).Groups(sGroupName).Value.Trim
5683 With task.NewReferences(iNewReferences - 1)
5684 If System.Text.RegularExpressions.Regex.IsMatch(sText, "^.*$") Then
5685 Dim iRef As Integer = Math.Max(SafeInt(sGroupName.Replace("text", "")) - 1, 0)
5686 .Items.Add(New clsSingleItem)
5687 .Items(0).MatchingPossibilities.Add(sText)
5688 .Items(0).sCommandReference = sText
5689 Adventure.sReferencedText(iRef) = sText
5690 End If
5691 End With
5692
5693 End Select
5694
5695 Next
5696
5697 Return True
5698 DoesntMatch:
5699 If sCommand.Contains("% %") AndAlso Not re.RightToLeft Then
5700 ' Ok, we have 2 references back to back. Try a match from right to left
5701 Return InputMatchesCommand(task, sInput, sCommand, bSecondChance, True)
5702 End If
5703 If Not bSecondChance AndAlso Not htblSecondChanceTasks.ContainsKey(task.Key) Then
5704 If iNewReferences > 0 AndAlso iNewReferences <= task.NewReferences.Length AndAlso (
5705 (task.NewReferences(iNewReferences - 1).ReferenceType = ReferencesType.Object AndAlso task.HasObjectExistRestriction) _
5706 OrElse (task.NewReferences(iNewReferences - 1).ReferenceType = ReferencesType.Character AndAlso task.HasCharacterExistRestriction) _
5707 OrElse (task.NewReferences(iNewReferences - 1).ReferenceType = ReferencesType.Location AndAlso task.HasLocationExistRestriction)) Then
5708 htblSecondChanceTasks.Add(task, task.Key)
5709 End If
5710 End If
5711 Next
5712 Return False
5713 End Function
5714
5715 Private Function CopyRef(ByVal ref As clsNewReference) As clsNewReference
5716
5717 Dim nr As clsNewReference = Nothing
5718
5719 If ref IsNot Nothing Then
5720 nr = New clsNewReference(ref.ReferenceType)
5721 For iItem As Integer = 0 To ref.Items.Count - 1
5722 Dim itm As New clsSingleItem
5723 itm.MatchingPossibilities = ref.Items(iItem).MatchingPossibilities.Clone
5724 itm.bExplicitlyMentioned = ref.Items(iItem).bExplicitlyMentioned
5725 itm.sCommandReference = ref.Items(iItem).sCommandReference
5726 nr.Items.Add(itm)
5727 Next
5728 nr.Index = ref.Index
5729 nr.ReferenceMatch = ref.ReferenceMatch
5730 End If
5731 Return nr
5732 End Function
5733
5734 Private Sub RefineMatchingPossibilitesUsingRestrictions(ByVal task As clsTask)
5735 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Checking scope: Applicable")
5736
5737 Dim NewRefs(task.NewReferencesWorking.Length - 1) As clsNewReference
5738
5739 Dim lAdded(task.NewReferencesWorking.Length - 1) As Generic.List(Of String)
5740
5741 For i As Integer = 0 To task.NewReferencesWorking.Length - 1
5742 lAdded(i) = New Generic.List(Of String)
5743 If task.NewReferencesWorking(i) IsNot Nothing Then
5744 NewRefs(i) = New clsNewReference(task.NewReferencesWorking(i).ReferenceType)
5745 NewRefs(i).Index = task.NewReferencesWorking(i).Index
5746 NewRefs(i).ReferenceMatch = task.NewReferencesWorking(i).ReferenceMatch
5747 End If
5748 Next
5749
5750 ' We have to try every combination of references against all the others to see if it is a successful combination
5751 If task.NewReferencesWorking IsNot Nothing AndAlso task.NewReferencesWorking.Length > 0 AndAlso task.NewReferencesWorking(0) IsNot Nothing Then
5752
5753 For Each itm0 As clsSingleItem In task.NewReferencesWorking(0).Items
5754
5755 Dim bAddedItem0 As Boolean = False
5756 ReDim NewReferences(0)
5757 NewReferences(0) = New clsNewReference(task.NewReferencesWorking(0).ReferenceType)
5758 NewReferences(0).Index = task.NewReferencesWorking(0).Index
5759 NewReferences(0).ReferenceMatch = task.NewReferencesWorking(0).ReferenceMatch
5760 Dim itmOut0 As New clsSingleItem
5761 itmOut0.sCommandReference = itm0.sCommandReference
5762
5763 For Each sKey0 As String In itm0.MatchingPossibilities
5764
5765 NewReferences(0).Items.Clear()
5766 Dim itmSingle0 As New clsSingleItem
5767 itmSingle0.MatchingPossibilities.Add(sKey0)
5768 NewReferences(0).Items.Add(itmSingle0)
5769
5770 If task.NewReferencesWorking.Length > 1 Then
5771
5772 For Each itm1 As clsSingleItem In task.NewReferencesWorking(1).Items
5773
5774 Dim bAddedItem1 As Boolean = False
5775 ReDim Preserve NewReferences(1)
5776 NewReferences(1) = New clsNewReference(task.NewReferencesWorking(1).ReferenceType)
5777 NewReferences(1).Index = task.NewReferencesWorking(1).Index
5778 NewReferences(1).ReferenceMatch = task.NewReferencesWorking(1).ReferenceMatch
5779 Dim itmOut1 As New clsSingleItem
5780 itmOut1.sCommandReference = itm1.sCommandReference
5781
5782 For Each sKey1 As String In itm1.MatchingPossibilities
5783
5784 NewReferences(1).Items.Clear()
5785 Dim itmSingle1 As New clsSingleItem
5786 itmSingle1.MatchingPossibilities.Add(sKey1)
5787 NewReferences(1).Items.Add(itmSingle1)
5788
5789 If task.NewReferencesWorking.Length > 2 Then
5790 ' TODO, when more than 2 refs...
5791 Else
5792 If PassRestrictions(task.arlRestrictions) Then
5793 If Not bAddedItem0 Then NewRefs(0).Items.Add(itmOut0)
5794 If Not bAddedItem1 Then NewRefs(1).Items.Add(itmOut1)
5795 If Not lAdded(0).Contains(sKey0) Then itmOut0.MatchingPossibilities.Add(sKey0)
5796 If Not lAdded(1).Contains(sKey1) Then itmOut1.MatchingPossibilities.Add(sKey1)
5797 bAddedItem0 = True
5798 bAddedItem1 = True
5799 If Not lAdded(0).Contains(sKey0) Then lAdded(0).Add(sKey0)
5800 If Not lAdded(1).Contains(sKey1) Then lAdded(1).Add(sKey1)
5801 End If
5802 End If
5803 Next sKey1
5804
5805 Next itm1
5806 Else
5807 If PassRestrictions(task.arlRestrictions) Then
5808 If Not bAddedItem0 AndAlso Not lAdded(0).Contains(sKey0) Then NewRefs(0).Items.Add(itmOut0)
5809 itmOut0.MatchingPossibilities.Add(sKey0)
5810 bAddedItem0 = True
5811 If Not lAdded(0).Contains(sKey0) Then lAdded(0).Add(sKey0)
5812 End If
5813 End If
5814
5815 Next sKey0
5816 Next itm0
5817
5818 End If
5819
5820 ' Check to see if this refined our possibilities to unique items
5821 Dim bCheckNextScope As Boolean = False
5822
5823 For iNR As Integer = 0 To NewRefs.Length - 1 ' Each nr As clsNewReference In NewRefs
5824 Dim nr As clsNewReference = NewRefs(iNR)
5825 Dim bResetRef As Boolean = False
5826 If nr IsNot Nothing AndAlso nr.Items IsNot Nothing Then
5827 If nr.Items.Count = 0 Then
5828 bCheckNextScope = True
5829 bResetRef = True
5830 End If
5831 For iI As Integer = 0 To nr.Items.Count - 1 ' Each itm As clsSingleItem In nr.Items
5832 Dim itm As clsSingleItem = nr.Items(iI)
5833 If itm.MatchingPossibilities.Count = 0 Then
5834 bCheckNextScope = True
5835 ' Reset refs to original
5836 If task.NewReferencesWorking(iNR).Items.Count > iI Then
5837 itm.MatchingPossibilities = task.NewReferencesWorking(iNR).Items(iI).MatchingPossibilities.Clone
5838 bResetRef = True
5839 End If
5840 ElseIf itm.MatchingPossibilities.Count > 1 Then
5841 bCheckNextScope = True
5842 ' Leave existing refs to further refine by visibility
5843 End If
5844 Next
5845 If bResetRef Then NewRefs(iNR) = CopyRef(task.NewReferences(iNR))
5846 End If
5847 Next
5848 If bCheckNextScope Then
5849 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Checking scope: Visible")
5850
5851 For Each nr As clsNewReference In NewRefs
5852 If nr IsNot Nothing Then
5853 For Each itm As clsSingleItem In nr.Items
5854 For i As Integer = itm.MatchingPossibilities.Count - 1 To 0 Step -1
5855 Select Case nr.ReferenceType
5856 Case ReferencesType.Object
5857 If Not Adventure.htblObjects(itm.MatchingPossibilities(i)).IsVisibleTo(Adventure.Player.Key) Then itm.MatchingPossibilities.RemoveAt(i)
5858 Case ReferencesType.Character
5859 If Not Adventure.htblCharacters(itm.MatchingPossibilities(i)).CanSeeCharacter(Adventure.Player.Key) Then itm.MatchingPossibilities.RemoveAt(i)
5860 Case ReferencesType.Direction, ReferencesType.Number, ReferencesType.Text
5861 ' Don't think these are applicable
5862 Case ReferencesType.Location
5863 ' Doesn't make sense to restrict by visible for Location
5864 Case ReferencesType.Item
5865 Dim sItemKey As String = itm.MatchingPossibilities(i)
5866 Dim ob As clsObject = Nothing
5867 Dim ch As clsCharacter = Nothing
5868 If Adventure.htblObjects.TryGetValue(sItemKey, ob) Then
5869 If Not ob.IsVisibleTo(Adventure.Player.Key) Then itm.MatchingPossibilities.RemoveAt(i)
5870 ElseIf Adventure.htblCharacters.TryGetValue(sItemKey, ch) Then
5871 If Not ch.CanSeeCharacter(Adventure.Player.Key) Then itm.MatchingPossibilities.RemoveAt(i)
5872 End If
5873 Case Else
5874 TODO("Refine visible possibilites for " & nr.ReferenceType.ToString & " references")
5875 End Select
5876 Next i
5877 Next itm
5878 End If
5879 Next nr
5880 End If
5881
5882 ' Check to see if this refined our possibilities to unique items
5883 bCheckNextScope = False
5884
5885 For iNR As Integer = 0 To NewRefs.Length - 1
5886 Dim nr As clsNewReference = NewRefs(iNR)
5887 Dim bResetRef As Boolean = False
5888 If nr IsNot Nothing AndAlso nr.Items IsNot Nothing Then
5889 If nr.Items.Count = 0 Then
5890 bCheckNextScope = True
5891 bResetRef = True
5892 End If
5893 For iI As Integer = nr.Items.Count - 1 To 0 Step -1
5894 Dim itm As clsSingleItem = nr.Items(iI)
5895 If itm.MatchingPossibilities.Count = 0 Then
5896 nr.Items.RemoveAt(iI)
5897 If nr.Items.Count = 0 Then
5898 bCheckNextScope = True
5899 ' Reset refs to original
5900 itm.MatchingPossibilities = task.NewReferencesWorking(iNR).Items(iI).MatchingPossibilities.Clone
5901 bResetRef = True
5902 Else
5903 ' We still have some items, so at least our Visible scope reduced from previous
5904 End If
5905 ElseIf itm.MatchingPossibilities.Count > 1 Then
5906 ' Leave existing refs to further refine by visibility
5907 bCheckNextScope = True ' JCW - Added 13/08/12 - not sure how we would be leaving to further refine otherwise...
5908 End If
5909 Next
5910 If bResetRef Then NewRefs(iNR) = CopyRef(task.NewReferences(iNR))
5911 End If
5912 Next
5913
5914 If bCheckNextScope Then
5915 DebugPrint(ItemEnum.Task, task.Key, DebugDetailLevelEnum.High, "Checking scope: Seen")
5916
5917 ' Remove any unseen references from our set
5918 For Each nr As clsNewReference In NewRefs
5919 If nr IsNot Nothing Then
5920 For Each itm As clsSingleItem In nr.Items
5921 For i As Integer = itm.MatchingPossibilities.Count - 1 To 0 Step -1
5922 Select Case nr.ReferenceType
5923 Case ReferencesType.Object
5924 If Not Adventure.htblObjects(itm.MatchingPossibilities(i)).SeenBy(Adventure.Player.Key) Then itm.MatchingPossibilities.RemoveAt(i)
5925 Case ReferencesType.Character
5926 If Not Adventure.htblCharacters(itm.MatchingPossibilities(i)).SeenBy(Adventure.Player.Key) Then itm.MatchingPossibilities.RemoveAt(i)
5927 Case ReferencesType.Location
5928 If Not Adventure.htblLocations(itm.MatchingPossibilities(i)).SeenBy(Adventure.Player.Key) Then itm.MatchingPossibilities.RemoveAt(i)
5929 End Select
5930 Next i
5931 Next itm
5932 End If
5933 Next nr
5934 End If
5935
5936 bCheckNextScope = False
5937
5938 ' Check to see if this refined our possibilities to unique items
5939 For iNR As Integer = 0 To NewRefs.Length - 1
5940 Dim nr As clsNewReference = NewRefs(iNR)
5941 Dim bResetRef As Boolean = False
5942 If nr IsNot Nothing AndAlso nr.Items IsNot Nothing Then
5943 If nr.Items.Count = 0 Then
5944 bCheckNextScope = True
5945 bResetRef = True
5946 End If
5947 For iI As Integer = 0 To nr.Items.Count - 1
5948 Dim itm As clsSingleItem = nr.Items(iI)
5949 If itm.MatchingPossibilities.Count = 0 Then
5950 bCheckNextScope = True
5951 bResetRef = True
5952 ElseIf itm.MatchingPossibilities.Count > 1 Then
5953 bCheckNextScope = True
5954 ' Leave existing refs to further refine by visibility
5955 End If
5956 Next
5957 If bResetRef Then NewRefs(iNR) = CopyRef(task.NewReferences(iNR))
5958 End If
5959 Next
5960
5961 task.NewReferencesWorking = NewRefs
5962 End Sub
5963
5964
5965 Private Function GetGeneralTask(ByVal sInput As String, ByVal iMinimumPriority As Integer, ByVal bSecondChance As Boolean) As String
5966 Dim iPriorityFail As Integer = Integer.MaxValue ' Lowest priority task that matches input and has output
5967 Dim sNoRefTask As String = "" ' We may match on a task, but find no references. If so, at least return this rather than no task at all
5968
5969 GetGeneralTask = Nothing
5970 If Not bSecondChance Then htblSecondChanceTasks.Clear()
5971 If iMinimumPriority > 0 AndAlso iMinimumPriority < iPriorityFail Then iPriorityFail = iMinimumPriority ' Because if we're continuing on from an earlier execution, we shouldn't run lower priority tasks
5972
5973 Try
5974 sAmbTask = Nothing
5975 Dim htblTasks As TaskHashTable = CType(IIf(bSecondChance, htblSecondChanceTasks, htblCompleteableGeneralTasks), TaskHashTable)
5976
5977 For Each tk As TaskKey In listTaskKeys
5978 If htblTasks.ContainsKey(tk.sTaskKey) Then
5979 Dim tas As clsTask = htblTasks(tk.sTaskKey)
5980
5981 If tas.Priority >= iMinimumPriority AndAlso Not (tas.LowPriority AndAlso tas.Priority > iPriorityFail) Then
5982
5983 ' Don't run Library tasks if this is a continuation task (v4)
5984 If iMinimumPriority > 0 AndAlso tas.IsLibrary AndAlso Adventure.dVersion < 5 Then
5985 GoTo FoundTask
5986 End If
5987
5988 For iCom As Integer = 0 To tas.arlCommands.Count - 1
5989 Dim sCom As String = tas.arlCommands(iCom)
5990
5991 If InputMatchesCommand(tas, sInput, sCom, bSecondChance, False, tas.RegExs(iCom)) Then
5992
5993 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.Medium, "Task '" & tas.Description & "' matches input.")
5994 iMatchedTaskCommand = iCom
5995
5996 ' Now see if user typed unique references (or none at all) which allow us to run the task
5997
5998 Dim bOkToRun As Boolean = True
5999
6000 tas.NewReferencesWorking = tas.CopyNewRefs(tas.NewReferences)
6001 ' If any refs are vague, refine using restrictions
6002 Dim bMatchesPreRefine As Boolean = True
6003 For Each nr As clsNewReference In tas.NewReferences
6004 If nr IsNot Nothing Then
6005 For Each itm As clsSingleItem In nr.Items
6006 If itm.MatchingPossibilities.Count <> 1 Then
6007 bMatchesPreRefine = False
6008 Exit For
6009 End If
6010 Next itm
6011 End If
6012 Next nr
6013
6014 ' Remove any references that don't pass the restrictions from our set
6015 RefineMatchingPossibilitesUsingRestrictions(tas)
6016
6017 ' If we still have at least one matching possibility in each reference item, then run this task, else we don't pass
6018 For Each nr As clsNewReference In tas.NewReferencesWorking
6019 If nr IsNot Nothing Then
6020 For Each itm As clsSingleItem In nr.Items
6021 If itm.MatchingPossibilities.Count = 0 Then
6022 ' Can we fall back to previous refs? We need to fire this task rather than fall thru to not understood...
6023 If bMatchesPreRefine Then
6024 tas.NewReferencesWorking = tas.CopyNewRefs(tas.NewReferences)
6025 Else
6026 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.High, "No matches found.")
6027 ' Should we perhaps fall back anyway and prompt for disambiguity - unless a lower priority one matches. Hmm.... may need
6028 ' to run the whole thing again with a different parameter.
6029 If sNoRefTask = "" Then sNoRefTask = tas.Key
6030 bOkToRun = False
6031 End If
6032 Exit For
6033 End If
6034 If itm.MatchingPossibilities.Count > 1 Then
6035 If sAmbTask Is Nothing Then
6036 ' We have an ambiguity that needs to be resolved
6037 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.High, "Multiple matches. Prompt for ambiguity.")
6038 sAmbTask = tas.Key
6039 Else
6040 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.High, "Multiple matches, but we already have an ambiguity.")
6041 End If
6042 bOkToRun = False
6043 End If
6044 Next itm
6045 End If
6046 Next nr
6047
6048 If bOkToRun Then
6049 ' Woo-hoo, we have a unique match!
6050 If tas.References.Count > 0 Then
6051 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.High, "Command matches without ambiguity.")
6052 Else
6053 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.High, "Command matches.")
6054 End If
6055
6056 NewReferences = tas.NewReferencesWorking
6057 Dim bDoesThisPass As Boolean = PassRestrictions(tas.arlRestrictions, , tas)
6058
6059 If Not bDoesThisPass AndAlso tas.FailOverride.ToString <> "" AndAlso sRestrictionText = "" AndAlso ContainsWord(sInput, "all") Then
6060 sRestrictionText = tas.FailOverride.ToString
6061 End If
6062
6063 ' If we pass restrictions, or if we haven't yet passed but we have output
6064
6065 If bDoesThisPass OrElse sRestrictionText <> "" Then
6066 If bDoesThisPass Then
6067 If tas.Priority > iPriorityFail Then
6068 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.Medium, "Task passes restrictions and overrides previous failing task output")
6069 Else
6070 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.Medium, "Task passes restrictions.")
6071 End If
6072 ElseIf sRestrictionText <> "" Then
6073 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.Medium, "Task doesn't pass restrictions, but is current highest priority failing task with restriction output.")
6074 End If
6075
6076 GetGeneralTask = tas.Key
6077 If sRestrictionText <> "" Then iPriorityFail = tas.Priority
6078
6079 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.High, "Task priority: " & tas.Priority)
6080
6081 If bDoesThisPass OrElse Adventure.TaskExecution = clsAdventure.TaskExecutionEnum.HighestPriorityTask Then GoTo FoundTask
6082
6083 Else
6084 DebugPrint(ItemEnum.Task, tas.Key, DebugDetailLevelEnum.Medium, "Task does not pass restrictions.")
6085 End If
6086
6087 Exit For ' task
6088 End If
6089
6090 End If
6091 Next
6092 End If
6093 End If
6094 Next
6095 FoundTask:
6096
6097 If GetGeneralTask Is Nothing AndAlso sNoRefTask <> "" Then GetGeneralTask = sNoRefTask
6098
6099 If GetGeneralTask Is Nothing AndAlso sAmbTask Is Nothing AndAlso Not bSecondChance Then
6100 ' Ok, no luck. Let's go back and see if one of our 'exist' tasks worked
6101 DebugPrint(ItemEnum.Task, "", DebugDetailLevelEnum.Medium, "No matches found. Checking again using existance.")
6102 Return GetGeneralTask(sInput, iMinimumPriority, True)
6103 End If
6104 Catch ex As Exception
6105 ErrMsg("GetGeneralTask Error", ex)
6106 End Try
6107 End Function
6108
6109
6110 Private Function IsNoun(ByVal sName As String) As Boolean
6111 Dim re As New System.Text.RegularExpressions.Regex("")
6112 For Each ob As clsObject In Adventure.htblObjects.Values
6113 Dim sOb As String = ob.sRegularExpressionString
6114 If System.Text.RegularExpressions.Regex.IsMatch(sName, "^" & sOb & "s?$") Then Return True
6115 Next ob
6116 Return False
6117 End Function
6118
6119
6120 ''' <summary>
6121 ''' Converts a lazy Advanced Command to strict format, removing possibility for double spaces
6122 ''' </summary>
6123 ''' <param name="sCommand"></param>
6124 ''' <returns></returns>
6125 ''' <remarks></remarks>
6126 Public Function CorrectCommand(ByVal sCommand As String) As String
6127 Dim sNewCommand As String = ProcessBlock(sCommand)
6128 If sNewCommand <> sCommand Then
6129 Debug.WriteLine(String.Format("Converted ""{0}"" to ""{1}""", sCommand, sNewCommand))
6130 sCommand = sCommand
6131 End If
6132 Return sNewCommand
6133 End Function
6134
6135 ' E.g. from "get {the} ball" > "get ", from "{the} ball" > "the", " ball" > ""
6136 Private Function GetSubBlock(ByRef sBlock As String) As String
6137 Dim iDepth As Integer = 0
6138 Dim sNewBlock As String = ""
6139
6140 For i As Integer = 0 To sBlock.Length - 1
6141 sNewBlock &= sBlock(i)
6142 Select Case sBlock(i)
6143 Case "{"c, "["c
6144 If iDepth = 0 AndAlso sNewBlock <> sBlock(i) Then
6145 sBlock = sRight(sBlock, sBlock.Length - sNewBlock.Length + 1)
6146 Return sLeft(sNewBlock, i)
6147 End If
6148 iDepth += 1
6149 Case "]"c, "}"c
6150 iDepth -= 1
6151 If iDepth = 0 Then
6152 sBlock = sRight(sBlock, sBlock.Length - sNewBlock.Length)
6153 Return sNewBlock
6154 End If
6155 Case "/"c
6156 If iDepth = 0 Then
6157 sBlock = sRight(sBlock, sBlock.Length - sNewBlock.Length)
6158 Return sNewBlock
6159 End If
6160 End Select
6161 Next
6162 sBlock = ""
6163 Return sNewBlock
6164 End Function
6165
6166 ' Returns True if any part of the block is mandatory (either inside [] or not in brackets at all)
6167 Private Function ContainsMandatoryText(ByVal sBlock As String) As Boolean
6168 If sBlock = "" Then Return False
6169
6170 Dim iLevel As Integer = 0
6171 For i As Integer = 0 To sBlock.Length - 1
6172 Select Case sBlock(i)
6173 Case " "c
6174 ' Ignore
6175 Case "{"c
6176 iLevel += 1
6177 Case "}"c
6178 iLevel -= 1
6179 Case Else
6180 If iLevel = 0 Then Return True
6181 End Select
6182 Next
6183 Return False
6184 End Function
6185
6186 ' A block should be the complete entry between two brackets, or between a bracket and a slash
6187 Private Function ProcessBlockOld(ByVal sBlock As String) As String
6188 Dim sAfter As String = sBlock
6189 Dim sNextBlock As String = ""
6190 Dim sBefore As String = ""
6191
6192 Do
6193 sNextBlock = GetSubBlock(sAfter)
6194 If sNextBlock <> "" Then
6195 If sNextBlock.StartsWith("{") Then
6196 ' */ "] {#} {" => "]{ #}{"
6197 ' "] {#} [" => ?
6198 ' "} {#} [" => ?
6199 ' "} {#} {" => ? /*
6200 ' "{#} " => "{# }" if block starts with open bracket
6201 ' " {#} " => " {# }"
6202 ' "}{#} " => "}{# }" -- should this be " }{#} " => " }{# }" ?
6203 If (sBefore = "" OrElse sRight(sBefore, 1) = " " OrElse sRight(sBefore, 1) = "}") AndAlso sAfter.StartsWith(" ") Then
6204 If sNextBlock.Contains("/") Then
6205 sNextBlock = "{[" & sLeft(sNextBlock.Substring(1), sNextBlock.Length - 2) & "] }"
6206 Else
6207 sNextBlock = sLeft(sNextBlock, sNextBlock.Length - 1) & " }"
6208 End If
6209 sAfter = sRight(sAfter, sAfter.Length - 1)
6210 End If
6211
6212 ' End block
6213 ' " {#}" => "{ #}" or "{ [#/#]}
6214 If sBefore.EndsWith(" ") AndAlso sAfter = "" Then
6215 If sNextBlock.Contains("/") Then
6216 sNextBlock = "{ [" & sLeft(sNextBlock.Substring(1), sNextBlock.Length - 2) & "]}"
6217 Else
6218 sNextBlock = "{ " & sLeft(sNextBlock.Substring(1), sNextBlock.Length - 1)
6219 End If
6220 sBefore = sLeft(sBefore, sBefore.Length - 1)
6221 End If
6222 sBefore &= "{" & ProcessBlock(sMid(sNextBlock, 2, sNextBlock.Length - 2)) & "}"
6223 ElseIf sNextBlock.StartsWith("[") Then
6224 sBefore &= "[" & ProcessBlock(sMid(sNextBlock, 2, sNextBlock.Length - 2)) & "]"
6225 ElseIf sNextBlock.EndsWith("/") Then
6226 sBefore &= ProcessBlock(sLeft(sNextBlock, sNextBlock.Length - 1)) & "/"
6227 Else
6228 sBefore &= sNextBlock
6229 End If
6230 End If
6231 Loop While sAfter <> ""
6232 Return sBefore
6233 End Function
6234
6235 ' A block should be the complete entry between two brackets, or between a bracket and a slash
6236 Private Function ProcessBlock(ByVal sBlock As String) As String
6237 Dim sAfter As String = sBlock
6238 Dim sNextBlock As String = ""
6239 Dim sBefore As String = ""
6240
6241 Do
6242 sNextBlock = GetSubBlock(sAfter)
6243 If sNextBlock <> "" Then
6244 If sNextBlock.StartsWith("{") Then
6245 ' */ "] {#} {" => "]{ #}{"
6246 ' "] {#} [" => ?
6247 ' "} {#} [" => ?
6248 ' "} {#} {" => ? /*
6249 ' "{#} " => "{# }" if block starts with open bracket
6250 ' " {#} " => " {# }"
6251 ' "}{#} " => "}{# }" -- should this be " }{#} " => " }{# }" ?
6252
6253 Dim bContainsMandatory As Boolean = ContainsMandatoryText(sAfter)
6254 If bContainsMandatory AndAlso sAfter.StartsWith(" ") Then
6255 ' If before final [] block then _{x}_ => _{x_}
6256 If sBefore = "" OrElse sBefore.EndsWith(" ") OrElse sBefore.EndsWith("}") Then
6257 If sNextBlock.Contains("/") Then
6258 sNextBlock = "{[" & sLeft(sNextBlock.Substring(1), sNextBlock.Length - 2) & "] }"
6259 Else
6260 sNextBlock = sLeft(sNextBlock, sNextBlock.Length - 1) & " }"
6261 End If
6262 sAfter = sRight(sAfter, sAfter.Length - 1)
6263 End If
6264 ElseIf Not bContainsMandatory AndAlso sBefore.EndsWith(" ") Then
6265 ' If after final [] block then _{x}_ => {_x}_
6266 If sNextBlock.Contains("/") Then
6267 sNextBlock = "{ [" & sLeft(sNextBlock.Substring(1), sNextBlock.Length - 2) & "]}"
6268 Else
6269 sNextBlock = "{ " & sLeft(sNextBlock.Substring(1), sNextBlock.Length - 1)
6270 End If
6271 sBefore = sLeft(sBefore, sBefore.Length - 1)
6272 End If
6273
6274 ' End block
6275 ' " {#}" => "{ #}" or "{ [#/#]}
6276 If sBefore.EndsWith(" ") AndAlso sAfter = "" Then
6277 If sNextBlock.Contains("/") Then
6278 sNextBlock = "{ [" & sLeft(sNextBlock.Substring(1), sNextBlock.Length - 2) & "]}"
6279 Else
6280 sNextBlock = "{ " & sLeft(sNextBlock.Substring(1), sNextBlock.Length - 1)
6281 End If
6282 sBefore = sLeft(sBefore, sBefore.Length - 1)
6283 End If
6284 sBefore &= "{" & ProcessBlock(sMid(sNextBlock, 2, sNextBlock.Length - 2)) & "}"
6285 ElseIf sNextBlock.StartsWith("[") Then
6286 sBefore &= "[" & ProcessBlock(sMid(sNextBlock, 2, sNextBlock.Length - 2)) & "]"
6287 ElseIf sNextBlock.EndsWith("/") Then
6288 sBefore &= ProcessBlock(sLeft(sNextBlock, sNextBlock.Length - 1)) & "/"
6289 Else
6290 sBefore &= sNextBlock
6291 End If
6292 End If
6293 Loop While sAfter <> ""
6294 Return sBefore
6295 End Function
6296
6297 Private sDirectionsRE As String
6298 Public Function ConvertToRE(ByVal sCommand As String, Optional ByVal bReplaceRefs As Boolean = True, Optional ByVal bTerminate As Boolean = True) As String
6299 Dim sC As String = sCommand
6300
6301 ' Convert any special RE characters
6302 sC = sC.Replace("+", "\+").Replace("(", "\(").Replace(")", "\)")
6303
6304 ' Convert wildcards
6305 sC = sC.Replace(" * ", " ([[#]] )?")
6306 sC = sC.Replace("* ", "([[#]] )?")
6307 sC = sC.Replace(" *", "( [[#]])?")
6308 sC = sC.Replace("*", "[[#]]")
6309 sC = sC.Replace("[[#]]", ".*?")
6310
6311 sC = sC.Replace("_", " ")
6312
6313 ' Convert optional text and mandatory text
6314 sC = sC.Replace("{", "(").Replace("}", ")?").Replace("[", "(").Replace("]", ")").Replace("/", "|")
6315
6316 If bReplaceRefs Then
6317 ' Replace references
6318 If sDirectionsRE Is Nothing Then
6319 For eDirection As DirectionsEnum = DirectionsEnum.North To DirectionsEnum.NorthWest
6320 sDirectionsRE &= Adventure.sDirectionsRE(eDirection).ToLower.Replace("/", "|")
6321 If eDirection <> DirectionsEnum.NorthWest Then sDirectionsRE &= "|"
6322 Next
6323 End If
6324 sC = sC.Replace("%direction%", "(?<direction>" & sDirectionsRE & ")")
6325 ' TODO - replace above with custom names if changed
6326
6327 sC = sC.Replace("%objects%", "(?<objects>.+?)")
6328 sC = sC.Replace("%characters%", "(?<characters>.+?)")
6329
6330 For iref As Integer = 1 To 5
6331 sC = sC.Replace("%object" & iref & "%", "(?<object" & iref & ">.+?)")
6332 sC = sC.Replace("%character" & iref & "%", "(?<character" & iref & ">.+?)")
6333 sC = sC.Replace("%number" & iref & "%", "(?<number" & iref & ">-?[0-9]+)")
6334 sC = sC.Replace("%text" & iref & "%", "(?<text" & iref & ">.+?)")
6335 sC = sC.Replace("%location" & iref & "%", "(?<location" & iref & ">.+?)")
6336 sC = sC.Replace("%item" & iref & "%", "(?<item" & iref & ">.+?)")
6337 sC = sC.Replace("%direction" & iref & "%", "(?<direction" & iref & ">" & sDirectionsRE & ")")
6338 Next
6339 End If
6340 sC = sC.Trim
6341
6342 If bTerminate Then
6343 Return "^" & sC & "$"
6344 Else
6345 Return sC
6346 End If
6347 End Function
6348
6349 Private Function GetHtblKeys(ByVal sRefType As String, ByVal iRef As Integer) As System.Collections.ICollection
6350 Select Case sRefType
6351 Case "ReferencedObject1", "ReferencedObject2", "ReferencedObject3", "ReferencedObject4", "ReferencedObject5", "ReferencedObjects"
6352 Return Adventure.htblObjects.Keys
6353 Case "ReferencedDirection", "number", "character", "text"
6354 Return New Collection
6355 Case Else
6356 iRef = iRef
6357 End Select
6358
6359 Return Nothing
6360 End Function
6361
6362 Private Function GetHtblAtPos(ByVal htbl As Hashtable, ByVal iPos As Integer) As Object
6363 Dim iCounter As Integer = 0
6364 For Each item As Object In htbl.Values
6365 iCounter += 1
6366 If iCounter = iPos Then Return item
6367 Next
6368
6369 Return Nothing
6370 End Function
6371
6372
6373 ' Returns the number of references in a task
6374 Private Function NumberOfRefs(ByVal cTask As clsTask) As Integer
6375 Dim sTokens() As String = cTask.arlCommands(0).Split(" "c)
6376 Dim iNoRefs As Integer = 0
6377
6378 For Each sToken As String In sTokens
6379 Select Case sToken
6380 Case "%character%", "%characters", "%direction%", "%number%", "%numbers%", "%object1%", "%object2%", "%object3%", "%object4%", "%object5%", "%objects%", "%text%", "%location%"
6381 iNoRefs += 1
6382 End Select
6383 Next
6384
6385 Return iNoRefs
6386 End Function
6387
6388 #If Not Adravalon Then
6389 Private Sub tmrEvents_Tick(sender As Object, e As EventArgs) Handles tmrEvents.Tick
6390 TimeBasedStuff()
6391 End Sub
6392 #Else
6393 ' Frontend will have the timer and call TimeBasedStuff() directly.
6394 #End If
6395
6396 End Class