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

luni, 4 iunie 2018

PyGame : First interface - part 8.

The PyGame - first interface is a series of python tutorials using PyGame python module and other python modules that help us create a good interface.
If you look at the Wikipedia website then the first phrase is clear:
  In computing, an interface is a shared boundary across which two or more separate components of a computer system exchange information.
Today I will start with ThorPy python module.
This python module comes with the version 1.5.9.
You can read more about this python and test examples at the official webpage.
You can install this python module with the pip tool:

c:\Python364\Scripts>pip install thorpy
Collecting thorpy
  Downloading https://files.pythonhosted.org/packages/09/aa/...
.../thorpy-1.6.tar.gz (373kB)
    100% |████████████████████████████████| 378kB 374kB/s
<5 .10="" python_version=""><2 .0.0=""><2 .0.0="">...
Installing collected packages: thorpy
Successfully installed thorpy-1.6

This is the result of submenus from official website.

duminică, 28 ianuarie 2018

PyGame : Test with an animated image.

This is a simple tutorial about how to create a bouncing ball effect with pygame python module.
The source code is very simple and you need a transparent image named earth.png .
The variables I used is size, speed, ball, ballrect.
I used ballrect with  get_rect().
The result get pygame Rect object.
This  has several virtual attributes which can be used to move and align the Rect:

  • x,y
  • top, left, bottom, right
  • topleft, bottomleft, topright, bottomright
  • midtop, midleft, midbottom, midright
  • center, centerx, centery
  • size, width, height
  • w,h

All of these attributes can be assigned to ballrect variable.
import sys
import pygame
pygame.init()
 
size = width, height = 640, 420
speed = [1, 1]
black = 0, 0, 0
 
screen = pygame.display.set_mode(size)
 
ball = pygame.image.load("earth.png")
ballrect = ball.get_rect()
 
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
 
    ballrect = ballrect.move(speed)
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]
 
    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()

pygame.display.update()
The result of this source code :

luni, 21 august 2017

PyGame : The pymunk python module.

First about pymunk python module:
Pymunk is an easy-to-use pythonic 2d physics library that can be used whenever you need 2d rigid body physics from Python. Perfect when you need 2d physics in your game, demo or other application!
I install it with pip and python 2.7 and I test it with one example from the official website.
The source code is this:

import sys, random
import os

description = """
---- Newton's Cradle ----
A screensaver version of Newton's Cradle with an interactive mode
/s - Run in fullscreen screensaver mode
/p #### - Display a preview of the screensaver using a window handler
/i - Interactive mode
"""

if len(sys.argv) < 2:
    print(description)
    sys.exit()

is_interactive = False
display_flags = 0
if sys.argv[1] == "/p":  # preview mode
    os.environ['SDL_VIDEODRIVER'] = 'windib'
    os.environ['SDL_WINDOWID'] = sys.argv[2]
    display_size = (100, 100)
    is_interactive = False

### We must set OS env before the pygame imports..
import pygame
from pygame.locals import *
from pygame.color import *

if sys.argv[1] == "/s":  # fullscreen screensaver mode
    display_size = (0, 0)
    is_interactive = False
    display_flags = display_flags | FULLSCREEN  # FULLSCREEN) # | DOUBLEBUF | HWSURFACE     )
elif sys.argv[1] == "/i":  # interactive
    display_size = (600, 600)
    is_interactive = True

import pymunk as pm
from pymunk import Vec2d


def drawcircle(image, colour, origin, radius, width=0):
    if width == 0:
        pygame.draw.circle(image, colour, origin, int(radius))
    else:
        if radius > 65534 / 5:
            radius = 65534 / 5
        circle = pygame.Surface([radius * 2 + width, radius * 2 + width]).convert_alpha()
        circle.fill([0, 0, 0, 0])
        pygame.draw.circle(circle, colour, [circle.get_width() / 2, circle.get_height() / 2], radius + (width / 2))
        if int(radius - (width / 2)) > 0:
            pygame.draw.circle(circle, [0, 0, 0, 0], [circle.get_width() / 2, circle.get_height() / 2],
                               abs(int(radius - (width / 2))))
        image.blit(circle, [origin[0] - (circle.get_width() / 2), origin[1] - (circle.get_height() / 2)])

def reset_bodies(space):
    for body in space.bodies:
        body.position = Vec2d(body.start_position)
        body.force = 0, 0
        body.torque = 0
        body.velocity = 0, 0
        body.angular_velocity = 0
    color = random.choice(list(THECOLORS.values()))
    for shape in space.shapes:
        shape.color = color

