def get_config_path():
  path_name = ""
  try:
    path_name = os.path.join(os.environ["HOME"], "." + GAME_NAME_SHORT)
  except:
    error_message("Couldn't find environment variable HOME, reverting to APPDATA. This is normal under Windows.")
    try:
      path_name = os.path.join(os.environ["APPDATA"], GAME_NAME_SHORT)
    except:
      error_message("Couldn't get environment variable for home directory, using data directory instead.")
      path_name = data.filepath("saves")
  if not os.path.exists(path_name):
    os.mkdir(path_name)
  return path_name
def write_config():
  file_path = os.path.join(get_config_path(), "config.txt")
  try:
    conffile = codecs.open(file_path, "w", "utf_8")
    for world in WORLDS:
      print >> conffile, "unlocked\t%(world)s\t%(unlocked)s" % {"world": world, "unlocked": Variables.vdict["unlocked" + world]}
      print >> conffile, "hiscore\t%(world)s\t%(hiscore)s" % {"world": world, "hiscore": Variables.vdict["hiscore" + world]}
      print >> conffile, "besttime\t%(world)s\t%(besttime)s" % {"world": world, "besttime": Variables.vdict["besttime" + world]}
    print >> conffile, "sound\t%s" % bool_to_str(Variables.vdict["sound"])
    print >> conffile, "dialogue\t%s" % bool_to_str(Variables.vdict["dialogue"])
    print >> conffile, "fullscreen\t%s" % bool_to_str(Variables.vdict["fullscreen"])
  except:
    error_message("Could not write configuration file to " + file_path)
    return False
  return True
 def __init__(self, object, anim_name, frameno, frame_length):
     try:
         self.image = pygame.image.load(data.picpath(object, anim_name, frameno)).convert()
     except:
         try:
             self.image = pygame.image.load(
                 data.picpath("brown", anim_name, frameno)
             ).convert()  # Fallback to brown tileset
         except:
             self.image = pygame.image.load(
                 data.picpath("object", "idle", 0)
             ).convert()  # Fallback to default object image
             error_message("Object graphic missing: " + object + "_" + anim_name + "_" + str(frameno))
     self.frame_length = frame_length
     self.image.set_colorkey((255, 0, 255))
     return
def play_sound(sound_id, volume = 1.0):
  if not Variables.vdict["sound"]:
    return
  snd = None
  if (not sounds.has_key(sound_id)):
    try:
      sound_path = data.filepath(os.path.join("sounds", sound_id + ".ogg"))
      snd = sounds[sound_id] = pygame.mixer.Sound(sound_path)
    except:
      error_message("No sound device available or sound file not found: " + sound_id + ".ogg")
      return
  else:
    snd = sounds[sound_id]
  try:
    snd.set_volume(volume)
    snd.play()
  except:
    error_message("Could not play sound")
  return
Beispiel #5
0
def write_config():
    """
    Writes the config stored in the variables class to the configuration file.
    Prints an error message if unsuccesful.
    """
    file_path = os.path.join(get_config_path(), 'config.txt')
    try:
        conffile = codecs.open(file_path, 'w', 'utf_8')
        for world in WORLDS:
            print >> conffile, 'unlocked\t%(world)s\t%(unlocked)s' % {'world': world, 'unlocked': variables.vdict['unlocked' + world]}
            print >> conffile, 'hiscore\t%(world)s\t%(hiscore)s' % {'world': world, 'hiscore': variables.vdict['hiscore' + world]}
            print >> conffile, 'besttime\t%(world)s\t%(besttime)s' % {'world': world, 'besttime': variables.vdict['besttime' + world]}
        print >> conffile, 'sound\t%s' % bool_to_str(variables.vdict['sound'])
        print >> conffile, 'dialogue\t%s' % bool_to_str(variables.vdict['dialogue'])
        print >> conffile, 'fullscreen\t%s' % bool_to_str(variables.vdict['fullscreen'])
        print >> conffile, 'character\t%s' % variables.vdict['character']
    except Exception:
        error_message('Could not write configuration file to ' + file_path)
        return False
    return True
