This is an old revision of the document!


Laborator 3 - PyGame/Phaser

PyGame

Introducere

PyGame este o bibliotecă Python folosită pentru creearea de jocuri și aplicații multimedia. PyGame este bazat pe biblioteca SDL.

Creearea unei ferestre

Pentru a putea desena, avem nevoie de o fereastră. Pentru a creea o astfel de fereastră se apelează funcția set_mode() can în exemplu de mai jos. Această funcție primește ca argument un tuplu cu 2 elemente ce reprezintă rezoluția ferestrei.

import pygame
 
screen = pygame.display.set_mode((800, 600))

Bucla principală

Pentru dezvoltarea aplicațiilor grafice, avem nevoie de o buclă infinită creeată explicit de programator. Astfel, la fiecare pas al buclei, putem modifica starea programului în funcție de input-ul utilizatorului și de evenimentele declanșate de diferite componente ale acestuia.

import pygame
 
screen = pygame.display.set_mode((800, 600))
 
running = True
while running:
    # procesare evenimente utilizator
 
    # verificare eveniment de ieșire (de exemplu dacă utilizatorul apasă tasta Esc sau butonul X
    if eveniment_iesire():
        running = False
 
    # modificare stare curentă a jocului
 
    # desenare stare curentă a jocului modificată la pasul anterior
 
    # Este necesară apelarea funcției flip() pentru a desena ce s-a modifcat la pasul anterior
    pygame.display.flip()
 
pygame.quit()

Desenare

Pentru a desena elemente grafice în PyGame, folosim pygame.draw

După cum puteți obseva în link-ul anterior, există mai multe forme suportate de pygame. Drept exemplu, vom desena un dreptunghi:

# -*- coding: utf-8 -*-
 
import pygame
 
screen = pygame.display.set_mode((800, 600))
 
# pygame.draw.rect(Surface, color, Rect, width=0) -> Rect
# După cum puteți vedea din semnătura functiei draw.rect(), aceasta
# primește:
#   - o suprafață pe care să deseneze dreptunghiul
#   - o culoare, în format RGB
#   - un obiect de tip Rect
#        Rect(left, top, width, height) -> Rect
#         
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(120, 120, 200, 100))
 
# Afișam modificările pe ecran
pygame.display.flip()
 
# Așteptăm 3000 ms pentru a vedea rezultatul desenării
pygame.time.wait(3000)

Adăugare imagini

Pentru a adăuga o imagine, procedăm în același fel, dar mai întâi, încărcăm imaginea în memorie.

import pygame
 
screen = pygame.display.set_mode((800, 600))
 
# Încărcăm imaginea în memorie
image = pygame.image.load('image.png')
 
# Transferăm pixelii imaginii în fereastră
screen.blit(image, (0, 0))
 
pygame.display.flip()
 
# Așteptăm din nou 3000 de milisecunde pentru a vedea imaginea desenată
pygame.time.wait(3000)

Input de la utilizator

import pygame
 
screen = pygame.display.set_mode((800, 600))
running = True
while running:
    for event in pygame.event.get():
        # Calea noastra de iesire, declansat cand inchidem fereastra.
        if event.type == pygame.QUIT:
            running = False
            break
 
        if event.type == KEYDOWN:
            if event.key == K_UP:
                print 'sageata sus'
            elif event.key == K_DOWN:
                print 'sageata jos'
            elif event.key == K_LEFT:
                print 'sageata stanga'
            elif event.key == K_RIGHT:
                print 'sageata dreapta'
            elif event.key == K_SPACE:
                print 'space'
 
pygame.quit()

Demo

În această arhivă puteți găsi jocul Pong scris în PyGame. Mai multe detalii despre cum funcționează acesta veți primi în timpul laboratorului.

pong.zip

Instalare python și pip pe Windows fără drepturi de administrator

- Descărcați Python:

https://www.python.org/ftp/python/2.7.12/python-2.7.12.msi

- Navigați în directorul în care ați descărcat Python și rulați comanda de mai jos pentru instalare:

msiexec /a python-2.7.12.msi /qb TARGETDIR=C:\development\

- Descărcați scriptul de mai jos și salvați-l în directorul C:\development (folosiți Click dreapta → Save link as):

https://bootstrap.pypa.io/get-pip.py

- Navigați în directorul C:\development și rulati comanda:

python.exe get-pip.py

- Rulati comanda de mai jos pentru a instala pygame

python.exe Lib\site-packages\pip\__main__.py install pygame --user

- Din directorul C:\development puteți rula orice script folosind:

python.exe $nume_script

Phaser

Exerciții

Creeați un joc la alegere pornind de la unul dintre scheletele de cod de mai jos.

- Python/PyGame

main.py
import pygame
import sys
 
WIDTH = 800
HEIGHT = 600
 
FPS = 60
 
COLOR_BLACK = (0, 0, 0)
COLOR_RED = (255, 0, 0)
 
def main():
    # Initialize imported pygame modules
    pygame.init()
 
    # Set the window's caption
    pygame.display.set_caption("Pong")
 
    clock = pygame.time.Clock()
 
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
 
    background = pygame.Surface((WIDTH, HEIGHT))
    background = background.convert()
    background.fill(COLOR_BLACK)
 
    # Blit everything to screen
    screen.blit(background, (0, 0))
 
    # Update the screen
    pygame.display.flip()
 
    # Main loop
    while True:
        clock.tick(FPS)
 
        # Erase everything drawn at last step by filling the background
        # with color black
        background.fill(COLOR_BLACK)
 
        # Check for Quit event
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
 
        # Check for key presses and update paddles accordingly
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_w]:
            # Do something
            pass
        if keys_pressed[pygame.K_s]:
            # Do something
            pass
        if keys_pressed[pygame.K_UP]:
            # Do something
            pass
        if keys_pressed[pygame.K_DOWN]:
            # Do something
            pass
 
        # Update game state
 
        # Render current game state
        pygame.draw.rect(background,
                     COLOR_RED,
                     pygame.Rect(100, 120, 200, 400))
 
        pygame.display.flip()
        screen.blit(background, (0, 0))
 
 
if __name__ == '__main__':
    main()

- JavaScript/Phaser

main.js
 

https://phaser.io/sandbox/

http://www.zekechan.net/getting-started-html5-game-development-pong1/

https://github.com/zekechan/phaser-html5-tutorial-pong

ii/lab/laborator3.1479973969.txt.gz · Last modified: 2016/11/24 09:52 by iulian_gabriel.radu
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0