Joomla CSS Guide is a really useful site if you are a Joomla template developer. I especially like the A-Z Joomla CSS section.
Thanks to Henry for showing me this site!
Joomla CSS Guide is a really useful site if you are a Joomla template developer. I especially like the A-Z Joomla CSS section.
Thanks to Henry for showing me this site!
Just today somebody asked me why I am doing a pygame tutorial, since I am “a ruby guy”, whatever that’s supposed to mean. I never claimed to be “a ruby guy”. I program in Pascal as well. Go ahead and call me a “Pascal guy”. Or a “C guy”.
Anyways, such minor issues apart. There are Ruby bindings for SDL called (amazingly enough) Ruby/SDL. Now this is not “pygame in Ruby”. Ruby/SDL is a Ruby wrapper for SDL. As such, its API looks like the original SDL API. Pygame, is not a wrapper. It is a python library for developing multimedia applications that uses SDL internally. Confused? I hope not. Ruby/SDL is probably comparable to PySDL which seems to be a Python wrapper for SDL.
I started writing the pygame tutorial because a few people asked me to. Pygame is more popular than Ruby/SDL. (Note: I said more popular, not better. I have no opinion on which is better. I’m only interested in being able to use both). I’m not going to do a Ruby/SDL tutorial, at least not now, but I can at least give you something to get started. First of all, you need to get Ruby/SDL installed. On Debian that translates to:
# aptitude install libsdl-ruby1.8
at least if you are using Etch. If you are not on Debian or one of its derivates.
Once it is installed you can start off by going to /usr/share/doc/libsdl-ruby1.8/examples and studying the examples there. They show you just about everything you need to know. I will also add a small example of my own, adapted from my pygame tutorial.
1 #! /usr/bin/ruby -w 2 3 require 'sdl' 4 5 SDL.init SDL::INIT_VIDEO 6 screen = SDL::set_video_mode 640, 480, 24, SDL::SWSURFACE 7 x = y = 0 8 9 BGCOLOR = screen.format.mapRGB 0, 0, 0 10 LINECOLOR = screen.format.mapRGB 255, 255, 255 11 12 running = true 13 14 while running 15 while event = SDL::Event2.poll 16 case event 17 when SDL::Event2::Quit 18 running = false 19 when SDL::Event2::MouseMotion 20 x = event.x 21 y = event.y 22 end 23 end 24 25 screen.fill_rect 0, 0, 640, 480, BGCOLOR 26 screen.draw_line x, 0, x, 479, LINECOLOR 27 screen.draw_line 0, y, 639, y, LINECOLOR 28 screen.flip 29 end
That’s it! Have fun..
I have begun play Batte for Wesnoth again. This time I’m challenging myself to recruit as little as possible. As an initial test I was able to complete the first episode of “The South Guard” (on easy level to begin with) without recruiting any units. It wasn’t really difficult either. Of course I did get those two merman warriors which you can find by the river. Maybe I’ll try without them next time (not that I really used them in battle much).
The benefit of doing this is that your loyal units will get much more battle exposure and thereby be able to advance quicker. Since they are loyal they don’t cost you too much either. This means that you store up more money for the times when you really need it.
Playing the game this way might help you work on your strategy. I can think of a few things. You really have to protect your injured units in a different way (somebody will always be low on health) as well as making sure somebody is kept fresh for battle at all times. In addition to that, I noticed that I paid much more attention to the day/cycle, retreating when evening comes and charging ahead when day breaks. Finally, under normal circumstances I’m quite lazy about positioning my units. But when you don’t have many units you take your time to position a unit so that he cannot be attacked by more enemies than he can handle at a time.
I expect to be able to play episode 2 (Proven by the Sword) as well without recruiting a single unit. After that I may have to recruit one or two. We’ll see.
Right now I’m busy aptitude installing wesnoth-server as well as installing wesnoth on my friend’s machine. This evening we will try to play multi-player. I wonder if I can get somebody else to come over and join in as well..
In the last tutorial, you learned how to draw lines. This time we will deal with mouse events. As usual we will keep it simple.
Already in the first tutorial you learned about the QUIT event. Now let’s add a little bit of code to track the position of the mouse on our window. This is done by the MOUSEMOTION event. The code looks as follows:
1 #! /usr/bin/env python 2 3 import pygame 4 5 x = y = 0 6 running = 1 7 screen = pygame.display.set_mode((640, 400)) 8 9 while running: 10 event = pygame.event.poll() 11 if event.type == pygame.QUIT: 12 running = 0 13 elif event.type == pygame.MOUSEMOTION: 14 print "mouse at (%d, %d)" % event.pos 15 16 screen.fill((0, 0, 0)) 17 pygame.display.flip()
Most of the code should look familiar by now. What is new is the check to see if we have an event of the type MOUSEMOTION (line 13). Also notice that if the event is a mouse motion event we can get a little bit more information out of the Event object. In the next line (14), we use call event.pos to get the current coordinates of the mouse pointer. This method returns a pair of values representing the x-position and y-position of the mouse pointer.
Note that the values returned by event.pos are relative to the top left-hand corner of the window, not the entire screen (unless, of course, the window covers the entire screen). You probably already know that the top-left hand corner is (0, 0) in screen coordinates.
Exercises
MOUSEMOTION in the example above with MOUSEBUTTONDOWN. Run the program. Move the mouse over the window and press any mouse button. What happens?Seeing screen coordinates dumped onto you terminal window is exciting for just about 0.02 seconds. Let’s do something else. Since what we have learned so far is drawing lines we will stick to that. Here is a program that draws lines that cut the mouse pointer’s coordinates.
1 #! /usr/bin/env python 2 3 import pygame 4 5 bgcolor = 0, 0, 0 6 linecolor = 255, 255, 255 7 x = y = 0 8 running = 1 9 screen = pygame.display.set_mode((640, 400)) 10 11 while running: 12 event = pygame.event.poll() 13 if event.type == pygame.QUIT: 14 running = 0 15 elif event.type == pygame.MOUSEMOTION: 16 x, y = event.pos 17 18 screen.fill(bgcolor) 19 pygame.draw.line(screen, linecolor, (x, 0), (x, 399)) 20 pygame.draw.line(screen, linecolor, (0, y), (639, y)) 21 pygame.display.flip()
There is really nothing new in this code so I don’t think you will have any difficult understanding it. We have already learned how to set the color of the line we are drawing, so let’s extend the program slightly:
1 #! /usr/bin/env python 2 3 import pygame 4 5 bgcolor = 0, 0, 0 6 blueval = 0 7 bluedir = 1 8 x = y = 0 9 running = 1 10 screen = pygame.display.set_mode((640, 400)) 11 12 while running: 13 event = pygame.event.poll() 14 if event.type == pygame.QUIT: 15 running = 0 16 elif event.type == pygame.MOUSEMOTION: 17 x, y = event.pos 18 19 screen.fill(bgcolor) 20 pygame.draw.line(screen, (0, 0, blueval), (x, 0), (x, 399)) 21 pygame.draw.line(screen, (0, 0, blueval), (0, y), (639, y)) 22 blueval += bluedir 23 if blueval == 255 or blueval == 0: bluedir *= -1 24 pygame.display.flip()
Exercises
Mouse buttons
If you have been doing the exercises so far then you already know how to deal with a mouse button being pressed. Let’s look at an example.
1 #! /usr/bin/env python 2 3 import pygame 4 5 LEFT = 1 6 7 running = 1 8 screen = pygame.display.set_mode((320, 200)) 9 10 while running: 11 event = pygame.event.poll() 12 if event.type == pygame.QUIT: 13 running = 0 14 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT: 15 print "You pressed the left mouse button at (%d, %d)" % event.pos 16 elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT: 17 print "You released the left mouse button at (%d, %d)" % event.pos 18 19 screen.fill((0, 0, 0)) 20 pygame.display.flip()
In this example we handle the two events MOUSEBUTTONDOWN and MOUSEBUTTONUP. Run the program and try this. Press the left mouse button down. While holding the button down, move it to a different position, the release the mouse button. Good, now you know how that works.
Exercises
Conclusion
In this tutorial you have learned how to deal with mouse motion and mouse button state. I think you are now comfortable enough with what events that we can look into them into some detail. Up to now we have been using poll() to get an event off the event queue, for the sake of simplicity. In the next tutorial you will see why that is not really a good idea and what you should do instead. Don’t worry, it won’t really become more complicated.
We will also learn a few more drawing methods.
If I were to list the games I have spent the most time playing overall, the first two Bard’s Tale games will certainly be on that list. Quite possibly, they would even top it. There was a time that pretty much the only thing I used my Amiga 500 for was to play The Bard’s Tale (as well as develop a Bards Tale character editor).
The Bard’s Tale is essentially a computer role-playing game. You control a party of adventurers through the town of Skara Brae and into a number of dungeons, which get more and more challenging. Very rarely can your party relax, because there are monsters everywhere.
You start the game off by selecting your party. You have several different character classes to choose from, including warriors and spellcasters of various forms. Then there is the bard. You should always have a bard. He, apart from drinking ale (or better yet, red wine), can play various tunes. These tunes are magical, and can for instance affect how well the party perfoms in battle.
Winning a battle usually means you get some gold which is handy because it allows you to buy weapons, armor and other goodies. Sometimes you also get lucky and find other items which may be useful in your quest.
Battling also means that members of your party get injured. That is not a problem because you can take them to one of several temples for healing. Just as in the real world, healing is not free however, and this is another time when some gold comes in handy. In addition, your spellcasters use mana to cast their spells. They will need this mana recharged from time to time. There is a place where this can be done (for a fee, of course).
As per usual with role-playing games, your characters gain experience from battles. When a character reaches enough experience points he will upgrade a certain skill, be it dexterity, intelligence or whatever. Spellcasters also get to learn new spells, as well as progress to higher levels.
Daytime tends to be fairly boring in Skara Brae. Thankfully night sets in before you know it and that is when the interesting monsters show up. Early on in the game it is a good idea to stay close to a temple at night so that you can heal your players. Because once a sorcerer starts throwing spells at the party, everybody gets burned.
The Bard’s Tale II and III work exactly like the first one but with larger maps and each brings a slew of new monsters. I never played Bard’s Tale III very much so I cannot really comment on whether or not their are any other new elements in the game.
I am not sure why I found these games so addictive. But I did (and I still do, but don’t tell anybody). I still have the Bard’s Tale games although now they are in ADF format. From time to time I start playing one of them again, just for old times sake.
In my last retrogaming post I mentioned that there are quite a few open source clones of Dungeon Master available. Funny enough, although The Bard’s Tale also attracted a large community of devoted fans, there don’t seem to be any open source BTs out there. At least I haven’t been able to find one. There are, however quite a few projects to create “Bard’s Tale-like” games, whatever that means.
You may want to try the Devil Whiskey demo out to see if it suits you. There is a version 2.0 of the game, but the latest demo available is only 1.2. Shifting Suns promised that they would make this game open source eventually, but I’m not sure what happened about that. If you want to download the demo, you will notice that the URL on the site is wrong. The URL should be this and nothing else.
If anybody knows of an open source Bard’s Tale clone, please let me know. Or if you are working on one yourself. I’ll gladly test it and let others know about it. I could even help out with some coding. Hm, come to think of it, maybe I should just start writing my own Bard’s Tale clone. If ever I had an itch to scratch, this would be it..
If you want to know more about The Bard’s Tale, you can check this site out. Or you could just Google around, whichever you prefer. There also seems to be some modern adaption available, but I only know about the classic that I played on the Amiga (as well as on the Commodore 64).
Finally let me say that there is a Bard’s Tale IV petition. If you feel strongly about such things, you can take your political standpoint by being counted here. So far 1447 have made their voices heard.
If you are into open source (or, if you prefer, free software) and games then you should know about Free Gamer, an excellent blog dedicated to open source games. It really is a good blog that I have learned a lot from. If you don’t read Free Gamer already then I suggest you start doing so.
It is quite interesting really. I recently wrote a post about Dungeon Master, and now Free Gamer has a post out about Damnation of the Gods, yet another Dungeon Master clone. The project aims to be a Dungeon Master clone “with lots of extra features” (which could be good or bad, depending on what those features are).
The game looked interesting so I downloaded it and set about to compile. The game doesn’t use any auto(conf|make), so it’s just a matter of selecting a makefile and typing make. Or at least it should be. I had a lot of errors trying to compile this thing, and it took quite some time to fix it all. Thankfully most of the errors were fairly straightforward.
A tip here is to run make inside vim. That way, anytime there is an error, vim will open up the source file and jump to the line where the error occurred. Very handy! Just read the error message and it will give you a good clue about what is wrong.
Eventually I had managed to get everything compiled and I was ready to try the game out. Instead of seeing a nice Dungeon Master clone I got a segfault. Go figure! After all that work.. And I was too tired to start debugging it as well. Too bad, because it looks like it could be a really nice game.
I will get back to Damnation of the Gods eventually. I’ll debug it until I get it to run. Then I’ll post what I did in case anybody else is interested in trying to compile it. In the meantime, to those of you who have managed to get it running, tips are always welcome.
Sadly it seems like the project is dead. The last release, 0.17, was made in September 2005. Then again, “dead” is of course an interesting concept. This is an open source game. The source code is available on Sourceforge. If anybody is interested, you could always contact the original developer and ask about the game. Maybe the game just needs contributors to move forward. It could also be that the original developer has lost interest in the game (that happens from time to time), in which case you could ask to take over.
There are a lot of games that are no longer actively developed. I happen to meet a lot of people who say their dream is to get into games programming. Well, here is an excellent opportunity. Take Damnation of the Gods, or any other open source game that seems abandoned, contact the developers and let them know that you would like to resurrect the game. I’m talking games here but of course the same applies to any open source project, just in case games isn’t your cup of tea.
JRuby is an implementation of the Ruby language. Contrary to what some people seem to think, it is not a stripped-down version of Ruby (look elsewhere for that). And it is not a different language. (Somebody actually tried suggesting to me the other day that the relationship Ruby-JRuby is comparable to that of Java-JavaScript. That is utter nonsense.)
So JRuby is Ruby, with the added bonus of giving you access to the Java class library. And no, that does not mean that you have to write Ruby code that looks like it was Java. Let’s take a look.
Looking inwards
You can learn a lot about JRuby classes by reflection. Here, for example, I create an instance of a javax::swing::JLabel and then list all the available methods.
1 #! /usr/local/bin/jruby -w
2
3 require 'java'
4
5 label = javax::swing::JLabel.new "Test"
6 label.methods.each { |method|
7 puts method
8 }
If you run this program it will list all the methods available on javax::swing::JLabel instances, and there are many (./listmethods.rb | wc -l tells me 917 lines). You can always use grep to find specific methods. For instance, I wanted to find only methods that contain the word visible:
% ./listmethods.rb | egrep '[vV]isible'
compute_visible_rect
scrollRectToVisible
visible_rect
visible=
set_visible
setVisible
visibleRect
get_visible_rect
computeVisibleRect
scroll_rect_to_visible
getVisibleRect
visible
visible?
is_visible
isVisible
If you study this output you will notice that the JRuby “java classes” come packed with goodies to make things feel “right” for a Ruby programmer. For instance, instead of:
javax::swing::JFrame.new.setVisible(true)
you can, if you so wish, do:
javax::swing::JFrame.new.visible = true
Let’s look at an example where we create a JFrame holding a JLabel. But let’s make it look like Ruby, not Java (not that I’m suggesting there is anything wrong with Java).
1 #! /usr/local/bin/jruby -w 2 3 require 'java' 4 5 include_class 'javax.swing.JLabel' 6 include_class 'javax.swing.JFrame' 7 8 class Frame < JFrame 9 def initialize 10 super "JRuby/Swing Demo" 11 default_close_operation = JFrame::EXIT_ON_CLOSE 12 label = JLabel.new "" 13 label.text = "JRuby is Ruby!" 14 add label 15 pack 16 end 17 end 18 19 frame = Frame.new 20 unless frame.visible? 21 puts "The frame exists but is not yet visible." 22 end 23 frame.visible = true 24
If you look at lines 11, 13 and 23 you see that I am using assignment instead of setter methods. (Incidentally, it seems that default_close_operation is broken, at least for me. Then again, I am using a release candidate..) Also on line 20 I am using frame.visible? rather than frame.isVisible(). So if you already are a Ruby programmer, there is no need to learn “the Java way” (although that also works).
I’ll give you one final example. How would you create a singleton class in JRuby? The same you would do it in Ruby, of course. Look at the following:
1 #! /usr/local/bin/jruby -w
2
3 require 'java'
4 require 'singleton'
5
6 include_class 'javax.swing.JLabel'
7 include_class 'javax.swing.JFrame'
8
9 class SingletonFrame < JFrame
10 include Singleton
11
12 def initialize
13 super "Singleton Frame"
14 setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
15 label = JLabel.new "JRuby/Swing"
16 add label
17 pack
18 end
19 end
20
21 frame1 = SingletonFrame.instance
22 frame2 = SingletonFrame.instance
23
24 puts "frame2 visibility: #{frame2.isVisible}"
25 frame1.setVisible true
26 puts "frame2 visibility: #{frame2.isVisible}"
27
Note that frame1 and frame2 are references to the same object. Also, you cannot call new on SingletonFrame (go ahead and try it). This works just like any Ruby programmer would expect.
I have just scraped the surface of what is possible with JRuby (after all this is not a tutorial). Hopefully I may have tickled somebody’s curiosity out there. And hopefully I’ve been able to show with these few examples that by using JRuby you are not “losing” anything as compared to Ruby (and then I mean C-Ruby or whatever you want to call it).
Welcome to part 2 in my pygame tutorial. This time we will build upon what you learned last time as we start drawing onto surfaces. We will continue to move very slowly so that everybody gets a chance to learn.
Drawing a line
You draw a line by using pygame.draw.line. You can also use pygame.draw.aaline which draws an anti-aliased line. Using anti-aliasing can make the line appear less jagged in some cases at the expense of the function call being much slower.
To draw a blue line from (0, 0) to (200, 100) (note: we are measuring in pixels) onto the surface screen you do:
pygame.draw.line(screen, (0, 0, 255), (0, 0), (200, 100))
You could also do this:
blue = 0, 0, 255
point1 = 0, 0
point2 = 200, 100
pygame.draw.line(screen, blue, point1, point2)
This is will do exactly the same thing as the previous example, but is (possibly) more readable. Let’s try to put this together to a little program. We will draw two diagonal lines: one going from the top left-hand corner to the bottom right-hand corner and one from the top right-hand corner to the bottom left-hand corner. We will use pygame.draw.line for one of the lines and pygame.draw.aaline for the other.
1 #! /usr/bin/env python 2 3 import pygame 4 5 screen = pygame.display.set_mode((640, 480)) 6 running = 1 7 8 while running: 9 event = pygame.event.poll() 10 if event.type == pygame.QUIT: 11 running = 0 12 13 screen.fill((0, 0, 0)) 14 pygame.draw.line(screen, (0, 0, 255), (0, 0), (639, 479)) 15 pygame.draw.aaline(screen, (0, 0, 255), (639, 0), (0, 479)) 16 pygame.display.flip()
I hope you recognize most of the code from the first tutorial. If you run the program you should see a big blue ‘x’ across the window.
Exercises
linecolor, topleft, bottomright and so on. Modify the program to make use of the variables.
pygame.draw.line.Moving things around
Now that we know how to draw lines on the screen with pygame, let’s start moving them around. Moving lines around is simple. we store the line coordinates in variables. Inside the event loop we modify the values of those variables. Let’s draw a line that jumps up and down.
1 #! /usr/bin/env python 2 3 import pygame 4 5 y = 0 6 dir = 1 7 running = 1 8 width = 800 9 height = 600 10 screen = pygame.display.set_mode((width, height)) 11 linecolor = 255, 0, 0 12 bgcolor = 0, 0, 0 13 14 while running: 15 event = pygame.event.poll() 16 if event.type == pygame.QUIT: 17 running = 0 18 19 screen.fill(bgcolor) 20 pygame.draw.line(screen, linecolor, (0, y), (width-1, y)) 21 22 y += dir 23 if y == 0 or y == height-1: dir *= -1 24 25 pygame.display.flip()
There we go. The y-position of the line is determined by the variable y which increased by dir in each iteration of the event loop. The value of dir is 1 when the line is moving downwards, or -1 when the line is moving upwards. Simple, isn’t it?
Exercises
screen.fill(bgcolor) and run the program. What happens?Drawing a color bar
Our final example for today will draw a single color bar (“copper bar” if you’ve ever owned an Amiga). Just like our last example, this one will also jump.
1 #! /usr/bin/env python 2 3 import pygame 4 5 y = 0 6 dir = 1 7 running = 1 8 barheight = 124 9 screen = pygame.display.set_mode((800, 600)); 10 11 barcolor = [] 12 for i in range(1, 63): 13 barcolor.append((0, 0, i*4)) 14 for i in range(1, 63): 15 barcolor.append((0, 0, 255 - i*4)) 16 17 while running: 18 event = pygame.event.poll() 19 if event.type == pygame.QUIT: 20 running = 0 21 22 screen.fill((0, 0, 0)) 23 for i in range(0, barheight): 24 pygame.draw.line(screen, barcolor[i], (0, y+i), (799, y+i)) 25 26 y += dir 27 if y + barheight > 599 or y < 0: 28 dir *= -1 29 30 pygame.display.flip()
In this example I create an array called colorbar (for the lack of a better name). This will hold values for the colorbar as it shifts from black to bright blue and back to black. Keep in mind that a color is composed of red, green and blue. Each one of these can be a value between 0 and 255.
If I change the blue value by one for each new line, I would get a really smooth gradient bar. But, the height would be 256 pixels from black to blue and another 256 pixels from blue back to black = 512 pixels, which is too high. There would hardly be enough space in our window to see the bar moving up and down.
So I have to decide on a bar height that I find acceptable. I settled on 124, which means I have 62 pixels from the black to blue gradient and another 62 for the blue to black gradient. This also means that I have to move from a blue value of 1 to a blue value of 255 in 62 pixels. The change in blue per line must be 4 per line.
I use two for loops to populate the barcolor array. The first loop pushes increasing values of blue to the array and the second one decreasing values of blue. It is important to notice that this array is nothing other than a lookup. It doesn’t contain the bar as you see it on the screen. It just contains color values.
Run it and see what it looks like. Once you’ve seen it run, analyze the code and make sure you understand exactly how it works. Then start experimenting with it.
Exercises
pygame.draw.aaline for drawing the lines. Run the program. Do you notice any difference in speed?Conclusion
In this tutorial you have learned to draw lines. We will be staying with methods of drawing to the screen a little while longer, before we move on to other interesting things like loading and displaying images. In the next tutorial you will also learn a bit about mouse events.
2007.12.11:Added explanation of what the colorbar array does in the last example. Thanks to reader Sergy for pointing out that it needed some explanation.
If you would like to try RSSOwl on Debian etch, here is a quick how to get it running:
First, download the RSSOwl package (the latest stable at the time of writing was 1.2.3). Next, become root and create a directory for rssowl (I used /usr/local/rssowl). Extract the archive into this directory. In summary:
# mkdir /usr/local/rssowl
# cd /usr/local/rssowl
# tar zxf /home/lorenzod/downloads/rssowl_1_2_3_linux_bin.tar.gz
Next create a launcher script called /usr/local/bin/rssowl. Add the following lines to it:
#! /bin/sh export MOZILLA_FIVE_HOME=/usr/lib/xulrunner export LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME:$LD_LIBRARY_PATH cd /usr/local/rssowl ./run.sh
(You may have found posts similar to this one. They may have told you to set MOZILLA_FIVE_HOME to /usr/lib/mozilla or something similar. Well, don’t.)
Finally make sure you have the required dependencies installed. First of all you will need Gtk2. It’s very likely that you have it because it’s getting very difficult not to get it installed (trust me, I’ve tried). You will also need to have Iceweasel.
That should be it. Open up a shell and type rssowl and it should start. If it doesn’t you are probably missing some dependency. Read the error message. It can probably guide you.
If, after trying it for a while, you feel that RSSOwl is not for you then try this:
# aptitude install raggle
This is the first part of my pygame tutorial, aimed at beginners. I will keep it small and simple, meaning I will proceed very slowly. I am not going to go into too much detail. I will explain just about as much as is necessary to get you started. You will need to have the pygame documentation available. Always keep it open while you are going through this tutorial.
One little thing before we begin. I am chronically lazy. It is amazing that I even manage to get out of bed every day. So please don’t expect this to be a regular thing. I will write tutorials as and when my eyes are open.
What you will need
If you are on Debian or one of its derivates, try this (as root):
# aptitude install python-pygame
That will install pygame and all dependencies for you. Other distros and operating systems: both Python and pygame are most likely available in your repositories. Figure out how to install them and you are ready to go.
What you should know already
It is a good idea if you at least have some basic knowledge of Python. I guess you could be learning it as you go along, but I will assume that you know how to program in Python already.
Getting started
First of all, let us look at creating a pygame application that does absolutely nothing. Well, nearly absolutely nothing. It actually does display a window. It also does some very rudimentary event handling. You can see this as a template for the next few programs that we will write.
Here is the code:
1 #! /usr/bin/env python 2 3 import pygame 4 5 screen = pygame.display.set_mode((640, 400)) 6 7 while 1: 8 pass
First of all, to use pygame we have to import it. Then we create a Surface that is 640 pixels wide and 400 pixels high. There are a lot more things you can do with set_mode, but we will keep it simple at this point.
Next we enter into an infinite loop. We need this because otherwise the window will
If you run this program it should display a 640×400 window. That wasn’t too difficult was it. If you try to close this application by clicking on the window’s close button, you will notice that it does nothing. You will have to go activate the terminal that you started the program from and
hit CTRL+C to stop the program. We will fix that soon.
Exercises
pygame.display.set_mode twice with different sizes. What do you expect should happen? Run the program. What actually happens? Can you explain why?Adding an event loop
Our first example was maybe a little too simple. Staring at a completely blank window soon gets boring. Also, having to go to the terminal and hit CTRL+C to close the window seems a little awkward. Let’s add a bit of code!
Here is an updated version of the first program:
1 #! /usr/bin/env python 2 3 import pygame 4 5 screen = pygame.display.set_mode((640, 400)) 6 running = 1 7 8 while running: 9 event = pygame.event.poll() 10 if event.type == pygame.QUIT: 11 running = 0 12
What is new is that I have added a simple event loop. The loop is controlled by a flag called running. As long as the flag is set the loop keeps running. Inside the loop we use the poll method to grab the next event from the event queue. There are other ways of doing this, but polling works just fine for now.
There are several different event types that pygame knows about and can respond to. One of these is QUIT, which gets triggered when the user clicks on the window’s close button. All we do if we get an event of this type is clear the running flag, which will exit the loop and cause the program to terminate. Still simple, isn’t it.
Exercises
running flag. Make sure that the program still jumps out of the event loop on the QUIT event.Finishing touches to the template
As a final step before we start doing real things, let’s add just a little bit more so that we have a complete template for what follows. We will paint the our Surface and we will learn how to do a bit of screen flipping. First the code:
1 #! /usr/bin/env python 2 3 import pygame 4 5 screen = pygame.display.set_mode((640, 400)) 6 running = 1 7 8 while running: 9 event = pygame.event.poll() 10 if event.type == pygame.QUIT: 11 running = 0 12 screen.fill((0, 0, 0)) 13 pygame.display.flip() 14
We have added just two lines of code. The first one sets a background color for the Surface. We have passed in a sequence of three values: red, green and blue. Each one can be a value between 0 and 255. Since we set all to zero, we get a black screen. You should experiment with different values for red, green and blue.
The next thing that is new is that we call pygame.display.flip. Drawing directly to the screen is usually a very bad idea. Instead, we have a invisible buffer that we draw onto. When we have finished drawing we make the buffer visible. That way we get flicker-free animations (when we get to that).
Exercises
Conclusion
So what have you learned so far? Not an awful lot, by the looks of it. But in a way you have. You have acquired some basics that you will need to understand the next tutorial, which will come soon. In the meantime, try your hands on a few of the exercises. If you complete all you can make up a few of your own.