logo

Les joysticks

Pygame reconnait les joysticks. Il suffit de les brancher, puis d'affecter à chaque bouton les actions voulues.

Un exemple

Voici l'exemple précédent avec les sprites, où on remplace les touches par un joystick :

from pygame import *
fenetre = display.set_mode((620,350))
display.set_caption('Tutoriel pygame')
init()
clock = time.Clock()


#les spritesheets
danse = image.load('danser.png')
danseSprite = [danse.subsurface((x%8)*110,(x//8)*128,110,128)for x in range(80)]
 
perso = image.load('professor.png')
imageSprite = {K_UP:[perso.subsurface(x,0,64,64)for x in range(0,576,64)],
               K_LEFT:[perso.subsurface(x,64,64,64)for x in range(0,576,64)],
               K_DOWN:[perso.subsurface(x,128,64,64)for x in range(0,576,64)],
               K_RIGHT:[perso.subsurface(x,192,64,64)for x in range(0,576,64)]}

#paramètres de départ
jouer = True
etat = 0
xSprite,ySprite = 202,202
direction = K_DOWN
index_img = 0
index_danse = 0 

# -------- boucle du jeu -----------
while jouer:
    #
    # les événements
    #
    # actions possibles joystick : JOYAXISMOTION, JOYBUTTONDOWN, JOYBUTTONUP
    for events in event.get():
        if events.type == QUIT: # fermer la fenetre de jeu
            jouer = False
        elif events.type == JOYBUTTONDOWN:
            print("Joystick button pressed.")
        elif events.type == JOYBUTTONUP:
            print("Joystick button released.")
        elif events.type == JOYAXISMOTION:
            print("Joystick croix.")

    # Pour chaque joystick:
    for j in range(joystick.get_count()):
        joysticky = joystick.Joystick(j)
        joysticky.init()

        #gestion croix
        axes = joysticky.get_numaxes()
        for i in range(axes):
            axis = joysticky.get_axis(i)
            #print(round(axis,1),i,"joy",j)
            if i==0 and axis<-0.5:
                direction = K_LEFT
                index_img = (index_img+1)%4
                xSprite = xSprite + round(axis,1)*8
            elif i==0 and axis>0.5:
                direction = K_RIGHT
                index_img = (index_img+1)%4
                xSprite = xSprite + round(axis,1)*8
            elif i==1 and axis<-0.5:
                direction = K_UP
                index_img = (index_img+1)%4
                ySprite = ySprite + round(axis,1)*8
            elif i==1 and axis>0.5:
                direction = K_DOWN
                index_img = (index_img+1)%4
                ySprite = ySprite + round(axis,1)*8
        #les boutons
        buttons = joysticky.get_numbuttons()
        for i in range(buttons):
            bouton = joysticky.get_button(i)
            #print("bouton "+str(i)+" appuyé",bouton)
            if bouton and i==2:
                etat=1
                xSprite,ySprite = 202,202
                direction = K_DOWN
                index_img = 0
                index_danse = 0 
            if bouton and i==4:
                etat=0
    if etat==1:
        fonte = font.SysFont('comicsansms', 20)
        text = fonte.render('Appuyer sur la gachette gauche pour quitter', True, (100, 255, 0), (0, 125, 255))
        fenetre.fill((200,200,200))
        fenetre.blit(text, (20, 300))
        fenetre.blit(imageSprite[direction][index_img],(xSprite,ySprite))
    if etat==0:
        fonte = font.SysFont('comicsansms', 36)
        text = fonte.render('Appuyer sur le bouton B', True, (0, 255, 0), (0, 5, 255))
        fenetre.fill((255,255,0))
        fenetre.blit(text, (20, 20))
        index_danse = (index_danse +1)%(len(danseSprite))
        fenetre.blit(danseSprite[index_danse],(100,100))
        
    #display.flip()
    display.flip()
    # 25 frames par seconde.
    clock.tick(25)

# quitter
quit()

Un exemple : le tank

Téléchargez les images suivantes :

Recopiez le code suivant dans le même dossier que les images et analysez-le.

from pygame import *
from math import *
fenetre = display.set_mode((820,850))
display.set_caption('Tutoriel pygame : le tank')
init()
clock = time.Clock()


#les images
canon = image.load('tank_canon.png')
tank = image.load('tank.png')
boulet = image.load('boulet.png')

#paramètres de départ
jouer = True
etat = 0
angle = 0
angle_canon = 0
xTank = 300
yTank = 300
tir=False

# -------- boucle du jeu -----------
while jouer:
    #
    # les événements
    #
    # actions possibles joystick : JOYAXISMOTION, JOYBUTTONDOWN, JOYBUTTONUP
    for events in event.get():
        if events.type == QUIT: # fermer la fenetre de jeu
            jouer = False
        elif events.type == JOYBUTTONDOWN:
            print("Joystick button pressed.")
        elif events.type == JOYBUTTONUP:
            print("Joystick button released.")
        elif events.type == JOYAXISMOTION:
            print("Joystick croix.")

    # Pour chaque joystick:
    for j in range(joystick.get_count()):
        joysticky = joystick.Joystick(j)
        joysticky.init()

        #gestion croix
        axes = joysticky.get_numaxes()
        for i in range(axes):
            axis = joysticky.get_axis(i)
            #print(round(axis,1),i,"joy",j)
            if i==0 and axis<-0.5:
                angle = (angle + 2)%360
            elif i==0 and axis>0.5:
                angle = (angle - 2)%360
            elif i==1 and axis<-0.5:
                xTank = xTank + cos(pi*(angle+90)/180)*8
                yTank = yTank - sin(pi*(angle+90)/180)*8
            elif i==1 and axis>0.5:
                xTank = xTank - cos(pi*(angle+90)/180)*8
                yTank = yTank + sin(pi*(angle+90)/180)*8
        #les boutons
        buttons = joysticky.get_numbuttons()
        for i in range(buttons):
            bouton = joysticky.get_button(i)
            #print("bouton "+str(i)+" appuyé",bouton)
            if bouton and i==2:
                if not tir:
                    tir= True
                    xboulet = -boulet.get_width()/2 + xTank + 75*cos(pi*(angle+angle_canon+90)/180)
                    yboulet = -boulet.get_height()/2 + yTank - 75*sin(pi*(angle+angle_canon+90)/180)
                    dx = cos(pi*(angle+angle_canon+90)/180)*20
                    dy =  -sin(pi*(angle+angle_canon+90)/180)*20
                    
            if bouton and i==4:
                angle_canon=angle_canon+2
            if bouton and i==5:
                angle_canon=angle_canon-2
    
    if etat==0:
        fenetre.fill((215,215,215))
        tank_rot = transform.rotate(tank,angle)
        canon_rot = transform.rotate(canon,angle+angle_canon)
        L,l=tank_rot.get_size()
        Lc,lc=canon_rot.get_size()
        fenetre.blit(tank_rot, (xTank-L/2, yTank-l/2))
        fenetre.blit(canon_rot, (xTank-Lc/2, yTank-lc/2))
        if tir:
            fenetre.blit(boulet, (xboulet, yboulet))
            xboulet = xboulet + dx
            yboulet = yboulet + dy
            if not 0<xboulet<800 or not 0<yboulet<850:
                tir = False
    #display.flip()
    display.flip()
    # 25 frames par seconde.
    clock.tick(25)

# quitter
quit()