Way of the Geek home
Your One Stop Geek Shop

Latest Podcast

Week in Geek #24
  • InnerGeek

  • A Vote For CHAOS!
    [September 24th 2008]

    A Vote For CHAOS!

  • Categories

    expand
  • Login





    Register Recover password
  • Member

  • Current Article

    Simple Python Game 2: Electric Boogaloo
    Posted by Devin de Gruyl on Aug 20th, 2008

    Yesterday, I posted an article that contained a listing for a small game written in the Python programming language, based on the “Face the Devil” endgame from the old game show The Joker’s Wild. Today, I’ll go back through that listing line-by-line, and show you the theory behind the program. Hopefully, this will show you the way a computer “thinks” and how a good programming language instructs a computer to do your bidding.

    Hopefully, this will help pull back the curtain and give you a good idea what it’s like to think in terms of program code, and who knows? It might even inspire you to start your own experimentations in this field. Lord knows, we need more coders these days and less Joe Endusers who think the pinnacle of computer mastery is using Excel for grocery lists… heh. (No offense intended to anyone who actually does that, of course…)

    Let’s start at the top and work our way through the program step-by-step:

    Like many languages these days, Python supports modules, outside libraries that contain functions that extend the basic set of Python commands, allowing you to do things the core language doesn’t allow you to do (the actual number of commands Python understands is very small, which can account for much of its low learning curve). Python can be extended to a nearly endless degree through use of modules. Here, we’ll be using three modules that come as part of the standard Python distribution: Random, OS, and Time. Each contains a useful command for the game.

    These two commands set two important variables for gameplay. Unlike other languages, in Python it isn’t necessary (or, indeed, possible) to define a specific type for each variable; all you have to do is create it in this fashion, and Python will “do the right thing” based on whatever data you see fit to place there. Again, this goes a long way toward making Python a much more newbie-friendly language than, say, C or C++, since you don’t have to worry about setting variables to be signed or unsigned integers before you can do anything useful with them.

    The value variable is what veterans of BASIC from before it was “visual” might recognize as an array, a single variable that could point to any one of several possible items. In this case, value contains every possible outcome of the wheels – six dollar amounts ($25, $50, $75, $100, $150, or $200) and a special case, which we’ll refer to in this list as 0 for the time being.

    The one called devilwheel is a special case. Note, here, that we have our first call to a function provided by an external module, random.randint(x,y). This generates a random integer between x and y, then stores it in devilwheel. This is how the program determines which of the three wheels on our slot machine will have the Devil on it, if and when it comes up during gameplay. I’ll explaim more about how this works later on.

    Fairly self-explanatory. This simply resets the variable to zero, just in case we have anything laying around in memory we don’t want.

    Now the fun begins. This command begins a loop, which is a series of repetitive commands that will continue to execute so long as a certain condition is met. In this case, so long as score remains below 1000, the following commands will execute over and over, but as soon as score exceeds 1000, the loop will end.

    The wheel variable is used to tell us which wheel (out of the three) we’re on now. If you learned to program on an old Commodore or Apple you’re probably familiar with something like:

    10 FOR N=1 TO 3
    20 PRINT “WAY OF THE GEEK”
    30 NEXT N

    …which will output WAY OF THE GEEK three times. In Python, this same incremental feature is achieved by use of the range(x,y) function, which creates a range of integers between x and y. This is useful for keeping track of loop iterations, as we do here. For count in wheel not only begins the loop, but also creates a variable count that keeps track of the number of times the loop is performed. Once count reaches the end of the wheel range (in this case, 3) the loop will terminate and the program will resume from the next command following.

    The first line in this snippet resets window, the variable we use to keep track of the value of the current window, to zero. As you learn more about programming in general this type of “garbage collection” will soon become second nature.

    At its core, the following two lines are where the “magic” happens. We first generate a random integer v between 0 and 6, using the same random.randint(x,y) command we used earlier in the listing. The window=value[v] command in the following line tells Python to look in position v in the value array we defined at the top of the listing, and pass its contents to the window variable.

    To illustrate: Suppose the number generated by v is 4. value[4] would thus be “150” (remember, computers tend to start counting at zero, not one like most humans do), so that value (150) would be passed to the window variable, where it’ll be useful in the next section.

    This part is long, and frankly could probably be more elegantly coded, but it’s still useful as an example of conditional statements. What these lines do is look at the current value of window and runs a series of tests on it, going down the line. If window is currently set to “25,” it will execute the series of commands you see following the colon (:) in the listing – in this case, printing “$25” to the screen and incrementing the score variable by 25. If not, Python skips over those commands and looks to the next elif (“else if”) condition, which checks to see if window is worth “50,” and the process will continue in this fashion until the window value is found in the list.

    The final elif statement is actually an else, which does the same thing but just means “When all else fails, this is what you do.” A good way to think of the else condition is as a “default” action to take if none of the previous if/elif conditions apply. In this case, it’s used if window is set to 0, which sets up its own conditional. Python, as with virtually every other modern language, supports as many nested loops as you, the programmer, feel are necessary to get the job done. As you can see here, we have an if…else condition nestled inside of an else condition itself.

    In this case, the program checks the current value of count, and compares it to the previously established devilwheel random number. If these integers match, the program knows this is the wheel where the Devil was placed, and outputs an appropriate response – which contains another function call, this time to the OS module, that terminates the program and returns the user to the command prompt. There is also a call made to the time module that instructs the program to pause for one second between printing the word “DEVIL” and giving you the “Game Over” message; this is done as a level of “user friendliness,” to give the player a chance to see the Devil before the program abruptly terminates (which might give the incorrect impression that the game crashed rather than simply exited normally).

    If window is worth 0 and we aren’t on the Devil’s wheel, I’ve told the program to go ahead and treat that 0 as a second $50 space.

    Another call to time.sleep(1), which waits one second in between outputting the contents of each window.

    We print the current value of score to the screen and perform a check; if our total score is over $1,000, we get a victory message and the program ends (with the os._exit(99) function). If not, the game tells us how much more we have to go to reach the magic number, and presents us with the option to quit while we’re ahead, or risk our winnings on another spin.

    The raw_input function outputs a prompt and waits for a user response, which is then stored in a variable (in this case, choice). The program then performs a conditional check on choice and acts accordingly. The continue command in the “y” option brings the loop all the way back up to the top where the big loop began (while score < 1000:).

    And there you have it! A little more instructive than “Hello World,” yet still manageable enough for most neophyte code monkeys to understand what’s going on, I hope. Plus you get a fun little time-waster out of the bargain as well, which ain’t bad!

    It’s also an illustration of just how easy Python is to learn. Believe it or not, I knew very little about Python when I sat down to write this game, yet within about two hours of experimentation and poring over documentation (both online and dead-tree) I was proficient enough to crank out a complete and playable (if woefully noninteractive) game that paid tribute to one of my other major obsessions in life, classic TV game shows.

    If you successfully entered this program and can understand how it works, then congratulations! You’ve cleared the biggest hurdle in learning how to program, which is actually learning the theory. You’re now sufficiently armed to read more about Python, or indeed any high-level language, and try your own hand at writing a small but useful app.

    You might even be able to take this “engine” and dress it up a bit. There are ways it can be improved: As it is, for example, the game doesn’t behave correctly if you end up with exactly $1,000 after a turn. You might also want to incorporate a rule from the actual Joker’s Wild show whereby spinning three identical dollar amounts counted as an automatic win (my game, as is, doesn’t check for that). It’s even possible to add a GUI with graphics and sound, once you’ve learned the syntax for so doing.

    I don’t know if this will become a regular series, but I will try to add more tutorials of this nature in the future. For now, I highly recommend www.python.org for further reading on the subject of Python, including a series of tutorials and superb documentation.

    Until next time, remember: Don’t fear code!  It’s just a language you haven’t learned yet…

    Posted in code, lessons   | email this article 

    If you liked that, try...

    1. HOWTO: Code a Simple Game in Python
    2. The ion3 Window Manager: Little, Not So Yellow, Different.
    3. Linux Cheat-Sheet
    4. Microsoft to Run PHP on .NET
    5. Retro-Active: Starcade / The Video Game

    You can leave a response

    No Comments »

    No comments yet.

    Leave a comment

    Captcha

    Enter the letters you see above.
    Can't see anything? Having problems? Email the admin

  • Contact Us

    Twitter Us!
    Podcast RSS
    EMAIL US!
    Podcast Voicemail:
    206-338-3288

    Our Podlinez Number:
    712-318-9815

    Find us on:

    Add our podcast to your iTunes
    Add our podcast to your Zune
    Find us on TPN
    Find us on Blubrry
  • Advertisement

    Advertise on Way of the Geek