예제 #1
0
    def newGame(self, fn, root):
        """Start a new game"""

        #create the new save file
        self.savegame = save.Save(fn)

        #get the new game node from the game xml file
        newgameNode = data.getChild(root, "newgame")

        #create the map, loading connections since it's the active one
        self.map = tilemap.Tilemap(
            os.path.join(settings.path, "data",
                         data.getAttr(newgameNode, "map", data.D_STRING)))
        self.map.loadConnections()

        #create the player
        playerNode = data.getChild(root, "player")
        self.player = player.Player(
            playerNode, self.map,
            data.getAttr(newgameNode, "position", data.D_INT2LIST),
            data.getAttr(newgameNode, "level", data.D_INT))

        #if there's a new game script, run it
        script = data.getOptionalChild(newgameNode, "script")
        if script is not None:
            s = script_engine.Script(script)
            self.scriptEngine.run(s)
예제 #2
0
   def __init__(self, screen, node):
      """
      Set up the screen - load any images and play any music.

      screen - the screen to blit to.
      node - the <screen> node.
      """

      #store the screen for later
      self.screen = screen

      #set up the timer
      #time of -1 means no time limit
      self.time = data.getAttr(node, "time", data.D_INT)
      self.count = 0
      self.trackTime = (self.time != -1)
      
      #find out the background color
      #use american spelling of color by convention
      self.bgColor = data.getAttr(node, "bgcolor", data.D_INT3LIST)

      #find the music to play if any
      self.music = None
      for track in data.getChildren(node, "music"):
         self.music = os.path.join(settings.path, "data", data.getAttr(track, "file", data.D_STRING))

      #load all images
      self.images = []
      for image in data.getChildren(node, "image"):
         self.images.append(IntroImage(self.screen, image))
예제 #3
0
    def __init__(self, node, mMap):
        """
      Set up the warp and create the script.

      node - the <warp> node to get data from.
      mMap - the map the warp belongs to.
      """

        #store the map for later
        self.map = mMap

        #parse the node
        self.position = tuple(data.getAttr(node, "position", data.D_INT2LIST))
        self.targetMap = os.path.join(
            settings.path, "data",
            data.getAttr(node, "targetmap", data.D_STRING))
        self.targetPosition = tuple(
            data.getAttr(node, "targetposition", data.D_INT2LIST))

        #triggered by walkonto
        self.trigger = EV_WALKONTO

        #event levels aren't currently checked
        self.level = 0
        self.targetLevel = 0
예제 #4
0
   def __init__(self, node, mMap, position, level):
      """
      Set up the player.

      node - the <player> node.
      mMap - the map to start on.
      position - the position to start at.
      level - the level to start on.
      """

      #init the sprite
      sprite.Sprite.__init__(self, node, mMap, position, level)

      #create status tilesets
      self.statusTilesets = {}
      self.statusTilesets[sprite.S_WALK] = self.tileset
      for statusNode in data.getChildren(node, "status"):
         try:
            status = STATUSNAMES[data.getAttr(statusNode, "name", data.D_STRING)]
         except KeyError:
            raise data.DInvalidAttributeError(statusNode, "name")
         tsPath = os.path.join(settings.path, "data", data.getAttr(statusNode, "tileset", data.D_STRING))
         ts = tileset.Tileset(tsPath)
         self.statusTilesets[status] = ts

      #create an empty party
      #overridden with unpickled party if restoring from a save
      self.party = pokemon.Party()

      #set up scripting
      self.scriptCommands["addToParty"] = self.command_addToParty
예제 #5
0
   def __init__(self, node, mMap, position=None, level=None):
      """
      aa

      node - the <sprite> node.
      mMap - the map to put the sprite on.
      position - the position to start at. If None it gets taken from the node.
      level - the level to start on. If None it gets taken from the node.
      """

      #init the VisibleObject
      objects.VisibleObject.__init__(self)

      #store the map for later
      self.map = mMap

      #create the tileset
      #determine the tile offset, so that the sprite is drawn at the centre bottom of a map tile
      tilesetPath = os.path.join(settings.path, "data", data.getAttr(node, "tileset", data.D_STRING))
      self.tileset = tileset.Tileset(tilesetPath)

      #determine position, and initialise destination to position
      if position is None:
         self.position = tuple(data.getAttr(node, "position", data.D_INT2LIST))
      else:
         self.position = position
      self.destination = self.position

      #determine the level
      if level is None:
         self.level = data.getAttr(node, "level", data.D_INT)
      else:
         self.level = level

      #find out the id, if there is one
      self.id = data.getOptionalAttr(node, "id", data.D_STRING, None)

      #initialise variables
      self.direction = DIR_DOWN
      self.status = S_WALK
      self.speed = 1 #walking
      self.walkCycle = 0
      self.busy = False
      self.switch = False
      self.locked = False
      self.hasBumped = False

      #no script engine given yet
      self.scriptEngine = script_engine.ScriptEngine()

      #for scripting
      self.scriptCommands["foo"] = self.command_foo

      #create the basic walk animations
      #set the current animation but don't play it (so it can be ticked without errors)
      self.animations[DIR_UP] = animation.Animation([12,12,13,13,14,14,15,15])
      self.animations[DIR_DOWN] = animation.Animation([0,0,1,1,2,2,3,3])
      self.animations[DIR_LEFT] = animation.Animation([4,4,5,5,6,6,7,7])
      self.animations[DIR_RIGHT] = animation.Animation([8,8,9,9,10,10,11,11])
      self.animation = self.animations[0]
예제 #6
0
   def __init__(self, screen, skillsNode, poke):
      """
      aa

      screen - the screen to blit to.
      statsNode - the <stats> node from the menu XML file.
      poke - the pokemon.
      """

      self.screen = screen

      fFont = font.Font(os.path.join(settings.path, "data", data.getAttr(skillsNode, "font", data.D_STRING)))

      size = ((self.screen.get_width()/2)-(OBJECTBUFFER*2), (self.screen.get_height()/2)-(OBJECTBUFFER*2))
      fn = os.path.join(settings.path, "data", data.getAttr(skillsNode, "box", data.D_STRING))
      self.statsBox = box.Box(size, fn).convert(self.screen)

      stats = {"HP": pokemon.ST_HP,
               "Attack": pokemon.ST_ATTACK,
               "Defense": pokemon.ST_DEFENSE,
               "Sp Attack": pokemon.ST_SPATTACK,
               "Sp Defense": pokemon.ST_SPDEFENSE,
               "Speed": pokemon.ST_SPEED}
      order = ["HP", "Attack", "Defense", "Sp Attack", "Sp Defense", "Speed"]
      
      pointerY = BORDER
      for stat in order:
         fFont.writeText(stat, self.statsBox, (BORDER, pointerY))
         text = str(poke.stats[stats[stat]])
         fFont.writeText(text, self.statsBox, (size[0]-fFont.calcWidth(text)-BORDER, pointerY))
         pointerY += fFont.height+LINEBUFFER
      
      self.statsBoxLocation = (self.screen.get_width()-size[0]-OBJECTBUFFER, OBJECTBUFFER)
예제 #7
0
    def __init__(self, screen, node):
        """Load the image and determine it's position."""

        #store screen for later
        self.screen = screen

        #open the image
        fn = os.path.join(settings.path, "data",
                          data.getAttr(node, "file", data.D_STRING))
        self.image = data.getImage(fn, "Intro file.").convert(self.screen)
        transparency = data.getAttr(node, "transparency", data.D_INT3LIST)
        self.image.set_colorkey(transparency)

        #calculate where the centres are for the screen and the image
        screenCentre = self.screen.get_width() / 2, self.screen.get_height(
        ) / 2
        imageCentre = self.image.get_width() / 2, self.image.get_height() / 2

        #find out the location of the image
        location = data.getAttr(node, "location", data.D_INT2LIST)

        #calculate its position on the screen
        #location (0,0) should be dead centre, (-100, 100) bottom left
        self.position = ((screenCentre[0] - imageCentre[0]) +
                         ((location[0] * screenCentre[0]) / 100),
                         (screenCentre[1] - imageCentre[1]) +
                         ((location[1] * screenCentre[1]) / 100))
