Python PyGame: 2

Python PyGame: 2

In my first blog I covered the basics of getting PyGame installed on your Widnows machine with Python 2.7. We also went over the core methodology of IDEA: ALTER presented in the “Game Programming The Express Line to Learning” book I’m using to start this series. For review:

  • IDEA (the game framework)
  • 1.Import & Initialize
  • 2.Display Configuration
  • 3.Entities
  • 4.Action (broken into the ALTER steps)
    • ALTER
    • 1.Assign values to key variables
    • 2.Loop (infinite w/breakout clause)
    • 3.Timer (setup framerate)
    • 4.Event Handling
    • 5.Refresh Display

Today I’m going to take us a step further into the game development world with three programs. All of these are covered in great depth in the book, so, my purpose is simple introdcution to the concepts and you can walk through it with me if you like. I am a believer that if you do anything 10,000 times you’ll be much farther advanced than today, so, it may feel tedious to type the code out, but over time, you’ll engrain it into your brain.

The book itself is written largely towards total beginners to programming, so, I am sparsely choosing which ones I do. The three programs today are drawCircles, mouseEvents, and Paint. So, you’ll see how to draw stuff on your canvas, interact with the user through keyboard and mouse, and then put it all together.

Let’s check out the first program, drawCircles:

Two points of interest. We’re using PyGame’s draw command to create a lot of circles of various colors and starting at different points. Secondly, we’re demonstrating out ability to save files back to a folder (in this case we’re converting the screen into a bitmap). One additional thing is the use of a function call as opposed to just doing everything in one go. It’s not so impressive here, but, it will be more handy when we begin writing larger programs or using object oriented techniques.

Go ahead and run this and look in your file folder. You’ll find this image:

Personally, whenever I get a chance to draw things I inevitably want to draw fractals like it’s 1980. I’ll post a small addendum later to do that.

Okay, so the second program is called mouseEvents.py. It grabs a few user events and prints them to the console. Let’s take a look at the code:

So, you can see the IDEA:ALTER is still working for us here (it will keep working for us too). Outside of the normal stuff, we’re using the PyGame Event Handler to grab when the user hits the Close button, presses a key down, or clicks the mouse. One thing of interest is that the simple pygame.KEYDOWN event is all you need to create a keylogger and steal people’s passwords all day long. There’s a reason Python is a popular language among black and white hat hackers. It’s easy, light, and fast.

Run this program and you’ll be able to see the console spit out everything you do:

That’s good fun…

Okay now let’s put them together into a Paint program. This silly task shows us a lot of good features of game programming. Let’s take a look at the first part where we define some functions:

The first function is interfacing with the input from the user to determine what to do. Primarily what color and line width to use for the paint brush. The second function is reporting back what color and width the user has chosen. Setting the MyFont to the “None” of SysFont means it will use the default font on whatever system is running the program. That’s a handy thing to keep in mind.
Okay, the second part defines the main function:

So once we are inside the main loop, we check first to see if the user has quit, and then handle the mouse and keyboard. If any key is pressed we update the values of myData. If the mouse is held down we use pygame’s draw command and feed it MyData’s variables. Result? Paint:

Okay, so, that’s it for today. With these kind of fundamentals we are ready to tackle some bigger concepts and move towards more object oriented games. See you next time.

Python PyGame: 1

Introduction:

A particular nephew of mine asked if I could help him write a computer game. I said of course, but I really had no idea what this meant. So, I did some quick research on Amazon and came up with a couple of books to run through on the subject. The next few blogs will be working through “Game Programming The Express Line to Learning”. It was written in 2006 fro Python (which you wouldn’t know by the name). Why Python? Because I’m teaching myself Python and I enjoyed my experiences with Django and Python on the more familiar web development side of things. Okay, enough with the chatter, onto some meat.

Assumptions:
This is written assuming you have Python 2.7 installed on your Windows 64bit machine. If not, modify accordingly.
You’re at least a level 1 programmer with a +1 ring of protection… (j/k).

Editors: I have switched to notepad++ for my Python work because my free PyCharm ran out. A major bummer because PyCharm is super awesome. Luckily, notepad++ is pretty good to when you add in the right extensions.

