Pygame – Engine basilare

Post image of Pygame – Engine basilare

Ho trovato del codice che avevo scritto più di un anno fa e lo pubblico, è una base utile per capire come funziona pygame, un motore per il linguaggio python basato sulle sdl che offre rispetto ad esse una vasta gamma di funzioni orientate ai giochi a partire dalla classe sprite.
Per comodità ho messo ogni classe in una finestra diversa ma per provarlo mettete tutto in un’unico sorgente :D

#!/usr/bin/python
import pygame, os, sys
from pygame.locals import *

__all__ = ["keys","mouse","GameWindow","ImageLoader","FontManager"]
#variabili globali
keys = {}
mouse = []

class GameWindow:
  global schermo,keys,mouse
  game_running = True
  mouse_max = 12
  fps = 60
  def __init__(self,title,width=640,height=480,keylist=[]):
    self.width = width
    self.height = height
    pygame.init()
    self.schermo= pygame.display.set_mode((width,height),DOUBLEBUF)
    pygame.display.set_caption(title)
    self.keylist = keylist
    self.mouse = []
    self.keys = {}
    for i in range(self.mouse_max):
      self.mouse.append(False)
    for i in self.keylist:
      self.keys[i] = False
    #esporto in modo che e' possibile accedervi tramite var globali
    global keys,mouse
    schermo = self.schermo
    keys = self.keys
    mouse = self.mouse
  def game_end(self):
    pygame.display.quit()
    sys.exit(0)
  def run(self):
    clock = pygame.time.Clock()
    while (self.game_running):
      clock.tick(self.fps)
      for evento in pygame.event.get():
        self.input(evento)
      self.update()
      self.draw()
      pygame.display.flip()
    self.game_end()
  def input(self,evento):
    if evento.type == QUIT or (evento.type == KEYDOWN and evento.key == K_ESCAPE):
      self.__class__.game_running = False
      return
    if evento.type == KEYDOWN:
      if evento.key not in self.keylist:
        return
      self.keys[evento.key] = True
    elif evento.type == KEYUP:
      if evento.key not in self.keylist:
        return
      self.keys[evento.key] = False
    elif evento.type == MOUSEBUTTONDOWN:
      self.mouse[evento.button] = True
    elif evento.type == MOUSEBUTTONUP:
      self.mouse[evento.button] = False
  def update(self):
    pass
  def draw(self):
    self.schermo.fill(0x39d2c2)
class ImageLoader:
  img_path = "img" #la cartella dentro cui mettere le immagini
  ext = ".png"
  def __init__(self):
    if not pygame.image.get_extended():
      raise SystemExit, "Spiacente, e' necessaria la libreria SDL_image!"
  def image_path(self,name):
    return os.path.join(self.img_path,name+self.ext)
  def image_load(self,name):
    img_name = self.image_path(name)
    try:
      img = pygame.image.load(img_name)
    except pygame.error:
      raise SystemExit, 'Impossibile caricare "%s" %s'%(img_name, pygame.get_error())
    return img.convert()
  def image_load_raw(self,name):
    img_name = self.image_path(name)
    try:
      img = pygame.image.load(img_name)
    except pygame.error:
      raise SystemExit, 'Impossibile caricare "%s" %s'%(img_name, pygame.get_error())
    return img
class FontManager:
  f_path = "font"
  ext = ".ttf"
  def __init__(self):
    if not pygame.font:
      raise SystemExit, "Spiacente, e' necessaria la libreria SDL_font!"
    pygame.font.init()
    self.font_list = []
  def set_target(self,schermo):
    self.schermo = schermo
  def font_path(self,name):
    return os.path.join(self.f_path,name+self.ext)
  def font_load(self,name,size):
    f_name = self.font_path(name)
    try:
      self.font_list.append(pygame.font.Font(f_name,size))
    except pygame.error:
      raise SystemExit, 'Impossibile caricare "%s" %s'%(f_name, pygame.get_error())
    return len(self.font_list)-1
  def text(self,font_id,testo,colore):
    return self.font_list[font_id].render(testo,True,colore)
  def draw_text(self,x,y,testo):
    self.schermo.blit(testo,(x,y))
#in sviluppo   
class SoundManager:
  snd_path = "sound"
  def __init__(self):
    if not pygame.mixer:
      raise SystemExit, "Spiacente e' necessaria la libreria SDL_mixer!"
    pygame.mixer.init()
    self.sound_list = []
  def sound_path(self,name):
    return os.path.join(self.snd_path,name)
  def sound_load(self,name,loop):
    pass
if __name__ == "__main__":
  app = GameWindow("Example")
  app.run()
Posted by admin   @   16 January 2010

Like this post? Share it!

RSS Digg Twitter StumbleUpon Delicious Technorati Facebook

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

You must be logged in to post a comment.

Previous Post
«
Next Post
Powered by Wordpress   |   Lunated designed by ZenVerse   |   Logo by Luminoz