예제 #8
0
   def loadPokemon(self):
      """
      Load the pokemon, and create the main pokemon box common to all pages.

      Uses the currentPoke attribute to search party for correct pokemon.
      """

      #get the required pokemon
      self.poke = self.party[self.currentPoke]
      speciesNode = self.poke.speciesNode

      #get the <main> child of the <pokemon> node
      mainNode = data.getChild(self.menuNode, "main")

      #create the font
      fFont = font.Font(os.path.join(settings.path, "data", data.getAttr(mainNode, "font", data.D_STRING)))

      #create the main box, which will cover the top left quarter of the screen
      size = ((self.screen.get_width()/2)-(OBJECTBUFFER*2), (self.screen.get_height()/2)-(OBJECTBUFFER*2))
      fn = os.path.join(settings.path, "data", data.getAttr(mainNode, "box", data.D_STRING))
      self.mainBox = box.Box(size, fn).convert(self.screen)

      #write the pokemon level and name, then draw the pokemon
      fFont.writeText("Lv%i" % self.poke.level, self.mainBox, (BORDER, BORDER)) #top left
      fFont.writeText(self.poke.getName(), self.mainBox, ((size[0]-fFont.calcWidth(self.poke.getName()))/2, BORDER)) #top centre
      self.battler = self.poke.getBattler()
      self.mainBox.blit(self.battler, ((size[0]-self.battler.get_width())/2, size[1]-self.battler.get_height()-BORDER)) #bottom centre
예제 #9
0
    def __init__(self, screen, node):
        """
      Set up the screen - load any images and play any music.

      screen - the screen to blit to.
      node - the <screen> node.
      """

        #store the screen for later
        self.screen = screen

        #set up the timer
        #time of -1 means no time limit
        self.time = data.getAttr(node, "time", data.D_INT)
        self.count = 0
        self.trackTime = (self.time != -1)

        #find out the background color
        #use american spelling of color by convention
        self.bgColor = data.getAttr(node, "bgcolor", data.D_INT3LIST)

        #find the music to play if any
        self.music = None
        for track in data.getChildren(node, "music"):
            self.music = os.path.join(
                settings.path, "data",
                data.getAttr(track, "file", data.D_STRING))

        #load all images
        self.images = []
        for image in data.getChildren(node, "image"):
            self.images.append(IntroImage(self.screen, image))
예제 #10
0
    def newGame(self, fn, root):
        """Start a new game"""

        # create the new save file
        self.savegame = save.Save(fn)

        # get the new game node from the game xml file
        newgameNode = data.getChild(root, "newgame")

        # create the map, loading connections since it's the active one
        self.map = tilemap.Tilemap(os.path.join(settings.path, "data", data.getAttr(newgameNode, "map", data.D_STRING)))
        self.map.loadConnections()

        # create the player
        playerNode = data.getChild(root, "player")
        self.player = player.Player(
            playerNode,
            self.map,
            data.getAttr(newgameNode, "position", data.D_INT2LIST),
            data.getAttr(newgameNode, "level", data.D_INT),
        )

        # if there's a new game script, run it
        script = data.getOptionalChild(newgameNode, "script")
        if script is not None:
            s = script_engine.Script(script)
            self.scriptEngine.run(s)
예제 #11
0
   def getBattler(self):
      graphicsNode = data.getChild(self.speciesNode, "graphics")
      battleNode = data.getChild(graphicsNode, "battle")
      battler = data.getImage(os.path.join(settings.path, "data", data.getAttr(battleNode, "front", data.D_STRING)), battleNode.ditto_fn)
      trans = data.getAttr(battleNode, "transparency", data.D_INT3LIST)
      battler.set_colorkey(trans)

      return battler
예제 #12
0
   def __init__(self, screen, partyNode, location):
      self.screen = screen
      self.location = location

      emptyNode = data.getChild(partyNode, "empty")
      fn = os.path.join(settings.path, "data", data.getAttr(emptyNode, "file", data.D_STRING))
      self.box = pygame.image.load(fn).convert(self.screen)
      self.box.set_colorkey(data.getAttr(partyNode, "transparency", data.D_INT3LIST))
예제 #13
0
    def __init__(self, screen, infoNode, poke):
        """
      aa

      screen - the screen to blit to.
      infoNode - the <info> node from the menu XML file.
      poke - the pokemon.
      """

        self.screen = screen

        fFont = font.Font(
            os.path.join(settings.path, "data",
                         data.getAttr(infoNode, "font", data.D_STRING)))

        size = ((self.screen.get_width() / 2) - (OBJECTBUFFER * 2),
                (self.screen.get_height() / 2) - (OBJECTBUFFER * 2))
        fn = os.path.join(settings.path, "data",
                          data.getAttr(infoNode, "box", data.D_STRING))
        self.infoBox = box.Box(size, fn).convert(self.screen)

        info = {
            "No.": data.getAttr(poke.speciesNode, "dex", data.D_STRING),
            "Name": poke.getName(),
            "Type": "TODO",
            "OT": str(poke.trainer),
            "ID No.": str(poke.trainerID),
            "Item": str(poke.heldItem)
        }
        order = ["No.", "Name", "Type", "OT", "ID No.", "Item"]

        pointerY = BORDER
        for inf in order:
            fFont.writeText(inf, self.infoBox, (BORDER, pointerY))
            text = info[inf]
            fFont.writeText(
                text, self.infoBox,
                (size[0] - fFont.calcWidth(text) - BORDER, pointerY))
            pointerY += fFont.height + LINEBUFFER

        self.infoBoxLocation = (self.screen.get_width() - size[0] -
                                OBJECTBUFFER, OBJECTBUFFER)

        size = (self.screen.get_width() - (OBJECTBUFFER * 2),
                (self.screen.get_height() / 2) - (OBJECTBUFFER * 2))
        self.memoBox = box.Box(size, fn).convert(self.screen)

        pointerY = BORDER
        fFont.writeText("%s nature." % "TODO", self.memoBox,
                        (BORDER, pointerY))
        pointerY += fFont.height + LINEBUFFER
        fFont.writeText("Met in %s." % "TODO", self.memoBox,
                        (BORDER, pointerY))

        self.memoBoxLocation = (OBJECTBUFFER, self.screen.get_height() -
                                size[1] - OBJECTBUFFER)
예제 #14
0
   def __init__(self, text, screen, drawCursor=True):
      """
      Create the dialog box and load cursors.

      text - a list of lines of text to go in the dialog.
      font - the font with which to write the text.
      screen - the surface to draw the dialog onto.
      soundManager - the sound manager.
      drawCursor - whether a continuation cursor should be drawn when the text has finished writing.
      """

      #store variables we'll need again
      self.text = text.split(LINESEP)
      self.screen = screen
      self.drawCursor = drawCursor
      
      #determine the speed to write at, in characters per tick
      if settings.textSpeed == "SLOW":
         self.speed = 1
      elif settings.textSpeed == "MEDIUM":
         self.speed = 2
      elif settings.textSpeed == "FAST":
         self.speed = 4

      #parse the dialog xml file
      fn = os.path.join(settings.path, "data", globs.DIALOG)
      root = data.getTreeRoot(fn, "Ditto main")
      transparency = data.getAttr(root, "transparency", data.D_INT3LIST)

      #create font
      fontPath = os.path.join(settings.path, "data", globs.FONT)
      self.font = font.Font(fontPath)

      #create the box
      size = ((self.screen.get_width()-(OBJECTBUFFER*2), (len(self.text)*(self.font.height+LINEBUFFER))-LINEBUFFER+(BORDER*2)))
      self.box = box.Box(size).convert(self.screen)

      #load the cursors
      cursorPath = os.path.join(settings.path, "data", data.getAttr(root, "cursor", data.D_STRING))
      self.cursor = data.getImage(cursorPath).convert(self.screen)
      self.cursor.set_colorkey(transparency)
      self.cursorLocation = (self.screen.get_width()-OBJECTBUFFER-BORDER-self.cursor.get_width(),
                             self.screen.get_height()-OBJECTBUFFER-BORDER-self.cursor.get_height())

      cursorPath = os.path.join(settings.path, "data", data.getAttr(root, "sidecursor", data.D_STRING))
      self.sideCursor = data.getImage(cursorPath).convert(self.screen)
      self.sideCursor.set_colorkey(transparency)

      #calculate location of dialog box
      self.location = OBJECTBUFFER, self.screen.get_height()-self.box.get_height()-OBJECTBUFFER

      #start progress at 0 and set drawing and busy
      self.progress = 0
      self.writing = True
      self.busy = True