def main():
    pygame.init()
    screen = pygame.display.set_mode(display_size, display_flags)
    width, height = screen.get_size()

    def to_pygame(p):
        """Small hack to convert pymunk to pygame coordinates"""
        return int(p.x), int(-p.y + height)

    def from_pygame(p):
        return to_pygame(p)

    clock = pygame.time.Clock()
    running = True
    font = pygame.font.Font(None, 16)

    ### Physics stuff
    space = pm.Space()
    space.gravity = (0.0, -1900.0)
    space.damping = 0.999  # to prevent it from blowing up.
    mouse_body = pm.Body(body_type=pm.Body.KINEMATIC)

    bodies = []
    for x in range(-100, 150, 50):
        x += width / 2
        offset_y = height / 2
        mass = 10
        radius = 25
        moment = pm.moment_for_circle(mass, 0, radius, (0, 0))
        body = pm.Body(mass, moment)
        body.position = (x, -125 + offset_y)
        body.start_position = Vec2d(body.position)
        shape = pm.Circle(body, radius)
        shape.elasticity = 0.9999999
        space.add(body, shape)
        bodies.append(body)
        pj = pm.PinJoint(space.static_body, body, (x, 125 + offset_y), (0, 0))
        space.add(pj)

    reset_bodies(space)
    selected = None

    if not is_interactive:
        pygame.time.set_timer(USEREVENT + 1, 70000)  # apply force
        pygame.time.set_timer(USEREVENT + 2, 120000)  # reset
        pygame.event.post(pygame.event.Event(USEREVENT + 1))
        pygame.mouse.set_visible(False)

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "newtons_cradle.png")

            if event.type == pygame.USEREVENT + 1:
                r = random.randint(1, 4)
                for body in bodies[0:r]:
                    body.apply_impulse_at_local_point((-6000, 0))
            if event.type == pygame.USEREVENT + 2:
                reset_bodies(space)

            elif event.type == KEYDOWN and event.key == K_r and is_interactive:
                reset_bodies(space)
            elif event.type == KEYDOWN and event.key == K_f and is_interactive:
                r = random.randint(1, 4)
                for body in bodies[0:r]:
                    body.apply_impulse_at_local_point((-6000, 0))

            elif event.type == MOUSEBUTTONDOWN and is_interactive:
                if selected != None:
                    space.remove(selected)
                p = from_pygame(Vec2d(event.pos))
                hit = space.point_query_nearest(p, 0, pm.ShapeFilter())
                if hit != None:
                    shape = hit.shape
                    rest_length = mouse_body.position.get_distance(shape.body.position)
                    ds = pm.DampedSpring(mouse_body, shape.body, (0, 0), (0, 0), rest_length, 1000, 10)
                    space.add(ds)
                    selected = ds

            elif event.type == MOUSEBUTTONUP and is_interactive:
                if selected != None:
                    space.remove(selected)
                    selected = None

            elif event.type == KEYDOWN:
                running = False
            elif event.type == MOUSEBUTTONDOWN:
                running = False

        mpos = pygame.mouse.get_pos()
        p = from_pygame(Vec2d(mpos))
        mouse_body.position = p

        ### Clear screen
        screen.fill(THECOLORS["black"])

        ### Draw stuff
        for c in space.constraints:
            pv1 = c.a.position + c.anchor_a
            pv2 = c.b.position + c.anchor_b
            p1 = to_pygame(pv1)
            p2 = to_pygame(pv2)
            pygame.draw.aalines(screen, THECOLORS["lightgray"], False, [p1, p2])

        for ball in space.shapes:
            p = to_pygame(ball.body.position)
            drawcircle(screen, ball.color, p, int(ball.radius), 0)
            # pygame.draw.circle(screen, ball.color, p, int(ball.radius), 0)

        ### Update physics
        fps = 50
        iterations = 25
        dt = 1.0 / float(fps) / float(iterations)
        for x in range(iterations):  # 10 iterations to get a more stable simulation
            space.step(dt)

        ### Flip screen
        if is_interactive:
            screen.blit(font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]), (0, 0))
            screen.blit(font.render("Press left mouse button and drag to interact", 1, THECOLORS["darkgrey"]),
                        (5, height - 35))
            screen.blit(font.render("Press R to reset, any other key to quit", 1, THECOLORS["darkgrey"]),
                        (5, height - 20))

        pygame.display.flip()
        clock.tick(fps)