Beispiel #6
0
def get_config_path():
    """
    This function returns a path for saving config in the user's home directory.
    It's compatible with both UNIX-likes (environment variable HOME) and 
    Windows (environment variable APPDATA).
    Prints error messages if unsuccesful, and reverts to a 'saves' directory
    under the data directory instead.
    """
    path_name = ''
    try:
        path_name = os.path.join(os.environ['HOME'], '.' + GAME_NAME_SHORT)
    except KeyError:
        error_message('Couldn\'t find environment variable HOME, reverting to APPDATA. This is normal under Windows.')
        try:
            path_name = os.path.join(os.environ['APPDATA'], GAME_NAME_SHORT)
        except KeyError:
            error_message('Couldn\'t get environment variable for home directory, using data directory instead.')
            path_name = data.filepath('saves')
    if not os.path.exists(path_name):
        os.mkdir(path_name)
    return path_name
Beispiel #7
0
def write_log():
    file_path = os.path.join(get_config_path(), 'log.txt')
    old_log = ''
    if os.path.exists(file_path):
        conffile = open(file_path)
        count = 0
        for line in conffile:
            old_log = old_log + line
            count += 1
            if count > MAX_OLD_LOG_LINES:
                break
    if variables.vdict.has_key('log'):
        try:
            conffile = codecs.open(file_path, 'w', 'utf_8')
            print >> conffile, 'Log updated ' + str(datetime.date.today())
            print >> conffile, variables.vdict['log']
            print >> conffile, ''
            print >> conffile, old_log
        except:
            error_message('Could not write log file to ' + file_path)
            return False
    return True
def write_log():
  file_path = os.path.join(get_config_path(), "log.txt")
  old_log = ""
  if os.path.exists(file_path):
    conffile = open(file_path)
    count = 0
    for line in conffile:
      old_log = old_log + line
      count += 1
      if count > MAX_OLD_LOG_LINES:
        break
  if Variables.vdict.has_key("log"):
    try:
      conffile = codecs.open(file_path, "w", "utf_8")
      print >> conffile, "Log updated " + str(datetime.date.today())
      print >> conffile, Variables.vdict["log"]
      print >> conffile, ""
      print >> conffile, old_log
    except:
      error_message("Could not write log file to " + file_path)
      return False
  return True
