Italy's daily coronavirus death toll and new cases fall

Python and Pygame - A Primer

So you're sitting around, playing some simple game on your computer, and you finally realize that as a developer, you can make games too. After a little research you come across this "python" thing that is fairly popular among the dev crowd, but also has a nice 2D game library. Using the Pygame library with Python you finally can realize your quick and simple games. So it's time to get started.
As a quick and dirty primer into both Python and Pygame, the first thing we need to do is get everything set up. Python itself is a pretty flexible little language that can be used for a whole number of things, but today we will be working in a Windows environment. That said, installing both on linux and other OSs python supports is just as easy, it just may take a little more reading on the corresponding sites.
Installing python on Windows is pretty awesomely simple. What you need to do is head over to the Downloads Section at the Python website. Right at the top is the "Windows Installer" for 2.6.4. I myself am using 2.6.4 for school reasons right now, but as far as I know, Pygame works just fine with 3.1, so if you are so inclined, go for it.
Installing Pygame is really the same process, downloading and running the installer for Windows. It can be found in its respective Downloads Section over at the Pygame website. Once you have that installed, we are ready to get started.
For every programming language out there, there is the perfect editor. As far as Python goes, I am sure this is the case as well, however the Python Windows install does come with a very, very simple editor. This is slightly convenient, but I can imagine after using it that some of you may want something else. For that, I say Google is always a good choice. So far, I have not had too many complaints involving IDLE, the built-in Python IDE. To get to it, you simply open your start menu, find Python and it will be one of the menu items. When you get it open it should look something like this:
Just the Python
Shell
If you are the observant type, or even not, you will notice we don't really have an edit window. What we get initially is the Python shell, which is kind of neat in itself. You can just start handing it Python code if you wanted. I guess if you need to test a few lines you could, but more importantly, if things go wrong, the errors will end up here.
So to finally get things rolling, let's get a new window up. To do this, just use the menu in the shell, file->new window. This will, as you may have guessed, open up a new editing window. To get started, we have to first import Pygame into Python. To do this, well you use the import command. Typically, you are going to go ahead and "initialize" Pygame at the same time you import it:
#Import and Init
import pygame
pygame.init()
Ok, this gets us started, but what can we do with Pygame? Well, the answer would be lots, but for this introduction, let's just get something on the screen. We will first get something to happen, which requires us to handle the window and background. Here is what the basic code will look like:
#Set Up the Window
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Sprite Test!")

#SOTC Green Background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((20, 130, 57))
What we have here is some serious Pygame code. To start we are going to setup a screen object and set the window title, or "caption" as Pygame puts it. As you can probably guess, this is where we set the size of the window as well. This is also where we get to check out a cool feature of Python as well, tuples. In a nutshell, they are just really simple, memory efficient lists. You can create a tuple with a simple, comma separated list surrounded by parentheses. I don't know where the name came from, but it sounds fun, no?
So we have our screen object, with the size passed as a tuple. Once we have the window all set up, we have to define a background surface. Now when I say surface, I am really talking about a Pygame object called a surface. According to the docs, a surface represents an image, but in the case of our background, it is a large rectangle that we can fill.
Before we fill our image though, we are going to convert it. What this does is convert the image to another type, in this case (since we pass it no arguments) it converts it to the same properties as your screen, thus making it more efficient for rendering. Converting helps a lot for how we are going to display our images, so it is important we do it. It is also important that we convert it once. Once we have it converted, we fill it in with a color, SOTC green actually.
Ok, so we have a fancy screen object, and we have a background, but what do we do with it all. Well, when we are talking about Pygame, we need to do all of our drawing in a loop. So, lets just make a simple, plain ol' loop:
framerate = pygame.time.Clock()
GameGo = True

while GameGo:

  framerate.tick(60)

  screen.blit(background, (0, 0))

  pygame.display.update()
Pretty simple code here, and this code is added write after you get your background defined. The first thing we do is create a Pygame clock object, which is used to animate our objects. Right now, of course, we have nothing more than a background, but it's a start. After we define a variable that allows our loop to run, we can get into the loop.
The first thing we ever do in the loop is tick the clock another frame, which is as easy as a method call in this case. Once we have moved forward in time, we go and "blit" our background to the display. Blitting is, put simply, pushing data from one memory block to another, so it can be super quick. Once we have our background in position, we just need to update the screen. Again, just another method call.
Before we go and run it however, we have to add an out for Pygame, i.e. tell it when things are over. With a short if statement, we have a solution:
#Handle a Close Event
for event in pygame.event.get():
  if event.type == pygame.QUIT:
    GameGo = False
All this is doing is ending the loop when a Pygame "quit" event is triggered. We haven't added logic for such an event to occur, but without it, Pygame can be very temperamental. Once that code is in the loop, we can run it. In the end we will end up with a fascinating window like this:
Our
Background
It is certainly very.......green, isn't it? I admit, it is not the most interesting thing in the world, but it is a very simple start in Python and Pygame. But what if we want to maybe load in an image? Well, that is easy enough to add to our code. To load in an image, we use the image.load() Pygame function:
#Load and Convert the SOTC Logo
sotcLogo = pygame.image.load("sotc_logo.gif")
sotcLogo = sotcLogo.convert()
Again, once we load in the image, we need to go ahead and convert it so it will "blit" fast. Other than that, our image loading is done. We can go ahead and blit it, but we have to do it AFTER the background, because everything is drawn in order. So, we need to draw the background first, then whatever we draw after than is drawn on top of it. In the end, all of our code will look like this:
#Import and Init
import pygame
pygame.init()

#Set Up the Window
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Sprite Test!")

#SOTC Green Background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((20, 130, 57))

#Load and Convert the SOTC Logo
sotcLogo = pygame.image.load("sotc_logo.gif")
sotcLogo = sotcLogo.convert()

#Clock and Loop Variables
framerate = pygame.time.Clock()
GameGo = True

#The Main Loop
while GameGo:

  #Tick the Clock
  framerate.tick(60)

  #Blit our Images
  screen.blit(background, (0, 0))
  screen.blit(sotcLogo, (100, 100))

  #Update the Display
  pygame.display.update()

  #Handle a Close Event
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      GameGo = False
So what we end up with here is something like so:
Loading a Simple
Image
And that is our primer, loading up Pygame, getting a background, and loading an image. It's not a game, but it is the start on the way to one. Pygame is pretty powerful, and Python is a pretty flexible language.
Source Files:

Comments