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


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
         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)
   def check_hover(self, mouse):
      if self.obj.collidepoint(mouse):
         self.is_hover = True 
         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:
      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))
... 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

    import OpenGL
    from OpenGL.GL import *
    from OpenGL.GLU import *

    from OpenGL.GLUT import *

    from OpenGL.GL.EXT import *

    from OpenGL.GL.ARB.shader_objects import *
    from OpenGL.GL.ARB.vertex_shader import *
    from OpenGL.GL.ARB.fragment_shader import *
    from OpenGL.GL.ARB.multitexture import *

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
    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 - first interface - part 4

This is another tutorial about pygame.
Tha 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 *
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))
Let's start the pygame window and display the box.
if __name__ == '__main__':
        pygame.display.set_caption("Hello world")
        screen = pygame.display.set_mode((320,240))
        mess = []
        while 1:
                display_box(screen,"Hello world text")
                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 see in the next image.

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

vineri, 9 august 2013

PyGame - first interface - part 3

Today I will show you just few tips about pygame window.
If we want to put the window in the centre of the screen we can use this:
import os
os.environ['SDL_VIDEO_CENTERED'] = '1'
Most of the pygame windows is made by :
def main():
  background_colour = (25,25,255)
  screen = pygame.display.set_mode((320,240))
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

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 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 FONT is not here. I will try to fix this issue.

duminică, 3 martie 2013

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 error:

>>> im2=pygame.image.load("9.png")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
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: simple 2D game no need to use threads. Also bad configuration of game , wrong sprites , group classes used or using unoptimized images heavily and you will have a low performance.

5. Use profiler to test how much time your game spend on event handling, computing and drawing. Don't guess what is wrong?