예제 #15
0
    def __init__(self, node, mMap, position=None, level=None):
        """
      Initialise the sprite, and set up movement and scripts.

      node - the <npc> node.
      mMap - the map to start on.
      position - the position to start in. If unspecified gets taken from the <npc> node.
      level - the level to start on. If unspecified gets taken from the <npc> node.
      """

        #initialize the sprite
        sprite.Sprite.__init__(self, node, mMap, position, level)

        self.initialPosition = self.position  #store initial position anchor

        #determine what auto movements to do
        #use the first <movement> node if one exists, otherwise no movement
        self.move = MT_NONE
        movements = data.getChildren(node, "movement")
        if movements:
            movementNode = movements[0]
            movementType = data.getAttr(movementNode, "type", data.D_STRING)

            #if asked to wander, set movement and get wander radius
            #note this uses taxicab distance, and a taxicab circle is a diamond like this:
            #  X
            # XXX
            #XX.XX
            # XXX
            #  X
            #maybe change this due to the possibility to easily block an npc on the diamond points
            if movementType == "wander":
                self.move = MT_WANDER
                self.wanderRadius = data.getAttr(movementNode, "radius",
                                                 data.D_INT)

            #if asked to follow a track , set the movement and parse for the course
            elif movementType == "track":
                self.move = MT_TRACK
                self.course = []
                self.stepCycle = 0
                for op in data.getAttr(movementNode, "course",
                                       data.D_STRING).split(","):
                    try:
                        self.course.append(INSTRUCTIONS[op])
                    except KeyError:
                        raise error.DUnsupportedError("Unknown NPC file",
                                                      "NPC movement step", op)

        #create any event scripts
        self.scripts = {}
        for s in data.getChildren(node, "script"):
            if data.getAttr(s, "trigger", data.D_STRING) == "investigate":
                self.scripts[events.EV_INVESTIGATE] = script_engine.Script(s)
예제 #16
0
    def getBattler(self):
        graphicsNode = data.getChild(self.speciesNode, "graphics")
        battleNode = data.getChild(graphicsNode, "battle")
        battler = data.getImage(
            os.path.join(settings.path, "data",
                         data.getAttr(battleNode, "front", data.D_STRING)),
            battleNode.ditto_fn)
        trans = data.getAttr(battleNode, "transparency", data.D_INT3LIST)
        battler.set_colorkey(trans)

        return battler
예제 #17
0
   def __init__(self, node, mMap, position=None, level=None):
      """
      Initialise the sprite, and set up movement and scripts.

      node - the <npc> node.
      mMap - the map to start on.
      position - the position to start in. If unspecified gets taken from the <npc> node.
      level - the level to start on. If unspecified gets taken from the <npc> node.
      """

      #initialize the sprite
      sprite.Sprite.__init__(self, node, mMap, position, level)

      self.initialPosition = self.position #store initial position anchor

      #determine what auto movements to do
      #use the first <movement> node if one exists, otherwise no movement
      self.move = MT_NONE
      movements = data.getChildren(node, "movement")
      if movements:
         movementNode = movements[0]
         movementType = data.getAttr(movementNode, "type", data.D_STRING)

         #if asked to wander, set movement and get wander radius
         #note this uses taxicab distance, and a taxicab circle is a diamond like this:
         #  X
         # XXX
         #XX.XX
         # XXX
         #  X
         #maybe change this due to the possibility to easily block an npc on the diamond points
         if movementType == "wander":
            self.move = MT_WANDER
            self.wanderRadius = data.getAttr(movementNode, "radius", data.D_INT)

         #if asked to follow a track , set the movement and parse for the course  
         elif movementType == "track":
            self.move = MT_TRACK
            self.course = []
            self.stepCycle = 0
            for op in data.getAttr(movementNode, "course", data.D_STRING).split(","):
               try:
                  self.course.append(INSTRUCTIONS[op])
               except KeyError:
                  raise error.DUnsupportedError("Unknown NPC file", "NPC movement step", op)

      #create any event scripts
      self.scripts = {}
      for s in data.getChildren(node, "script"):
         if data.getAttr(s, "trigger", data.D_STRING) == "investigate":
            self.scripts[events.EV_INVESTIGATE] = script_engine.Script(s)
예제 #18
0
def init(fn):
   """
   Initialise the pygame mixer and parse XML file for sound effect locations.

   fn - the path to the XML file.
   """

   #initialise the pygame mixer
   pygame.mixer.init()

   #parse the XML file
   root = data.getTreeRoot(fn)
   for effect in data.getChildren(root, "soundeffect"):
      e = SOUNDEFFECTS[data.getAttr(effect, "name", data.D_STRING)]
      effects[e] = os.path.join(settings.path, "data", data.getAttr(effect, "file", data.D_STRING))
예제 #19
0
   def __init__(self, screen, partyNode, font, location, poke):
      self.screen = screen
      self.font = font
      self.location = location
      self.poke = poke

      self.speciesNode = poke.speciesNode

      graphicsNode = data.getChild(self.speciesNode, "graphics")
      iconNode = data.getChild(graphicsNode, "icon")
      fn = os.path.join(settings.path, "data", data.getAttr(iconNode, "file", data.D_STRING))
      image = data.getImage(fn, iconNode.ditto_fn)
      self.iconSize = data.getAttr(iconNode, "size", data.D_INT2LIST)
      self.icon = image.subsurface((0,0), self.iconSize)
      self.icon.set_colorkey(data.getAttr(iconNode, "transparency", data.D_INT3LIST))
예제 #20
0
    def setup(self, game):
        """
      Get the script engine ready to run scripts.

      game - the Game object to run scripts on.
      """

        #store game object
        self.game = game

        self.font = font.Font(os.path.join(settings.path, "data",
                                           globs.FONT))  #create the font

        #initialise variables needed to run
        self.running = False
        self.queue = []
        self.currentCommand = 0
        self.waiting = False
        self.waitingFor = None
        self.countDown = 0

        #initialise script variables
        self.variables = {}
        self.result = None

        #determine behaviour scripts
        tree = data.getTree(globs.BEHAVIOURS)
        root = tree.getroot()
        self.behaviours = {}
        for behaviourNode in data.getChildren(root, "behaviour",
                                              globs.BEHAVIOURS):
            i = data.getAttr(behaviourNode, "index", data.D_INT,
                             globs.BEHAVIOURS)
            s = data.getChild(behaviourNode, "script", globs.BEHAVIOURS)
            self.behaviours[i] = Script(s, False)
예제 #21
0
   def __init__(self, screen, partyNode, font, hpBar, location, poke):
      PartyBox.__init__(self, screen, partyNode, font, location, poke)

      self.border = 3
      self.lineBuffer = 0

      sideNode = data.getChild(partyNode, "side")
      fn = os.path.join(settings.path, "data", data.getAttr(sideNode, "file", data.D_STRING))
      self.box = pygame.image.load(fn).convert(self.screen)
      self.box.set_colorkey(data.getAttr(partyNode, "transparency", data.D_INT3LIST))

      self.box.blit(hpBar, (self.box.get_width()-hpBar.get_width()-self.border, self.border))
      self.font.writeText(poke.getName(), self.box, (self.iconSize[0]+self.border, self.border))
      self.font.writeText("Lv%s" % poke.level, self.box, (self.iconSize[0]+self.border, self.border+self.font.height+self.lineBuffer))
      text = "%s/%s" % (poke.currentHP, poke.stats[pokemon.ST_HP])
      self.font.writeText(text, self.box, (self.box.get_width()-self.font.calcWidth(text)-self.border, self.border+hpBar.get_height()))
예제 #22
0
   def setup(self, game):
      """
      Get the script engine ready to run scripts.

      game - the Game object to run scripts on.
      """

      #store game object
      self.game = game


      self.font = font.Font(os.path.join(settings.path, "data", globs.FONT)) #create the font

      #initialise variables needed to run
      self.running = False
      self.queue = []
      self.currentCommand = 0
      self.waiting = False
      self.waitingFor = None
      self.countDown = 0

      #initialise script variables
      self.variables = {}
      self.result = None

      #determine behaviour scripts
      tree = data.getTree(globs.BEHAVIOURS)
      root = tree.getroot()
      self.behaviours = {}
      for behaviourNode in data.getChildren(root, "behaviour", globs.BEHAVIOURS):
         i = data.getAttr(behaviourNode, "index", data.D_INT, globs.BEHAVIOURS)
         s = data.getChild(behaviourNode, "script", globs.BEHAVIOURS)
         self.behaviours[i] = Script(s, False)
예제 #23
0
   def __init__(self, moveId):
      self.moveId = moveId
      
      fn = os.path.join(settings.path, "data", globs.MOVES)
      root = data.getTreeRoot(fn)

      self.moveNode = None
      for m in data.getChildren(root, "move"):
         if data.getAttr(m, "id", data.D_STRING) == moveId:
            self.moveNode = m
            break
      if self.moveNode is None:
         raise error.DittoInvalidResourceException(fn, "MOVE %s" % self.moveId)

      self.name = data.getAttr(self.moveNode, "name", data.D_STRING)
      self.maxPP = data.getAttr(self.moveNode, "pp", data.D_INT)
      self.currPP = self.maxPP
예제 #24
0
   def __init__(self, screen, movesNode, poke):
      self.screen = screen

      fFont = font.Font(os.path.join(settings.path, "data", data.getAttr(movesNode, "font", data.D_STRING)))

      size = ((self.screen.get_width()/2)-(OBJECTBUFFER*2), (fFont.height+BORDER)*2)
      fn = os.path.join(settings.path, "data", data.getAttr(movesNode, "box", data.D_STRING))

      moves = poke.moves
      self.moveBoxes = []
      for move in moves:
         if move is not None:
            b = box.Box(size, fn).convert(self.screen)
            fFont.writeText(move.name, b, (BORDER, BORDER))
            text = "PP %i/%i" % (move.currPP, move.maxPP)
            fFont.writeText(text, b, (size[0]-fFont.calcWidth(text)-BORDER, BORDER+fFont.height))

            self.moveBoxes.append(b)
