本文整理汇总了Python中map.Map.addLayer方法的典型用法代码示例。如果您正苦于以下问题:Python Map.addLayer方法的具体用法?Python Map.addLayer怎么用?Python Map.addLayer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类map.Map
的用法示例。
在下文中一共展示了Map.addLayer方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: endCapture
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
def endCapture(self):
if (self.mBrushBehavior != BrushBehavior.Capture):
return
self.mBrushBehavior = BrushBehavior.Free
tileLayer = self.currentTileLayer()
# Intersect with the layer and translate to layer coordinates
captured = self.capturedArea()
captured &= QRect(tileLayer.x(), tileLayer.y(),
tileLayer.width(), tileLayer.height())
if (captured.isValid()):
captured.translate(-tileLayer.x(), -tileLayer.y())
map = tileLayer.map()
capture = tileLayer.copy(captured)
stamp = Map(map.orientation(),
capture.width(),
capture.height(),
map.tileWidth(),
map.tileHeight())
# Add tileset references to map
for tileset in capture.usedTilesets():
stamp.addTileset(tileset)
stamp.addLayer(capture)
self.stampCaptured.emit(TileStamp(stamp))
else:
self.updatePreview()
示例2: read
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
def read(self, fileName):
uncompressed = QByteArray()
# Read data
f = QFile(fileName)
if (f.open(QIODevice.ReadOnly)) :
compressed = f.readAll()
f.close()
uncompressed, length = decompress(compressed, 48 * 48)
# Check the data
if (uncompressed.count() != 48 * 48) :
self.mError = self.tr("This is not a valid Droidcraft map file!")
return None
uncompressed = uncompressed.data()
# Build 48 x 48 map
# Create a Map -> Create a Tileset -> Add Tileset to map
# -> Create a TileLayer -> Fill layer -> Add TileLayer to Map
map = Map(Map.Orientation.Orthogonal, 48, 48, 32, 32)
mapTileset = Tileset.create("tileset", 32, 32)
mapTileset.loadFromImage(QImage(":/tileset.png"), "tileset.png")
map.addTileset(mapTileset)
# Fill layer
mapLayer = TileLayer("map", 0, 0, 48, 48)
# Load
for i in range(0, 48 * 48):
tileFile = int(uncompressed[i])&0xff
y = int(i / 48)
x = i - (48 * y)
tile = mapTileset.tileAt(tileFile)
mapLayer.setCell(x, y, Cell(tile))
map.addLayer(mapLayer)
return map
示例3: copySelection
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
def copySelection(self, mapDocument):
currentLayer = mapDocument.currentLayer()
if (not currentLayer):
return
map = mapDocument.map()
selectedArea = mapDocument.selectedArea()
selectedObjects = mapDocument.selectedObjects()
tileLayer = currentLayer
copyLayer = None
if (not selectedArea.isEmpty() and type(tileLayer)==TileLayer):
# Copy the selected part of the layer
copyLayer = tileLayer.copy(selectedArea.translated(-tileLayer.x(), -tileLayer.y()))
elif (not selectedObjects.isEmpty()):
# Create a new object group with clones of the selected objects
objectGroup = ObjectGroup()
for mapObject in selectedObjects:
objectGroup.addObject(mapObject.clone())
copyLayer = objectGroup
else:
return
# Create a temporary map to write to the clipboard
copyMap = Map(map.orientation(),
copyLayer.width(), copyLayer.height(),
map.tileWidth(), map.tileHeight())
copyMap.setRenderOrder(map.renderOrder())
# Resolve the set of tilesets used by this layer
for tileset in copyLayer.usedTilesets():
copyMap.addTileset(tileset)
copyMap.addLayer(copyLayer)
self.setMap(copyMap)
示例4: toMap
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
def toMap(self, variant, mapDir):
self.mGidMapper.clear()
self.mMapDir = mapDir
variantMap = variant
orientationString = variantMap.get("orientation", '')
orientation = orientationFromString(orientationString)
if (orientation == Map.Orientation.Unknown):
self.mError = self.tr("Unsupported map orientation: \"%s\""%orientationString)
return None
staggerAxisString = variantMap.get("staggeraxis", '')
staggerAxis = staggerAxisFromString(staggerAxisString)
staggerIndexString = variantMap.get("staggerindex", '')
staggerIndex = staggerIndexFromString(staggerIndexString)
renderOrderString = variantMap.get("renderorder", '')
renderOrder = renderOrderFromString(renderOrderString)
nextObjectId = variantMap.get("nextobjectid", 0)
map = Map(orientation,
variantMap.get("width",0),
variantMap.get("height",0),
variantMap.get("tilewidth",0),
variantMap.get("tileheight",0))
map.setHexSideLength(variantMap.get("hexsidelength", 0))
map.setStaggerAxis(staggerAxis)
map.setStaggerIndex(staggerIndex)
map.setRenderOrder(renderOrder)
if (nextObjectId):
map.setNextObjectId(nextObjectId)
self.mMap = map
map.setProperties(self.toProperties(variantMap.get("properties", {})))
bgColor = variantMap.get("backgroundcolor", '')
if (bgColor!='' and QColor.isValidColor(bgColor)):
map.setBackgroundColor(QColor(bgColor))
for tilesetVariant in variantMap.get("tilesets", []):
tileset = self.__toTileset(tilesetVariant)
if not tileset:
return None
map.addTileset(tileset)
for layerVariant in variantMap.get("layers", []):
layer = self.toLayer(layerVariant)
if not layer:
return None
map.addLayer(layer)
return map
示例5: stampFromContext
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
def stampFromContext(selectedTool):
stamp = TileStamp()
stampBrush = dynamic_cast(selectedTool, StampBrush)
if stampBrush:
# take the stamp from the stamp brush
stamp = stampBrush.stamp()
else:
fillTool = dynamic_cast(selectedTool, BucketFillTool)
if fillTool:
# take the stamp from the fill tool
stamp = fillTool.stamp()
else:
mapDocument = DocumentManager.instance().currentDocument()
if mapDocument:
# try making a stamp from the current tile selection
tileLayer = dynamic_cast(mapDocument.currentLayer(), TileLayer)
if (not tileLayer):
return stamp
selection = mapDocument.selectedArea()
if (selection.isEmpty()):
return stamp
selection.translate(-tileLayer.position())
copy = tileLayer.copy(selection)
if (copy.size().isEmpty()):
return stamp
map = mapDocument.map()
copyMap = Map(map.orientation(),
copy.width(), copy.height(),
map.tileWidth(), map.tileHeight())
# Add tileset references to map
for tileset in copy.usedTilesets():
copyMap.addTileset(tileset)
copyMap.setRenderOrder(map.renderOrder())
copyMap.addLayer(copy.take())
stamp.addVariation(copyMap)
return stamp
示例6: setTile
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
def setTile(self, tile):
if type(tile)==list:
tile = tile[0]
if (self.mTile == tile):
return
self.mTile = tile
self.mMapScene.disableSelectedTool()
previousDocument = self.mMapScene.mapDocument()
if (tile):
self.mMapView.setEnabled(not self.mTile.tileset().isExternal())
map = Map(Map.Orientation.Orthogonal, 1, 1, tile.width(), tile.height())
map.addTileset(tile.sharedTileset())
tileLayer = TileLayer(QString(), 0, 0, 1, 1)
tileLayer.setCell(0, 0, Cell(tile))
map.addLayer(tileLayer)
objectGroup = None
if (tile.objectGroup()):
objectGroup = tile.objectGroup().clone()
else:
objectGroup = ObjectGroup()
objectGroup.setDrawOrder(ObjectGroup.DrawOrder.IndexOrder)
map.addLayer(objectGroup)
mapDocument = MapDocument(map)
self.mMapScene.setMapDocument(mapDocument)
self.mToolManager.setMapDocument(mapDocument)
mapDocument.setCurrentLayerIndex(1)
self.mMapScene.enableSelectedTool()
mapDocument.undoStack().indexChanged.connect(self.applyChanges)
else:
self.mMapView.setEnabled(False)
self.mMapScene.setMapDocument(None)
self.mToolManager.setMapDocument(None)
if (previousDocument):
previousDocument.undoStack().disconnect()
del previousDocument
示例7: MapReaderPrivate
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
class MapReaderPrivate():
def tr(self, sourceText, disambiguation = '', n = -1):
return QCoreApplication.translate('MapReader', sourceText, disambiguation, n)
def trUtf8(self, sourceText, disambiguation = '', n = -1):
return QCoreApplication.translate('MapReader', sourceText, disambiguation, n)
def __init__(self, mapReader):
self.p = mapReader
self.mMap = None
self.mError = QString('')
self.mReadingExternalTileset = False
self.xml = QXmlStreamReader()
self.mGidMapper = GidMapper()
def readMap(self, device, path):
self.mError = QString('')
self.mPath = path
map = None
self.xml.setDevice(device)
if (self.xml.readNextStartElement() and self.xml.name() == "map"):
map = self.__readMap()
else:
self.xml.raiseError(self.tr("Not a map file."))
self.mGidMapper.clear()
return map
def readTileset(self, device, path):
self.mError = ''
self.mPath = path
tileset = None
self.mReadingExternalTileset = True
self.xml.setDevice(device)
if (self.xml.readNextStartElement() and self.xml.name() == "tileset"):
tileset = self.__readTileset()
else:
self.xml.raiseError(self.tr("Not a tileset file."))
self.mReadingExternalTileset = False
return tileset
def openFile(self, file):
if (not file.exists()):
self.mError = self.tr("File not found: %s"%file.fileName())
return False
elif (not file.open(QFile.ReadOnly | QFile.Text)):
self.mError = self.tr("Unable to read file: %s"%file.fileName())
return False
return True
def errorString(self):
if self.mError != '':
return self.mError
else:
return self.tr("%d\n\nLine %d, column %s"%(self.xml.lineNumber(), self.xml.columnNumber(), self.xml.errorString()))
def __readUnknownElement(self):
qDebug("Unknown element (fixme): "+self.xml.name()+" at line "+self.xml.lineNumber()+", column "+self.xml.columnNumber())
self.xml.skipCurrentElement()
def __readMap(self):
atts = self.xml.attributes()
mapWidth = Int(atts.value("width"))
mapHeight = Int(atts.value("height"))
tileWidth = Int(atts.value("tilewidth"))
tileHeight = Int(atts.value("tileheight"))
hexSideLength = Int(atts.value("hexsidelength"))
orientationString = atts.value("orientation")
orientation = orientationFromString(orientationString)
if (orientation == Map.Orientation.Unknown):
self.xml.raiseError(self.tr("Unsupported map orientation: \"%s\""%orientationString))
staggerAxisString = atts.value("staggeraxis")
staggerAxis = staggerAxisFromString(staggerAxisString)
staggerIndexString = atts.value("staggerindex")
staggerIndex = staggerIndexFromString(staggerIndexString)
renderOrderString = atts.value("renderorder")
renderOrder = renderOrderFromString(renderOrderString)
nextObjectId = Int(atts.value("nextobjectid"))
self.mMap = Map(orientation, mapWidth, mapHeight, tileWidth, tileHeight)
self.mMap.setHexSideLength(hexSideLength)
self.mMap.setStaggerAxis(staggerAxis)
self.mMap.setStaggerIndex(staggerIndex)
self.mMap.setRenderOrder(renderOrder)
if (nextObjectId):
self.mMap.setNextObjectId(nextObjectId)
bgColorString = atts.value("backgroundcolor")
if len(bgColorString)>0:
self.mMap.setBackgroundColor(QColor(bgColorString))
while (self.xml.readNextStartElement()):
if (self.xml.name() == "properties"):
self.mMap.mergeProperties(self.__readProperties())
elif (self.xml.name() == "tileset"):
self.mMap.addTileset(self.__readTileset())
elif (self.xml.name() == "layer"):
self.mMap.addLayer(self.__readLayer())
elif (self.xml.name() == "objectgroup"):
self.mMap.addLayer(self.__readObjectGroup())
#.........这里部分代码省略.........
示例8: Scene
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
class Scene(engine.Module):
"""Główny ekran gry."""
def __init__(self, _engine):
super(Scene, self).__init__(_engine)
self._background = pygame.Surface((self._resx, self._resy))
self.surface = self._background.copy()
self._actual = []
self._client = _engine.options['client'] = sock.Client(_engine.options['host'], _engine.options['port'])
self._play = True
self._refresh = True
self._submodules = ()
self._map = None
self._playerID = None
def _loadMap(self, _width, _height):
self._map = Map(self._engine, self, (_width, _height))
self._heroLayer = ObjectsLayer(self._map) # Warstwa graczy
self._mineLayer = ObjectsLayer(self._map) # Warstwa min
self._map.addLayer('Hero', 3, self._heroLayer)
self._map.addLayer('Mine', 2, self._mineLayer)
self._submodules = (self._map,)
def isPlaying(self):
"""Czy gracz nadal gra?"""
return self._play
def screenUpdated(self):
"""Aktualizuje obrazy tła i submoduły."""
super(Scene, self).screenUpdated()
self._refresh = True
self._background = pygame.Surface((self._resx, self._resy))
self.surface = pygame.transform.smoothscale(self.surface, (self._resx, self._resy))
for submodule in self._submodules:
submodule.screenUpdated()
def show(self):
if not self._play:
self._engine.previousModule()
return
try:
self._last = time.time()
while self._engine.tick():
_upd = self._client.update(.5/self._engine.options['fps'])
if self._play and _upd != True:
utils.drawText(self.surface, _upd, 20, (255, 255, 255), (self._resx / 2, self._resy / 2))
self._play = False
self._engine.show(self.surface)
time.sleep(5)
self._engine.previousModule()
raise SceneQuit()
if self._client.countdown:
if not self._map:
self._loadMap(self._client.countdown.mapSize.x, self._client.countdown.mapSize.y)
if self._playerID == None:
self._playerID = self._client.countdown.playerId
self.surface = self._background.copy()
utils.drawText(self.surface, 'Gracz %d. >%d<' % (self._client.countdown.playerId, self._client.countdown.number), 30, (255, 255, 255), (self._resx / 2, self._resy / 2))
self._engine.show(self.surface)
continue
if self._client.result:
utils.drawText(self.surface, 'Gra zakonczona!', 40, (255, 255, 255), (self._resx / 2, self._resy / 2))
if len(self._client.result.winners) == 1:
utils.drawText(self.surface, 'Wygral gracz %d!' % self._client.result.winners[0], 40, (255, 255, 255), (self._resx / 2, self._resy / 2 + 40))
elif len(self._client.result.winners):
utils.drawText(self.surface, 'Wygrali gracze %s!' % (', '.join([str(i) for i in self._client.result.winners])), 40, (255, 255, 255), (self._resx / 2, self._resy / 2 + 40))
self._play = False
self._engine.show(self.surface)
time.sleep(10)
self._engine.previousModule()
raise SceneQuit()
if self._client.map:
if not self._map:
self._engine.previousModule()
self._play = False
raise SceneQuit()
for mine in self._client.map.mines:
_id = mine.position.x, mine.position.y
if not self._mineLayer.get(_id):
_mine = ObjectsLayer.Sprite(utils.loadImage('data/gfx/bomb.png', alpha = True))
self._mineLayer.add(_id, _mine)
self._mineLayer.move(_id, _id)
for _id, player in enumerate(self._client.map.playersPositions):
if not self._heroLayer.get(_id):
self._heroLayer.add(_id, ObjectsLayer.Sprite(utils.loadImage('data/gfx/hero/n.png', alpha = True)))
_hero = self._heroLayer.get(_id)
_pos = _hero.getPos()
#.........这里部分代码省略.........
示例9: Scene
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
class Scene(engine.Module):
"""Główny ekran gry."""
def __init__(self, _engine):
super(Scene, self).__init__(_engine)
self._background = pygame.Surface((self._resx, self._resy))
self.surface = self._background.copy()
self._actual = []
self._client = _engine.options['client'] = sock.BomberFactory(self._process, self._connectionError)
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
self._gameloop = LoopingCall(self._render)
self._network = reactor.connectTCP(_engine.options['host'], _engine.options['port'], self._client)
self._play = True
self._refresh = True
self._submodules = ()
self._map = None
self._playerID = None
def __del__(self):
self._network.disconnect()
def _loadMap(self, _width, _height):
self._map = Map(self._engine, self, (_width, _height))
self._heroLayer = ObjectsLayer(self._map) # Warstwa graczy
self._mineLayer = ObjectsLayer(self._map) # Warstwa min
self._map.addLayer('Hero', 3, self._heroLayer)
self._map.addLayer('Mine', 2, self._mineLayer)
self._submodules = (self._map,)
def isPlaying(self):
"""Czy gracz nadal gra?"""
return self._play
def screenUpdated(self):
"""Aktualizuje obrazy tła i submoduły."""
super(Scene, self).screenUpdated()
self._refresh = True
self._background = pygame.Surface((self._resx, self._resy))
self.surface = pygame.transform.smoothscale(self.surface, (self._resx, self._resy))
for submodule in self._submodules:
submodule.screenUpdated()
def show(self):
if not self._play:
self._engine.previousModule()
return
self._last = time.time()
from twisted.internet import reactor
self._gameloop.start(self._engine.getFPS() and 1.0 / self._engine.getFPS() or 0.0)
reactor.run()
self._gameloop.stop()
def _render(self):
self._engine.tick()
for event in self._engine.events():
if event.type == QUIT:
self._play = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self._engine.runLoop = False
from twisted.internet import reactor
reactor.stop()
return
if self._map:
if event.key in (K_w, K_UP):
self._client.sendAction('u')
self._last = time.time()
elif event.key in (K_s, K_DOWN):
self._client.sendAction('d')
self._last = time.time()
elif event.key in (K_a, K_LEFT):
self._client.sendAction('l')
self._last = time.time()
elif event.key in (K_d, K_RIGHT):
self._client.sendAction('r')
self._last = time.time()
elif event.key in (K_RETURN, K_RCTRL, K_LCTRL):
self._client.sendAction('c')
self._last = time.time()
elif event.key == K_q:
self._client.sendAction('e')
self._last = time.time()
if self._map and self._last + 1./self._engine.options['fps'] < time.time():
self._client.sendAction('m')
self._last = time.time()
if not self._map and self._playerID == None:
self.surface = self._background.copy()
#.........这里部分代码省略.........
示例10: read
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
def read(self, fileName):
# Read data.
file = QFile(fileName)
if (not file.open(QIODevice.ReadOnly)):
self.mError = self.tr("Cannot open Replica Island map file!")
return 0
_in = QDataStream(file)
_in.setByteOrder(QDataStream.LittleEndian)
_in.setFloatingPointPrecision(QDataStream.SinglePrecision)
# Parse file header.
mapSignature = _in.readUInt8()
layerCount = _in.readUInt8()
backgroundIndex = _in.readUInt8()
if (_in.status() == QDataStream.ReadPastEnd or mapSignature != 96):
self.mError = self.tr("Can't parse file header!")
return 0
# Create our map, setting width and height to 0 until we load a layer.
map = Map(Map.Orientation.Orthogonal, 0, 0, 32, 32)
map.setProperty("background_index", QString.number(backgroundIndex))
# Load our Tilesets.
typeTilesets = QVector()
tileIndexTilesets = QVector()
self.loadTilesetsFromResources(map, typeTilesets, tileIndexTilesets)
# Load each of our layers.
for i in range(layerCount):
# Parse layer header.
_type = _in.readUInt8()
tileIndex = _in.readUInt8()
scrollSpeed = _in.readFloat()
levelSignature = _in.readUInt8()
width = _in.readUInt32()
height = _in.readUInt32()
if (_in.status() == QDataStream.ReadPastEnd or levelSignature != 42):
self.mError = self.tr("Can't parse layer header!")
return 0
# Make sure our width and height are consistent.
if (map.width() == 0):
map.setWidth(width)
if (map.height() == 0):
map.setHeight(height)
if (map.width() != width or map.height() != height):
self.mError = self.tr("Inconsistent layer sizes!")
return 0
# Create a layer object.
layer = TileLayer(self.layerTypeToName(_type), 0, 0, width, height)
layer.setProperty("type", QString.number(_type))
layer.setProperty("tile_index", QString.number(tileIndex))
layer.setProperty("scroll_speed", QString.number(scrollSpeed, 'f'))
map.addLayer(layer)
# Look up the tileset for this layer.
tileset = tilesetForLayer(_type, tileIndex, typeTilesets, tileIndexTilesets)
# Read our tile data all at once.
#tileData = QByteArray(width*height, b'\x00')
bytesNeeded = width*height
tileData = _in.readRawData(bytesNeeded)
bytesRead = len(tileData)
if (bytesRead != bytesNeeded):
self.mError = self.tr("File ended in middle of layer!")
return 0
i = 0
# Add the tiles to our layer.
for y in range(0, height):
for x in range(0, width):
tile_id = tileData[i]&0xff
i += 1
if (tile_id != 255):
tile = tileset.tileAt(tile_id)
layer.setCell(x, y, Cell(tile))
# Make sure we read the entire *.bin file.
if (_in.status() != QDataStream.Ok or not _in.atEnd()):
self.mError = self.tr("Unexpected data at end of file!")
return 0
return map
示例11: Scene
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
class Scene(engine.Module):
"""Główny ekran gry."""
def __init__(self, _engine):
super(Scene, self).__init__(_engine)
self.side = utils.loadImage('data/gfx/side.png')
self._background = pygame.Surface((self._resx, self._resy))
self._background.blit(self.side, (self._resx - 232, self._resy - 1500))
self.surface = self._background.copy()
self._actual = []
self._level = utils.loadLevel('data/level.dat')
self._map = Map(_engine, self, self._level)
self._minimap = Minimap(_engine, self._map)
self._cursor = Cursor(_engine, self._map)
self._creatureLayer = CreatureLayer(self._map, self._cursor) # Warstwa potworów
self._map.addLayer('Creatures', 2, self._creatureLayer)
self._map.addLayer('Missiles', 3, MissilesLayer(self._map)) # Warstwa pocisków(strzał, kuli ognia itp.)
self._shadow = ShadowLayer(self._map)
self._map.addLayer('Shadow', 5, self._shadow) # Mgła wojny
self._monsters = []
self._freeobjects = pygame.sprite.Group() # Wolne obiekty na scenie
_counter = 0
_start = 0
# szukanie bohatera w lochu
for l, storey in enumerate(self._level):
for row in storey:
for cell in row:
if cell.getModifier() & field.MODIFIER_HERO:
self._hero = hero.Hero(self._map, cell.getGrid() + (l,))
self._hero.move((0, 0, 0))
self._map.switchStorey(l)
_start = l
self._creatureLayer.add('hero', self._hero.getSprite(self._creatureLayer, 'hero'))
break
# szukanie potworów
for l, storey in enumerate(self._level):
for row in storey:
for cell in row:
if cell.getModifier() & field.MODIFIER_SPIDER:
_monster = Spider(self._map, cell.getGrid() + (l,))
self._monsters.append(('spider', _monster))
if l == _start:
self._creatureLayer.add('spider_' + str(_counter), _monster.getSprite(self._creatureLayer, 'spider_' + str(_counter)))
self._actual.append(('spider_' + str(_counter), _monster))
_monster.move((0, 0, 0))
_counter += 1
elif cell.getModifier() & field.MODIFIER_SKELETON:
_monster = Skeleton(self._map, cell.getGrid() + (l,))
self._monsters.append(('skeleton', _monster))
if l == _start:
self._creatureLayer.add('skeleton_' + str(_counter), _monster.getSprite(self._creatureLayer, 'skeleton_' + str(_counter)))
self._actual.append(('skeleton_' + str(_counter), _monster))
_monster.move((0, 0, 0))
_counter += 1
elif cell.getModifier() & field.MODIFIER_MAGE:
_monster = Mage(self._map, cell.getGrid() + (l,))
self._monsters.append(('mage', _monster))
if l == _start:
self._creatureLayer.add('mage_' + str(_counter), _monster.getSprite(self._creatureLayer, 'mage_' + str(_counter)))
self._actual.append(('mage_' + str(_counter), _monster))
_monster.move((0, 0, 0))
_counter += 1
elif cell.getModifier() & field.MODIFIER_TROLL:
_monster = Troll(self._map, cell.getGrid() + (l,))
self._monsters.append(('troll', _monster))
if l == _start:
self._creatureLayer.add('troll_' + str(_counter), _monster.getSprite(self._creatureLayer, 'troll_' + str(_counter)))
self._actual.append(('troll_' + str(_counter), _monster))
_monster.move((0, 0, 0))
_counter += 1
if not self._hero:
raise Exception('Brak bohatera w lochu!?')
self._statusbar = StatusBar(_engine, self._hero) # pasek życia/many itp. / statusu
self.inventory = Inventory(_engine, self._hero, self._hero.inventory, self._freeobjects)
self.chestitems = ChestItems(_engine, self._hero, self._freeobjects)
self._submodules = (self._map, self._minimap, self._statusbar, self.inventory, self.chestitems, self._cursor)
self._play = True
self._refresh = True
def isPlaying(self):
"""Czy gracz nadal gra?"""
return self._play
def screenUpdated(self):
"""Aktualizuje obrazy tła i submoduły."""
super(Scene, self).screenUpdated()
self._refresh = True
self._background = pygame.Surface((self._resx, self._resy))
self._background.blit(self.side, (self._resx - 232, self._resy - 1500))
self.surface = pygame.transform.smoothscale(self.surface, (self._resx, self._resy))
for submodule in self._submodules:
submodule.screenUpdated()
#.........这里部分代码省略.........
示例12: read
# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import addLayer [as 别名]
def read(self, fileName):
file = QFile(fileName)
if (not file.open (QIODevice.ReadOnly)):
self.mError = self.tr("Could not open file for reading.")
return None
# default to values of the original flare alpha game.
map = Map(Map.Orientation.Isometric, 256, 256, 64, 32)
stream = QTextStream(file)
line = QString()
sectionName = QString()
newsection = False
path = QFileInfo(file).absolutePath()
base = 10
gidMapper = GidMapper()
gid = 1
tilelayer = None
objectgroup = None
mapobject = None
tilesetsSectionFound = False
headerSectionFound = False
tilelayerSectionFound = False # tile layer or objects
while (not stream.atEnd()):
line = stream.readLine()
if line == '':
continue
startsWith = line[0]
if (startsWith == '['):
sectionName = line[1:line.index(']')]
newsection = True
continue
if (sectionName == "header"):
headerSectionFound = True
#get map properties
epos = line.index('=')
if (epos != -1):
key = line[:epos].strip()
value = line[epos + 1:].strip()
if (key == "width"):
map.setWidth(Int(value))
elif (key == "height"):
map.setHeight(Int(value))
elif (key == "tilewidth"):
map.setTileWidth(Int(value))
elif (key == "tileheight"):
map.setTileHeight(Int(value))
elif (key == "orientation"):
map.setOrientation(orientationFromString(value))
else:
map.setProperty(key, value)
elif (sectionName == "tilesets"):
tilesetsSectionFound = True
epos = line.index('=')
key = line[:epos].strip()
value = line[epos + 1:].strip()
if (key == "tileset"):
_list = value.split(',')
absoluteSource = _list[0]
if (QDir.isRelativePath(absoluteSource)):
absoluteSource = path + '/' + absoluteSource
tilesetwidth = 0
tilesetheight = 0
if len(_list) > 2:
tilesetwidth = Int(_list[1])
tilesetheight = Int(_list[2])
tileset = Tileset.create(QFileInfo(absoluteSource).fileName(), tilesetwidth, tilesetheight)
ok = tileset.loadFromImage(absoluteSource)
if not ok:
self.mError = self.tr("Error loading tileset %s, which expands to %s. Path not found!"%(_list[0], absoluteSource))
return None
else :
if len(_list) > 4:
tileset.setTileOffset(QPoint(Int(_list[3]),Int(_list[4])))
gidMapper.insert(gid, tileset)
if len(_list) > 5:
gid += Int(_list[5])
else :
gid += tileset.tileCount()
map.addTileset(tileset)
elif (sectionName == "layer"):
if (not tilesetsSectionFound):
self.mError = self.tr("No tilesets section found before layer section.")
return None
tilelayerSectionFound = True
epos = line.index('=')
if (epos != -1):
key = line[:epos].strip()
value = line[epos + 1:].strip()
if (key == "type"):
tilelayer = TileLayer(value, 0, 0, map.width(),map.height())
map.addLayer(tilelayer)
elif (key == "format"):
if (value == "dec"):
base = 10
#.........这里部分代码省略.........