Download the appropriate installer.
If you go to the obvious place [http://pygame.org/download.shtml], you’ll notice there are no Windows 64bit installations.

If you try to install a 32 bit version, then on the next step you’ll get this error:

 
You have to go here for those: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

Run the installer. Select the Entire Features to be installed and change the directory to your Python27 location.

Now open up IDLE and type: import pygame
It should think a bit and then come back to a >>> line.
If it does not you’re probably missing libraries, so go find them and download them.

So, now it’s time to write your first game.
Go ahead and make a folder inside your Python27 folder called games and then put another one in there called idea:

The core idea this book sets us up with surprisingly takes the form of ingenious acronyms! Acronyms are largely responsible for our higher pay and social eschewing. Regardless, they are a constant.
Here’s the SETUP:
IDEA and ALTER
Where A=ALTER
Thus, it’s really: IDE[ALTER]
What does it mean in pseudo-code?
IDEA (the game framework) =
1.Import & Initialize
2.Display Configuration
3.Entities
4.Action (broken into the ALTER steps)
ALTER
1.Assign values to key variables
2.Loop (infinite w/breakout clause)
3.Timer (setup framerate)
4.Event Handling
5.Refresh Display

 
Okay,now that we have a total understanding of what we’ll be diong from the beginning game to the end game, let’s jump right into the intro program that does nothing but display a blue screen:

Create a file called idea.py inside the games/idea folder.
Slap this code in there:

Let’s go over some of the less obvious things. We’re using an infinite loop. True. This appears to be acceptable in the gaming world, whereas I’m used to this being an unforgivable sin in the web world. Pygame is doing most of the heavy lifting. You don’t really need to know that pygame is a wrapper around SDL (Simple DirectMedia Layer: http://www.libsdl.org/ ), but, take it for granted that someone (Pete Shinners) did a lot of heavy lifting for you to make writing games fun and easy. Thanks Pete!
The clock.tick(30) is setting your FPS (FRAMES PER SECOND).
BLIT = Copies data from one rectangle to another (moves objects)
FLIP = displaying graphics on the screen the easiest way will be slow and create a flicker effect. Thus we use the “screen flipping” technique that implements “double buffering” routines (most new systems support this now) that is a special kind of blit which copies the screen object onto the visual display. This reduces screen refresh rates and improves the flicker effect.
And Blue = RGB value 0,0,255.

Open a command prompt and run this file:

You’ll see this:

It’s fairly amazing that something this awesome could be so easy… okay, so it’s not fairly amazing, but it is the foundation for everything from here on out.

Okay, so now lets move a box across a screen so we can see this screen refresh stuff in actions.
Create a new game file called movebox.py and slap this code in there (I made a new folder under the same name):

 

Not much has changed, but we have added another entity. Now we have a background and a box. Then in the Events we have told the box to move positions to the right on the X axis. We’ve also added in a “collision” detection with the edge so it will start over. Nothing mind blowing. Go run it.

 

You’ll see an animated version of this:
 

Okay, that’s a bit cooler than a blue background. Okay, that took us through to chapter 5. So, next blog we’ll get into some more interesting elements around drawing and events. Thanks!

Resources:
http://www.amazon.com/Game-Programming-Line-Express-Learning/dp/0470068221
http://pygame.org
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame
http://pygame.org/docs/tut/newbieguide.html
http://notepad-plus-plus.org/
 

Django & Python Adventure Part 6

Today I am going to focus on incorporating JQuery into Django. If you’re following along this is material covered in chapter 6 of Ayman Hourieh’s “Django 1.0 Web Site Development”. The book was published in March 2009, so this will be an interesting test of what’s changed in JQuery in 21 months. It was common practice back then to download a copy of JQuery, but, today I believe utilizing CDNs (Content Delivery Network) is the preferred method.

The big players run these CDNs:
• Microsoft: http://www.asp.net/ajaxlibrary/cdn.ashx
• Google: http://code.google.com/apis/libraries/
• JQuery: http://code.jquery.com/

As an interesting aside, some developers worry about their applications being unable to connect to the CDN 100% of the time. If you want to read more on this, read this blog about getting around it:

http://code-inside.de/blog-in/2011/02/06/howto-jquery-hosted-cdn-version-local-fallback/

One final note, it’s best to use the .min version of whatever JQuery as it has been “minified” to work faster for you application.

We only want to reference this once, so we’ll drop it in the Master Page base.html:

The first thing I want to implement is AJAX-enabled search functionality on the bookmarks. The book suggests the best practice of writing the search form without AJAX (so it should work if the AJAX fails) and then add on the AJAX functionality. This is called “Progressive Enhancement” and it simply means we try not to leave anyone out of the fun.

First: bookmarks/forms.py:

Second: bookmarks/views.py
Notice the search is already implemented in Django. We’re calling it with Bookmark.objects.filter(). When we passit arguments, they must be in the format: field__operator. For a .Net programmer I still find the double underscore a little odd, but, whatever. There are other operators we could use aside from “icontains”. “contains”, “startswith”, and “exact” are some others. You can see this gives you similar power to a SQL SELECT blah FROM blah WHERE… Again, Django is handling the ORM code for us so this is what we’ll use to query the Model.

Third: implement templates/search.html

Fourth: update urls.py
(r’^search/$’, search_page),

Now test it out:

Very cool. We’ve now created our base search functionality with a few lines of code. Now we can add in the AJAX for browsers that can handle it (have JavaScript enabled).

First: update base.html to have a link to the search page:

Second: update the views.py

Third: update the search.html

Fourth: create the search.js file. This…

Again, we can test it. Notice this time the page does not reload. That is the JQuery AJAX call handling the manipulation of the innerHTML of the page for you:

AJAX accomplished! It’s a brand new day. Next time I’ll be doing something a little more advanced, but this was a good start.

Thanks,
Mike

© Copyright Duke Hall - Designed by Pexeto