예제 #25
0
    def __init__(self, moveId):
        self.moveId = moveId

        fn = os.path.join(settings.path, "data", globs.MOVES)
        root = data.getTreeRoot(fn)

        self.moveNode = None
        for m in data.getChildren(root, "move"):
            if data.getAttr(m, "id", data.D_STRING) == moveId:
                self.moveNode = m
                break
        if self.moveNode is None:
            raise error.DittoInvalidResourceException(fn,
                                                      "MOVE %s" % self.moveId)

        self.name = data.getAttr(self.moveNode, "name", data.D_STRING)
        self.maxPP = data.getAttr(self.moveNode, "pp", data.D_INT)
        self.currPP = self.maxPP
예제 #26
0
   def __init__(self, screen, infoNode, poke):
      """
      aa

      screen - the screen to blit to.
      infoNode - the <info> node from the menu XML file.
      poke - the pokemon.
      """

      self.screen = screen

      fFont = font.Font(os.path.join(settings.path, "data", data.getAttr(infoNode, "font", data.D_STRING)))

      size = ((self.screen.get_width()/2)-(OBJECTBUFFER*2), (self.screen.get_height()/2)-(OBJECTBUFFER*2))
      fn = os.path.join(settings.path, "data", data.getAttr(infoNode, "box", data.D_STRING))
      self.infoBox = box.Box(size, fn).convert(self.screen)

      info = {"No.": data.getAttr(poke.speciesNode, "dex", data.D_STRING),
              "Name": poke.getName(),
              "Type": "TODO",
              "OT": str(poke.trainer),
              "ID No.": str(poke.trainerID),
              "Item": str(poke.heldItem)}
      order = ["No.", "Name", "Type", "OT", "ID No.", "Item"]

      pointerY = BORDER
      for inf in order:
         fFont.writeText(inf, self.infoBox, (BORDER, pointerY))
         text = info[inf]
         fFont.writeText(text, self.infoBox, (size[0]-fFont.calcWidth(text)-BORDER, pointerY))
         pointerY += fFont.height+LINEBUFFER

      self.infoBoxLocation = (self.screen.get_width()-size[0]-OBJECTBUFFER, OBJECTBUFFER)

      size = (self.screen.get_width()-(OBJECTBUFFER*2), (self.screen.get_height()/2)-(OBJECTBUFFER*2))
      self.memoBox = box.Box(size, fn).convert(self.screen)

      pointerY = BORDER
      fFont.writeText("%s nature." % "TODO", self.memoBox, (BORDER, pointerY))
      pointerY += fFont.height+LINEBUFFER
      fFont.writeText("Met in %s." % "TODO", self.memoBox, (BORDER, pointerY))

      self.memoBoxLocation = (OBJECTBUFFER, self.screen.get_height()-size[1]-OBJECTBUFFER)
예제 #27
0
    def __init__(self, screen, skillsNode, poke):
        """
      aa

      screen - the screen to blit to.
      statsNode - the <stats> node from the menu XML file.
      poke - the pokemon.
      """

        self.screen = screen

        fFont = font.Font(
            os.path.join(settings.path, "data",
                         data.getAttr(skillsNode, "font", data.D_STRING)))

        size = ((self.screen.get_width() / 2) - (OBJECTBUFFER * 2),
                (self.screen.get_height() / 2) - (OBJECTBUFFER * 2))
        fn = os.path.join(settings.path, "data",
                          data.getAttr(skillsNode, "box", data.D_STRING))
        self.statsBox = box.Box(size, fn).convert(self.screen)

        stats = {
            "HP": pokemon.ST_HP,
            "Attack": pokemon.ST_ATTACK,
            "Defense": pokemon.ST_DEFENSE,
            "Sp Attack": pokemon.ST_SPATTACK,
            "Sp Defense": pokemon.ST_SPDEFENSE,
            "Speed": pokemon.ST_SPEED
        }
        order = ["HP", "Attack", "Defense", "Sp Attack", "Sp Defense", "Speed"]

        pointerY = BORDER
        for stat in order:
            fFont.writeText(stat, self.statsBox, (BORDER, pointerY))
            text = str(poke.stats[stats[stat]])
            fFont.writeText(
                text, self.statsBox,
                (size[0] - fFont.calcWidth(text) - BORDER, pointerY))
            pointerY += fFont.height + LINEBUFFER

        self.statsBoxLocation = (self.screen.get_width() - size[0] -
                                 OBJECTBUFFER, OBJECTBUFFER)
예제 #28
0
   def __init__(self, fn):
      """
      Open the tileset image, and set up animations.

      fn - the path to the tileset image.
      """

      #parse the XML file
      root = data.getTreeRoot(fn)      
      self.tileSize = data.getAttr(root, "tilesize", data.D_INT2LIST) 
      self.transparency = data.getAttr(root, "transparency", data.D_INT3LIST)

      #create the tiles
      tilesetPath = os.path.join(settings.path, "data", data.getAttr(root, "file", data.D_STRING))
      self.openImage(tilesetPath)

      #create animations for the tileset
      self.autoAnimations = {}
      self.walkontoAnimations = {}
      for anim in root.findall("animation"):
         trigger = data.getAttr(anim, "trigger", data.D_STRING)
         tile = data.getAttr(anim, "tile", data.D_INT)
         frames = data.getAttr(anim, "frames", data.D_INTLIST)
         a = animation.Animation(frames)
         
         if trigger == "auto":
            a.play(True)
            self.autoAnimations[tile] = a
         elif trigger == "walkonto":
            self.walkontoAnimations[tile] = a
예제 #29
0
    def __init__(self, fn):
        """
      Open the tileset image, and set up animations.

      fn - the path to the tileset image.
      """

        #parse the XML file
        root = data.getTreeRoot(fn)
        self.tileSize = data.getAttr(root, "tilesize", data.D_INT2LIST)
        self.transparency = data.getAttr(root, "transparency", data.D_INT3LIST)

        #create the tiles
        tilesetPath = os.path.join(settings.path, "data",
                                   data.getAttr(root, "file", data.D_STRING))
        self.openImage(tilesetPath)

        #create animations for the tileset
        self.autoAnimations = {}
        self.walkontoAnimations = {}
        for anim in root.findall("animation"):
            trigger = data.getAttr(anim, "trigger", data.D_STRING)
            tile = data.getAttr(anim, "tile", data.D_INT)
            frames = data.getAttr(anim, "frames", data.D_INTLIST)
            a = animation.Animation(frames)

            if trigger == "auto":
                a.play(True)
                self.autoAnimations[tile] = a
            elif trigger == "walkonto":
                self.walkontoAnimations[tile] = a
예제 #30
0
    def __init__(self, screen, savegame=None):
        """
      Open the save file (or make a new one) and create camera and script engine.

      screen - the screen to render to.
      sound - the sound manager.
      savegame - path to the save file to open, or None to start a new game.
      """

        #store variables for use later
        self.screen = screen

        #parse the game XML file
        fn = os.path.join(settings.path, "data", "game.xml")
        root = data.getTreeRoot(fn, "Ditto main")
        for p in data.getChildren(root, "property"):
            if data.getAttr(p, "name", data.D_STRING) == "menu":
                self.menuPath = data.getAttr(p, "value", data.D_STRING)

        #create script engine and initialise variables
        self.scriptEngine = script_engine.ScriptEngine()
        self.scriptEngine.setup(self)
        self.paused = False
        self.foregroundObject = None

        #if there's a save, open it
        #else start a new game
        if savegame is not None:
            self.openSave(savegame, root)
        else:
            self.newGame(os.path.join(settings.path, "saves", "ditto.sav"),
                         root)

        #put the player onto the map and play music
        self.map.sprites["PLAYER"] = self.player
        sound.playMusic(self.player.map.music)

        #create a camera and attach to the player
        self.camera = camera.Camera(screen)
        self.camera.attachTo(self.player)
예제 #31
0
    def __init__(self, fn):
        """
      Load the image and cut out the individual characters.

      fn - the font XML file.
      """

        #parse the XML file
        root = data.getTreeRoot(fn)
        path = os.path.join(settings.path, "data",
                            data.getAttr(root, "file", data.D_STRING))
        self.height = data.getAttr(root, "height", data.D_INT)
        transparency = data.getAttr(root, "transparency", data.D_INT3LIST)

        #load the image
        image = data.getImage(path, fn)
        image.set_colorkey(transparency)

        #cut out the tiles and store them in a dictionary
        self.characters = {}
        for c in data.getChildren(root, "character"):
            char = data.getAttr(c, "char", data.D_STRING)
            width = data.getAttr(c, "width", data.D_INT)
            location = data.getAttr(c, "location", data.D_INT2LIST)
            self.characters[char] = image.subsurface(location[0], location[1],
                                                     width, self.height)
