Jump to content
xisto Community
Sign in to follow this  

[pygame] Python Game

Recommended Posts

On this tutorial we will see how to draw a circle on the screen and move it around using the arrows of the keyboard.
(Don't worry if you don't get anything, the code will be analysed line by line)

#!/usr/bin/env python import pygamefrom pygame.locals import * if not pygame.font:	print 'Atention, there are no fonts.' if not pygame.mixer:	print 'Atention, there is no sound.' pygame.init()  red = (255, 0, 0)black = (0, 0, 0)  window_width = 640window_height = 480 window = pygame.display.set_mode((window_width, window_height))  ray_circle = 10 xpos = 50ypos = 50 circle = pygame.draw.circle(window, red, (xpos, ypos), ray_circle) movement_x = 5movement_y = 5 pygame.display.flip() pygame.key.set_repeat(1000, 100) while True:	for event in pygame.event.get():		pass 	key_pressed = pygame.key.get_pressed() 	if key_pressed[K_LEFT]:		xpos -= movement_x 	if key_pressed[K_RIGHT]:		xpos += movement_x  	if key_pressed[K_UP]:		ypos -= movement_y 	if key_pressed[K_DOWN]:		ypos += movement_y 	window.fill(black)	circle = pygame.draw.circle(window, red, (xpos, ypos), ray_circle)	pygame.display.flip()

Ok, let's start explaining line by line.
#!/usr/bin/env python

This line is only for people who have Linux, and it shows where to find the executable of Python.
There are two versions of this line, "#!/usr/bin/env python" and "#!/usr/bin/python".
This line need to be the first of the file (in this case, the whitespace is revelant).
There are some diferences between both, but they are irrevelant on day by day job, and they doesn't fit this tutorial.

import pygamefrom pygame.locals import *

