Introduction to Interactive Programming in Python - Week 3
Week 3 introduces the basics of event-driven programming and covers the differences between local and global variables. This week's mini project is "Guess the Number", a simple game where the player attempts to guess a randomly generated secret number in a certain number of tries.
My re-creation of Guess the Number in JavaScript.
Event-Driven Programming: This type of programming sets the groundwork for allowing us to build interactive games later in the course, such as Pong and RiceRocks (a clone of the classic arcade game Asteroids). In event-driven programming, our program waits for events to occur, and then execute event-handler functions once these events occur. So what is an event? An event can be any action that your computer and program registers. Some of the main events include the following:
Input events
Keyboard events
Mouse events
Timer events
Global/Local Variables: A function is like a mini program within a program. Each function has its own purpose separate from the program as a whole, and it may contain its own variables. Variables that are defined within a function are called local variables and they have a local scope. On the other hand, variables that are not defined in a function are defined in the global scope of the program. These are called global variables. There is only one global scope of a program, and it is created when the program starts. However, there can be multiple local scopes, and they are created when a function is called and destroyed after the function is executed. A local variable can't be accessed in the global scope, but a global variable can be accessed and modified in a local scope (i.e., within a function) by using the "global" statement in Python.
Mini Project 3
This week's mini project is to create the game Guess the Number. To do so, we need to write three categories of functions: a helper function to start and restart the game, event handlers for the control panel of the graphical user interface (GUI), and an input_guess function that contains the main logic of the game. We'll also need to register the event handlers and start the GUI frame. Note that the syntax for this final step is specific to CodeSkulptor, but the concept applies to other GUI packages in Python such as Tkinter.