예제 #32
0
    def __init__(self, screen, savegame=None):
        """
      Open the save file (or make a new one) and create camera and script engine.

      screen - the screen to render to.
      sound - the sound manager.
      savegame - path to the save file to open, or None to start a new game.
      """

        # store variables for use later
        self.screen = screen

        # parse the game XML file
        fn = os.path.join(settings.path, "data", "game.xml")
        root = data.getTreeRoot(fn, "Ditto main")
        for p in data.getChildren(root, "property"):
            if data.getAttr(p, "name", data.D_STRING) == "menu":
                self.menuPath = data.getAttr(p, "value", data.D_STRING)

        # create script engine and initialise variables
        self.scriptEngine = script_engine.ScriptEngine()
        self.scriptEngine.setup(self)
        self.paused = False
        self.foregroundObject = None

        # if there's a save, open it
        # else start a new game
        if savegame is not None:
            self.openSave(savegame, root)
        else:
            self.newGame(os.path.join(settings.path, "saves", "ditto.sav"), root)

        # put the player onto the map and play music
        self.map.sprites["PLAYER"] = self.player
        sound.playMusic(self.player.map.music)

        # create a camera and attach to the player
        self.camera = camera.Camera(screen)
        self.camera.attachTo(self.player)
예제 #33
0
   def __init__(self, node, mMap):
      """
      Set up the warp and create the script.

      node - the <warp> node to get data from.
      mMap - the map the warp belongs to.
      """

      #store the map for later
      self.map = mMap

      #parse the node
      self.position = tuple(data.getAttr(node, "position", data.D_INT2LIST))
      self.targetMap = os.path.join(settings.path, "data", data.getAttr(node, "targetmap", data.D_STRING))
      self.targetPosition = tuple(data.getAttr(node, "targetposition", data.D_INT2LIST))

      #triggered by walkonto
      self.trigger = EV_WALKONTO

      #event levels aren't currently checked
      self.level = 0
      self.targetLevel = 0
예제 #34
0
   def __init__(self, screen, partyNode, party):
      self.screen = screen
      self.partyNode = partyNode
      self.font = font.Font(os.path.join(settings.path, "data", data.getAttr(partyNode, "font", data.D_STRING)))
      self.party = party

      self.foregroundObject = None

      fn = os.path.join(settings.path, "data", data.getAttr(partyNode, "hpbar", data.D_STRING))
      hpBar = pygame.image.load(fn).convert(self.screen)
      hpBar.set_colorkey(data.getAttr(partyNode, "transparency", data.D_INT3LIST))

      self.border = 5
      self.lineBuffer = 2

      self.shadow = pygame.Surface((self.screen.get_width(), self.screen.get_height()))
      self.shadow.fill((10,10,10))
      self.shadow.set_alpha(100)

      self.boxes = []
      self.current = 0

      main = MainBox(self.screen, partyNode, self.font, hpBar, (self.border, self.border+25), self.party[0])
      self.boxes.append(main)

      pointerX = (self.border*2)+main.box.get_width()
      pointerY = self.border
      for i in range(1, len(self.party)):
         b = SideBox(self.screen, partyNode, self.font, hpBar, (pointerX,pointerY), self.party[i])
         self.boxes.append(b)
         pointerY += b.box.get_height()+self.border

      for i in range(len(self.party), 6):
         b = EmptyBox(self.screen, partyNode, (pointerX,pointerY))
         self.boxes.append(b)
         pointerY += b.box.get_height()+self.border

      self.busy = True
예제 #35
0
   def __init__(self, node, triggered=True):
      if triggered:
         trig = data.getAttr(node, "trigger", data.D_STRING)
         if trig == "investigate":
            self.trigger = events.EV_INVESTIGATE
         elif trig == "walkonto":
            self.trigger = events.EV_WALKONTO
         elif trig == "load":
            self.trigger = events.EV_LOAD
         elif trig == "newgame":
            self.trigger = events.EV_NEWGAME

      fn = os.path.join(settings.path, "data", data.getAttr(node, "source", data.D_STRING))
      scriptId = data.getAttr(node, "id", data.D_STRING)

      source = getSource(fn, scriptId)
      ast = script_yacc.parse(source, fn, scriptId)

      f = open(OUT_AST, "w")
      ast.pprint(f)
      f.close()
      
      self.commands = script_compiler.toCommands(ast)
예제 #36
0
   def __init__(self, screen, node):
      """Load the image and determine it's position."""

      #store screen for later
      self.screen = screen

      #open the image
      fn = os.path.join(settings.path, "data", data.getAttr(node, "file", data.D_STRING))
      self.image = data.getImage(fn, "Intro file.").convert(self.screen)
      transparency = data.getAttr(node, "transparency", data.D_INT3LIST)
      self.image.set_colorkey(transparency)

      #calculate where the centres are for the screen and the image
      screenCentre = self.screen.get_width()/2, self.screen.get_height()/2
      imageCentre = self.image.get_width()/2, self.image.get_height()/2

      #find out the location of the image
      location = data.getAttr(node, "location", data.D_INT2LIST)

      #calculate its position on the screen
      #location (0,0) should be dead centre, (-100, 100) bottom left
      self.position = ((screenCentre[0]-imageCentre[0])+((location[0]*screenCentre[0])/100),
                       (screenCentre[1]-imageCentre[1])+((location[1]*screenCentre[1])/100))
예제 #37
0
    def __init__(self, node, mMap):
        """
      Set up the event and create the script.

      node - the <script> node to get data from.
      mMap - the map the script belongs to.
      """

        #store the map for later
        self.map = mMap

        #parse the node
        self.position = tuple(data.getAttr(node, "position", data.D_INT2LIST))
        trigger = data.getAttr(node, "trigger", data.D_STRING)
        if trigger == "investigate":
            self.trigger = EV_INVESTIGATE
        elif trigger == "walkonto":
            self.trigger = EV_WALKONTO

        #event levels aren't currently checked
        self.level = 0

        #create the script object
        self.script = script_engine.Script(node)
예제 #38
0
    def __init__(self, screen, movesNode, poke):
        self.screen = screen

        fFont = font.Font(
            os.path.join(settings.path, "data",
                         data.getAttr(movesNode, "font", data.D_STRING)))

        size = ((self.screen.get_width() / 2) - (OBJECTBUFFER * 2),
                (fFont.height + BORDER) * 2)
        fn = os.path.join(settings.path, "data",
                          data.getAttr(movesNode, "box", data.D_STRING))

        moves = poke.moves
        self.moveBoxes = []
        for move in moves:
            if move is not None:
                b = box.Box(size, fn).convert(self.screen)
                fFont.writeText(move.name, b, (BORDER, BORDER))
                text = "PP %i/%i" % (move.currPP, move.maxPP)
                fFont.writeText(text, b,
                                (size[0] - fFont.calcWidth(text) - BORDER,
                                 BORDER + fFont.height))

                self.moveBoxes.append(b)
예제 #39
0
    def __init__(self, node, triggered=True):
        if triggered:
            trig = data.getAttr(node, "trigger", data.D_STRING)
            if trig == "investigate":
                self.trigger = events.EV_INVESTIGATE
            elif trig == "walkonto":
                self.trigger = events.EV_WALKONTO
            elif trig == "load":
                self.trigger = events.EV_LOAD
            elif trig == "newgame":
                self.trigger = events.EV_NEWGAME

        fn = os.path.join(settings.path, "data",
                          data.getAttr(node, "source", data.D_STRING))
        scriptId = data.getAttr(node, "id", data.D_STRING)

        source = getSource(fn, scriptId)
        ast = script_yacc.parse(source, fn, scriptId)

        f = open(OUT_AST, "w")
        ast.pprint(f)
        f.close()

        self.commands = script_compiler.toCommands(ast)
예제 #40
0
    def loadPokemon(self):
        """
      Load the pokemon, and create the main pokemon box common to all pages.

      Uses the currentPoke attribute to search party for correct pokemon.
      """

        #get the required pokemon
        self.poke = self.party[self.currentPoke]
        speciesNode = self.poke.speciesNode

        #get the <main> child of the <pokemon> node
        mainNode = data.getChild(self.menuNode, "main")

        #create the font
        fFont = font.Font(
            os.path.join(settings.path, "data",
                         data.getAttr(mainNode, "font", data.D_STRING)))

        #create the main box, which will cover the top left quarter of the screen
        size = ((self.screen.get_width() / 2) - (OBJECTBUFFER * 2),
                (self.screen.get_height() / 2) - (OBJECTBUFFER * 2))
        fn = os.path.join(settings.path, "data",
                          data.getAttr(mainNode, "box", data.D_STRING))
        self.mainBox = box.Box(size, fn).convert(self.screen)

        #write the pokemon level and name, then draw the pokemon
        fFont.writeText("Lv%i" % self.poke.level, self.mainBox,
                        (BORDER, BORDER))  #top left
        fFont.writeText(self.poke.getName(), self.mainBox,
                        ((size[0] - fFont.calcWidth(self.poke.getName())) / 2,
                         BORDER))  #top centre
        self.battler = self.poke.getBattler()
        self.mainBox.blit(self.battler,
                          ((size[0] - self.battler.get_width()) / 2, size[1] -
                           self.battler.get_height() - BORDER))  #bottom centre
