program HowToRespondToKeystrokes; uses SwinGame,sgTypes; procedure Main(); var clr : LongWord; begin OpenGraphicsWindow('Keyboard Input' ,240 ,180 ); LoadDefaultColors(); clr := RGBAColor(255 ,255 ,255 ,64 ); ClearScreen(ColorWhite ); repeat ProcessEvents(); FillRectangle(clr ,0 ,0 ,240 ,180 ); if KeyReleased(vk_a ) then DrawText('A Release' ,ColorBlue ,'Arial' ,14 ,20 ,40 ); if KeyTyped(vk_a ) then DrawText('A Typed' ,ColorGreen ,'Arial' ,14 ,20 ,70 ); if KeyDown(vk_a ) then DrawText('A Down' ,ColorRed ,'Arial' ,14 ,20 ,100 ); if KeyUp(vk_a ) then DrawText('A Up' ,ColorTurquoise ,'Arial' ,14 ,20 ,130 ); DrawText('KeyBoard Input' ,ColorRed ,'Arial' ,18 ,60 ,15 ); RefreshScreen(60 ); until WindowCloseRequested() or KeyTyped(vk_ESCAPE ) or KeyTyped(vk_q ); ReleaseAllResources(); end; begin Main(); end.
How To Respond To Keystrokes
This intermediate level how to explains how to receive and act upon the different states of a keyboard strokes. For example, KeyDown, KeyUp, or KeyTyped. Using these in your program is essential for performing and handling events such as Fire a bullet in a space simulation game, or moving a person to a new location.
ProcessEvents listens to user interactions with your game including key strokes.
The Input API offers many methods for testing key strokes. AnyKeyPresses, KeyDown, KeyUp, KeyTyped, MouseDown, MouseX or MouseY. Explore the Input API to To validate any event you must begin by calling ProcessEvents in your code. This starts SwinGame listening for events. Hitting a key is an event. You need to listen for them and test if the key pressed is the one you need.
In the code below you can see how various key strokes are tested and the reaction to the event if the test is TRUE.
- Create a simple game that moves an image or a sprite across the screen.
- Create a simple program that controls the volume playback of a piece of music.