Вопрос

Making a textbased game. I have a command prompt its made from richtextbox as outputbox and textbox for inputtextbox. i need to make some commands like "cls" "dir" "config". lots of more commands in my list. i just stuck how to that and how to approach to solution. Here is my code i tyred some of 'em with select case method but its too primitive.

    Private Sub Output(s As String)
    If s <> "" Then
        nCounter = nCounter + 1
        sCounter = Convert.ToString(nCounter)
        consoleoutputbox.AppendText(vbCrLf & sCounter & " " & s)
    End If
End Sub
Private Sub consoleinputbox_KeyDown(sender As Object, e As KeyEventArgs) Handles consoleinputbox.KeyDown
    Dim Command As String = consoleinputbox.Text
    If e.KeyCode = Keys.Enter Then
        If Command <> "" Then
            Select Case Command
                Case "cls"
                    consoleoutputbox.Clear()
                    consoleinputbox.Clear()
                    consoleinputbox.Focus()
                    nCounter = 0
                Case "help"
                    Output("Welcome to help section. Avaliable commands:")
                    Output("help, cls")
                Case Else
                    Output(Command)
                    consoleinputbox.Clear()
                    consoleinputbox.Focus()
            End Select
        End If
    End If
End Sub
Это было полезно?

Решение

Perhaps a Dictionary(Of String, Action) would help. Put each thing(s) you want done into sub routines and add them to the dictionary with the command as the key:

Dim Commands As New Dictionary(Of String, Action)
Commands.Add("test1", New Action(AddressOf test))

Then just pass the string to the dictionary as the index and invoke the sub routine

Commands("test1").Invoke()

Другие советы

One option might be to define a module and add methods named after your commands. You could then use Reflection to find and invoke the method with the name entered by the user as a command.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top