Pages

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

sâmbătă, 1 octombrie 2016

PyGame : Effects - part 003.

This is a part 003 from pygame tutorial series and is a little more advanced for you.
The reason comes with get_palette and set_palette functions and gif image with 8 bits.
Of course, I could use pygame.PixelArray but is not the purpose of this tutorial.
The python script comes with one surface screen, one surface for image and also one surface of a blur.
I set the resolution to be sized at 640,480. I have motion vectors for two directions and with this I make a circle follow path from sin and cos.
The path come from x and y variables ( width and height).
With angle_xd and angle_yd I increment the angles.
This is the result:
This is the source code:
import pygame, pygame.transform, pygame.image
from pygame.surfarray import *
from pygame.locals import *
from numpy import *
resolution  = array((640,480))
PI  = 3.14159
DEG2RAD = PI/180
print resolution[0], resolution[1]

def main():
    
    pygame.init()

    screen = pygame.display.set_mode(resolution,0,8)
    sprite = pygame.image.load("test_random.gif")
    sprite.set_palette(sprite.get_palette())
    sprite.set_colorkey((255,255,255))
    screen.set_palette(sprite.get_palette())
    area_work = pygame.Surface(resolution,0,8)
    area_work.set_palette(sprite.get_palette())

    angle_xd = 0
    angle_yd = 0
    
    while 1:

        for e in pygame.event.get():
            if e.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN):
                return
        x    = ((resolution[0])/5)*cos((angle_xd*DEG2RAD))+((resolution[0])/2-128)
        print x
        y    = ((resolution[1])/5)*sin((angle_yd*DEG2RAD))+((resolution[1])/2-128)
        angle_xd  += 1
        angle_yd  += 1
        area_work = pygame.transform.scale(screen, (resolution[0]+8,resolution[1]+8))
        tmp = pygame.surfarray.array2d(area_work)
        blur = array(tmp)
        blur[1:,:]  += tmp[:-1,:]*32
        blur[:-1,:] += tmp[1:,:]*32
        blur[:,1:]  += tmp[:,:-1]*32
        blur[:,:-1] += tmp[:,1:]*32
        blur /= 31
        blit_array(screen, blur[8:resolution[0]+32,8:resolution[1]+32])
        screen.blit(sprite,(x,y))
 pygame.display.update()

if __name__ == '__main__': main()

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 comes 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 the screen.

This is the effect result:
pygame python
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 makes 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 green 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.

miercuri, 29 august 2012

PyGame : Test class show text "Hello World" .

I wrote in my journal:
Today I received an email in which I asked about python and how to display a text message. I hate this approach, especially on the internet there are hundreds of materials on this subject.
This made ​​me remember my blog and I write a new tutorial on pygame.
I use the old class from last pygame tutorials, see here.
The source code it's pretty simple.
The news is function show_text().
To do this I use pygame functions, see pygame documentation.
Let's see the final source code.

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 text window")

  self.quit = False
  
 def update(self):
  print "update function"
  self.show_text()
  return
 
 def draw(self):
  self.screen.fill(color_black)
  self.show_text()
  pygame.display.flip()

 def show_text(self):
  font = pygame.font.Font(None, 36)
  text = font.render("Hello World!", 1, (100, 100, 100))
  textpos = text.get_rect()
  textpos.centerx = self.screen.get_rect().centerx
  self.screen.blit(text, textpos)

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

The result is this:

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.