プログラミング講座(154) テキストアドベンチャーゲーム

以前、Small Basic フォーラムでテキストベースアドベンチャーゲームについて質問を受けたことがありました。そのときに作ったプログラムを今回少しずつ手直ししてみようと思います。最初のプログラムは FCD758-0 です。
プログラムの冒頭
プログラムの冒頭はこんな感じです。プログラムで何度も利用する選択肢を選ぶ処理 Choose をサブルーチンにして、プログラムを簡略化するよう、工夫しています。
stage_0:
TextWindow.Writeline(“You’re at a fork in the road.”)
TextWindow.Writeline(“Which way do you go? “)
choices=”LEFT,RIGHT,STAY”
Choose()
If id = 1 Then
 Goto stage_1_1
ElseIf id = 2 Then
 Goto stage_1_2
ElseIf id = 3 Then
 Goto stage_1_3
Else
 TextWindow.WriteLine(“Invalid choise.”)
 Goto stage_0
EndIf
1つめのステージ
選んだ選択肢によって1つめのステージが3つに分かれています。
stage_1_1:
TextWindow.Writeline(“Good choice, you find some money. :)”)
TextWindow.Writeline(“Have a nice day.”)
Goto end
stage_1_2:
stage_1_3:
ラストシーン
このサンプルでは改行だけしました。
end:
TextWindow.Writeline(“”)
‘ end of program
選択肢の処理
ちょっと懲りすぎかもしれませんが、カンマで区切った選択肢を与えると選んだ結果を番号 (id) で返すというサブルーチンを作りました。この処理自体は少々長いですが、このサブルーチンを呼び出すことで、メイン側の負担を減らしています。
Sub Choose
 ’ param choices – e.g. “A,B,C”
 ’ return id – e.g. 1 for A
 ’ work a,c,choice,i,len,n,p,u – will be broken
 ’ Make array of choice
 len = Text.GetLength(choices)
 p = 1
 i = 0
 While p <= len
  c = Text.GetIndexOf(Text.GetSubTextToEnd(choices,p), ",")
  If c = 0 Then
   c = len + 1
  Else
   c = c + p – 1
  EndIf
  i = i + 1
  choice[i] = Text.GetSubText(choices, p, c – p)
  p = c + 1
 EndWhile
 ' Dispaly choices
 n = i
 For i = 1 To n
  TextWindow.Write(choice[i])
  If i < n – 1 Then
   TextWindow.Write(" ")
  ElseIf i = n – 1 Then
   TextWindow.Write(" or ")
  EndIf
 EndFor
 TextWindow.WriteLine("")
 ' Input
 a = TextWindow.Read()
 ' Convert to upper case
 u = Text.ConvertToUpperCase(a)
 ' Search id of choces
 id = n
 While choice[id] u And 0 < id
  id = id – 1
 EndWhile
EndSub
プログラムは以上です。次回以降このプログラムを少しずつ改良していこうと思います。
(つづく)

コメントを残す