The Pygame is a module for Python (i assume you already have this installed, otherwise you should find on the repositories of your Linux distro, or move into the oficial website at http://www.pygame.org/download.shtml where you'll find the downloads for Windows and Mac, or the sources if you want to compile your own).

Being Pygame a module, you need to import it, using the command "import pygame"

The pygame.locals has things like keyboard key codes, and to be faster accessing them, you import the module directaly.

if not pygame.font:	print 'Atention, there are no fonts.' if not pygame.mixer:	print 'Atention, there is no sound.'

This two blocs are optional, but it's always handy. In case that the program can't load the fonts of pygame, or can't access the sound, this prints an error on the console.


This command starts all the modules that are imported when we use "import game". If you want, it's possible to start modules one by one, but normally, that is not necessary.
If you are using one interpretre like IDLE, you should receive a tuple, that shows the modules that have been started with success, and those who are not. (At normal conditions this command should return (6,0), 6 modules started correctaly, 0 not started)

red = (255, 0, 0)black = (0, 0, 0)

I think when your doing a tutorial, there should not be numbers out of nowhere, so i started the variables red and black containing the RGB color to that color. (RGB means Red, Green, Blue, the max value for R/G/B is 255, so definig a color is easy, take a look at my red, 255 of red, 0 of green and 0 of blue, so it's red definetly, my black 0 red, 0 green, 0 blue, no color = black :) )
The red will be the color of the circle, and the black will be the color to clean the screen after each frame (this will be explained right away).

window_width = 640window_height = 480

AS i told before, numbers shouldn't appear out of nowhere, so i created a variable with the numbers needed for the width and height of the screen, 640x480 will be the size of the window.
If you want to change the size of the window, just change those values ;D

window = pygame.display.set_mode((window_width, window_height))
This line creates a window, with the size of 640x480 (because of the variables we created before)
Ok, those brackets are really needed, the info should come in a tuple, window = pygame.display.set_mode(window_width, window_height) wouldn't work.

ray_circle = 10 xpos = 50ypos = 50

The variable ray_circle will define the ray of the circle in pixels.

The variables xpos and ypos will define the position where the circle will be shown on the first frame.

circle = pygame.draw.circle(window, red, (xpos, ypos), ray_circle)
Now we will create the circle, using the module draw of pygame. With this we can create the images without using the sprites created on other programs (obviously the draw only draws basic geometric figures).
The draw can also create rectangles. To see everything that it can create, go to the oficial documentation of the module that can be found here.

The pygame.draw.circle needs the next arguments: name of the window variable where it will draw the circle, color of the circle, a tuple with the center position of circle (x, y), and the ray of the circle.

ok, so this circle will be created on our window, with red color, at the position (50,50) (because we defined those variables before), and a ray of 10.

movement_x = 5movement_y = 5

This will define the number of pixels that the circle will move on the "x" axle and "y" axle.


This command will refresh the window, so if any movement happens, this command "sticks" everything on the window to be seen. (There is another way to do this but it's more difficult ;D )

pygame.key.set_repeat(1000, 100)
At normal conditions, Pygame doesn't "accept" a key pressed as a loop. So, if you press the left key and "glue" the finger on it, it will only move the circle to left 1 time.
To "fight" this we use the "set_repeat".

The first value is the time that we have to "un-glue" the finger untill the Pygame accepts the first loop. The second value, is the interval that exists between each loop. Every values will be given in milliseconds (1000 milliseconds = 1 second). In this example, when you press left key, and "glue" the finger, the circle will move 5 pixels to the left, after 1second it will move 5 pixels to left every 100 milissenconds (50 pixels per second). This is a little difficult to explain in a foreign language, the best way is to change the values and see how the program will react.

while True:

Every game has to have a main loop, to process the input during frames.

for event in pygame.event.get():		pass

The module "event" of Pygame is the one that gets all the events that occur. The function get() will return a list with everything that passes determined moment (to try this, try to change "pass" with "print event").
This list ocupies a lot of memory space if runned for a long time, the best way is to clean it up with "pass".

key_pressed = pygame.key.get_pressed()
This variable will store the keys that are pressed, so after it can compares with the "if"'s that we have later in the code, and if the key pressed is found on the "if" it will execute the code.

if key_pressed[K_LEFT]:		xpos -= movimento_em_x
In the case that the pressed key is the left arrow, we change the position of the circle.

The "grid" will be something like this:
|0 x

To move the circle to the left, we need to subtract the x value, to move it to right, we need to add the x value, to move it to top, we need to add the y value, to move it down, we need to subtract the value of y.

That is what the next blocs will do.

if key_pressed[K_RIGHT]:		xpos += movement_x  	if key_pressed[K_UP]:		ypos -= movement_y 	if key_pressed[K_DOWN]:		ypos += movement_y

Now that the program knows where to move, it's time to place it on the window.


But, before we show the next circle, we need to clean the one before, we do this filling the screen withour black color. (Clean this line to see what happens)

We haven't done this at the beggining cause the screen is already black.

circle = pygame.draw.circle(window, red, (xpos, ypos), ray_circle)

Now that the window is cleaned, it's time to place the new circle at it's new position.


Like before, to show the new circle we need to refresh the window, and like we've seen before, this is made using the command pygame.display.flip().

Ok, now you have your first game, a ball that moves around a black window. (Fine it's not unreal or starcraft, but we need to start somewhere, right?)

Play with this code to see what happens.
Any doubt, post here. :(

Share this post

Link to post
Share on other sites

Thanks for the help. I was wondering how to make somathing like this. But do you know how to add AI so that something's chasing you?

Hello I don't know if I am of good help but since this is very basic game I would suggest either that you fill your so called AI (artificial intelligence) with random number and move it according to this or you fill it with position of the persons dot and then it would follow it. And you could add some more good things like level which would increase AI's speed and accurancy in the following and choosing the closest path and so on.

Generally thing with the AI is that if you write more code you are better with it. So stick to this rule even in simple games.

Share this post

Link to post
Share on other sites

de4thpr00f, have you tried using PyGlet instead of Pygame? It seems like a more developed API to me, depending only on Python. It also includes OpenGL for Python as opposed to having to install PyOpenGL manually. If you already heard of this, tell me what you think.

Share this post

Link to post
Share on other sites

Ok, this is my first post here. So here goes.
I have been programming in pygame for the last few weeks. I know it doesn't sound like long but it has a really low learning curve. That example was pretty good, albeit very basic, but i would have done the keyboard input differently. when you do get_keys(), it actually checks through all the keys on the keyboard at the same time. There is a better way to do this so it just checks for the one key. Consider using:

for event in pygame.get():								 	  if event.type ==   pygame.K_LEFT:				xpos -= movement_x	  if event.type == pygame.K_RIGHT:
etc. etc. etc.

MASONBRO-- You will have to set them up with an if statement, that if they aren't at your location, they will go x amount to (x, y) coordinate. If you let me know how much experience you have in Python, and are still interested i should be able to help you out!

Share this post

Link to post
Share on other sites
Circle wont move![pygame] Python Game

I am sure I am doing something wrong with my program, but I have gone over the code very carefully, and don't see the problem. Everything in the program works fine, execpt the circle stays perfectly still! Please Help!!

-question by guest

Share this post

Link to post
Share on other sites

I don't know python but just seeing those keystroke commands seem simlar to Flash with theirs. Maybe I can learn Python, I wonder if it has a hard learning curve.... but I guess just like all programming languages it takes time and effort into learning.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.