예제 #41
0
   def __init__(self, node, mMap):
      """
      Set up the event and create the script.

      node - the <script> node to get data from.
      mMap - the map the script belongs to.
      """

      #store the map for later
      self.map = mMap

      #parse the node
      self.position = tuple(data.getAttr(node, "position", data.D_INT2LIST))
      trigger = data.getAttr(node, "trigger", data.D_STRING)
      if trigger == "investigate":
         self.trigger = EV_INVESTIGATE
      elif trigger == "walkonto":
         self.trigger = EV_WALKONTO

      #event levels aren't currently checked
      self.level = 0

      #create the script object
      self.script = script_engine.Script(node)
예제 #42
0
    def setup(self, game):
        self.symbols = symbols.Symbols(game, self)

        self.script = None
        self.result = False
        self.currentCmd = 0

        self.caller = None

        self.waitingFor = None

        #determine behaviour scripts
        root = data.getTreeRoot(globs.BEHAVIOURS)
        self.behaviours = {}
        for behaviourNode in data.getChildren(root, "behaviour"):
            i = data.getAttr(behaviourNode, "index", data.D_INT)
            s = data.getChild(behaviourNode, "script")
            self.behaviours[i] = script.Script(s, False)
예제 #43
0
   def setup(self, game):
      self.symbols = symbols.Symbols(game, self)

      self.script = None
      self.result = False
      self.currentCmd = 0

      self.caller = None

      self.waitingFor = None

      #determine behaviour scripts
      root = data.getTreeRoot(globs.BEHAVIOURS)
      self.behaviours = {}
      for behaviourNode in data.getChildren(root, "behaviour"):
         i = data.getAttr(behaviourNode, "index", data.D_INT)
         s = data.getChild(behaviourNode, "script")
         self.behaviours[i] = script.Script(s, False)
예제 #44
0
   def calcStats(self):
      statsNode = data.getChild(self.speciesNode, "basestats")
      
      baseStats = {}
      baseStats[ST_HP] = data.getAttr(statsNode, "hp", data.D_INT)
      baseStats[ST_ATTACK] = data.getAttr(statsNode, "attack", data.D_INT)
      baseStats[ST_DEFENSE] = data.getAttr(statsNode, "defense", data.D_INT)
      baseStats[ST_SPATTACK] = data.getAttr(statsNode, "spatk", data.D_INT)
      baseStats[ST_SPDEFENSE] = data.getAttr(statsNode, "spdef", data.D_INT)
      baseStats[ST_SPEED] = data.getAttr(statsNode, "speed", data.D_INT)

      self.stats[ST_HP] = (((self.IVs[ST_HP]+(2*baseStats[ST_HP])+(self.EVs[ST_HP]/4)+100)*self.level)/100)+10

      for stat in [ST_ATTACK, ST_DEFENSE, ST_SPATTACK, ST_SPDEFENSE, ST_SPEED]:
         self.stats[stat] = (((self.IVs[stat]+(2*baseStats[stat])+(self.EVs[stat]/4))*self.level)/100)+5
예제 #45
0
    def calcStats(self):
        statsNode = data.getChild(self.speciesNode, "basestats")

        baseStats = {}
        baseStats[ST_HP] = data.getAttr(statsNode, "hp", data.D_INT)
        baseStats[ST_ATTACK] = data.getAttr(statsNode, "attack", data.D_INT)
        baseStats[ST_DEFENSE] = data.getAttr(statsNode, "defense", data.D_INT)
        baseStats[ST_SPATTACK] = data.getAttr(statsNode, "spatk", data.D_INT)
        baseStats[ST_SPDEFENSE] = data.getAttr(statsNode, "spdef", data.D_INT)
        baseStats[ST_SPEED] = data.getAttr(statsNode, "speed", data.D_INT)

        self.stats[ST_HP] = ((
            (self.IVs[ST_HP] + (2 * baseStats[ST_HP]) +
             (self.EVs[ST_HP] / 4) + 100) * self.level) / 100) + 10

        for stat in [
                ST_ATTACK, ST_DEFENSE, ST_SPATTACK, ST_SPDEFENSE, ST_SPEED
        ]:
            self.stats[stat] = ((
                (self.IVs[stat] + (2 * baseStats[stat]) +
                 (self.EVs[stat] / 4)) * self.level) / 100) + 5
예제 #46
0
   def __init__(self, fn):
      """
      Load the image and cut out the individual characters.

      fn - the font XML file.
      """

      #parse the XML file
      root = data.getTreeRoot(fn)
      path = os.path.join(settings.path, "data", data.getAttr(root, "file", data.D_STRING))
      self.height = data.getAttr(root, "height", data.D_INT)
      transparency = data.getAttr(root, "transparency", data.D_INT3LIST)

      #load the image
      image = data.getImage(path, fn)
      image.set_colorkey(transparency)

      #cut out the tiles and store them in a dictionary
      self.characters = {}
      for c in data.getChildren(root, "character"):
         char = data.getAttr(c, "char", data.D_STRING)
         width = data.getAttr(c, "width", data.D_INT)
         location = data.getAttr(c, "location", data.D_INT2LIST)
         self.characters[char] = image.subsurface(location[0], location[1], width, self.height)
예제 #47
0
   def setup(self):
      """Initialize pygame, find the main game file and parse it."""

      #initialise pygame
      pygame.init()

      #find the main game file and parse it
      if settings.path is not None:
         fn = os.path.join(settings.path, "data", "game.xml")
      else:
         raise error.DittoInvalidResourceException("settings.py", "path")
      root = data.getTreeRoot(fn, "Ditto Main")
      for p in data.getChildren(root, "property"):
         if data.getAttr(p, "name", data.D_STRING) == "tilesize":
            globs.TILESIZE = data.getAttr(p, "value", data.D_INT2LIST)
         elif data.getAttr(p, "name", data.D_STRING) == "font":
            globs.FONT = data.getAttr(p, "value", data.D_STRING)
         elif data.getAttr(p, "name", data.D_STRING) == "dialog":
            globs.DIALOG = data.getAttr(p, "value", data.D_STRING)
         elif data.getAttr(p, "name", data.D_STRING) == "pokemon":
            globs.POKEMON = data.getAttr(p, "value", data.D_STRING)
         elif data.getAttr(p, "name", data.D_STRING) == "soundeffects":
            soundPath = os.path.join(settings.path, "data", data.getAttr(p, "value", data.D_STRING))
         elif data.getAttr(p, "name", data.D_STRING) == "moves":
            globs.MOVES = os.path.join(settings.path, "data", data.getAttr(p, "value", data.D_STRING))
         elif data.getAttr(p, "name", data.D_STRING) == "behaviours":
            globs.BEHAVIOURS = os.path.join(settings.path, "data", data.getAttr(p, "value", data.D_STRING))

      #if there's an icon specified, use it      
      if len(data.getChildren(root, "icon")) > 0:
         node = data.getChild(root, "icon")
         iconPath = os.path.join(settings.path, "data", data.getAttr(node, "file", data.D_STRING))
         icon = data.getImage(iconPath, fn)
         pygame.display.set_icon(icon)

      #set up the main window
      windowSize = settings.screenSize[0]*globs.TILESIZE[0], settings.screenSize[1]*globs.TILESIZE[1]   
      self.screen = pygame.display.set_mode(windowSize)
      pygame.display.set_caption("%s --- Ditto Engine" % data.getAttr(root, "title", data.D_STRING))

      #create a clock object
      self.clock = pygame.time.Clock()

      #initialise sound
      sound.init(soundPath)

      #set up the initial scene, the intro
      self.activeScene = intro.Intro(self.screen)
예제 #48
0
    def setup(self):
        """Initialize pygame, find the main game file and parse it."""

        #initialise pygame
        pygame.init()

        #find the main game file and parse it
        if settings.path is not None:
            fn = os.path.join(settings.path, "data", "game.xml")
        else:
            raise error.DittoInvalidResourceException("settings.py", "path")
        root = data.getTreeRoot(fn, "Ditto Main")
        for p in data.getChildren(root, "property"):
            if data.getAttr(p, "name", data.D_STRING) == "tilesize":
                globs.TILESIZE = data.getAttr(p, "value", data.D_INT2LIST)
            elif data.getAttr(p, "name", data.D_STRING) == "font":
                globs.FONT = data.getAttr(p, "value", data.D_STRING)
            elif data.getAttr(p, "name", data.D_STRING) == "dialog":
                globs.DIALOG = data.getAttr(p, "value", data.D_STRING)
            elif data.getAttr(p, "name", data.D_STRING) == "pokemon":
                globs.POKEMON = data.getAttr(p, "value", data.D_STRING)
            elif data.getAttr(p, "name", data.D_STRING) == "soundeffects":
                soundPath = os.path.join(
                    settings.path, "data",
                    data.getAttr(p, "value", data.D_STRING))
            elif data.getAttr(p, "name", data.D_STRING) == "moves":
                globs.MOVES = os.path.join(
                    settings.path, "data",
                    data.getAttr(p, "value", data.D_STRING))
            elif data.getAttr(p, "name", data.D_STRING) == "behaviours":
                globs.BEHAVIOURS = os.path.join(
                    settings.path, "data",
                    data.getAttr(p, "value", data.D_STRING))

        #if there's an icon specified, use it
        if len(data.getChildren(root, "icon")) > 0:
            node = data.getChild(root, "icon")
            iconPath = os.path.join(settings.path, "data",
                                    data.getAttr(node, "file", data.D_STRING))
            icon = data.getImage(iconPath, fn)
            pygame.display.set_icon(icon)

        #set up the main window
        windowSize = settings.screenSize[0] * globs.TILESIZE[
            0], settings.screenSize[1] * globs.TILESIZE[1]
        self.screen = pygame.display.set_mode(windowSize)
        pygame.display.set_caption("%s --- Ditto Engine" %
                                   data.getAttr(root, "title", data.D_STRING))

        #create a clock object
        self.clock = pygame.time.Clock()

        #initialise sound
        sound.init(soundPath)

        #set up the initial scene, the intro
        self.activeScene = intro.Intro(self.screen)
예제 #49
0
 def getName(self):
     if self.nickname is None:
         return data.getAttr(self.speciesNode, "name", data.D_STRING)
     else:
         return self.nickname
예제 #50
0
    def __init__(self, species, level):
        self.species = species

        fn = os.path.join(settings.path, "data", globs.POKEMON)
        root = data.getTreeRoot(fn, "Ditto main")

        for sp in data.getChildren(root, "species"):
            if data.getAttr(sp, "id", data.D_STRING) == self.species:
                self.speciesNode = sp
                break

        self.nickname = None

        self.level = level
        self.exp = 0

        typeNode = data.getChild(self.speciesNode, "type")
        self.type1 = data.getAttr(typeNode, "primary", data.D_STRING)
        self.type2 = data.getOptionalAttr(typeNode, "secondary", data.D_STRING,
                                          None)

        self.PID = random.randint(0, 4294967295)
        self.trainer = None
        self.trainerID = None

        self.ability = None

        self.gender = G_MALE
        self.nature = 0
        self.shiny = False

        self.form = 0
        self.happiness = 0
        self.pokerus = False

        self.EVs = {
            ST_HP: 0,
            ST_ATTACK: 0,
            ST_DEFENSE: 0,
            ST_SPEED: 0,
            ST_SPATTACK: 0,
            ST_SPDEFENSE: 0
        }

        self.IVs = {
            ST_HP: random.randint(0, 31),
            ST_ATTACK: random.randint(0, 31),
            ST_DEFENSE: random.randint(0, 31),
            ST_SPEED: random.randint(0, 31),
            ST_SPATTACK: random.randint(0, 31),
            ST_SPDEFENSE: random.randint(0, 31)
        }

        self.stats = {}
        self.calcStats()

        self.currentHP = self.stats[ST_HP]
        self.status = None

        self.moves = [None, None, None, None]
        movesNode = data.getChild(self.speciesNode, "attacks")
        moveNodes = sorted(data.getChildren(movesNode, "move"),
                           key=lambda n: int(n.attrib["level"]))
        i = 0
        for node in moveNodes[-4:]:
            self.moves[i] = moves.Move(data.getAttr(node, "id", data.D_STRING))
            i += 1

        self.ballCaughtIn = 0

        self.heldItem = None
예제 #51
0
   def __init__(self, size, fn=None):
      """
      Initialize a surface and draw the box onto it.

      size - the size of the box.
      fn - the path to a box xml config file.
      """

      #initialize the pygame Surface
      pygame.Surface.__init__(self, size)

      #if no filename given, use the game default box
      if fn == None:
         fn = os.path.join(settings.path, "data", globs.DIALOG)

      #parse the box xml file
      root = data.getTreeRoot(fn)
      tilesetPath = os.path.join(settings.path, "data", data.getAttr(root, "file", data.D_STRING))
      tileset = data.getImage(tilesetPath)
      transparency = data.getAttr(root, "transparency", data.D_INT3LIST)
      tileset.set_colorkey(transparency)
      tileSize = data.getAttr(root, "tilesize", data.D_INT2LIST)
      data.check((tileSize[0]+1)*3==tileset.get_width()+1, tilesetPath)
      data.check((tileSize[1]+1)*3==tileset.get_height()+1, tilesetPath)

      #fill transparent
      self.fill((255,0,255))
      self.set_colorkey((255,0,255))

      #cut each of the nine tiles out from the tileset
      tileNW = tileset.subsurface((0,0), tileSize)
      tileN = tileset.subsurface((tileSize[0]+1,0), tileSize)
      tileNE = tileset.subsurface(((tileSize[0]+1)*2,0), tileSize)
      tileW = tileset.subsurface((0,tileSize[1]+1), tileSize)
      tileC = tileset.subsurface((tileSize[0]+1,tileSize[1]+1), tileSize)
      tileE = tileset.subsurface(((tileSize[0]+1)*2,tileSize[1]+1), tileSize)
      tileSW = tileset.subsurface((0,(tileSize[1]+1)*2), tileSize)
      tileS = tileset.subsurface((tileSize[0]+1,(tileSize[1]+1)*2), tileSize)
      tileSE = tileset.subsurface(((tileSize[0]+1)*2,(tileSize[1]+1)*2), tileSize)

      #calculate how much of the box is not covered by edge tiles - all this middle must be covered by the centre tile
      #work out how many tiles it will take to cover that, and where to start drawing from
      middleSize = size[0]-(2*tileSize[0]), size[1]-(2*tileSize[1])
      dimensions = (middleSize[0]/tileSize[0])+1, (middleSize[1]/tileSize[1])+1
      origin = (size[0]-(dimensions[0]*tileSize[0]))/2, (size[1]-(dimensions[1]*tileSize[1]))/2

      #iterate over the required dimensions, drawing in the centre tiles
      #as we go down the first column only, draw in the left and right side tiles on the edge of the box
      #after we finish each column, draw the top and bottom tiles on the edge
      for x in range(0, dimensions[0]):
         for y in range(0, dimensions[1]):
            self.blit(tileC, (origin[0]+(x*tileSize[0]), origin[1]+(y*tileSize[1])))
            if x == 0:
               self.blit(tileW, (0, origin[1]+(y*tileSize[1])))
               self.blit(tileE, (size[0]-tileSize[0], origin[1]+(y*tileSize[1])))
         self.blit(tileN, (origin[0]+(x*tileSize[0]), 0))
         self.blit(tileS, (origin[0]+(x*tileSize[0]), size[1]-tileSize[1]))

      #draw the corner tiles in the corners
      self.blit(tileNW, (0, 0))
      self.blit(tileNE, (size[0]-tileSize[0], 0))
      self.blit(tileSW, (0, size[1]-tileSize[1]))
      self.blit(tileSE, (size[0]-tileSize[0], size[1]-tileSize[1]))
