May 16, 2008

[pygame] Python Game

Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > Others

free web hosting

[pygame] Python Game

de4thpr00f
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)

CODE
#!/usr/bin/env python

import pygame
from 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 = 640
window_height = 480

window = pygame.display.set_mode((window_width, window_height))


ray_circle = 10

xpos = 50
ypos = 50

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

movement_x = 5
movement_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.
CODE
#!/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.

CODE
import pygame
from 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.

CODE
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.

CODE
pygame.init()


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)

CODE
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 wink.gif )
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).

CODE
window_width = 640
window_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

CODE
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.

CODE
ray_circle = 10

xpos = 50
ypos = 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.

CODE
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.

CODE
movement_x = 5
movement_y = 5


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

CODE
pygame.display.flip()


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 )

CODE
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.

CODE
while True:


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

CODE
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".

CODE
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.

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:
y^
|
|
|
--------->
|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.

CODE
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.

CODE
screen.fill(black)


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.

CODE
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.

CODE
pygame.display.flip()


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. wink.gif
Cheerz

 

 

 


Reply

masonsbro
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?

Reply

hitmanblood
QUOTE(masonsbro @ Jan 26 2008, 08:08 PM) *
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.

Reply

dre
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.

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Similar Topics

Keywords : , pygame, python, game

  1. Help With Flash Player Game
    Bloody Penguin or Pingu (3)
  2. Text Based Game
    (3)
    Is it possible to make a Text Based game with only HTML and some PHP for chat? I dunno any
    languages besides HTML. =.= yeah Im a newbie.....
  3. Age Of Conan
    The Next Generation MMO Game (1)
    THIS POST IS STILL UNDER DEVELOPMENT Age of Conan I have decided to
    throw out some info about the game and hopefully it will be more popular. The releas date is 23
    may 2008 but if you book in advence you can start 3 days before and get some nice in-game item.
    All the info under here you can find here The official Age of Conan Site Combat Age of
    Conan’s combat system lets you take an active role in combat. Rather than pressing an auto-attack
    button, you actually control every chop, thrust, and swing of your weapon. Our combat system ....
  4. Game Lair
    (0)
    This isn't my site but here is a forum I'm usually at, Feel free to join or comment. C&C.
    Game Lair http://www.gamelair.com / http://www.gamelair.com/gameforums Gaming Entertainment
    Forums ....
  5. Budding Java Game Developers?
    Ever wanted to make your own java web-based game, but not had the time (8)
    Right, this is the first post of hopefully many in this thread. Basically the idea is to get many
    developers together to share ideas and knowledge to create our very own game. First we'll be
    asking for is any ideas of what kind of game everybody would like to make, and then we'll set
    about assigning tasks depending on everybodies skills. We will need programmers, artists,
    web-designers, even admin and marketing. This will be freeware, but the experience will be great.
    So, ideas anyone?....
  6. My Review On Nanostray 2
    Game Review (0)
    Nanostray 2 is like a Shoot-em-up, where the objective is to shoot thousands of nameless enemies
    with your super-powered ship. You control a ship, aided by two revolving drones and fly about
    blasting enemies in search for a cure to the Nanostray virus. It is a decent plot that serves its
    purpose as an excuse to start shooting. However, the game may be rather daunting to casual gamers
    because of its difficulty. The first two stages are quite easy, but novices will die at the later
    stages before they know it. There is also no way to save your game manually. The game is sa....
  7. Slavehack
    An online hacking GAME. (1)
    I found this game about 620 days ago whilst surfing for some *cough* stuff *cough* on the internet,
    i thought hey why not play it it can't harm me, but i was wrong, this game has taken over 600
    hours of my life away due to the addictingness of it. It's hard to get the hang of (or it was
    then because of the missing process page and the no tutorial), but now its easy. To
    'survive' in the game you need a nice set of software (currently the max is 5.0 when i
    started it was 1.5) to achieve this software you have to do riddles, once you've completed the
    ri....
  8. Xna Game Creator
    (4)
    I have not downloaded the program mentioned above. But if anyone knows how easy it is to make games
    with it, can someone explain to me the basics. I am not sure of it's strong points and it's
    weak points. Would it need a full knowledge of programming.....
  9. Game Dev Team
    Aim: to get a team together to develop an fps with scope to go mmo (3)
    Hey i'm new to these forums and i was just wandering if there are any guys or gals out there who
    wanna start making an fps in their spare time as part of a team. idealy i would love the project to
    get to the point of mmo but hey! and im easy on the dev language and any engines that may be
    used, getting a few people together to discuss would be great!....
  10. Naruto: Ultimate Ninja 3
    one game u cant miss. (8)
    This is one game you will have to buy. It's better than ever and the battles are different. For
    more info on this game, check out ign.com to view the reviews and more. /biggrin.gif"
    style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" />....
  11. Final Fantasy Tactics: War Of The Lions
    Game Review (2)
    QUOTE When Final Fantasy Tactics was first released for the PlayStation in 1997, it quickly
    became known as one of the best strategy role-playing games of all time. It won over players with
    its well-drawn graphics, captivating storyline, beautiful soundtrack and deep gameplay. Now
    re-released as Final Fantasy Tactics: War of the Lions on the PSP 10 years later, it is amazing how
    the game looks just as fresh as it did when it was first launched. Players of the original would be
    most pleased to discover some new features in their beloved game. There are new job ....
  12. How Many Games Consoles Have You Had And What Was You First And Most Recent Game
    (35)
    I've had:- Gameboy Gameboy colour Gameboy Advance Nintendo DS Lite Playstation
    Playstation 2 and my first ever game was SuperMario on the GB and my most recent game is Okami for
    PS2....
  13. 3d Ultra Cool Pool 8-ball Demo
    Test your skills in a game of virtual pool and become a master. (1)
    3D Ultra Cool Pool 8-ball demo Test your skills in a game of virtual pool and
    become a master. Take everything you know about pool and throw it in a blender. Cool
    Pool has all your favorites: Eight Ball, Cutthroat, Nine Ball, and more! But Cool Pool
    doesn't stop there. Add five wacky new pool games that could only exist on a computer, like
    Rocket Ball, Chameleon Ball, and 24 Cents, and you've got more fun than you can shake a cue
    stick. 3D Ultra Cool Pool: 8 Ball demo contains one of the many games that come as a part of Coo....
  14. The Best Game Programming Languages?
    (25)
    What are some good programming languages to program games in? C++? /unsure.gif"
    style="vertical-align:middle" emoid=":unsure:" border="0" alt="unsure.gif" /> Thanks /xd.gif"
    style="vertical-align:middle" emoid=":XD:" border="0" alt="xd.gif" />....
  15. Naruto Mmorpg
    a game idea (7)
    Here's a little idea of mine: a naruto MMORPG... Anyone who has seen Naruto will catch my
    drift: a game where one could move completly free like in the series. I was thinking some hybrid
    between Ragnarok online and The Elder Scrolls. With perhaps a choise between top view and first or
    third person. Adding the show's 'techniques' it would be quite something. Ofcourse,
    having a game built like that costs alot of money, and sending ideas to a big game company probable
    wouldn't have any effect. Perhaps Atari would do good with a new game xD Anyway, I ....
  16. Soccer Prediction Game Site
    I could do with some feedback please? (8)
    Hi Guys, I have recently signed up with qupis for a free hosting account to test out my site.
    It's based on the US Major League Soccer leagues, and is a prediction game. (I know it's a
    couple of weeks late, but i couldn't get it done in time unfortunately). If some of you could
    drop by, and cast your eye(s) over it, and post any feedback here, i would be most grateful. I
    don't mind whether it's good or bad, it will all help me try to improve the site in one way
    or another. If you can think of any features that would be useful or beneficial, please p....
  17. Help Me Find A Mmorpg Game!
    any recommendation? (23)
    hi, im a mmorpg gamer..i just want to get opinions/suggestions to you guys out there if what would
    be the best mmorpg games that is f2p (free 2 play) that i can download and play? thanks..
    /biggrin.gif" style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" /> Please be
    more descriptive in your topic titles. ....
  18. Making Games
    With Game Maker (16)
    Hi. /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> I just
    wanted everyone to know(if you didn't know already. /smile.gif" style="vertical-align:middle"
    emoid=":)" border="0" alt="smile.gif" />) of a pretty cool program called Game Maker. From my
    experience with it, it's very simple, yet you can still make awesome games with it. Now, when I
    say "awesome" keep in mind, you won't be able to make games like "Halo" or something like that
    with it. But you can make pretty cool games still, it is capable of 2D and 3D games, alth....
  19. Favorite Playstation 2 Game
    VOTE HERE!!! (18)
    I was just wondering what were some of the top favored games for the playstation 2. I liked the
    Ratchet and clank series, jak and daxter series, i liked the first kingdom hearts (havent played the
    second one), and i liked the Grand Theft Auto games too. My favorite would have to be the jak and
    daxter series mostly since the graphics were good, the gameplay was awesome, and the plot of the
    game was great. Vote for your favorite, and if you choose other please state what series or games
    that you liked.....
  20. Game Creation Forum
    Game Forum (4)
    Hello. I have made a forum about game creation. Where you can post your game onto there. I have
    already started and I want you to see. If you want to check out the games you may download them
    becuz they are free. Please reply to them as they had hard work. GUEST MAY POST TO ANY TOPIC OR
    JOIN NOW AND GET YOUR OWN NAME FREE gamecreation2006.smfforfree.com If you support this
    forum put the sentence below in your sig. I support Game Creation Forum. Visit Now
    www.gamecreation2006.smfforfree.com ....
  21. Recommended Online Games
    Recommend a Game here! (39)
    Make a list of games that you recommend: 1. AdventureQuest @ BattleOn.com 2. X-Kings @ x-kings.com
    3. Neopets @ neopets.com 4. Marapets @ marapets.com 5. Yahoo! Buzz Game @
    buzz.research.yahoo.com More coming soon. Try OGame (Google search it). Recommended Offline Games:
    1. The Sims 2. HyperBowl 3. Russian Square 4. Disaster City 5. Exile (1,2 and 3) 6. Avernum (1, 2
    and 3)....
  22. Interactive Buddy(flash Game)
    Bubble buddy go boom! (13)
    Ok, this game is hilarious! Interactive buddy! What you do is you have an Interactive
    buddy(the bubble on your screen!). You get to "play" with him. Everytime you, tickle, punch,
    grab, WHATEVER him, you get money. You can use the money to buy more weapons/tools at the top of the
    page, under "items". You can buy new skins (people) under "Skins". OMG! You can buy Geoge bush
    and make him say funny things buy throwing grenades at him. But he does cuss a tad, so go with the
    teletubby /smile.gif' border='0' style='vertical-align:middle' alt='smile.gif' />....
  23. Best Racing Game For Pc
    Opinions wanted (11)
    My friend wanted to buy a driving PC game but he doesn't know that much about racing games. The
    choices that we've come up is: Grand Turismo, Midnight Club, and Burnout. Is there any other
    games that would be really good for PC with wheel/brake? Thanks for your time.....
  24. Counter Strike
    New to the game! (18)
    I decided to buy CS the other week (dont ask me why) and was wondering if any of you could give me
    any tips on how to stay alive for longers. I consider myself as not too bad at it but I often find
    myself running in too quick and getting shot but I cant help it, so any tips? Thanks
    /biggrin.gif' border='0' style='vertical-align:middle' alt='biggrin.gif' /> ....
  25. Runescape (online Game By Jagex)
    Anyone play it? (44)
    HI, my runescape username is melkonianarg, and i'm basically a newbie on it. I was endering if
    anyone else on this forum had heard of it, or had played it or has an account. I have found out
    that the best way of playing it, other than simply completing quests is to get together in groups to
    do stuff, like abush people in the wilderness or all go mining. This way the most amount of raw
    materials is produced and can be made into bars of metal, followed by shields and weapons including
    swords , scimitars and bows, ranging from longbows to short bows...So anyone playe....
  26. Best Multiplayer Game Ever Challenge
    Which is the best? You decide! (17)
    Guys, I'm gonna have to go with Super Smash Brothers Melee on this one. No other game has
    lasted as long, been so over played and yet remained so amazingly intense and entertaining. No
    other game pushes skill, reactivity, tactics, and friendship to the limit the way SSBM does. Now, I
    know what all you Halo fanboys are thinking, "Psh, Halo is soooo much better blah blah blah" Halo
    doesn't hold a candle to this game! No other game has the diverse amount of characters and
    play strats, and yet easy learning curve. You gotta better game? Let's hear it&#....
  27. Need Help With My Python Programs
    just extremely basic stuff (10)
    ok, i am learning python, and i realy dont know much. my guide im using said to make a program
    where it asks your name, and if the name is yours your make it so there is a compliment, if it is
    another name you make it that its an insult, and anything else makes it say Nice name. here is what
    i wrote name = raw_input("What is your name?") if name == John: print "Your name is freaking
    sweet, you must be a god or something." elif name == Bob: print "You have a freakin' weird
    name, dude." else: print "Nice name,",name i donot understand what i am doing w....
  28. What's Your Favorite Game System - Console
    select one from each poll (170)
    i'm a computer game fan. it's expensive but more useful. it can be use for many purpose for
    your study and entertainment. much easier to use and most common to more people.....
  29. Super Smash Brothers Melee
    Does anyone still play this game? (59)
    I hadn't played this game for a long time until recently when I saw a guy making an awesome
    trick with Link. He mysteriously digged out a huge sword from the ground and his power and reached
    increased enormously. I've been trying to figure out how he performed this trick, but
    haven't found a clue. Does anyone know how to do it? I've heard there's also another
    trick where you can play as zelda and shiek at once (you control both player at the same time).....
  30. Best soccer game - Fifa or PES?
    (38)
    in my opinion, it's pro evolution soccer (3) /tongue.gif" style="vertical-align:middle"
    emoid=":P" border="0" alt="tongue.gif" />....

    1. Looking for , pygame, python, game

