Pages

Se afișează postările cu eticheta pygame. Afișați toate postările
Se afișează postările cu eticheta pygame. Afișați toate postările

sâmbătă, 1 octombrie 2011

PyGame : Test mouse class.

Today I will show how to test mouse with pygame.
This is very simple, just you try to use MOUSEBUTTONDOWN.
Also, the click mouse only registers once so you can use it with another event.
If you don't want to use an event handler, you can check for input with:
pygame.mouse.get_pos() 
pygame.mouse.get_pressed()
I created a class called Game, which contains four functions.
A function that needs to pay attention is mainLoop.
This function deals with events in the following order.
While there is no event QUIT then read events.
If there is event QUIT or MOUSEBUTTONDOWN then is running this:
Event QUIT the program is quit.
Event MOUSEBUTTONDOWN print mouse events next use update function with print "update function".
Press mouse buttons: left,right,mouse wheel ,spinning mouse wheel.
(1, 0, 0)
update function
(0, 0, 1)
update function
(0, 1, 0)
update function
(0, 0, 0)
update function
The code is shown below.
import pygame
from pygame.locals import *

screen_mode = (640, 480)
color_black = 0, 0, 0

class Game:
 def __init__(self):
  pygame.init()
  self.screen = pygame.display.set_mode(screen_mode)
  pygame.display.set_caption("Pygame first window")
  self.quit = False
  
 def update(self):
  print "update function"
  return
  
 def draw(self):
  self.screen.fill(color_black)
  pygame.display.flip()
  
 def mainLoop(self):
  while not self.quit:
   for event in pygame.event.get():
    if event.type == pygame.QUIT:
     self.quit = True
    elif  event.type  == pygame.MOUSEBUTTONDOWN:
     print pygame.mouse.get_pressed()
     self.update()
   self.draw()
 
if __name__ == '__main__':
 game = Game()
 game.mainLoop()

duminică, 7 august 2011

PyGame : The script tool with colors.

This is a simple script to allow us to see all colors used by pygame.
import pygame
from pygame.locals import *
from pygame.color import THECOLORS
from time import sleep

def main():
    WINSIZE = 640,480
    pygame.init()
    screen = pygame.display.set_mode(WINSIZE,0,8)
    pygame.display.set_caption('Colors in pygame!')

    for i,j in THECOLORS.iteritems():
        print i
 screen.fill(THECOLORS[i])
 font = pygame.font.Font(None, 36)
 text = font.render(i, 1,(0,0,0),(100,100,100))
 sleep(1.1)
 textpos = text.get_rect()
 textpos.centerx = screen .get_rect().centerx
 screen.blit(text, textpos)
 pygame.display.update()

if __name__=="__main__":
    main()
The script is very simple, just try it.

PyGame : The pygame.display routines

Start pygame display:
C:\>python
Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
>>> pygame.display.init()
pygame.display.Info() creates an object with some data about hardware:
>>> pygame.display.Info()
Here is the interpretation of the output.
hw: True if the display is hardware accelerated
wm: True if windowed display modes can be used
video_mem: The megabytes of video memory on the display. This is 0 if unknown
bitsize: Number of bits used to store each pixel
bytesize: Number of bytes used to store each pixel
masks: Four values used to pack RGBA values into pixels
shifts: Four values used to pack RGBA values into pixels
losses: Four values used to pack RGBA values into pixels
blit_hw: True if hardware Surface blitting is accelerated
blit_hw_CC: True if hardware Surface colorkey blitting is accelerated
blit_hw_A: True if hardware Surface pixel alpha blitting is accelerated
blit_sw: True if software Surface blitting is accelerated
blit_sw_CC: True if software Surface colorkey blitting is accelerated
blit_sw_A: True if software Surface pixel alpha blitting is acclerated
current_h, current_h: Width and height of the current video mode, or of the
desktop mode if called before the display.set_mode is called.
This will return the name of the currently running video driver.
>>> pygame.display.get_driver()
'directx'
Without arguments, list_modes returns a list of possible dimensions
>>> pygame.display.list_modes()
[(1024, 600), (800, 600), (640, 480), (640, 400), (600, 1024), (600, 800), (512,
 384), (480, 640), (400, 640), (400, 300), (384, 512), (320, 240), (320, 200)]
How to query a specific display mode.
>>> full=pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF
>>> pygame.display.mode_ok( [ 800,600 ], full, 32)
32
You can create such a script to help you.
>>> for i in pygame.display.list_modes():
...     a=pygame.display.mode_ok(i,full,16)
...     print "FULLSCREEN | HWSURFACE | DOUBLEBUF for "+str(i)+" x "+str(a)
...
FULLSCREEN | HWSURFACE | DOUBLEBUF for (1024, 600) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (800, 600) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (640, 480) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (640, 400) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (600, 1024) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (600, 800) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (512, 384) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (480, 640) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (400, 640) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (400, 300) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (384, 512) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (320, 240) x 16
FULLSCREEN | HWSURFACE | DOUBLEBUF for (320, 200) x 16
See more here.

luni, 21 martie 2011

PyGame : Using with Android.

What is Android?
Wikipedia says:
Android is an open-source software stack for mobile devices that includes an operating system, middleware, and key applications.[5][6] Google Inc. purchased the initial developer of the software, Android Inc.

Python on Android?

The Pygame Subset for Android is a port of a subset of Pygame functionality to the Android platform.
This pygame subset for Android, allows us the creation of Android-specific games.
In the chapter "samples" comes only with just one classic sliding numbers puzzle.
The good thing is, it can run on a PC.
I installed Fedora pygame with "yum install pygame" as root.
And I run the application example of "samples".
Here is the result:

It works great on Fedora.

marți, 12 octombrie 2010

PyGame : First interface - part 2

One thing necessary to create an interface and a game is using a "sprite system".
To illustrate this, I'll show you a sequence of source code:

import pygame
def must_quit():
    event = pygame.event.poll()
    return event.type == pygame.QUIT
screen = pygame.display.set_mode((640, 480))
SpriteImage = pygame.image.load('image.jpg')
while not must_quit():
    screen.blit(SpriteImage, (0, 0))
    pygame.display.flip()

It sounds simple but is not.
Why? Because when you work with multiple images when source code is more complicated.
For this we need a system and use the "classes".
Let's see:

class SpriteImage:
    def __init__(self, image_filename):
        self.image = pygame.image.load(image_filename)
    def paint(self):
        screen.blit(self.image, (0, 0))
screen = pygame.display.set_mode((640, 480))
sprite = SpriteImage('image.jpg')

This is a more simple way to use it.
Try learning more about pygame.
Good luck.

luni, 2 august 2010

PyGame : Info about driver and zbuffer.

Sometimes is very easy to see some info about pygame.
Just use this code:

>>> import pygame 
>>> from pygame import * 
>>> pygame.init()
(6, 0)
>>> pygame.display.gl_set_attribute(GL_DEPTH_SIZE, 16)
>>> pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF )

>>> print "ZBUFFER is:" ,pygame.display.gl_get_attribute(GL_DEPTH_SIZE)
ZBUFFER is: 24
>>> print "Driver is:", pygame.display.get_driver()
Driver is: x11
NOTE: The OpenGL flags are;

  GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE,
  GL_ACCUM_GREEN_SIZE,  GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE,
  GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO
You can see more here.

PyGame : Binary bitmate with pygame.

Is a very simple example.
I use this code :

import pygame
from pygame.locals import *
import random
import Numeric
from math import *
import random
WIDTH = 640     #width of screen
HEIGHT = 480    #height of screen
def main():
    pygame.display.init()
    
    screen = pygame.display.set_mode((WIDTH,HEIGHT),DOUBLEBUF,32)
    pixels = pygame.surfarray.pixels3d(screen)
    
    width = len(pixels)-1
    height = len(pixels[0])-1
    
    for y in xrange(height):
        for x in xrange(width):
   a=random.choice([0,1])
   if a==1 : b=(255,255,255)
   else : b=(0,0,0)
   pixels[x,y] = (b)
    pygame.display.update()
    done = False
    while not done:
        for e in pygame.event.get():
            if e.type == KEYDOWN:
                done = True
if __name__ == "__main__":
    main()
The most important is this line : 
pixels = pygame.surfarray.pixels3d(screen)
I use the random function to select "0" or "1" and set the colors.
Next, I fill the screen by update the screen with new values of pixels : pygame.display.update()
See below the result :

miercuri, 9 iunie 2010

PyGame : First interface - part 1


This is the first game based on pygame that I tried to use interface.
As shown in the picture below, we have three areas:
  • One at the top where there will be characters
  • One at the bottom where there will be buttons
  • A mini map on bottom left
I do not want to display the source code yet since it is rough.
I will present in future in a more understandable formula.
Good luck.

joi, 11 martie 2010

PyGame : OpenGL - part 2.

Today I will show you how we find stuff about graphics hardware.
We will use two modules: pyopengl and pygame.
Modules can import other modules.
Each module is only imported once per interpreter session.
>>> import pygame 
>>> import OpenGL 

The imports are taken in the local symbol table, so we need to do this:
>>> from pygame import *
>>> from OpenGL import *
>>> from OpenGL.GL import * 
>>> from OpenGL.GLUT import * 

The next thing you must do is call the function glutInit.
>>> glutInit()
['foo']

Use pygame init function to initialize the window:
>>> pygame.init()
(6, 0)
>>> pygame.display.set_mode((10,10),OPENGL|DOUBLEBUF)


Note:If we not create the window the next commands will not work.
About the beautiful glGetString function, we know.
This return a string describing the current GL connection.
You can use dir() and help() functions to see more.
But we see bellow, some example:
>>> dir(glGetString)
['__call__', '__class__', '__ctypes_from_outparam__', '__delattr__',
 '__dict__','__doc__', '__format__', '__getattribute__', '__hash__',
 '__init__', '__module__',
 '__name__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', 
'__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', 
'__subclasshook__',
 '__weakref__', '_b_base_', '_b_needsfree_', '_flags_', '_objects', 
'_restype_', 'argtypes', 'errcheck', 'restype']
>>> dir(glGetString())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', 
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Now, the parameters of this function are :
glGetString(GL_VERSION)
glGetString(GL_VENDOR)
glGetString(GL_RENDERER)
glGetStringi(GL_EXTENSIONS, i) 

Bellow, we see how we use these parameters:
>>> glGetString(GL_VERSION) 
'2.1.2 NVIDIA 173.14.22'
>>> glGetString(GL_VENDOR) 
'NVIDIA Corporation'
>>> glGetString(GL_RENDERER) 
'GeForce FX 5200/AGP/SSE/3DNOW!'

Because the GL_EXTENSIONS is a space-separated list of supported extensions to GL, we can use these commands:
>>> print glGetString(GL_EXTENSIONS)

Or you can format this result, see below
>>> print glGetString(GL_EXTENSIONS).split()
['GL_ARB_depth_texture', 'GL_ARB_fragment_program', ...

This is all.

sâmbătă, 28 martie 2009

PyGame : OpenGL - part 1

OpenGL is an application programming interface.
The PyOpenGL modules have many functions and several matrices for working with 3D graphics. This is one example of how to use PyOpenGL.
I've successfully tested it under Linux.

import os
import sys
import pygame
from pygame import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

def init_display(w, h):
 pygame.display.set_mode( (w,h) , pygame.OPENGL | pygame.DOUBLEBUF )
 glViewport(0, 0, w, h)
 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

 glEnable(GL_LIGHTING)

 glEnable(GL_LIGHT0)        

 glLight(GL_LIGHT0, GL_POSITION,  (0, 0, 1, 0))    
 glMatrixMode(GL_PROJECTION);

 glLoadIdentity();

 gluOrtho2D(-1, 1, -1, 1);

 glMatrixMode(GL_MODELVIEW);

def draw():
 glClearColor(0.0, 0.0, 0.0, 1.0)
 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
 glColor(0,1,0)
 glLight(GL_LIGHT0, GL_POSITION,  (1, 1, 1, 0))
 glMaterial(GL_FRONT, GL_AMBIENT, (0.1, 0.1, 0.1, 1.0))    

 glMaterial(GL_FRONT, GL_DIFFUSE, (1.0, 1.0, 1.0, 1.0))
 glutSolidTorus(0.1,0.5,24,24)
 pygame.display.flip()

def main():
 pygame.init()
 glutInit()
 init_display(800, 600)
 while 1:
  event=pygame.event.poll ()
  draw()
  if event.type is KEYDOWN:
   if event.key is K_ESCAPE:
    sys.exit(0)
main()

vineri, 27 februarie 2009

PyGame : How I used time on pygame.

This is a simple example.
The program shows some random colors.

import time
import random
import pygame

pygame.init()

def main():
    for i in range(60):
        screen = pygame.display.set_mode((800,600))
        pygame.display.set_caption("Some random colors!")

        bg = pygame.Surface(screen.get_size())
        bg = bg.convert()
        bg.fill((random.randint(1,255),random.randint(1,255),random.randint(1,255)))
        clock = pygame.time.Clock()
        Go = True
        while Go:
            clock.tick(2)
            screen.blit(bg,(0,0))
            pygame.display.flip()
            time.sleep(6)
            Go = False

if __name__ == "__main__":
    main()
As you see, try to create one loop:

        clock = pygame.time.Clock()
        Go = True
        while Go:
            clock.tick(2)
            ...  
            some code line 
            ...
            time.sleep(6)
            Go = False

miercuri, 18 februarie 2009

PyGame : Sounds in pygame.

First of all, you need two files. This is "load.py".

import os
import sys
import pygame
from pygame import mixer
pygame.mixer.init() 
def snd(nume):
    numeintreg = os.path.join("sunete",nume)
    sound = pygame.mixer.Sound(numeintreg)
    return sound
This is "main.py". The sounds "o.wav" can be any sound file.

import os
import sys
import pygame
from pygame import *
import load
def main():
     ocean=load.snd("o.wav")
     ocean.play()
main()

PyGame : Showing pictures on pygame

First of all, you need two files. This is "load.py"

import os
import sys
import pygame
def img(nume):
    numeintreg = os.path.join("date",nume)
    image = pygame.image.load(numeintreg)
    image = image.convert()
    return image
This is "main.py". The image "bk2.bmp" can be any image.
import os
import sys
import pygame
import load
def main():
    pygame.init()
    ecran = pygame.display.set_mode((640, 480))
    fundal = load.img('bk2.bmp')
    ecran.blit(fundal, (0, 0))
    pygame.display.flip()
main()

marți, 17 februarie 2009

PyGame : Keyboard on pygame

This is a short example of how to use the keyboard in pygame.

import os
import sys
import pygame
from pygame import *
def main():
   pygame.init()
   ecran = pygame.display.set_mode((640, 480))
   ruleaza= True
   action = "Help!"
   while ruleaza is True:
       for event in pygame.event.get():
           if event.type == QUIT:
               ruleaza == False
           elif event.type == KEYDOWN:
               if event.key == K_ESCAPE:
                   ruleaza = False
               elif event.key == K_LEFT:
                   action="L"
               elif event.key == K_RIGHT:
                   action="R"
           print action
main()

luni, 9 februarie 2009

About Pygame python module.

About PYGAME we can find out from web articles and we can get a picture of this python module:
Yet another powerful open source 2D game engine. Pygame is a set of modules allows you to create fully featured games and multimedia programs in the python language. Pygame is portable and runs on every platform and operating system.
Pygame is free. Released under the LGPL license, you can create an open source, free, freeware, shareware, and commercial games with it. See the license for full details.

The Python PyGame module is easy to use in both procedural and object programming.
The installation process is easy:
pip install pygame
The official web page can be found here.
The Wikipedia page with info about this python module can be found here.
The pypi webpage can be found here.
All documentation can be found on this webpage.