if __name__ == '__main__':
    sys.exit(main()

I test with this command:

C:\Python27>python.exe newtons_cradle.py /i

The result work well, see the next image: 

sâmbătă, 29 iulie 2017

PyGame : The experimental gfxdraw.

This is a tutorial about gfxdraw how to use.
Note: this is an EXPERIMENTAL feature for PyGame ( meaning this API may change, or disappear in later pygame releases).
First about this gfxdraw we can use this:
  • pygame module for drawing shapes
  • pygame.gfxdraw.pixel — place a pixel
  • pygame.gfxdraw.hline — draw a horizontal line
  • pygame.gfxdraw.vline — draw a vertical line
  • pygame.gfxdraw.rectangle — draw a rectangle
  • pygame.gfxdraw.box — draw a box
  • pygame.gfxdraw.line — draw a line
  • pygame.gfxdraw.circle — draw a circle
  • pygame.gfxdraw.arc — draw an arc
  • pygame.gfxdraw.aacircle — draw an anti-aliased circle
  • pygame.gfxdraw.filled_circle — draw a filled circle
  • pygame.gfxdraw.ellipse — draw an ellipse
  • pygame.gfxdraw.aaellipse — draw an anti-aliased ellipse
  • pygame.gfxdraw.filled_ellipse — draw a filled ellipse
  • pygame.gfxdraw.pie — draw a pie
  • pygame.gfxdraw.trigon — draw a triangle
  • pygame.gfxdraw.aatrigon — draw an anti-aliased triangle
  • pygame.gfxdraw.filled_trigon — draw a filled trigon
  • pygame.gfxdraw.polygon — draw a polygon
  • pygame.gfxdraw.aapolygon — draw an anti-aliased polygon
  • pygame.gfxdraw.filled_polygon — draw a filled polygon
  • pygame.gfxdraw.textured_polygon — draw a textured polygon
  • pygame.gfxdraw.bezier — draw a Bézier curve
Nou about the example I will use into this tutorial. Is a very simple class with an anti-aliased ellipse.
This class used pygame.gfxdraw.aaellipse , see the doc:
pygame.gfxdraw.aaellipse()
    draw an anti-aliased ellipse
      aaellipse(surface, x, y, rx, ry, color) -> None
      Draws anti aliased edges of an ellipse onto a surface.
#!/usr/bin/python

import random
import math

import pygame
from pygame.locals import *
from pygame import *
from pygame import gfxdraw

#create a math function
def linear_interp(a, b, x):
 return a*(1-x) + b*x

#a class python to show on display
class Screen():
 def __init__(self):
  pygame.init()

  self.display_flags = DOUBLEBUF
  rect = self.width, self.height = 640, 480

  if pygame.display.mode_ok(rect, self.display_flags):
   self.screen = pygame.display.set_mode(rect, self.display_flags)

 def shell_print(self,text):
  print text

 def aaellipse(self,surface, x, y, rx, ry, color):
  pygame.gfxdraw.ellipse(surface, x, y, rx, ry, color)

show = Screen()

run = 1
clock = pygame.time.Clock()

show.shell_print("test")
show.aaellipse(show.screen, x=300, y=200, rx=100, ry=60, color=(8, 8, 160))

while run:
 events = pygame.event.get()

 for event in events:
  if event.type == QUIT:
   run = 0

 pygame.display.flip()

 clock.tick(60)
To understand the class methods I used two: shell_print and aaellipse.
The shell_print is used just to print a input text to python shell.
The aaellipse take all inputs for the default pygame.gfxdraw.ellipse.
The result is a simple blue ellipse at 300 and 200 points and sized with 100 and 60.
Another aspect to note is use of the surface into show.aaellipse : show.screen.
This means that the drawing screen is used and not another defined surface.
Of course we can change Screen class to help us - decorators, other defining surfaces, initializations...

vineri, 26 mai 2017

PyGame : First interface - part 7.

Today I will start with another feature: add text from the keyboard.
The interface needs to be filled with text and a good way is to read the keyboard.
My example using this feature and print the text into one row and let you erase chars when you typing.
First, you need to know I used python version 2.7.13 and the last pygame version 1.9.2.0a from here.
I used also the PyCharm version Community Edition 2017.1.3.
Let see the source code for this example:
import pygame
from pygame.locals import *

def name():
    pygame.init()
    screen = pygame.display.set_mode((480, 360))
    name = ""
    font = pygame.font.Font(None, 50)
    while True:
        for evt in pygame.event.get():
            if evt.type == KEYDOWN:
                if evt.unicode.isalpha():
                    name += evt.unicode
                elif evt.key == K_BACKSPACE:
                    name = name[:-1]
                elif evt.key == K_SPACE:
                    name = name+str(" ")
            elif evt.type == QUIT:
                return
        screen.fill((0, 0, 0))
        block = font.render(name, True, (255, 255, 255))
        rect = block.get_rect()
        rect.center = screen.get_rect().center
        screen.blit(block, rect)
        pygame.display.flip()

if __name__ == "__main__":
    name()
The result of this python script can see into image below:

joi, 25 mai 2017

PyGame : Fix error install pygame module on python 3.4.

Today I started to install pygame with python 3.4.1.
I got a lot of errors first with pip tool, see all errors.
C:\Python34\Scripts>pip install pygame
Downloading/unpacking pygame
  Running setup.py (path:C:\Users\mythcat\AppData\Local\Temp\pip_build_mythcat\
pygame\setup.py) egg_info for package pygame


    WARNING, No "Setup" File Exists, Running "config.py"
    Using WINDOWS configuration...

    Path for SDL not found.
    Too bad that is a requirement! Hand-fix the "Setup"
    Path for FONT not found.
    Path for IMAGE not found.
    Path for MIXER not found.
    Path for PNG not found.
    Path for JPEG not found.
    Path for PORTMIDI not found.
    Path for COPYLIB_tiff not found.
    Path for COPYLIB_z not found.
    Path for COPYLIB_vorbis not found.
    Path for COPYLIB_ogg not found.

    If you get compiler errors during install, doublecheck
    the compiler flags in the "Setup" file.


    Continuing With "setup.py"
    Error with the "Setup" file,
    perhaps make a clean copy from "Setup.in".
    Traceback (most recent call last):
      File "", line 17, in 
      File "C:\Users\mythcat\AppData\Local\Temp\pip_build_mythcat\pygame\setup.py", line 165, in 
        extensions = read_setup_file('Setup')
      File "C:\Python34\lib\distutils\extension.py", line 164, in read_setup_file
        line = expand_makefile_vars(line, vars)
      File "C:\Python34\lib\distutils\sysconfig.py", line 423, in expand_makefile_vars
        s = s[0:beg] + vars.get(m.group(1)) + s[end:]
    TypeError: Can't convert 'NoneType' object to str implicitly
    Complete output from command python setup.py egg_info:

WARNING, No "Setup" File Exists, Running "config.py"

Using WINDOWS configuration...

Path for SDL not found.

Too bad that is a requirement! Hand-fix the "Setup"

Path for FONT not found.

Path for IMAGE not found.

Path for MIXER not found.

Path for PNG not found.

Path for JPEG not found.

Path for PORTMIDI not found.

Path for COPYLIB_tiff not found.

Path for COPYLIB_z not found.

Path for COPYLIB_vorbis not found.

Path for COPYLIB_ogg not found.

If you get compiler errors during install, doublecheck

the compiler flags in the "Setup" file.

Continuing With "setup.py"

Error with the "Setup" file,

perhaps make a clean copy from "Setup.in".

Traceback (most recent call last):

  File "", line 17, in 

  File "C:\Users\mythcat\AppData\Local\Temp\pip_build_mythcat\pygame\setup.py", line 165, in 

    extensions = read_setup_file('Setup')

  File "C:\Python34\lib\distutils\extension.py", line 164, in read_setup_file

    line = expand_makefile_vars(line, vars)

  File "C:\Python34\lib\distutils\sysconfig.py", line 423, in expand_makefile_vars

    s = s[0:beg] + vars.get(m.group(1)) + s[end:]

TypeError: Can't convert 'NoneType' object to str implicitly

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in C:\Users\mythcat\AppData\Local\Temp\pip_build_mythcat\pygame
Storing debug log for failure in C:\Users\mythcat\pip\pip.log

C:\Python34\Scripts>pip install pygame-1.9.3-cp34-cp34m-win_amd64.whl
pygame-1.9.3-cp34-cp34m-win_amd64.whl is not a supported wheel on this platform.
Storing debug log for failure in C:\Users\mythcat\pip\pip.log

C:\Python34\Scripts>pip3 install pygame-1.9.3-cp34-cp34m-win_amd64.whl
pygame-1.9.3-cp34-cp34m-win_amd64.whl is not a supported wheel on this platform.
Storing debug log for failure in C:\Users\mythcat\pip\pip.log
The solution come with the executable pygame-1.9.2a0-hg_8d9e6a1f2635%2B.win-amd64-py3.4.msi from here and now working very well.

duminică, 12 martie 2017

PyGame : How play ogg file.

Let's see how to play file.ogg file with pygame python module.
import pygame
import time
pygame.init()
pygame.mixer.music.load('file.ogg')
pygame.mixer.music.play()
time.sleep(1.5)

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.

sâmbătă, 26 decembrie 2015

PyGame : The Star Wars - tutorial from internet.

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

duminică, 21 decembrie 2014

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

PyGame module comes with sound feature and this allows 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 an 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 needed 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 the button is hovering:
draw - will deal with drawing the button, color, and mouse...;
check_hover - return boolean value based on mous eover 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 the 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

PyGame : Working with Pygame Subset for Android.

This is an old tutorial I make for PGS4A - Pygame Subset for Android
I tried to rebuild this python module but it does not exist.
For me, it is the end of this series of tutorials.
Read this tutorial if you have PGS4A.

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 tell 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 unarchive the PGS4A - Pygame Subset for Android go to in folder and will see these 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 the 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&gt; 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&gt; 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&gt; yes

Please enter your name or the name of your organization.
&gt; 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 located 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 configures 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...

PyGame : First interface - part 4.

This is another tutorial about pygame.
The main goal of this tutorial is to make one box with some text for your application or game.
First, I import the pygame module and I set two colors: black and green:
import pygame
import pygame.font
import pygame.event
import pygame.draw
import string
from pygame.locals import *
black=(0,0,0)
green=(0,255,0)
Tne next step is to make a function to create the display box.
def display_box(screen,mess):
        fontobject = pygame.font.Font(None,18)
        pygame.draw.rect(screen,black,((screen.get_width() / 2) - 100,
                (screen.get_height() / 2) - 10,200,20), 0)
        pygame.draw.rect(screen,green,((screen.get_width() / 2) - 101,
                (screen.get_height() / 2) - 11,200,20), 1)
        if len(mess) != 0:
                screen.blit(fontobject.render(mess, 1, (25,255,25)),
                ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 9))
        pygame.display.flip()
