number guess purebasic conversion
Posted: Wed Aug 05, 2020 6:43 am
Hi All. I was taking a python course(slow interpreted language), and I thought I would convert some of the exercises to speedy executable PureBasic code just to see how easy it would be. So I started with a simple guess your number program in a window. What was trivial in the console was far more complicated for me in a window. I've always struggled with event driven programming, but I've committed to learning much more about it. My first problem is having two event loops, I've heard you should always try to have only one event loop in your program, but then I can't exit gracefully from the program. I thought of just having a timer delay after the program is over, with AddWindowTimer or like a hit any key to end the program, but the way I did it with shortcuts to the window would entail me to put in every key on the keyboard as shortcuts. I thought of Examine_Keyboard and Keyboard_inkey, but in the help it seems these are more for game applications. Of course that may not be the case. Any help to point me in the right direction would be appreciated.
Code: Select all
high = 101
low = 0
guess = 50
guessed = #False
x=0
Window_0 = OpenWindow(#PB_Any, 0, 0, 800, 600, "I Guess Number",#PB_Window_SystemMenu | #PB_Window_SizeGadget | #PB_Window_ScreenCentered)
If IsWindow(Window_0)
AddKeyboardShortcut(Window_0,#PB_Shortcut_C ,1)
AddKeyboardShortcut(Window_0,#PB_Shortcut_L ,2)
AddKeyboardShortcut(Window_0,#PB_Shortcut_H ,3)
AddKeyboardShortcut(Window_0,#PB_Shortcut_Escape ,4)
Editor_0 = EditorGadget(#PB_Any, 0,0,800,600)
Font2 = LoadFont(#PB_Any, "Verdana", 12)
SetGadgetFont(Editor_0, FontID(Font2))
AddGadgetItem(Editor_0, -1, "Please think of a number between 0 and 100!")
AddGadgetItem(Editor_0, -1, "Enter 'h' To indicate high guess, 'l' To indicate low guess, " + #LF$ + "And 'c' To indicate correct guess.")
While Not guessed
guess = (high + low) / 2
AddGadgetItem(Editor_0, -1, "Is your secret number " + Str(guess) + "?")
Repeat
Event = WaitWindowEvent()
If Event = #PB_Event_CloseWindow ; If the user has pressed on the close button
End
EndIf
MenuID = EventMenu()
Select Event
Case #PB_Event_Menu
Select MenuID
Case 1
AddGadgetItem(Editor_0, -1, "Game over. Your secret number was " + Str(guess))
guessed = #True
Break
Case 2
low = guess
Break
Case 3
high = guess
Break
Case 4
End
EndSelect
EndSelect
ForEver
Wend
Repeat
Event = WaitWindowEvent()
MenuID = EventMenu()
Select Event
Case #PB_Event_Menu
Select MenuID
Case 4
End
EndSelect
EndSelect
Until Event = #PB_Event_CloseWindow
Else
MessageRequester("Error","Could Not Open Window")
End
EndIf