IPB

Welcome Guest ( Log In | Register )



Tags
This content has not been tagged yet
 
Reply to this topicStart new topic

[pygame] Python Game


de4thpr00f
no avatar
Member [Level 2]
*****
Group: Members
Posts: 76
Joined: 21-November 07
Member No.: 53,412



Post #1 post Dec 30 2007, 03:55 PM
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
Go to the top of the page
+Quote Post
masonsbro
no avatar
Newbie
*
Group: Members
Posts: 1
Joined: 26-January 08
Member No.: 56,893



Post #2 post Jan 26 2008, 07: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?
Go to the top of the page
+Quote Post
hitmanblood
no avatar
Privileged Member
*********
Group: [HOSTED]
Posts: 786
Joined: 13-April 07
From: mreža
Member No.: 41,558



Post #3 post Jan 29 2008, 01:52 AM
QUOTE(masonsbro @ Jan 26 2008, 08:08 PM) [snapback]370552[/snapback]
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.
Go to the top of the page
+Quote Post
dre
no avatar
Super Member
*********
Group: [HOSTED]
Posts: 456
Joined: 3-January 07
From: The West Side
Member No.: 36,424



Post #4 post Apr 8 2008, 05:51 AM
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.
Go to the top of the page
+Quote Post
dwolters
no avatar
Newbie [Level 3]
***
Group: [HOSTED]
Posts: 47
Joined: 18-May 08
Member No.: 62,305



Post #5 post May 18 2008, 09:23 AM
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:
CODE
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!
Go to the top of the page
+Quote Post
proskiier23
no avatar
Newbie [Level 2]
**
Group: Members
Posts: 35
Joined: 25-May 09
From: 21210
Member No.: 82,413



Post #6 post Jun 3 2009, 05:15 PM
pretty neat thanks for the post... pretty cool
Go to the top of the page
+Quote Post
iGuest
no avatar
Hail Caesar!
*********************
Group: Members
Posts: 5,876
Joined: 21-September 07
Member No.: 50,369



Post #7 post Aug 6 2009, 04:19 PM
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
Go to the top of the page
+Quote Post

Reply to this topicStart new topic

Collapse

> Similar Topics

    Topic Title Replies Topic Starter Views Last Action
No new   14 Spudd 1,024 25th September 2009 - 08:24 PM
Last post by: Spudd
No New Posts   8 rob86 191 18th October 2009 - 01:52 AM
Last post by: inverse_bloom
No new 55 OpaQue 308,911 11th October 2009 - 07:55 PM
Last post by: iG-heya
No New Posts   3 xboxrulz 9,616 1st August 2004 - 10:58 AM
Last post by: Critical_Impact
No new   59 Etherion 44,883 5th October 2009 - 10:08 AM
Last post by: contactskn
No new   62 harad 48,354 25th October 2009 - 03:09 PM
Last post by: Raidation
No New Posts   2 bounda 1,472 3rd February 2009 - 08:22 AM
Last post by: Veradesigns
No new   56 LILJOHN 56,560 5th December 2008 - 04:51 PM
Last post by: buxgoddess
No new   79 Torch89 71,795 11th September 2009 - 08:47 PM
Last post by: iG-Geowil
No New Posts   5 Donegal 7,937 22nd June 2009 - 03:32 PM
Last post by: Idolon
No New Posts   8 purplemonkeydishwasher000 10,020 21st October 2009 - 08:48 AM
Last post by: inverse_bloom
No New Posts   7 Donegal 7,439 13th August 2004 - 07:52 AM
Last post by: LunchBox
No New Posts   13 bttfpromo 18,961 24th June 2006 - 06:51 AM
Last post by: lone_wild_wolf
No new   55 Bash 25,663 25th October 2009 - 05:28 PM
Last post by: iG-darwin
No New Posts 1 holyium 6,362 20th August 2004 - 07:06 AM
Last post by: Too_Hot


 



RSS Open Discussion Time is now: 8th November 2009 - 09:59 AM

Web Hosting Powered by ComputingHost.com.