1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
def clavier(event):
""" Gestion de l'événement Appui sur une touche du clavier """
global posX, posY
# init nom de touche clavier
touche = event.keysym
# init position par avance
dx, dy = (posX, posY)
# déplacement vers le haut
# touche 'z' ou flèche du clavier
if touche in ("z", "Up"):
dy = posY - 10
# déplacement vers le bas
# touche 's' ou flèche du clavier
elif touche in ("s", "Down"):
dy = posY + 10
# déplacement vers la droite
# touche 'd' ou flèche du clavier
elif touche in ("d", "Right"):
dx = posX + 10
# déplacement vers la gauche
# touche 'q' ou flèche du clavier
elif touche in ("q", "Left"):
dx = posX - 10
# end if
# y a-t-il un mur à la nouvelle position ?
if canvas.find_overlapping(dx, dy, dx, dy):
# pour faire joli : vraiment pas indispensable
print("mur détecté en ({x}, {y})".format(x=dx, y=dy))
# pas de mur, on peut se déplacer vers là
else:
# màj position
posX, posY = (dx, dy)
# Repositionnement du pion
canvas.coords(pion, posX-5, posY-5, posX+5, posY+5)
# end if
# end def
def dessiner_decor (chemin_fichier):
""" dessin du labyrinthe """
global taille_bloc
# init taille bloc
taille_bloc = 10
with open(chemin_fichier) as fichier:
data = fichier.readlines()
lignes = len(data)
for ligne in range(lignes):
ligne_data = data[ligne].strip("\r\n ")
colonnes = len(ligne_data)
for colonne in range(colonnes):
if ligne_data[colonne] == "B":
x = colonne * taille_bloc
y = ligne * taille_bloc
canvas.create_rectangle(
x, y, x+taille_bloc, y+taille_bloc,
fill="black", outline="black",
)
# end if - data "B"
# end for - colonne
# end for - ligne
# end with - fichier
# end def
# Création de la fenêtre
fenetre = Tk()
# Création d'un widget Canvas
canvas = Canvas(fenetre, width=520, height=200, highlightthickness=0, bg="white")
canvas.pack(padx=5, pady=5)
dessiner_decor("Laby.txt")
Button(fenetre, text="Quitter", command=fenetre.destroy).pack(padx=5, pady=5)
# Position du pion au départ
posX, posY = (15, 185)
pion = canvas.create_rectangle(posX-5, posY-5, posX+5, posY+5, width=1, outline="black", fill="medium purple")
# événements clavier
fenetre.bind_all("<Key>", clavier)
# boucle principale
fenetre.mainloop() |