예제 #52
0
   def __init__(self, fn):
      """
      Open the map data file, set border tiles and connections, and add NPCs and other events.

      fn - the filename of the map XML file.
      """

      #for the scripting engine
      script_engine.ScriptableObject.__init__(self)

      #store variables we'll need later
      self.fn = fn

      #get a script engine (singleton)
      self.scriptEngine = script_engine.ScriptEngine()

      #parse the XML file
      root = data.getTreeRoot(fn)
      self.music = os.path.join(settings.path, "data", data.getAttr(root, "music", data.D_STRING))

      #open the actual map data file to create the map tile data
      mapPath = os.path.join(settings.path, "data", data.getAttr(root, "file", data.D_STRING))
      self.openMap(mapPath)

      #create the tileset
      tilesetPath = os.path.join(settings.path, "data", data.getAttr(root, "tileset", data.D_STRING))
      self.tileset = tileset.Tileset(tilesetPath)

      #set the border tiles
      self.borderTiles = {}
      borderNode = data.getChild(root, "border")

      #set each border node with the correct tile indexes, subtracting 1 because the tileset starts at 1 not 0
      self.borderTiles[BD_NW] = data.getAttr(borderNode, "nw", data.D_INT)-1
      self.borderTiles[BD_NE] = data.getAttr(borderNode, "ne", data.D_INT)-1
      self.borderTiles[BD_SW] = data.getAttr(borderNode, "sw", data.D_INT)-1
      self.borderTiles[BD_SE] = data.getAttr(borderNode, "se", data.D_INT)-1
      
      #create any connections from the map
      #connected maps will not be loaded until the map becomes the main game map
      #connections are stored as {direction: (filename, offset)}
      self.connections = {}
      self.connectedMaps = {}
      for c in data.getChildren(root, "connection"):
         side = data.getAttr(c, "side", data.D_STRING)
         fp = os.path.join(settings.path, "data", data.getAttr(c, "map", data.D_STRING))
         offset = data.getAttr(c, "offset", data.D_INT)
         
         if side == "left":
            self.connections[sprite.DIR_LEFT] = (fp, offset)
         elif side == "right":
            self.connections[sprite.DIR_RIGHT] = (fp, offset)
         elif side == "up":
            self.connections[sprite.DIR_UP] = (fp, offset)
         elif side == "down":
            self.connections[sprite.DIR_DOWN] = (fp, offset)

      #create any NPCs, adding them to the sprite dictionary
      self.sprites = {}
      for n in data.getChildren(root, "npc"):
         spr = npc.NPC(n, self)
         self.sprites[spr.id] = spr

      #create a dictionary to hold positions reserved by moving sprites
      self.reservedPositions = {}

      #create script and warp events, adding them to the events dictionary
      #if a load script is defined, create it
      self.events = {}
      loadScript = None
      for s in data.getChildren(root, "script"):
         trigger = data.getAttr(s, "trigger", data.D_STRING)
         if trigger == "load":
            loadScript = script_engine.Script(s)   
         else:
            position = tuple(data.getAttr(s, "position", data.D_INT2LIST)) 
            self.events[position] = events.ScriptEvent(s, self)
            
      for w in root.findall("warp"):
         position = tuple(data.getAttr(w, "position", data.D_INT2LIST))
         self.events[position] = events.Warp(w, self)

      #if there is a load script, run it
      if loadScript is not None:
         self.scriptEngine.run(loadScript, self)
예제 #53
0
def calendar():
    conf = ""

    #cookies
    cookies = request.cookies
    if "courses" in cookies:
        cs = json.loads(cookies.get("courses"))
    else:
        cs = []

    if "credits" in cookies:
        credits = json.loads(cookies.get("credits"))
    else:
        credits = 0
        for i in cs:
            credits += data.getCredits(i["crn"])

    if "modal" in cookies:
        m = json.loads(cookies.get("modal"))
    else:
        m = "first"

    modalform = StartForm()

    form = CourseForm()
    if form.department.data == None:
        form.course.choices = data.getDeptCourses('ALL DEPTS')
    else:
        form.course.choices = data.getDeptCourses(form.department.data)
    form_clear = ClearForm()
    form_remove = RemoveForm()

    ch = []
    #for c in courses:
    for c in cs:
        ch.append((c["crn"], (c["title"] + " " + c["sect"])))
        form_remove.selcourses.choices = ch

    error = None

    #if the form is submitted validly
    if request.method == 'POST':
        if form.validate_on_submit():
            #reformat the form data into a dictionary of course info
            course = fmat(form.course.data)

            #if the course does not conflict with any pre-selected classes, add it to the class schedule
            conflicts = conflict(course, cs)
            if len(conflicts) == 0:
                #courses.append(course)
                cs.append(course)
                form_remove.selcourses.choices.append(
                    (course["crn"], (course["title"] + " " + course["sect"])))
                credits += data.getCredits(course["crn"])

            #if there are one or more conflicts with the current class schedule, do not add it and report conflict
            else:
                conlist = ", ".join(conflicts)
                conf = course["dept"] + " " + course["number"]
                error = 'The selected class, ' + course["title"] + ' (' + ''.join(
                    course["days"]
                ) + ', ' + ''.join(
                    course["times"]
                ) + '),' + ' conflicts with the following courses on your schedule: ' + conlist

        if form_remove.submit.data:
            print(form_remove.selcourses.data)
            for s in form_remove.selcourses.data:
                print(cs)
                for i in cs:
                    if i["crn"] == int(s):
                        print("yes")
                        cs.remove(i)
                        form_remove.selcourses.choices.remove(
                            (int(s), (i["title"] + " " + i["sect"])))
                        credits -= data.getCredits(i["crn"])

        if modalform.start.data:
            if m == "first":
                m = "yes"
            else:
                m = "no"

    attr = []
    for i in cs:
        attr.extend(data.getAttr(i["crn"]))
    attr = ", ".join(list(set(attr)))

    res = make_response(
        render_template('calendar.html',
                        title='Calendar',
                        modalform=modalform,
                        form=form,
                        cform=form_clear,
                        rform=form_remove,
                        error=error,
                        courses=cs,
                        creds=credits,
                        attributes=attr,
                        conf=conf,
                        m=m))
    res.set_cookie("courses", json.dumps(cs))
    res.set_cookie("credits", json.dumps(credits))
    res.set_cookie("modal", json.dumps(m))

    return res
예제 #54
0
    def __init__(self, fn):
        """
      Open the map data file, set border tiles and connections, and add NPCs and other events.

      fn - the filename of the map XML file.
      """

        #for the scripting engine
        script_engine.ScriptableObject.__init__(self)

        #store variables we'll need later
        self.fn = fn

        #get a script engine (singleton)
        self.scriptEngine = script_engine.ScriptEngine()

        #parse the XML file
        root = data.getTreeRoot(fn)
        self.music = os.path.join(settings.path, "data",
                                  data.getAttr(root, "music", data.D_STRING))

        #open the actual map data file to create the map tile data
        mapPath = os.path.join(settings.path, "data",
                               data.getAttr(root, "file", data.D_STRING))
        self.openMap(mapPath)

        #create the tileset
        tilesetPath = os.path.join(
            settings.path, "data", data.getAttr(root, "tileset",
                                                data.D_STRING))
        self.tileset = tileset.Tileset(tilesetPath)

        #set the border tiles
        self.borderTiles = {}
        borderNode = data.getChild(root, "border")

        #set each border node with the correct tile indexes, subtracting 1 because the tileset starts at 1 not 0
        self.borderTiles[BD_NW] = data.getAttr(borderNode, "nw",
                                               data.D_INT) - 1
        self.borderTiles[BD_NE] = data.getAttr(borderNode, "ne",
                                               data.D_INT) - 1
        self.borderTiles[BD_SW] = data.getAttr(borderNode, "sw",
                                               data.D_INT) - 1
        self.borderTiles[BD_SE] = data.getAttr(borderNode, "se",
                                               data.D_INT) - 1

        #create any connections from the map
        #connected maps will not be loaded until the map becomes the main game map
        #connections are stored as {direction: (filename, offset)}
        self.connections = {}
        self.connectedMaps = {}
        for c in data.getChildren(root, "connection"):
            side = data.getAttr(c, "side", data.D_STRING)
            fp = os.path.join(settings.path, "data",
                              data.getAttr(c, "map", data.D_STRING))
            offset = data.getAttr(c, "offset", data.D_INT)

            if side == "left":
                self.connections[sprite.DIR_LEFT] = (fp, offset)
            elif side == "right":
                self.connections[sprite.DIR_RIGHT] = (fp, offset)
            elif side == "up":
                self.connections[sprite.DIR_UP] = (fp, offset)
            elif side == "down":
                self.connections[sprite.DIR_DOWN] = (fp, offset)

        #create any NPCs, adding them to the sprite dictionary
        self.sprites = {}
        for n in data.getChildren(root, "npc"):
            spr = npc.NPC(n, self)
            self.sprites[spr.id] = spr

        #create a dictionary to hold positions reserved by moving sprites
        self.reservedPositions = {}

        #create script and warp events, adding them to the events dictionary
        #if a load script is defined, create it
        self.events = {}
        loadScript = None
        for s in data.getChildren(root, "script"):
            trigger = data.getAttr(s, "trigger", data.D_STRING)
            if trigger == "load":
                loadScript = script_engine.Script(s)
            else:
                position = tuple(data.getAttr(s, "position", data.D_INT2LIST))
                self.events[position] = events.ScriptEvent(s, self)

        for w in root.findall("warp"):
            position = tuple(data.getAttr(w, "position", data.D_INT2LIST))
            self.events[position] = events.Warp(w, self)

        #if there is a load script, run it
        if loadScript is not None:
            self.scriptEngine.run(loadScript, self)