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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| from tkinter import Tk, Canvas, Frame
from numpy import loadtxt, ndenumerate
# Constants
CASE_SIZE = 20
PAC_SIZE = 8 # rayon
MOTIONS = {
'Up': (0, -1),
'Down': (0, 1),
'Left': (-1, 0),
'Right':(1, 0)
}
# Class
class Level():
def __init__(self):
self.level_number = 1
self.load_map()
def load_map(self):
file_name = 'Map/' + str(self.level_number) + '.txt'
self.map_game = loadtxt(file_name)
def get_map(self):
return self.map_game
class Pacman:
def __init__(self,map_game):
self.init_position(map_game)
def init_position(self,map_game):
for (x,y), value in ndenumerate(map_game):
if map_game[x,y] == 2:
self.case_row = x
self.case_column = y
break
def get_position(self):
return (self.case_row,self.case_column)
def update_pacman_pos(self,direction):
if direction:
cx = direction[0]
cy = direction[1]
if self.check_terrain(self):
self.case_row = self.case_row + cy
self.case_column = self.case_column + cx
def check_terrain(self):
row = self.case_row + self.cy
col = self.case_column + self.cx
if col >= 0 and col < self.map_game.shape[1] and \
row >= 0 and row < self.map_game.shape[0] and \
self.map_game[row,col] !=1:
return True
class GUI:
def __init__(self,map_game,root):
self.root = root
self.map_game = map_game
self.init_game_graphics()
self.init_terrain()
self.pacman_motion()
def init_game_graphics(self):
lar = self.map_game.shape[0]*CASE_SIZE
hau = self.map_game.shape[1]*CASE_SIZE
self.frame_game = Frame(self.root,bg="light yellow")
self.frame_game.pack()
self.can_game = Canvas(self.frame_game,width=lar, height=hau, bg="black")
self.can_game.pack(padx =10, pady=(0,10),side=('bottom'))
self.can_game.focus_set()
def init_terrain(self):
for (x,y), value in ndenumerate(self.map_game):
if self.map_game[x,y] == 1:
self.can_game.create_rectangle(y*CASE_SIZE,x*CASE_SIZE,
(y+1)*CASE_SIZE,(x+1)*CASE_SIZE,
outline='blue')
def cercle(self,x, y, r, coul ='black'):
self.can_game.create_oval(x-r, y-r, x+r, y+r, fill=coul)
def draw_boule(self,pos,coul):
row = pos[0]
col = pos[1]
self.boule = self.cercle(col*CASE_SIZE+CASE_SIZE/2,row*CASE_SIZE+CASE_SIZE/2, PAC_SIZE,coul)
def pacman_motion(self):
for key in MOTIONS:
self.can_game.bind('<%s>' % key, self.on_arrow)
def on_arrow(self, event):
direction = event.keysym
cx, cy = MOTIONS[direction]
return (cx,cy)
# Main
root = Tk()
launch_level = Level()
map_game = launch_level.get_map()
pacman = Pacman(map_game)
graphique = GUI(map_game,root)
graphique.draw_boule(pacman.get_position(),"gold")
pacman.update_pacman_pos(GUI.on_arrow)
root.mainloop() |
Partager