Source

gallox / gallox / settings.py

Full commit
import os

import pygame

class ControlDict(dict):
    defaults = dict(turn_left = pygame.K_LEFT,
                    turn_right = pygame.K_RIGHT,
                    boost = pygame.K_UP,
                    fire = pygame.K_SPACE)
    def __init__(self, filename):
        dict.__init__(self, **ControlDict.defaults)
        self.filename = filename
        self.load(filename)
        
    def load(self, filename):
        self.filename = filename
        if os.path.exists(filename):
            f = file(filename, "r")
            for line in f.readlines():
                line = line.strip()
                if line.startswith("#") or not "=" in line:
                    # comment
                    continue
                key, value = line.split("=", 1)
                try:
                    value = int(value.strip())
                except ValueError:
                    continue
                else:
                    self[key.strip()] = value
            f.close()
        else:
            print "Warning: Could not load controls from '%s'" % filename
            
    def save(self):
        f = file(self.filename, "w")
        f.write("\n".join(["=".join([k,str(v)]) for k,v in self.iteritems()]))
        f.close()
        
    def __setitem__(self, k, v):
        dict.__setitem__(self, k, v)
        self.save()

settings_path = os.path.abspath(os.path.join(os.path.dirname(__file__),"..", "controls.cfg"))
CONTROLS = ControlDict(settings_path)

CAMERA_SIZE = (400,400)

# variables
# px/s
SHIP_POWER = 35
# deg/s
TURN_STEP = 270


# total number of minutes with boost on from 100% to 0% fuel
BOOST_DURATION = 0.1
# percentage points per minute
MILEAGE = 100 / BOOST_DURATION


# world settings
#AIR_DRAG = 0.1
# ship will fall x px/s
GRAVITY = 5.75

# game settings
FPS = 40
#SAFE_COLOR = 128, 0, 0
ALPHA_COLOR = 255, 0, 255
BULLET_HOLE_RADIUS = 15  # < level/map dependent?

ALLOWED_LANDING_ANGLE = 45

# px/s
BULLET_SPEED = 400
GUN_BULLET_SPEED = BULLET_SPEED / 3.
SHIP_BULLET_SPEED = BULLET_SPEED


# paths
PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
DATA_PATH = os.path.join(PROJECT_DIR, "data")

GUI_DATA_PATH = os.path.join(DATA_PATH, "gui")




# ===== internal ===== #

SOUNDS = {"fueling":
                    {"name":"fueling.wav",
                     "loops":-1,
                     "fade_ms": 500},
          
          "alarm":
                    {"name":"alarm.wav",
                     "loops":-1,
                     "fade_ms": 500}
          }

DEFAULT_SPRITE_ATTRS = {"fix_no":False, "turnable":False, "resizable":False}
SPRITES = {
        "plattform":{"resizable":True},
        "gun":{"turnable":True},
        "ship":{"fix_no":True, "turnable":True},
           }
           
           
def mybool(s):
    """
    convert a string to a boolean and also consider "False" as False
    
    this is neccessary to save booleans with str(boolean) explicitly
    as "True" and "False". Otherwise False would have to be saved as
    "" what is too implicit.    
    """
    return s not in ("", "False")

# parameter types
BOOL = 1
INT = 2
FLOAT = 3
# list of functions to convert a value from a string back to its original type
CONVERT_FUNCTIONS = [None, mybool, int, float]
           
"""
General information about the parameters a sprite of a certain type
can have, structured as {type : [list of params]} dict where one 
parameter consists of 

  - a name, that is used for any internal usage
  - a repr_name, that is used whenever the name is displayed for the user
  - a type, that must be one of BOOL, INT, FLOAT
  - a default value
  - an args dict, that will be passed to the widget used for this type.
    
Two useful values for the arg dict of an int param are, for example, "min_val"
and "max_val" (used by gui.NumberInput) to control the range of the param value.
    
"""
SPRITE_PARAMS = {
        "plattform":[
                # all [%] values here are related to the player tank
                {"name": "tankSize",
                 "repr_name": "tank size [%]",
                 "type": FLOAT,
                 "default": 20,
                 "args": {"min_val":0,
                          "max_val":100}
                },
                {"name": "fuelSpeed",
                 "repr_name": "fuel speed [%/s]",
                 "type": FLOAT,
                 "default": 20,
                 "args": {"min_val":0,
                          "max_val":100}
                },
                {"name": "restockRate",
                 "repr_name": "restock rate [%/s]",
                 "type": FLOAT,
                 "default": 10,
                 "args": {"min_val":0,
                          "max_val":100}
                },
                    ],
        "gun":[
                {"name":"shotFreq",
                "repr_name":"shot frequency [shots/min]",
                "type":INT,
                "default": 5,
                "args":{"max_val":100,
                        "min_val":1}
                },   
                {"name":"rotSpeed",
                "repr_name":"rotary speed [deg/s]",
                "type":FLOAT,
                "default": 4,
                "args":{"max_val":100,
                        "min_val":0}
                },     
               {"name": "rotRange",
                "repr_name": "rotation range",
                "type": INT,
                "default":60,
                "args": {"max_val":361,
                         "min_val":0}
                },
                {"name": "autoAimScope",
                 "repr_name": "auto aim scope [px]",
                 "type": INT,
                 "default": False,
                 "args": {}
                },
               ],
        "ship":[],
           }