Python : Pygame

De Justine's wiki
Aller à la navigation Aller à la recherche

Attention, pygame ne marche qu'en 3.7. Utilisé ici avec venv. https://fr.wikibooks.org/wiki/Pygame/Concevoir_des_jeux_avec_Pygame#Blitting (tuto daté)

Premier "jeu"

Ici, on affiche un texte dans une fenêtre:

<syntaxhighlight lang='python'>

  1. !/usr/bin/env python3
  2. coding: utf-8

import pygame from pygame.locals import *

  1. Initialisation

pygame.init()

                      1. !!! Gestion de la fenêtre
  1. Création de l'écran en 800*600
  2. Noter les deux parenthèses

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

  1. On change le nom de la fenêtre

pygame.display.set_caption("Justine Game")

  1. On remplit l'arrière-plan

background = pygame.Surface(screen.get_size()) background = background.convert()

  1. Les chiffres sont la couleur

background.fill((250,250,250))

      1. On affiche un texte

font = pygame.font.Font(None, 36)

  1. (Texte, anticrénelage (1 oui 0 non), couleur

text = font.render("Salut à tous", 1, (10, 10, 10))

  1. On fait un rectangle qui englobe le texte

textpos = text.get_rect()

  1. Le centre du rectangle est celui de la fenêtre

textpos.centerx = background.get_rect().centerx textpos.centery = background.get_rect().centery

  1. On blitte le texte dans la fenêtre

background.blit(text, textpos)

      1. On blitte le tout dans la fenêtre

screen.blit(background, (0,0))

  1. update de toute la surface

pygame.display.flip()


                      1. !!! Boucle principale

running = True

while running:

   #On veut pouvoir fermer la fenêtre !
   for event in pygame.event.get():
       if event.type == QUIT:
           running = False
   screen.blit(background, (0, 0))
   pygame.display.flip()

</syntaxhighlight>