JavaScript EditorFree JavaScript Editor     Ajax Editor 

Main Page
  Previous Section Next Section

Getting Input from the Outside World

Since a text-based game uses the keyboard as its sole input device, we should take some time to make this as easy as possible. The player will be typing in sentences to command the text game to do something. This seems simple enough, but the problem is how to read these sentences. The standard function scanf() won't work correctly because of the possibility of whitespace and multiple arguments. We need a function that will get a line of input regardless of the characters that make up the line. This input will stop if and only if the user hits the Enter key. At this point, the sentence will be passed to the next piece of software in the parser chain. So the question is how to get a single line of text without the input line editor making decisions for us? The answer is to use single-character input and build up a string until the carriage return is pressed. This can be done using the getch() function with a tests for backspace and carriage return. Listing 14.1 is a typical line input function.

Listing 14.1 A Single-Line Input Function with Editing Capability
char *Get_Line(char *buffer)
// this function gets a single line of input and tolerates white space

int c,index=0;

// loop while user hasn't hit return
// implement backspace
     if (c==8 && index>0)

        buffer[--index] = ' ';
        printf("%c %c",8,8);

        }  // end if backspace
     if (c>=32 && c<=122)
        buffer[index++] = c;

        }  // end if in printable range

     }  // end while

// terminate string
buffer[index] = 0;
// return pointer to buffer or NULL
if (strlen(buffer)==0)

}  // end Get_Line

The function takes as a parameter a pointer to a buffer where the inputted string will be placed after the function executes. During execution, Get_Line() will allow the user to input a line of text and also to edit errors via the backspace key. As the characters are input, they are echoed out to the screen, so the user can see what he/she is typing. When the user hits the Enter key, the string is terminated with a NULL and the function ends.

Once the user has input the string, the game is ready to parse it. The parsing process has many phases (which we will cover shortly), but before we can parse the sentence and see what it means, we must know what the language is and how it is constructed.

      Previous Section Next Section

    JavaScript EditorAjax Editor     JavaScript Editor