def main():

    #Parsing level from parameters and parsing main config:

    level_name = None
    world_index = 0
    world = World(WORLDS[world_index])

    user_supplied_level = False

    parse_config()

    getlevel = False
    
    Variables.vdict["devmode"] = False

    if len(sys.argv) > 1:
        for arg in sys.argv:
          if getlevel:
            try:
              level_name = arg
              user_supplied_level = True
              end_trigger = END_NEXT_LEVEL
              menu_choice = MENU_QUIT
            except:
              error_message("Incorrect command line parameters")
              level_name = None
          elif arg == "-l":
            getlevel = True
          elif arg == "-dev":
            Variables.vdict["devmode"] = True
            Variables.vdict["verbose"] = True            
          elif arg == "-v":
            Variables.vdict["verbose"] = True

    #Initializing pygame and screen

    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
    caption = "Which way is up?"
    if (Variables.vdict["devmode"]):
      caption = caption + " - developer mode"
    pygame.display.set_caption(caption)

    apply_fullscreen_setting(screen)

    if (pygame.joystick.get_count() > 0):
      joystick = pygame.joystick.Joystick(0)
      joystick.init()
    else:
      joystick = None

    score = Score(0)

    done = False

    if not user_supplied_level:
      if (Variables.vdict["unlocked" + WORLDS[0]] == 0): # Nothing unlocked, go straight to the game
        end_trigger = END_NEXT_LEVEL
        menu_choice = MENU_QUIT
        level_name = world.get_level()
      else:                                      # Go to the menu first
        end_trigger = END_MENU
        menu_choice = 0

    bgscreen = None

    #Menu and level changing loop, actual game code is in game.py:

    while not done:
      if end_trigger == END_NEXT_LEVEL:
        if user_supplied_level:
          end_trigger = game.run(screen, level_name, world.index, score, joystick)
          if end_trigger == END_NEXT_LEVEL:
            user_supplied_level = False
            end_trigger = END_WIN
        else:
          end_trigger = game.run(screen, level_name, world.index, score, joystick)
          if end_trigger == END_NEXT_LEVEL:
            if world.is_next_level():
              level_name = world.get_level()
            else:
              end_trigger = END_WIN
          elif end_trigger == END_QUIT:
            display_bg("quit", screen)
            end_trigger = END_MENU
            bgscreen = screen.copy()
      if end_trigger == END_LOSE:
        display_bg("lose", screen)
        end_trigger = END_MENU
        menu_choice = world.index - 1
        bgscreen = screen.copy()
      elif end_trigger == END_WIN:
        display_bg("victory", screen)
        end_trigger = END_MENU
        menu_choice = 0
        bgscreen = screen.copy()
      elif end_trigger == END_QUIT or end_trigger == END_HARD_QUIT:
        done = True
      elif end_trigger == END_MENU:
        prev_score = score.score
        prev_time = score.time
        prev_levels = score.levels
        score = Score(0)
        if prev_score != 0:
          menu = Mainmenu(screen, prev_score, world, bgscreen, prev_time, prev_levels)
        else:
          menu = Mainmenu(screen, None, world, bgscreen)
        menu_choice = menu.run(menu_choice)
        if menu_choice == MENU_QUIT:
          end_trigger = END_QUIT
        elif menu_choice == MENU_SOUND:
          Variables.vdict["sound"] = not Variables.vdict["sound"]
          end_trigger = END_MENU
        elif menu_choice == MENU_DIALOGUE:
          Variables.vdict["dialogue"] = not Variables.vdict["dialogue"]
          end_trigger = END_MENU
        elif menu_choice == MENU_FULLSCREEN:
          Variables.vdict["fullscreen"] = not Variables.vdict["fullscreen"]
          end_trigger = END_MENU
          apply_fullscreen_setting(screen)
        elif menu_choice == MENU_WORLD:
          world_index += 1
          if world_index >= len(WORLDS):
            world_index = 0
          world = World(WORLDS[world_index])
          end_trigger = END_MENU
        else:
          level_name = world.get_level(menu_choice)
          end_trigger = END_NEXT_LEVEL

    write_config()
    write_log()

    return
  def __init__(self, screen, level_name = "w0-l0"):
    self.screen = screen
    self.image = None
    self.flipping = False
    self.flipcounter = 0
    self.set = "brown"  #The default tileset, can be changed through level configuration

    self.tiles = []
    self.objects = []

    self.scripted_events = []

    self.cached_ground_check = {}

    self.dust_color = COLOR_DUST["brown"]

    self.level_name = level_name

    self.orientation = 0

    conffile = codecs.open(data.levelpath(self.level_name), "r", "utf_8")

    tiley = 0
    values = []

    trigger = False
    current_event = None

    parse_tiles = False

    for line in conffile:

      if parse_tiles:
        if tiley < FULL_TILES_VER:
          tilex = 0
          while tilex < FULL_TILES_VER:
            if (line[tilex] == "W") or (line[tilex] == "B") or (line[tilex] == "S"):
              self.add_tile(line[tilex], (tilex, tiley))
            tilex += 1
          tiley += 1
          continue
        else:
          parse_tiles = False
          continue

      elif line.strip() != "":
          values = line.split()

          #Parsing special commands

          if trigger:
            if values[0] == "end" and values[1] == "trigger":
              trigger = False
            else:
              current_event.add_element(line)
            continue
          elif values[0] == "trigger":
            trigger = True
            current_event = Scripted_event(values[1], int(values[2]))
            self.scripted_events.append(current_event)
            continue
          elif values[0] == "tiles":
            parse_tiles = True
            continue
          elif values[0] == "set":
            self.set = values[1]
            continue

          #Parsing objects
          x, y = tile_coords_to_screen_coords(values[1], values[2])
          if values[0] == "player":
            self.player = Player(self.screen, x, y)
            continue
          elif values[0] == "spider":
            self.objects.append(Spider( self.screen, x, y, dir_from_str(values[3]) ))
            continue
          elif values[0] == "blob":
            self.objects.append(Blob(self.screen, x, y, self.player))
            continue
          elif values[0] == "lever":
            trigger_type = TRIGGER_FLIP
            if values[4] == "TRIGGER_FLIP":
              trigger_type = TRIGGER_FLIP
            self.objects.append( Item(self.screen, x, y, self.set, values[0], int(values[3]), trigger_type) )
            continue
          else:
            try:
              self.objects.append(Item(self.screen, x, y, self.set, values[0]))
            except:
              error_message("Couldn't add object '" + values[0] + "'")
            continue

    self.dust_color = COLOR_DUST[self.set]

    self.bg_animations = {}
    self.bg_animations["default"] = Animation(self.set + "_background", "static")
    self.current_animation = "default"
    self.rect = (self.bg_animations[self.current_animation].update_and_get_image()).get_rect()
    self.rect.centerx = SCREEN_WIDTH / 2
    self.rect.centery = SCREEN_HEIGHT / 2

    self.reset_active_tiles()
    return