Setting Setter Tutorial

Abstract

We can store settings and keybinds in a module for easy access.

Prerequisites

Json Coder
Extended Expand Path
configparser

Code

Place this code in a file called settingSetter.py, located in the same directory as the blend.

# http://upbge.wikidot.com/json-coder-tutorial
import jsonCoder as json
# http://upbge.wikidot.com/extended-expand-path-tutioral
from expandPath import expandPath
 
class SettingSetter():
  def __init__(self, iniPath='//system/settings.ini'):
    iniPath = expandPath(iniPath, check=True)
    # https://docs.python.org/3/library/configparser.html
    import configparser
    sheet = configparser.ConfigParser()
    # This make entrys case sensitive.
    sheet.optionxform = str
    # Read the .ini file into the the ConfigParser object
    sheet.read(iniPath)
 
    # Get every subsection in the sheet.
    for section in sheet.sections():
      for subsection in sheet[section]:
        msg = sheet[section][subsection]
        # We do some error checking so that we have better knowledge of what any problems are.
        try:  msg = json.loads(msg)
        except KeyError:
          err = iniPath+' :  unrecognized entry in ['+section+']['+subsection+']; '+msg
          raise KeyError(err)
        except FileNotFoundError:
          err = iniPath+' :  missing file in ['+section+']['+subsection+']; '+msg
          raise FileNotFoundError(err)
        # Every subsection needs to be unique, sense we store them as an attribute on the SettingSetter
        if hasattr(self, subsection):
          err = iniPath+':  duplicate entry in['+section+']['+subsection+']; all Subsection must be unique irrespective of Section.'
          raise KeyError(err)
        # Set the entry as an attribute for easy access.
        else:
          setattr(self, subsection, msg)
 
# Override this module with our custom object.
# https://sohliloquies.blogspot.com/2017/07/how-to-make-subscriptable-module-in.html
import sys
sys.modules[__name__] = SettingSetter()

Example .ini

Place this code in a file called setting.ini, located in //system/.

[Camera]
camScroll = 0.1
camZoom = 0.1

[Movement]
forward = {"Key": "EKEY"}
backward = {"Key": "DKEY"}
leftward = {"Key": "SKEY"}
rightward = {"Key": "FKEY"}
spaceward = {"Key": "SPACEKEY"}

Usage

Make shure you have the following files.
//jsonCoder.py
//expandPath.py
//settingSetter.py
//system/settings.ini

import settingSetter as keys
import bge
own = bge.logic.getCurrentController.owner
 
if keys.forward.held:
  own.worldPosition.y += keys.camScroll

Questions

Log in and edit this page to ask and answer questions.

Further Reading

Make a Subscriptable Module
Singleton
Bge Keybind Codes
Bge Input Events

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License