def load_texture(key, path, region=None, mipmap=False, wrap=None): texture_path = join(RESOURCES_DIR, path) texture = Image(texture_path, mipmap=mipmap).texture if region: texture = texture.get_region(*region) textures[key] = texture
def loadTileImages(self, ts): """Loads the images in filename into Kivy Images. :type ts: TiledTileset """ texture = Image(ts.source).texture ts.width, ts.height = texture.size # initialize the image array self.images = [0] * self.maxgid p = itertools.product( xrange(ts.margin, ts.height, ts.tileheight + ts.margin), xrange(ts.margin, ts.width, ts.tilewidth + ts.margin) ) for real_gid, (y, x) in enumerate(p, ts.firstgid): if x + ts.tilewidth - ts.spacing > ts.width: continue gids = self.map_gid(real_gid) if gids: x = x - ts.spacing # convert the y coordinate to opengl (0 at bottom of texture) y = ts.height - y - ts.tileheight + ts.spacing tile = texture.get_region(x, y, ts.tilewidth, ts.tileheight) for gid, flags in gids: self.images[gid] = tile
class Lamp(Widget): # Base variables TEXTURE = ObjectProperty(None) WIDTH = NumericProperty(1.0) HEIGHT = NumericProperty(1.0) X_UNIT = NumericProperty(1.0) Y_UNIT = NumericProperty(1.0) X = NumericProperty(1.0) Y = NumericProperty(1.0) # Run variables state = NumericProperty(1) xUnit = NumericProperty(1.0) yUnit = NumericProperty(1.0) curr_texture = ObjectProperty(None) x = NumericProperty(1.0) y = NumericProperty(1.0) def set_base(self, texture_dir, x, y): self.TEXTURE = Image(texture_dir).texture self.WIDTH = self.TEXTURE.width self.HEIGHT = self.TEXTURE.height self.X_UNIT = self.WIDTH / 3 self.Y_UNIT = self.HEIGHT / 1 self.X = x self.Y = y def reset(self): state = 1 def is_pressed(self, x, y): if x > self.x and y > self.y: if x < self.x + self.xUnit and y < self.y + self.yUnit: return True return False def change_state(self): self.state += 1 self.state %= 3 def update(self, xScale, yScale): self.xUnit = self.X_UNIT * xScale self.yUnit = self.Y_UNIT * yScale self.x = self.X * xScale self.y = self.Y * yScale self.curr_texture = self.TEXTURE.get_region(self.state * self.X_UNIT, 0, self.X_UNIT, self.Y_UNIT)
def loadTileImages(self, ts): """ Loads the images in filename into Kivy Images. This is a port of the code here: https://github.com/bitcraft/PyTMX/blob/master/pytmx/tmxloader.py :type ts: pytmx.TiledTileset """ tile_image_path = self.map_dir + '/' + ts.source Logger.debug( 'KivyTiledMap: loading tile image at {}'.format(tile_image_path)) texture = CoreImage(tile_image_path).texture ts.width, ts.height = texture.size tilewidth = ts.tilewidth + ts.spacing tileheight = ts.tileheight + ts.spacing Logger.debug( 'KivyTiledMap: TiledTileSet: {}x{} with {}x{} tiles'.format( ts.width, ts.height, tilewidth, tileheight)) # some tileset images may be slightly larger than the tile area # ie: may include a banner, copyright, ect. this compensates for that width = int((( (ts.width - ts.margin * 2 + ts.spacing) / tilewidth) * tilewidth) - ts.spacing) height = int((((ts.height - ts.margin * 2 + ts.spacing) / tileheight) * tileheight) - ts.spacing) Logger.debug('KivyTiledMap: TiledTileSet: true size: {}x{}'.format( width, height)) # initialize the image array Logger.debug('KivyTiledMap: initializing image array') self.images = [0] * self.maxgid p = itertools.product( xrange(ts.margin, height + ts.margin, tileheight), xrange(ts.margin, width + ts.margin, tilewidth)) # trim off any pixels on the right side that isn't a tile # this happens if extra graphics are included on the left, but they are not actually part of the tileset width -= (ts.width - ts.margin) % tilewidth for real_gid, (y, x) in enumerate(p, ts.firstgid): if x + ts.tilewidth - ts.spacing > width: continue gids = self.map_gid(real_gid) if gids: # invert y for OpenGL coordinates y = ts.height - y - ts.tileheight tile = texture.get_region(x, y, ts.tilewidth, ts.tileheight) for gid, flags in gids: self.images[gid] = tile
def loadTileImages(self, ts): """ Loads the images in filename into Kivy Images. This is a port of the code here: https://github.com/bitcraft/PyTMX/blob/master/pytmx/tmxloader.py :type ts: pytmx.TiledTileset """ tile_image_path = self.map_dir + '/' + ts.source Logger.debug('KivyTiledMap: loading tile image at {}'.format(tile_image_path)) texture = CoreImage(tile_image_path).texture ts.width, ts.height = texture.size tilewidth = ts.tilewidth + ts.spacing tileheight = ts.tileheight + ts.spacing Logger.debug('KivyTiledMap: TiledTileSet: {}x{} with {}x{} tiles'.format(ts.width, ts.height, tilewidth, tileheight)) # some tileset images may be slightly larger than the tile area # ie: may include a banner, copyright, ect. this compensates for that width = int((((ts.width - ts.margin * 2 + ts.spacing) / tilewidth) * tilewidth) - ts.spacing) height = int((((ts.height - ts.margin * 2 + ts.spacing) / tileheight) * tileheight) - ts.spacing) Logger.debug('KivyTiledMap: TiledTileSet: true size: {}x{}'.format(width, height)) # initialize the image array Logger.debug('KivyTiledMap: initializing image array') self.images = [0] * self.maxgid p = itertools.product( xrange(ts.margin, height + ts.margin, tileheight), xrange(ts.margin, width + ts.margin, tilewidth) ) # trim off any pixels on the right side that isn't a tile # this happens if extra graphics are included on the left, but they are not actually part of the tileset width -= (ts.width - ts.margin) % tilewidth for real_gid, (y, x) in enumerate(p, ts.firstgid): if x + ts.tilewidth - ts.spacing > width: continue gids = self.map_gid(real_gid) if gids: # invert y for OpenGL coordinates y = ts.height - y - ts.tileheight tile = texture.get_region(x, y, ts.tilewidth, ts.tileheight) for gid, flags in gids: self.images[gid] = tile
def populate_lists(self): for s in range(self.currentStory + 1): for l in range(len(self.renderList[s])): for i in range(self.iCount): for j in range(self.jCount): tile = self.mapFile.stories[self.currentStory].matrix[i][j] type = tile.get_graphics_type(l) if type[0] != None: graphicsInfo = tile.graphics[l] image = Image(graphicsInfo[0]).texture x = (i - j) * self.tileWidth / 2 + self.offset[0] + self.jCount * self.tileWidth / 2 y = (i + j) * self.tileHeight / 2 + self.offset[1] if (type[0] == 'object' or type[0] == 'wall') and type[1] == False: # Object means a rectangle, not animated means it goes into renderList self.renderList[s][l][i][j] = Rectangle(texture = image.get_region(graphicsInfo[1][0][0][0], graphicsInfo[1][0][0][1], graphicsInfo[2][0], graphicsInfo[2][1]), size = (self.tileWidth, self.tileWidth * graphicsInfo[2][1] / graphicsInfo[2][0]), pos = (x - self.tileWidth / 2, y) )
class Navigator(Widget): # Base variables TEXTURE = ObjectProperty(None) WIDTH = NumericProperty(1.0) HEIGHT = NumericProperty(1.0) X_UNIT = NumericProperty(1.0) Y_UNIT = NumericProperty(1.0) X = NumericProperty(1.0) Y = NumericProperty(1.0) # Run variables angle = NumericProperty(0.0) xUnit = NumericProperty(1.0) yUnit = NumericProperty(1.0) curr_texture = ObjectProperty(None) x = NumericProperty(1.0) y = NumericProperty(1.0) def set_base(self, texture_dir, x, y): self.TEXTURE = Image(texture_dir).texture self.WIDTH = self.TEXTURE.width self.HEIGHT = self.TEXTURE.height self.X_UNIT = self.WIDTH / 1 self.Y_UNIT = self.HEIGHT / 1 self.X = x self.Y = y def update(self, xScale, yScale): self.xUnit = self.X_UNIT * xScale self.yUnit = self.Y_UNIT * yScale self.x = self.X * xScale self.y = self.Y * yScale self.curr_texture = self.TEXTURE.get_region(0, 0, self.X_UNIT, self.Y_UNIT)
def render_tile(self, i, j, layer, story): tile = self.mapFile.stories[self.currentStory].matrix[i][j] type = self.mapFile.stories[story].matrix[i][j].get_graphics_type(layer) if type[0] != None: graphicsInfo = tile.graphics[layer] image = Image(graphicsInfo[0]).texture x = (i - j) * self.tileWidth / 2 + self.offset[0] + self.jCount * self.tileWidth/2 y = (i + j) * self.tileHeight / 2 + self.offset[1] self.renderList[story][layer][i][j].texture = image.get_region(graphicsInfo[1][0][0][0], graphicsInfo[1][0][0][1], graphicsInfo[2][0], graphicsInfo[2][1]) print("Type is:", type[0]) if type[0] == 'object' and type[1] == False: # Object means a rectangle, not animated means it goes into renderList self.renderList[story][layer][i][j].size = (self.tileWidth, self.tileWidth * graphicsInfo[2][1] / graphicsInfo[2][0]) self.renderList[story][layer][i][j].pos = (x - self.tileWidth/2, y) self.canvas.before.add(Color(1, 1, 1, 1)) for l in range(len(self.renderList[story])): if self.renderList[story][l][i][j] != [None]: self.canvas.before.add(self.renderList[story][l][i][j])
class LoAGame(Widget): colorList = ListProperty([0, 0.5, 1, 1]) importantList = [ "Player", "loadBlock", "startBlock", "endBlock", "spawnBlock", "enemy" ] blockSize = NumericProperty(1) cameraSpeed_x = NumericProperty(0) cameraSpeed_y = NumericProperty(0) gravity = NumericProperty(0.03) player = ObjectProperty(None) loadBlockMin = ObjectProperty(None) loadBlockMax = ObjectProperty(None) startBlock = ObjectProperty(None) endBlock = ObjectProperty(None) spawnBlock = ObjectProperty(None) levelNum = 1 levelNumMax = 1 levelImage = Image("Level_" + str(levelNum) + ".png").texture topRowPixels = levelImage.get_region(0, levelImage.height, levelImage.width, 1) topRowList = [int(ord(pix) / 25.6) for pix in topRowPixels.pixels] topRow = [topRowList[i:i + 4] for i in range(0, len(topRowList), 4)] test = [(6, 8), (16, 8), (16, 3), (30, 3), (16, 3), (16, 8), (25, 8), (25, 13), (25, 8)] enemy = ObjectProperty(None) def __init__(self, **kwargs): super(LoAGame, self).__init__(**kwargs) self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) self._keyboard.bind(on_key_up=self._on_keyboard_up) self.empty = EmptyBlock() self.add_widget(self.empty) self.posBlock = EmptyBlock(text="placeholder", colorList=[0, 0, 0, 1]) self.posBlock.setup(0, 0) self.add_widget(self.posBlock) self.enemy = Enemy() self.enemy.setup(19, 7) self.add_widget(self.enemy) self.startBlock = EmptyBlock(text="startBlock", colorList=[0, 0, 0, 0.2]) self.startBlock.setup(0, 0) self.add_widget(self.startBlock) self.endBlock = EmptyBlock(text="endBlock", colorList=[0, 1, 1, 1]) self.endBlock.setup(0, 0) self.add_widget(self.endBlock) self.spawnBlock = EmptyBlock(text="spawnBlock", colorList=[0, 0, 0, 0.2]) self.spawnBlock.setup(19, 7) self.add_widget(self.spawnBlock) self.loadBlockMin = EmptyBlock(text="loadBlock", colorList=[1, 1, 1, 0.2]) self.loadBlockMin.setup(0, 0) self.add_widget(self.loadBlockMin) self.loadBlockMax = EmptyBlock(text="loadBlock", colorList=[1, 1, 1, 0.2]) self.loadBlockMax.setup(0, 0) self.add_widget(self.loadBlockMax) self.newLevel(1) def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard.unbind(on_key_up=self._on_keyboard_up) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'w': self.player.keys[0] = 1 if keycode[1] == 'a': self.player.keys[1] = 1 if keycode[1] == 's': self.player.keys[2] = 1 if keycode[1] == 'd': self.player.keys[3] = 1 if keycode[1] == 'r': self.player.keys[4] = 1 if keycode[1] == 'q': self.player.keys[5] = 1 def _on_keyboard_up(self, keyboard, keycode): if keycode[1] == 'w': self.player.keys[0] = 0 if keycode[1] == 'a': self.player.keys[1] = 0 if keycode[1] == 's': self.player.keys[2] = 0 if keycode[1] == 'd': self.player.keys[3] = 0 if keycode[1] == 'r': self.player.keys[4] = 0 if keycode[1] == 'q': self.player.keys[5] = 0 def layout(self, *args): if self.width * self.height != 0: self.cameraSpeed_x = self.width / 50. self.cameraSpeed_y = self.height / 50. if self.width < self.height: self.blockSize = self.width / 20. else: self.blockSize = self.height / 20. for child in self.children: child.resize(self.blockSize) def on_pos(self, *args): Clock.schedule_once(self.layout, -1) def on_size(self, *args): Clock.schedule_once(self.layout, -1) def pixelTest(self, dim, texture, axis): if axis == 1: pixel = texture.get_region(dim, 0, 1, texture.height) if axis == 2: pixel = texture.get_region(0, dim, texture.width, 1) dataList = [int(ord(pix) / 25.6) for pix in pixel.pixels] return [dataList[i:i + 4] for i in range(0, len(dataList), 4)] def newLevel(self, level): self.levelNum = level self.levelImage = Image("Level_" + str(self.levelNum) + ".png").texture self.topRowPixels = self.levelImage.get_region(0, self.levelImage.height, self.levelImage.width, 1) self.topRowList = [ int(ord(pix) / 25.6) for pix in self.topRowPixels.pixels ] self.topRow = [ self.topRowList[i:i + 4] for i in range(0, len(self.topRowList), 4) ] self.spawnBlock.blockPos = self.startBlock.blockPos self.endBlock.blockPos = self.startBlock.blockPos self.loadBlockMin.blockPos = self.startBlock.blockPos self.loadBlockMax.blockPos = self.startBlock.blockPos while self.loadBlockMax.blockPos_x - self.startBlock.blockPos_x < int( self.levelImage.width / 2) - 2: self.loadBlockMax.blockPos_x += 1 self.loadLevelArea( int((self.loadBlockMin.blockPos_x - self.startBlock.blockPos_x)), int((self.loadBlockMax.blockPos_x - self.startBlock.blockPos_x)), self.levelImage) self.moveLoadBlocks() self.player.respawn() self.bgCenter(1, 1) def loadLevelArea(self, xMin, xMax, texture): y = 0 xMax *= 2 debugTime = time.time() if self.topRow[xMax] == [9, 0, 0, 9 ] or self.topRow[xMax] == [9, 0, 9, 9]: pixelsY = self.pixelTest(xMax, texture, 1) for y in range(1, len(pixelsY)): if pixelsY[y] == [9, 0, 0, 9] or pixelsY[y] == [9, 0, 9, 9]: pixelsX = self.pixelTest(texture.height - y - 2, texture, 2) if pixelsX[xMax + 1] == [ 9, 0, 0, 9 ] or pixelsX[xMax + 1] == [9, 0, 9, 9]: dx = 0 w = 1 h = 1 widType = pixelsY[y + 1] while xMax + dx + 1 < texture.width and pixelsX[ xMax + dx + 1] != [ 0, 0, 9, 9 ] and pixelsX[xMax + dx + 1] != [9, 0, 9, 9]: dx += 2 w += 1 while y < texture.height and pixelsY[y] != [ 0, 0, 9, 9 ] and pixelsY[y] != [9, 0, 9, 9]: y += 2 h += 1 xPos = xMax / 2 yPos = (texture.height - y) / 2 #print(w, h, xPos, yPos, widType) self.createWidget(w, h, xPos, yPos, widType) if time.time() - debugTime > 0.01: print(time.time() - debugTime, "xMax") xMin *= 2 debugTime = time.time() if self.topRow[xMin] == [0, 0, 9, 9 ] or self.topRow[xMin] == [9, 0, 9, 9]: pixelsY = self.pixelTest(xMin, texture, 1) for y in range(1, len(pixelsY)): if pixelsY[y] == [9, 0, 0, 9] or pixelsY[y] == [9, 0, 9, 9]: pixelsX = self.pixelTest(texture.height - y - 2, texture, 2) if pixelsX[xMin + 1] == [ 0, 0, 9, 9 ] or pixelsX[xMin + 1] == [9, 0, 9, 9]: dx = 0 w = 1 h = 1 widType = pixelsY[y + 1] while xMin - dx + 1 >= 0 and pixelsX[ xMin - dx + 1] != [ 9, 0, 0, 9 ] and pixelsX[xMin - dx + 1] != [9, 0, 9, 9]: dx += 2 w += 1 while y < texture.height and pixelsY[y] != [ 0, 0, 9, 9 ] and pixelsY[y] != [9, 0, 9, 9]: y += 2 h += 1 xPos = xMin / 2 - w + 1 yPos = (texture.height - y) / 2 self.createWidget(w, h, xPos, yPos, widType) if time.time() - debugTime > 0.01: print(time.time() - debugTime, "xMin") def unloadLevelArea(self): for child in self.children: if child.text not in self.importantList: if child.blockPos_x > self.loadBlockMax.blockPos_x + 1: #print("Removing", child) child.remove() elif child.blockPos_x + child.blockWidth < self.loadBlockMin.blockPos_x - 2: #print("Removing", child) child.remove() def createWidget(self, w, h, levX, levY, widType): x = levX + self.startBlock.blockPos_x y = levY + self.startBlock.blockPos_y collided = 0 for child in self.children: if child.collide_point( (x + 0.5) * self.blockSize, (y + 0.5) * self.blockSize) and child.text not in self.importantList: #print("Collided", levX, levY, child.text, widType) collided = 1 if collided == 0: if widType == [9, 9, 0, 9]: wall = Wall() wall.setup(w, h, x, y) wall.resize(self.blockSize) self.add_widget(wall) elif widType == [9, 9, 9, 9]: platform = Platform() platform.setup(w, h, x, y) platform.resize(self.blockSize) self.add_widget(platform) elif widType == [5, 0, 0, 9]: wall = Wall(text="kill", colorList=[0.5, 0, 0, 1]) wall.setup(w, h, x, y) wall.resize(self.blockSize) self.add_widget(wall) elif widType == [0, 5, 0, 9]: self.spawnBlock.blockPos = (x, y) elif widType == [0, 9, 9, 9]: self.endBlock.blockPos = (x, y) else: wall = Wall(text="placeholder", colorList=[0, 0, 0, 1]) wall.setup(w, h, x, y) wall.resize(self.blockSize) self.add_widget(wall) def goto(self, wid, point): wid.keys = [0 for i in wid.keys] if wid.blockPos_x - self.startBlock.blockPos_x + wid.blockWidth < point[ 0]: wid.keys[3] = 1 if wid.blockPos_x - self.startBlock.blockPos_x > point[0]: wid.keys[1] = 1 if wid.blockPos_y - self.startBlock.blockPos_y + wid.blockHeight < point[ 1]: wid.keys[0] = 1 if wid.blockPos_y - self.startBlock.blockPos_y > point[1]: wid.keys[2] = 1 def moveWid(self, wid): wid.velocity_x *= wid.slipFactor wid.velocity_y -= self.gravity if wid.keys[ 0] == 1 and wid.onGround > 0 and wid.velocity_y >= -self.gravity and wid.velocity_y <= 0.1 and wid.blockHeight != wid.blockHeightCrouch: wid.velocity_y = wid.vSpeed if wid.keys[2] == 1 and wid.onGround == 0: wid.velocity_y -= wid.vSpeed / 5 if wid.keys[2] == 1 and wid.onGround == 1: wid.crouchTime += 1 wid.blockHeight = wid.blockHeightCrouch wid.resize(self.blockSize) elif wid.keys[2] == 0: list1 = [(child.text != "platform") * (child.collide_widget(wid)) for child in self.children] wid.crouchTime = 0 wid.blockHeight = wid.blockHeightNorm wid.resize(self.blockSize) list2 = [(child.text != "platform") * (child.collide_widget(wid)) for child in self.children] if list2 != list1: wid.blockHeight = wid.blockHeightCrouch wid.resize(self.blockSize) if wid.blockPos_y + wid.velocity_y - self.startBlock.blockPos_y < -1: wid.kill() if wid.keys[1] == 1 and wid.velocity_x > -wid.hSpeed: wid.velocity_x = wid.velocity_x - (wid.hSpeed * wid.frictionFactor) if wid.keys[3] == 1 and wid.velocity_x < wid.hSpeed: wid.velocity_x = wid.velocity_x + (wid.hSpeed * wid.frictionFactor) if wid.blockPos_x + wid.velocity_x - self.startBlock.blockPos_x < 0: wid.velocity_x = 0 wid.blockPos_x = self.startBlock.blockPos_x if wid.blockPos_x + wid.velocity_x + wid.blockWidth - self.startBlock.blockPos_x > self.levelImage.width / 2 - 2: wid.velocity_x = 0 wid.blockPos_x = self.startBlock.blockPos_x + self.levelImage.width / 2 - 2 - wid.blockWidth wid.onGround = 0 for child in self.children: try: if child.text == "platform": child.testCollide(wid, self.blockSize, wid.velocity_y) elif child.text == "wall" or child.text == "kill": child.testCollide(wid, self.blockSize, wid.velocity_y, wid.velocity_x) except Exception as e: print(e) newPos = Vector(wid.blockPos) + Vector(wid.velocity) if wid.onGround > 0: if wid.velocity_y <= 0: wid.velocity_y = 0 newPos[1] = wid.groundHeight if wid.onGround == 1: wid.frictionFactor = 0.5 wid.slipFactor = 0.5 else: wid.frictionFactor = 0.1 wid.slipFactor = 1 wid.blockPos = newPos wid.repos(self.blockSize) def bgMove(self, x, y): for child in self.children: child.blockPos = Vector(child.blockPos) + [x, y] child.repos(self.blockSize) def bgCenter(self, camX, camY): x_dist = ((self.width - self.player.width) / 2 - self.player.pos[0]) / self.blockSize y_dist = ((self.height - self.player.height) / 3 - self.player.pos[1]) / self.blockSize x_mov = x_dist / camX y_mov = y_dist / camY self.bgMove(x_mov, y_mov) def moveLoadBlocks(self): while self.loadBlockMax.blockPos_x * self.blockSize - self.width < 1 * self.blockSize and self.loadBlockMax.blockPos_x - self.startBlock.blockPos_x < int( self.levelImage.width / 2) - 2: self.loadBlockMax.blockPos_x += 1 self.loadLevelArea( int((self.loadBlockMin.blockPos_x - self.startBlock.blockPos_x)), int((self.loadBlockMax.blockPos_x - self.startBlock.blockPos_x)), self.levelImage) while self.loadBlockMax.blockPos_x * self.blockSize - self.width > 2 * self.blockSize and self.loadBlockMax.blockPos_x - self.startBlock.blockPos_x > 1: self.loadBlockMax.blockPos_x -= 1 self.unloadLevelArea() while self.loadBlockMin.blockPos_x > -2 and self.loadBlockMin.blockPos_x - self.startBlock.blockPos_x > 1: self.loadBlockMin.blockPos_x -= 1 self.loadLevelArea( int((self.loadBlockMin.blockPos_x - self.startBlock.blockPos_x)), int((self.loadBlockMax.blockPos_x - self.startBlock.blockPos_x)), self.levelImage) while self.loadBlockMin.blockPos_x < -1 and self.loadBlockMin.blockPos_x - self.startBlock.blockPos_x < int( self.levelImage.width / 2) - 2: self.loadBlockMin.blockPos_x += 1 self.unloadLevelArea() def update(self, dt): #Load Blocks debugTime = time.time() self.moveLoadBlocks() if time.time() - debugTime > 0.01: print(time.time() - debugTime, "Load Block") #AI Control #Reset if self.player.keys[4] == 1: self.player.respawn() #Player Control debugTime = time.time() self.posBlock.blockPos_x = self.test[0][0] + self.startBlock.blockPos_x self.posBlock.blockPos_y = self.test[0][1] + self.startBlock.blockPos_y if self.enemy.collide_point( (self.test[0][0] + self.startBlock.blockPos_x) * self.blockSize, (self.test[0][1] + self.startBlock.blockPos_y) * self.blockSize): self.test = [self.test[i - 1] for i in range(0, len(self.test))] self.goto(self.enemy, self.test[0]) self.moveWid(self.enemy) if time.time() - debugTime > 0.01: print(time.time() - debugTime, "Move Enemy") debugTime = time.time() self.moveWid(self.player) #print(self.player.lives, self.player.health, self.player.invincibility) if time.time() - debugTime > 0.01: print(time.time() - debugTime, "Move Player") if self.player.collide_widget( self.endBlock) and self.levelNum < self.levelNumMax: self.newLevel(self.levelNum + 1) if self.player.collide_widget( self.enemy) and self.player.invincibility <= 0: self.player.health -= 1 self.player.invincibility = 60 if self.player.invincibility > 0: self.player.invincibility -= 1 if self.player.health <= 0: self.player.kill() #print(self.player.lives, self.player.health, self.player.invincibility) if self.player.keys[5] == 1: self.bgCenter(1, 1) Clock.unschedule(self.update) Clock.schedule_interval(self.update, 1.0 / 2.0) if self.player.keys[5] == 0: Clock.unschedule(self.update) Clock.schedule_interval(self.update, 1.0 / 60.0) debugTime = time.time() self.bgCenter(self.cameraSpeed_x, self.cameraSpeed_y) if time.time() - debugTime > 0.01: print(time.time() - debugTime, "bgCenter")
from kivy.core.image import Image as CoreImage forest_tiles = CoreImage('game-assets/tiles_forest.png').texture TEX_GRASS = forest_tiles.get_region(16, 48, 16, 16) TEX_TALLGRASS = forest_tiles.get_region(32, 48, 16, 16) TEX_BUSH = forest_tiles.get_region(240, 48, 16, 16) TEX_TREE = forest_tiles.get_region(240, 16, 16, 16) TEX_BLANK = forest_tiles.get_region(240, 0, 16, 16) if __name__ == "__main__": import cv2 test = CoreImage(TEX_GRASS) test2 = CoreImage(TEX_GRASS) print test
# carregar os dados da imagem diretamente de um bloco da memória import io from kivy.core.image import Image data = io.BytesIO(open("image.png", "rb").read()) im = Image(data, ext="png") # para imagem ficar salva em cache informe o filename im = Image(data, ext="png", filename="image.png") # Savar imagem from kivy.core.image import Image img = Image('hello.png') img.save('hello2.png') # salvar textura texture = Texture.create(...) img = Image(texture) img.save('hello3.png') # for example, load a 128x128 image that contain 4 64x64 images from kivy.core.image import Image texture = Image('mycombinedimage.png').texture bottomleft = texture.get_region(0, 0, 64, 64) bottomright = texture.get_region(0, 64, 64, 64) topleft = texture.get_region(0, 64, 64, 64) topright = texture.get_region(64, 64, 64, 64)
class Manager(RelativeLayout): touchLocationScreen = ListProperty() touchLocationUI = ListProperty() infoText = StringProperty('adventure awaits!') screen = ObjectProperty() selected = BooleanProperty(False) selectedObj = ObjectProperty(None) items = ListProperty([]) # holds all on-screen items def __init__(self, **kwargs): super(Manager, self).__init__(**kwargs) self.buildUI() self.loadItemSheet() self.screen = self.screenManager.current_screen self.orientation = 'vertical' def loadItemSheet(self): self.itemSheet = CImage('assets/art/item_sheet.png').texture def on_screen(self, instance, value): ''' on room change, inst. room items garbage collects all items not in inventory, and resets their spawn tag ''' # cleanup db.execute('UPDATE Item SET Spawned = ? WHERE Inventory = ?', (False,False)) db.commit() for i in self.items: self.remove_widget(i) self.items = [] room = value.name print 'room changed to ',room self.retrieveItems(room) def retrieveItems(self,room): ''' retrieve items from database relevant to new room ItemID=0, Holding=1, Room=2, X=3, Y=4, Inventory=5, Name=6, Spawned=7, Path=8 ''' i = db.execute('SELECT * FROM Item WHERE Room = ? OR Inventory = ?', (room,True)) for e in i: print e if e[7] and not e[5]: print '{} has spawned and is not an inventory item'.format(e[6]) else: position = (e[3],e[4]) print 'spawning {} at {}'.format(e[6],position) self.buildItem(position,e[6],e[8]) def buildItem(self,position,item,path): ''' populates screen with items for the room and inventory inventory slot positions: 1:(336.5,85.5), 2:(406.5,85.5), 3:(476.5,85.5), 4:(546.5,85.5), 5:(616.5,85.5), 6:(336.5,13.5), 7:(406.5,13.5), 8:(476.5,13.5), 9:(546.5,13.5), 0:(616.5,13.5), ''' x,y,h,w = path.split(',') x,y,h,w = int(x),int(y),int(h),int(w) tex = self.itemSheet.get_region(x,y,h,w) i = Item(texture = tex, pos = position, name = item) self.add_widget(i) self.items.append(i) db.execute('UPDATE Item SET Spawned = 1 WHERE Name = ? ',(item,)) def moveItem(self,item,inv=False): ''' moves item to inventory or ground, and labels such in DB ''' self.selected = False r = self.screen.name x = item.x y = item.y n = item.name print 'moving {} to {}'.format(n,(x,y)) if inv: curs.execute('UPDATE Item SET Inventory=?, Room=?, X=?, Y=? WHERE Name = ? ',(True,None,x,y,n)) else: curs.execute('UPDATE Item SET Inventory=?, Room=?, X=?, Y=? WHERE Name = ? ',(False,r,x,y,n)) db.commit() def on_touch_down(self, value): ''' looks for an item being selected, or moves player ''' #print('value.pos: {} value.spos: {}'.format(value.pos, value.spos)) x = int(value.pos[0]) y = int(value.pos[1]) # look for an item for i in self.items: if i.collide_point(x,y): self.selectedObj = i self.infoText = '{} picked up'.format(i.name) self.selected = True break else: self.selected = False # if no item selected, move player if not self.selected: localScreen = self.screenManager.to_local(x, y, True) if localScreen[0] < 0 or localScreen[1] < 0: pass # only update touchLocation for the screen when on screen else: self.touchLocationScreen = localScreen self.touchLocationUI = (x,y) self.infoText = str(localScreen) print '{}'.format(localScreen) def on_touch_up(self, value): ''' moves items, and checks if item is in inventory nodes ''' x = int(value.pos[0]) y = int(value.pos[1]) if self.selected is True: if self.inventory.collide_point(x, y): for node in self.nodes: if node.collide_point(x,y): self.selectedObj.center = node.center self.moveItem(self.selectedObj, inv=True) block = False break else: block = True if block: # blocked item placement self.selectedObj.center = (520,280) self.moveItem(self.selectedObj) elif self.screenManager.collide_point(x, y): self.moveItem(self.selectedObj) else: # blocked item placement self.selectedObj.center = (520,280) self.moveItem(self.selectedObj) pass self.infoText = '{} placed.'.format(self.selectedObj.name) def on_touch_move(self, value): ''' used for dragging items on screen ''' x = value.pos[0] y = value.pos[1] if self.selected: self.selectedObj.center = (x,y) #print 'x,y ',x,y #print 'object center: ',self.selectedObj.center def on_touchLocationScreen(self, instance, value): ''' take touch input on the manager and send to screen manager for handling ''' self.screenManager.touchLocation = self.touchLocationScreen def eventCompleted(self): #REDUNDANT pass def update(self, dt): #REDUNDANT #self.infoScreen.text = self.infoScreenText pass def on_infoText(self, instance, value): #print value self.info.text = self.infoText def buildInventory(self): n1 = Inventory(text='I1', slot=1) n2 = Inventory(text='I2', slot=2) n3 = Inventory(text='I3', slot=3) n4 = Inventory(text='I4', slot=4) n5 = Inventory(text='I5', slot=5) n6 = Inventory(text='I6', slot=6) n7 = Inventory(text='I7', slot=7) n8 = Inventory(text='I8', slot=8) n9 = Inventory(text='I9', slot=9) n0 = Inventory(text='I0', slot=0) self.inventory.add_widget(n1) self.inventory.add_widget(n2) self.inventory.add_widget(n3) self.inventory.add_widget(n4) self.inventory.add_widget(n5) self.inventory.add_widget(n6) self.inventory.add_widget(n7) self.inventory.add_widget(n8) self.inventory.add_widget(n9) self.inventory.add_widget(n0) self.nodes = [n1,n2,n3,n4,n5,n6,n7,n8,n9,n0] def buildUI(self): bottomBox = RelativeLayout() # 1024,188 self.screenManager = KYRScreenManager(size=(1068,450), size_hint=(None,None), pos=(25,224)) self.info = Info(text=self.infoText, multiline=True, readonly=True, size=(1064,30), size_hint=(None,None), pos=(25,167)) btnMenu = Button(text='menu', size=(196,120), size_hint=(None,None), pos=(28,16), opacity = .5) self.inventory = GridLayout(orientation='vertical',cols=5,pos=(333,-562),spacing=15) bottomBox.add_widget(self.info) bottomBox.add_widget(btnMenu) self.add_widget(self.inventory) self.add_widget(self.screenManager) self.add_widget(bottomBox) self.buildInventory()
int(root[0].attrib['tilewidth']), int(root[0].attrib['tileheight'])) tilesetList.append(Test) #creating a list of all the textures in the game. The index of the texture corresponds to its GID. tile_atlas = [] tile_atlas.append('0') #a placeholder for the 0th gid, a blank space for tileset in tilesetList: ts = Image(tileset.imagePath, allow_stretch=True).texture cols = tileset.imageWidth // tileset.tilesetTileWidth rows = tileset.imageHeight // tileset.tilesetTileHeight for i in range( tileset.tilesetLastGid): #adding in all the tiles in a tileset x = (i % cols) * tileset.tilesetTileWidth y = (rows - (i // cols) - 1) * tileset.tilesetTileHeight tile = ts.get_region(x, y, tileset.tilesetTileWidth, tileset.tilesetTileHeight) tile_atlas.append(tile) #reading in the character sprite: h = 64, w = 36, spacing = 32. They are 57px apart horizontally, spr = Image('sprite.png', allow_stretch=True).texture spr_down = [] spr_up = [] spr_right = [] spr_left = [] for i in range(5): frame = spr.get_region((26 + i * 57 + i * 33), 10, 36, 64) spr_down.append(frame) for i in range(5): frame = spr.get_region((26 + i * 57 + i * 33), 102, 36, 64) spr_up.append(frame) for i in range(4, -1, -1): #the frames are placed in opposite order.
def startImage(self): myimage = Image("./images/pippaSheet.png").texture #0 self.image_R.append(myimage.get_region(0, 0, 150, 170)) #4 self.image_R.append(myimage.get_region(150 * 3, 0, 150, 170)) #7 self.image_R.append(myimage.get_region(150 * 6, 0, 150, 170)) #6 self.image_R.append(myimage.get_region(150 * 5, 0, 150, 170)) #2 self.image_R.append(myimage.get_region(150 * 4, 0, 150, 170)) #4 self.image_R.append(myimage.get_region(150 * 5, 0, 150, 170)) self.image_Jumping_R.append(myimage.get_region(150 * 1, 0, 150, 170)) self.image_Jumping_R.append(myimage.get_region(150 * 2, 0, 150, 170)) myimage = Image("./images/pippaSheetL.png").texture #7 self.image_L.append(myimage.get_region(150 * 7, 0, 150, 170)) #4 self.image_L.append(myimage.get_region(150 * 2, 0, 150, 170)) #7 self.image_L.append(myimage.get_region(150 * 5, 0, 150, 170)) #6 self.image_L.append(myimage.get_region(150 * 4, 0, 150, 170)) #2 self.image_L.append(myimage.get_region(150 * 3, 0, 150, 170)) #4 self.image_L.append(myimage.get_region(150 * 4, 0, 150, 170)) self.image_Jumping_L.append(myimage.get_region(150 * 0, 0, 150, 170)) self.image_Jumping_L.append(myimage.get_region(150 * 1, 0, 150, 170))
class Palette(FloatLayout): def __init__(self, tileset = None, res = [64, 32], offset = 4, keyboard = None, mapCanvas = None, **kwargs): super(Palette, self).__init__(**kwargs) # Tileset is an path self.tileset = tileset # TilesetImage is the image file of the path self.tilesetImage = [] self.imageRes = [] # Palette dimensions self.offset = offset self.width = res[0] * 4 + self.offset * 2 self.height = res[1] * 2 + self.offset * 2 # Resolution for tiles in the palette. self.res = res # Register which canvas is being painted on: self.mapCanvas = mapCanvas # Listen to keyboard changes: self.keyboard = keyboard # Bindings self.bind(on_touch_down = self.on_down) self.bind(on_touch_move = self.on_move) self.bind(on_touch_up = self.on_up) # Populate the palette self.populate_palette() def on_down(self, parent, touch): # Check if the touch-down position is within the palette: if touch.pos[0] > self.offset and touch.pos[0] < self.width - self.offset and touch.pos[1] > self.offset and touch.pos[1] < self.height - self.offset: self.mapCanvas.clear_palette_selection() yDiv = self.res[1] / self.res[0] #Convert the touch.pos arguments into the tile-number x = touch.pos[0] // (self.width / 4) y = touch.pos[1] // (self.width / (4 / yDiv)) # Highlight the tile. self.highlight(x, y) self.mapCanvas.selectedPaint = [self.tileset, [ [ [x * self.imageRes[0], y * self.imageRes[1] ] ] ], [self.imageRes[0], self.imageRes[1]] ] else: print("not touching the palette!") def on_move(self, parent, touch): pass def on_up(self, parent, touch): pass def highlight(self, x, y): yDiv = (self.res[1] / self.res[0]) print(y) print(self.height) self.canvas.after.clear() with self.canvas.after: Color(0, 0.5, 1, 0.4) Rectangle(size = self.res, pos = (x * self.res[0] + self.offset, y * self.res[1] + self.offset)) self.mapCanvas.selectedPaint = self.tilesetImage.get_region(x * self.imageRes[0], y * self.imageRes[1], self.imageRes[0], self.imageRes[1] ) def populate_palette(self): if self.tileset != None: # Set image self.tilesetImage = Image(self.tileset).texture # Set background image: backgroundImagePath = join(globals.subDirectory['graphics'], "emptytile.png") backgroundImage = Image(backgroundImagePath).texture # Find the resolution of this image: yDiv = (self.res[1] / self.res[0]) / 4 self.imageRes = [self.tilesetImage.width / 4 , self.tilesetImage.width * yDiv] # Set new dimensions self.width = self.res[0] * 4 + self.offset * 2 self.height = self.res[1] * (self.tilesetImage.height / (self.tilesetImage.width * yDiv)) + self.offset * 2 # Draw the background: with self.canvas.before: Color(1, 1, 1, 0.5) Rectangle(size = self.size, pos = (self.offset, self.offset)) for x in range(4): for y in range(int(self.tilesetImage.height / (self.tilesetImage.width * yDiv))): with self.canvas.before: Color(1, 1, 1, 0.1) Rectangle(texture = backgroundImage, size = self.res, pos = (x * self.res[0] + self.offset, y * self.res[1] + self.offset )) # Draw the tileset in the palette for x in range(4): for y in range(int(self.tilesetImage.height / (self.tilesetImage.width * yDiv))): with self.canvas: Color(1, 1, 1, 1) Rectangle(texture = self.tilesetImage.get_region(x * self.imageRes[0], y * self.imageRes[1], self.imageRes[0], self.imageRes[1]), size = self.res, pos = (x * self.res[0] + self.offset, y * self.res[1] + self.offset ))