KeyDown() / JoyDown()

Share your advanced PureBasic knowledge/code with the community.
User avatar
Fluid Byte
Addict
Addict
Posts: 2336
Joined: Fri Jul 21, 2006 4:41 am
Location: Berlin, Germany

KeyDown() / JoyDown()

Post by Fluid Byte »

Just needed this for my game. Maybe this should be integrated natively like in BlitzBasic.

Code: Select all

Enumeration
	#PB_Joy_Left
	#PB_Joy_Right
	#PB_Joy_Up
	#PB_Joy_Down
	#PB_Joy_1
	#PB_Joy_2
	#PB_Joy_3
	#PB_Joy_4
	#PB_Joy_5
	#PB_Joy_7
	#PB_Joy_8
	#PB_Joy_9
	#PB_Joy_10
	#PB_Joy_11
	#PB_Joy_12
	#PB_Joy_13
	#PB_Joy_14
	#PB_Joy_15
	#PB_Joy_16
EndEnumeration

Global Dim KeyState(211)
Global Dim JoyState(19)

Procedure KeyDown(Key)
	Protected Result = KeyboardPushed(Key)
	
	If Result
		If KeyState(Key) : Result = 0 : EndIf		
		KeyState(Key) = #True		
		ProcedureReturn Result		
	EndIf	
	
	If KeyboardPushed(Key) = 0 : KeyState(Key) = #False : EndIf
EndProcedure

Procedure JoyDown(Joystick,Button)
	Protected Result
	
	Select Button
		Case #PB_Joy_Left  : If JoystickAxisX(Joystick) = -1 : Result = 1 : EndIf			
		Case #PB_Joy_Right : If JoystickAxisX(Joystick) =  1 : Result = 1 : EndIf			
		Case #PB_Joy_Up    : If JoystickAxisY(Joystick) = -1 : Result = 1 : EndIf			
		Case #PB_Joy_Down  : If JoystickAxisY(Joystick) =  1 : Result = 1 : EndIf
		Case #PB_Joy_1 To #PB_Joy_16
		Result = JoystickButton(Joystick,Button - #PB_Joy_Down)
	EndSelect
	
	If Result
		If JoyState(Button) : Result = 0 : EndIf		
		JoyState(Button) = #True
		ProcedureReturn Result
	EndIf	
	
	If Button > #PB_Joy_Down And JoystickButton(Joystick,Button - #PB_Joy_Down) = 0
		JoyState(Button) = #False
	EndIf
	
	If JoystickAxisX(Joystick) = 0 : JoyState(Button) = #False : EndIf
	If JoystickAxisY(Joystick) = 0 : JoyState(Button) = #False : EndIf
EndProcedure
Small example:

Code: Select all

InitSprite() : InitKeyboard() : InitJoystick()

OpenWindow(0,0,0,640,480,"void",#PB_Window_SystemMenu | #PB_Window_ScreenCentered)
OpenWindowedScreen(WindowID(0),0,0,640,480,0,0,0)

Color = #Red

Repeat
	Repeat
		EventID = WindowEvent()
		
		Select EventID
			Case #PB_Event_CloseWindow : End 
		EndSelect
	Until Event = 0
	
	ExamineKeyboard()
	ExamineJoystick(0)
	
	If KeyDown(#PB_Key_Left) Or JoyDown(0,#PB_Joy_Left) : X - 50 : EndIf
	If KeyDown(#PB_Key_Right) Or JoyDown(0,#PB_Joy_Right) : X + 50 : EndIf
	If KeyDown(#PB_Key_Up) Or JoyDown(0,#PB_Joy_Up) : Y - 50 : EndIf
	If KeyDown(#PB_Key_Down) Or JoyDown(0,#PB_Joy_Down) : Y + 50 : EndIf
	
	If KeyDown(#PB_Key_Space) Or JoyDown(0,#PB_Joy_1) : Color = Random($FFFFFF) : EndIf
	
	ClearScreen(0)
	
	StartDrawing(ScreenOutput())
	Box(X,Y,100,100,Color)
	StopDrawing()
	FlipBuffers()	
Until KeyboardPushed(#PB_Key_Escape)
Windows 10 Pro, 64-Bit / Whose Hoff is it anyway?