Searching Video's for , pygame, python, game
Similar
Help With
Flash Player
Game -
Bloody
Penguin or
Pingu
Text Based
Game
Age Of Conan
- The Next
Generation
MMO Game
Game Lair
Budding Java
Game
Developers?
- Ever
wanted to
make your
own java
web-based
game, but
not had the
time
My Review On
Nanostray 2
- Game
Review
Slavehack -
An online
hacking
GAME.
Xna Game
Creator
Game Dev
Team - Aim:
to get a
team
together to
develop an
fps with
scope to go
mmo
Naruto:
Ultimate
Ninja 3 -
one game u
cant miss.
Final
Fantasy
Tactics: War
Of The Lions
- Game
Review
How Many
Games
Consoles
Have You Had
And What Was
You First
And Most
Recent Game
3d Ultra
Cool Pool
8-ball Demo
- Test your
skills in a
game of
virtual pool
and become a
master.
The Best
Game
Programming
Languages?
Naruto
Mmorpg - a
game idea
Soccer
Prediction
Game Site -
I could do
with some
feedback
please?
Help Me Find
A Mmorpg
Game! -
any
recommendati
on?
Making Games
- With Game
Maker
Favorite
Playstation
2 Game -
VOTE
HERE!
3;!
Game
Creation
Forum - Game
Forum
Recommended
Online Games
- Recommend
a Game
here!
Interactive
Buddy(flash
Game) -
Bubble buddy
go boom!
Best Racing
Game For Pc
- Opinions
wanted
Counter
Strike - New
to the
game!
Runescape
(online Game
By Jagex) -
Anyone play
it?
Best
Multiplayer
Game Ever
Challenge -
Which is the
best? You
decide!
Need Help
With My
Python
Programs -
just
extremely
basic stuff
What's
Your
Favorite
Game System
- Console -
select one
from each
poll
Super Smash
Brothers
Melee - Does
anyone still
play this
game?
Best soccer
game - Fifa
or PES?
advertisement



[pygame] Python Game



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE