joi, 22 septembrie 2016

PyGame - effects - part 002.

This is another tutorial about pygame and python 2.7 is very simple.
I make this tutorial for educational purposes for the children versus python language.
I used for most common variables the romanian language and this will allow you to understand well the variables versus python language script.
I used this version of python:
C:\Python27>python.exe
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
This python script come with few functions:
Imagine_hasurata - fill the image 
ImaginePicatura - draw drop
Pregatire - setup drawing
I let rect variable for python pygame sprite.py ( need to be set the name to rect from rectangle).
Also I have two python class to make the drop and trail drop into screen.

This is the effect result:

This is the python script:
#! /usr/bin/env python
import pygame, random
from pygame.locals import *

aleator = 1.5
ecran_x = 640
ecran_y = 480
acceleratie = 1.0
marime_picatura = (3, 3)
culoare_start = 255
culoare_stop = 0
culoare_intre = 2

def Imagine_hasurata(f, i):
    lungime = f - i + 1
    interval = (culoare_start - culoare_stop) / (culoare_intre + 1)
    imagini = []
    for x in range(culoare_intre):
        image = pygame.Surface((1, lungime)).convert()
        color = culoare_start - (x + 1)*interval
        image.fill((color, color, color))
        imagini.append(image)
    return imagini

def ImaginePicatura():
    image = pygame.Surface(marime_picatura).convert()
    image.fill((culoare_start, culoare_start, culoare_start))
    return image

def Pregatire(Picatura, trasa):
    y = 0.0
    v = 0.0
    ylist = []
    while int(y) <  ecran_y:
        ylist.insert(0, int(y))
        v = v + acceleratie
        y = y + v
    Picatura.ylist = ylist[:]
    ylist.insert(0, ecran_y)
    trasa.imageset = []
    for i in range(len(ylist) - 1):
        trasa.imageset.insert(0, Imagine_hasurata(ylist[i], ylist[i + 1]))

class Picatura(pygame.sprite.Sprite):
    def __init__(self, x):
        pygame.sprite.Sprite.__init__(self, self.updategroup, self.displaygroup)
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.trasaindex = 0
        self.ynum = len(self.ylist)
    def update(self):
        self.ynum = self.ynum - 1
        if self.ynum < 0:
            self.kill()
        else:
            self.rect.centery = self.ylist[self.ynum]
            Trasare(self, self.trasaindex)
            self.trasaindex = self.trasaindex + 1

class Trasare(pygame.sprite.Sprite):
    def __init__(self, Picatura, trasaindex):
        pygame.sprite.Sprite.__init__(self, self.updategroup)
        self.imagini = self.imageset[trasaindex]
        self.rect = self.imagini[0].get_rect()
        self.rect.midtop = Picatura.rect.center
        self.update = self.start
    def start(self):
        self.add(self.displaygroup)
        self.update = self.fade
        self.imagenum = 0
        self.fade()
    def fade(self):
        if self.imagenum == len(self.imagini):
            self.kill()
        else:
            self.image = self.imagini[self.imagenum]
            self.imagenum = self.imagenum + 1

def main():
    pygame.init()
    ecran = pygame.display.set_mode((ecran_x, ecran_y))
    fundal = pygame.Surface(ecran.get_rect().size)

    updategroup = pygame.sprite.Group()
    displaygroup = pygame.sprite.RenderUpdates()

    Picatura.image = ImaginePicatura()
    Pregatire(Picatura, Trasare)

    for thing in [Picatura, Trasare]:
        thing.updategroup = updategroup
        thing.displaygroup = displaygroup

    ceas = pygame.time.Clock()

    while 1:

        for event in pygame.event.get():
            if event.type == QUIT:
                return

        displaygroup.clear(ecran, fundal)
        updategroup.update()

        if random.random() < aleator:
            Picatura(random.randrange(ecran_x))

        pygame.display.update(displaygroup.draw(ecran))
        ceas.tick(10)

if __name__ == '__main__':
    main()

miercuri, 27 ianuarie 2016

PyGame - effects - part 001.

Today I come one simple and nice tutorial about pygame python module over python version 3.4 .
The python script just make two effects. First is one fade effect from transparent to black.I also added one green color.
Another effect come with the dizzy star base math python module and random python module.
Because this combined colors grean and blue are funny I make star blue.
The script is simple :
  • created variables;
  • make pygame windows; 
  • make fade background function;
  • make one class for shape ( and this can be updated );
  • make loop the game and escape key option;
  •  ... and finally add shape class and variable into loop pygame script.
Let's see the script:
# Cătălin George Feștilă 
# http://free-tutorials.org

import pygame
import random
import math
from pygame.locals import *

#initialize pygame and random seed
pygame.init()
random.seed()

#transparent to black for fade effect
def background_fade():
    rec = pygame.Surface(screensize)
    if frame != 0:
        rec.set_alpha(10)
        rec.fill((0,0,0))
    else:
        rec.set_alpha(255)
        rec.fill(draw_color)
    screen.blit(rec,(0,0))
    del rec

#all mathmatical shapes
class shape():
    xy = [0,0]   #location
    rot = [0.0,0.0] #rotation
    color = '.'   #color/shape value
    dim_size = 1
 #constructor
    def __init__(self,xy,dim_size,color):
        self.xy = xy
        self.dim_size = dim_size
        
        self.rot = [(random.random()*(math.pi)),.002]
        self.color = color
 
 #define shape
    def set_shape(self,color):
        self.color = color
    
 #draw shape    
    def draw(self):
        #rotation
        self.rot[0] += self.rot[1]
        if self.rot[0] &gt; math.pi*2:
            self.rot[0] -= math.pi*2
        #blue/star
        if self.color == 'blue':
            for x in range(5):
                pygame.draw.aaline(screen,(0,0,255),\
                        (((math.cos(self.rot[0]+(x*((math.pi*2)/5)))*self.dim_size)+self.xy[0]),\
                        ((math.sin(self.rot[0]+(x*((math.pi*2)/5)))*self.dim_size)+self.xy[1])),\
                        (((math.cos(self.rot[0]+((x+2)*((math.pi*2)/5)))*self.dim_size)+self.xy[0]),\
                        ((math.sin(self.rot[0]+((x+2)*((math.pi*2)/5)))*self.dim_size)+self.xy[1])),\
                        1)

#start main pygame effect
while 1:
    #create variable for pygame
    screensize = (640,480)
    screen = pygame.display.set_mode(screensize, 0, 32)
    clock = pygame.time.Clock()
    #set frame 
    frame = 0
    draw_color = [0,255,0]
    #reftime = pygame.time.get_ticks()
    text = pygame.font.Font(None,25)
    #start drawing
    while 1:
        clock.tick(30)
        shapetest=shape((320,240),100,'blue')
        shapetest.draw()
        #check if is pressed any key 
        pygame.event.get()
        #if is press escape key
        if pygame.key.get_pressed()[pygame.K_ESCAPE]:
            pygame.quit()
            exit()
        #print clock.get_fps() on windows title
        pygame.display.set_caption(str(clock.get_fps()))   
        pygame.display.update()
        #start fade background
        background_fade()
        #change var frame for background_fade
        frame += 1
        #stop when frame is 100
        if frame == 100:
         break

    frame = 0
    
    pygame.display.update()
    background_fade()

    frame += 1
I make one screenshot to see how it's working.

sâmbătă, 26 decembrie 2015

PyGame and Star Wars - tutorial from internet.

This web tutorial will show you how to make your Star Wars carnival.
The autor of this article - Koldo Santisteban show us how to deal with Arduino device and Pygame python module.

duminică, 21 decembrie 2014

PyGame - using sound, mixer, volume, channels, fade-in and out effect .

PyGame module come with sound feature and this allow users to test some effects.
The next source code will make a window and also will play a song.
After, You can test all effects with python version 3.4.1 .
Just see the keys from source code and test it. The song is a ogg file.
I used this sample from a recording of the album Through the Devil Softly by the artist Hope Sandoval and The Warm Inventions from here.

Let's see the python script:
import pygame, sys

blue = (55, 75, 155)
 
pygame.init()
pygame.display.set_caption('pygame - using sound effect')
size = [460, 100]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
 
# load sound file
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)

pygame.mixer.music.set_volume(0.5)
sound = pygame.mixer.Sound("bird.ogg")
snd_array = pygame.sndarray.array(sound)
snd_out = pygame.sndarray.make_sound(snd_array)
snd_out.play()

mychannel=pygame.mixer.find_channel()
while pygame.mixer.find_channel is None: 
    print (pygame.mixer.find_channel)
allchannels=pygame.mixer.get_num_channels()
print ('all channels - ',allchannels)
print ('duration -',sound.get_length(),' seconds')
print ('press 1 - play sound')
print ('press 2 - play sound in a loop')
print ('press 3 - play sound with 9 seconds fade-in effect')
print ('press 4 - play sound just for 9 seconds')
print ('press 5 - play sound 3 more times')
print ('press 9 - stop playing with fadeout effect set 9 ')
print ('press 0 - stop playing instantly')
print ('press up arrow key - up volume')
print ('press down arrow key - down volume')
 
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1:
                sound.play()
            if event.key == pygame.K_2:
                sound.play(-1)
            if event.key == pygame.K_3:
                sound.play(-1, fade_ms=9000)
            if event.key == pygame.K_4:
                sound.play(-1, 9000)
            if event.key == pygame.K_5:
                sound.play(3)
            if event.key == pygame.K_9:
                sound.fadeout(9000)
            if event.key == pygame.K_0:
                sound.stop()
            if event.key == pygame.K_UP:
                sound.set_volume(sound.get_volume()+0.1)
                print(sound.get_volume())
            if event.key == pygame.K_DOWN:
                sound.set_volume(sound.get_volume()-0.1)
                print(sound.get_volume())
    screen.fill(blue)
    pygame.display.update()
    clock.tick(10)

sâmbătă, 7 septembrie 2013

PyGame - first interface - part 6 .

I will show you how to make a menu with buttons using pygame module.

The example is simple but you can update with new features.

I will make some buttons : Start game, Options and Exit game.

The pygame come with rect function to draw rectangles.

I start with one python class named my_button.

Like any graphic interface is need to make visual elements and link with actions.

For each button I draw one rectangle with text and functions to check mouse.

The functions of my_button are:

label - will add some text;

color - change color when button is hovering:

draw - will deal with drawing the button ,color and mouse...;

check_hover - return boolean value based on mouse over my_button;

import pygame

pygame.init()

class my_button:
   def __init__(self, text):
      self.text = text
      self.is_hover = False
      self.default_color = (100,100,100)
      self.hover_color = (0,255,25)
      self.font_color = (0,0,255)
      self.obj = None
      
   def label(self):
      font = pygame.font.Font(None, 22)
      return font.render(self.text, 1, self.font_color)
      
   def color(self):
      if self.is_hover:
         return self.hover_color
      else:
         return self.default_color
         
   def draw(self, screen, mouse, rect_coord, label_coord):
      self.obj  = pygame.draw.rect(screen, self.color(), rect_coord)
      screen.blit(self.label(), label_coord)
      self.check_hover(mouse)
      
   def check_hover(self, mouse):
      if self.obj.collidepoint(mouse):
         self.is_hover = True 
      else:
         self.is_hover = False
         
if __name__ == '__main__':

         
   start = my_button('Start game')
   option = my_button('Option')
   exit = my_button('Exit game')
   
   screen = pygame.display.set_mode((400,350))
   clock = pygame.time.Clock()

   run = True
   while run:
      screen.fill((0,0,0))
      mouse = pygame.mouse.get_pos()
      for event in pygame.event.get():
         if event.type == pygame.QUIT:
            run = False
         elif event.type == pygame.MOUSEBUTTONDOWN:
            if my_button_.obj.collidepoint(mouse):
               print('my_button start clicked')
            elif my_button_2.obj.collidepoint(mouse):
               print('my_button option clicked')
            elif my_button_3.obj.collidepoint(mouse):
               print('my_button exit clicked')
      
      start.draw(screen, mouse, (100,100,120,22), (125,103))
      option.draw(screen, mouse, (100,130,120,22), (125,133))
      exit.draw(screen, mouse, (100,160,120,22), (125,163))
      
      pygame.display.update()
      clock.tick(50)

... and this is result of the pygame script.

luni, 2 septembrie 2013

PyGame - first interface - part 5

Today I worked with pygame and OpenGL python modules.

I want to make a simple script to test and load pygame , OpenGL modules.

This is the script and give me also in vars some opengl features.

If modules and features can be loaded then return True or False in some vars.

import sys

try:
    import OpenGL
    from OpenGL.GL import *
    bOpenGL=True
except:
    bOpenGL=False
   
try:
    from OpenGL.GLU import *
    bGLU=True
except:
    bGLU=False

try:
    from OpenGL.GLUT import *
    bGLUT=True
except:
    bGLUT=False

try:
    from OpenGL.GL.EXT import *
    bEXT=True  
except:
    bEXT=False

try:
    from OpenGL.GL.ARB.shader_objects import *
    bshader_objects=True
except:
    bshader_objects=False
try:
    from OpenGL.GL.ARB.vertex_shader import *
    bvertex_shader=True
except:
    bvertex_shader=False
try:
    from OpenGL.GL.ARB.fragment_shader import *
    bfragment_shader=True
except:
    bfragment_shader=False
try:    
    from OpenGL.GL.ARB.multitexture import *
    bmultitexture=True
except:
    bmultitexture=False

if sys.version_info.major < 3:
    print "Python vers=",sys.version_info
    print "bOpenGL=", bOpenGL
    print "OpenGL vers=",OpenGL.__version__
    print "bGLU=", bGLU
    print "bGLUT=", bGLUT
    print "bEXT=", bEXT
    print "bshader_objects=", bshader_objects
    print "bvertex_shader=", bvertex_shader
    print "bfragment_shader=", bfragment_shader
    print "bmultitexture=", bmultitexture
else:
    print ("Python vers=",sys.version_info)
    print ("bOpenGL=", bOpenGL)
    print ("OpenGL vers=",OpenGL.__version__)
    print ("bGLU=", bGLU)
    print ("bGLUT=", bGLUT)
    print ("bEXT=", bEXT)
    print ("bshader_objects=", bshader_objects)
    print ("bvertex_shader=", bvertex_shader)
    print ("bfragment_shader=", bfragment_shader)
    print ("bmultitexture=", bmultitexture)

The output result is this :

$ python test.py 
Python vers= sys.version_info(major=2, minor=7, micro=3, releaselevel='final', serial=0)
bOpenGL= True
OpenGL vers= 3.0.1
bGLU= True
bGLUT= True
bEXT= True
bshader_objects= True
bvertex_shader= True
bfragment_shader= True
bmultitexture= True

joi, 15 august 2013

Working with Pygame Subset for Android - part 1

If you want to using pygame with android the you need to deal with PGS4A.

You can read the steps from the website but also you can see this tutorial with one example.

I use the python pygame script from here.

I don't add anything to the script and it's working very well on my tablet.

Many users told us to use something like that:

import android
android.init()

I don't use this just the python script from my example.

First after you download and unrchive the PGS4A - Pygame Subset for Android go to in folder and will see this files:

usertest@home:~/pgs4a-0.9.6$ ls
android.py  blacklist.txt       doc               private         src
assets      buildlib            libs              python-install  templates
bin         default.properties  local.properties  res             whitelist.txt

Now you need to test it if is working well...

usertest@home:~/pgs4a-0.9.6$ ./android.py test

All systems go!

... and install the android SDK.You will need to give all answers is need it.

usertest@home:~/pgs4a-0.9.6$ ./android.py installsdk

I'm compiling a short test program, to see if you have a working JDK
on your system.


The JDK is present and working. Good!


I'm downloading Apache Ant. This might take a while.


I'm extracting Apache Ant.


I've finished unpacking Apache Ant.


Opening http://developer.android.com/sdk/terms.html in a web browser.


Do you accept the Android SDK Terms and Conditions?
yes/no> yes

I'm downloading the Android SDK. This might take a while.

Created new window in existing browser session.

I'm extracting the Android SDK.


I've finished unpacking the Android SDK.


I'm about to download and install the required Android packages. This
might take a while.

Refresh Sources:
  Fetching https://dl-ssl.google.com/android/repository/addons_list-2.xml
  Validate XML
  Parse XML
  Fetched Add-ons List successfully
  Refresh Sources
  Fetching URL: https://dl-ssl.google.com/android/repository/repository-7.xml
  Validate XML: https://dl-ssl.google.com/android/repository/repository-7.xml
....
    Starting ADB server succeeded.
  Done. 5 packages installed.

I'm updating the library packages.

Updated local.properties
No project name specified, using project folder name 'library'.
If you wish to change it, edit the first line of build.xml.
Added file android-sdk/extras/google/play_licensing/library/build.xml
Added file android-sdk/extras/google/play_licensing/library/proguard-project.txt
Updated local.properties
No project name specified, using project folder name 'downloader_library'.
If you wish to change it, edit the first line of build.xml.
Added file android-sdk/extras/google/play_apk_expansion/downloader_library/build.xml
Added file android-sdk/extras/google/play_apk_expansion/downloader_library/proguard-project.txt

I've finished installing the required Android packages.


I can create an application signing key for you. Signing an
application with this key allows it to be placed in the Android Market
and other app stores.

Do you want to create a key?
yes/no> yes

I will create the key in the android.keystore file.

You need to back this file up. If you lose it, you will not be able to
upgrade your application.

You also need to keep the key safe. If evil people get this file, they
could make fake versions of your application, and potentially steal
your users' data.

Will you make a backup of android.keystore, and keep it in a safe
place?
yes/no> yes

Please enter your name or the name of your organization.
> free-tutorials.org

I've finished creating android.keystore. Please back it up, and keep
it in a safe place.


It looks like you're ready to start packaging games.

After that let's see the files we have it...

usertest@home:~/pgs4a-0.9.6$ ls
android.keystore             bin                    local.properties
android.py                   blacklist.txt          private
android-sdk                  buildlib               python-install
android-sdk_r20-linux.tgz    default.properties     res
apache-ant                   doc                    src
apache-ant-1.8.4-bin.tar.gz  libpeerconnection.log  templates
assets                       libs                   whitelist.txt

My pygame script is locate in : ~/Dropbox/AndroidApp/pygame-android/test001.

How I make the android application ? First I configure the application. You need to give all answers when use configure args...

usertest@home:~/pgs4a-0.9.6/bin$ ./android.py configure ~/Dropbox/AndroidApp/pygame-android/test001

... next I build it. If you use : install then will expect the emulator or device to install it. I don't use install , just release.

usertest@home:~/pgs4a-0.9.6/bin$ ./android.py build ~/Dropbox/AndroidApp/pygame-android/test001 release

After that will see in the bin folder your android pygame application.

usertest@home:~/pgs4a-0.9.6/bin$ ls
AndroidManifest.xml    classes.dex.d  test001-1.ap_.d
AndroidManifest.xml.d  jarlist.cache  test001-1-release.apk
build.prop             proguard.txt   test001-1-release-unaligned.apk
classes                res            test001-1-release-unsigned.apk
classes.dex            test001-1.ap_  test001-1-release-unsigned.apk.d

Let's see how is working...