Let's start the pygame window and display the box.
if __name__ == '__main__':
        pygame.init()
        pygame.display.set_caption("Hello world")
        screen = pygame.display.set_mode((320,240))
        pygame.font.init()
        mess = []
        while 1:
                display_box(screen,"Hello world text")
                pygame.display.update()
                pygame.time.delay(10)
                for event in pygame.event.get():
                        if event.type in (pygame.QUIT,pygame.KEYDOWN,pygame.MOUSEBUTTONDOWN):
                                raise SystemExit
The result of this source of code can be seen in the next image.

You can also change this source of code to make editbox or other GUI elements.

vineri, 9 august 2013

PyGame : First interface - part 3.

Today I will show you just a few tips about pygame window.
If we want to put the window in the center of the screen we can use this:
import os
os.environ['SDL_VIDEO_CENTERED'] = '1'
Most of the pygame windows are made by :
def main():
  background_colour = (25,25,255)
  screen = pygame.display.set_mode((320,240))
  screen.fill(background_colour)
This will create this window:

Now if you don't need a title window, like the next image...

... then you need to use this source code :
  screen = pygame.display.set_mode((320,240),NOFRAME)

luni, 24 iunie 2013

PyGame : The pygame module come without font module.

Today I try to see some old python source code.
I got this error and seam many python users have the same error.
NotImplementedError: font module not available
(ImportError: No module named font)
It's the last release of pygame.
When I try to config the pygame I got this
pygame-1.9.1release]$ python2.7 config.py
Using UNIX configuration...


