import pyglet from pyglet.window import key import sys import re # main window window = pyglet.window.Window() TILE_SIZE_X = 16 TILE_SIZE_Y = 16 class Level: """ Level: mostly map related stuff for now """ def __init__(self, mapfile): self.mapfile = mapfile self.tiles = [] self.load_mapfile() def load_mapfile(self): try: maph = open(self.mapfile) except Exception as error: print('Error while loading mapfile: ' + error) sys.exit(1) self.load_tiles(maph) self.load_map(maph) def load_tiles(self, maph): line = maph.readline().strip() while True: if re.match('^-- tiles$', line): print('Found tiles header: ' + line) break else: line = maph.readline().strip() last_tile = maph.tell() line = maph.readline().strip() while not re.match('^--', line): tile_file = re.compile('\d: ').split(line)[1] print('loading tile: ' + str(tile_file)) self.tiles.append(pyglet.resource.image(tile_file)) # save stream position before reading the new line to rewind it later last_tile = maph.tell() line = maph.readline().strip() print('Found other header, stop loading tiles') # "rewind" the stream so the header can be read by the next function maph.seek(last_tile) def load_map(self, maph): line = maph.readline().strip() while True: if re.match('^-- map$', line): print('Found map header: ' + line) break else: line = maph.readline().strip() # read map size line = maph.readline().strip() self.mapx, self.mapy = map(int, line.split('x')) print('map size: ' + str(self.mapx) + 'x' + str(self.mapy)) self.tile_map = [None] * self.mapy i = 0 while i < self.mapy: line = maph.readline().strip() line_lst = re.compile(',').split(line) # print(str(line_lst)) line_lst = [int(x) for x in line_lst] self.tile_map[i] = (line_lst) i += 1 def draw_map(self): for y in range(0, self.mapy): for x in range(0, self.mapx): tile_num = self.tile_map[y][x] self.tiles[tile_num].blit(x*TILE_SIZE_X, y*TILE_SIZE_Y) @window.event def on_key_press(symbol, modifiers): if symbol == key.Q: print('Will quit') elif symbol == key.LEFT: print('Left arrow') elif symbol == key.ENTER: print('Enter !') @window.event def on_draw(): window.clear() level.draw_map() label.draw() label = pyglet.text.Label('Plop World', x = window.width/2, y = window.height/2, anchor_x='center', anchor_y='center') brick_img = pyglet.resource.image('brick.png') road_img = pyglet.resource.image('road.png') level = Level('test_map.txt') pyglet.app.run()