Backup existing "Setup" file [Y/n]:

Hunting dependencies...
sh: smpeg-config: command not found
WARNING: "smpeg-config" failed!
SDL     : found 1.2.13
FONT    : not found
IMAGE   : found
MIXER   : not found
SMPEG   : not found
PNG     : found
JPEG    : found
SCRAP   : found
PORTMIDI: not found
PORTTIME: not found


Warning, some of the pygame dependencies were not found. Pygame can still
compile and install, but games that depend on those missing dependencies
will not run. Would you like to continue the configuration? [Y/n]:
Not only the FONT is not here. I will try to fix this issue.

duminică, 3 martie 2013

PyGame : 5 simple rules help you to programming in pygame.

Some rules when you want to use pygame:
1. Use hardware rendering :
>>> import pygame 
>>> show=pygame.display.set_mode((400,400), pygame.HWSURFACE | pygame.DOUBLEBUF)
2. Use function convert and load BMP file.
>>> im=pygame.image.load("9.bmp").convert()
... also you got the error:
>>> im2=pygame.image.load("9.png")
Traceback (most recent call last):
  File "", line 1, in 
pygame.error: File is not a Windows BMP file
3. Don't use reserved words in your variables, like display, time ...
4. Be advice about low performance. For example, a simple 2D game no needs to use threads. Also the bad configuration of game, wrong sprites, group classes used or using unoptimized images heavily and you will have a low performance.
5. Use the profiler to test how much time your game spend on event handling, computing, and drawing. Don't guess what is wrong?

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: