Skip to content

Commit

Permalink
Puts user input hard-coded keys in globals.py & rewrites configuratio…
Browse files Browse the repository at this point in the history
…n file handling.
  • Loading branch information
BertrandBordage committed Apr 12, 2013
1 parent 796139a commit 3b66650
Show file tree
Hide file tree
Showing 6 changed files with 148 additions and 110 deletions.
21 changes: 9 additions & 12 deletions controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def on_draw(self):
class GameController(Controller):
def __init__(self, window, show_gui=True):
super(GameController, self).__init__(window)
self.show_gui = show_gui
self.show_gui = show_gui # TODO: Rename into hud_enabled
self.sector = None
self.time_of_day = 0.0
self.count = 0
Expand All @@ -139,9 +139,6 @@ def __init__(self, window, show_gui=True):
self.show_fog = globals.config.getboolean('World', 'show_fog')
self.last_key = None
self.sorted = False
self.key_inventory = globals.config.getint('Controls', 'inventory')
self.key_sound_up = globals.config.getint('Controls', 'sound_up')
self.key_sound_down = globals.config.getint('Controls', 'sound_down')

def update(self, dt):
sector = sectorize(self.player.position)
Expand Down Expand Up @@ -361,11 +358,11 @@ def on_mouse_drag(self, x, y, dx, dy, button, modifiers):
self.on_mouse_motion(x, y, dx, dy)

def on_key_press(self, symbol, modifiers):
if symbol == key.B or symbol == key.F3:
if symbol == globals.TOGGLE_HUD_KEY:
self.show_gui = not self.show_gui
elif symbol == key.V:
elif symbol == globals.SAVE_KEY:
self.save_to_file()
elif symbol == key.M:
elif symbol == globals.INVENTORY_SORT_KEY:
if self.last_key == symbol and not self.sorted:
self.player.quick_slots.sort()
self.player.inventory.sort()
Expand All @@ -375,18 +372,18 @@ def on_key_press(self, symbol, modifiers):
self.player.inventory.change_sort_mode()
self.item_list.update_items()
self.inventory_list.update_items()
elif symbol == self.key_inventory:
elif symbol == globals.INVENTORY_KEY:
self.set_highlighted_block(None)
self.mouse_pressed = False
self.inventory_list.toggle()
elif symbol == self.key_sound_up:
elif symbol == globals.SOUND_UP_KEY:
globals.EFFECT_VOLUME = min(globals.EFFECT_VOLUME + .1, 1)
elif symbol == self.key_sound_down:
elif symbol == globals.SOUND_DOWN_KEY:
globals.EFFECT_VOLUME = max(globals.EFFECT_VOLUME - .1, 0)
self.last_key = symbol

def on_key_release(self, symbol, modifiers):
if symbol == key.T:
if symbol == globals.TALK_KEY:
self.toggle_text_input()
return pyglet.event.EVENT_HANDLED

Expand Down Expand Up @@ -484,7 +481,7 @@ def draw_label(self):
self.label.draw()

def text_input_callback(self, text_input, symbol, modifier):
if symbol == key.ENTER:
if symbol == globals.VALIDATE_KEY:
txt = text_input.text.replace('\n', '')
try:
self.command_parser.execute(txt, controller=self, user=self.player, world=self.model)
Expand Down
78 changes: 63 additions & 15 deletions globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,49 @@
GAME_MODE = CREATIVE_MODE


#
# User input
#

# Movement
MOVE_FORWARD_KEY = 'W'
MOVE_BACKWARD_KEY = 'S'
MOVE_LEFT_KEY = 'A'
MOVE_RIGHT_KEY = 'D'
JUMP_KEY = 'SPACE'
CROUCH_KEY = 'LSHIFT'
FLY_KEY = 'TAB'

# Action
INVENTORY_KEY = 'E'
INVENTORY_SORT_KEY = 'M'
INVENTORY_1_KEY = '1'
INVENTORY_2_KEY = '2'
INVENTORY_3_KEY = '3'
INVENTORY_4_KEY = '4'
INVENTORY_5_KEY = '5'
INVENTORY_6_KEY = '6'
INVENTORY_7_KEY = '7'
INVENTORY_8_KEY = '8'
INVENTORY_9_KEY = '9'
INVENTORY_10_KEY = '0'
TALK_KEY = 'T'
VALIDATE_KEY = 'ENTER'

# Settings
SOUND_UP_KEY = 'PAGEUP'
SOUND_DOWN_KEY = 'PAGEDOWN'
TOGGLE_HUD_KEY = 'F3'

# Various
SAVE_KEY = 'V'
ESCAPE_KEY = 'ESCAPE'

KEY_BINDINGS = dict(
(k.lower()[:-4], v) for k, v in locals().items() if k[-4:] == '_KEY'
)


#
# Saves
#
Expand Down Expand Up @@ -66,29 +109,31 @@
# Terrain generation
#

TERRAIN_CHOICES = {
TERRAIN_CHOICES = { # hill_height & max_trees mandatory for the moment.
'plains': {
'hill_height': '2',
'max_trees': '700',
'hill_height': 2,
'max_trees': 700,
},
'desert': {
'hill_height': '5',
'max_trees': '50',
'hill_height': 5,
'max_trees': 50,
},
'island': {
'hill_height': '8',
'max_trees': '700',
'hill_height': 8,
'max_trees': 700,
},
'mountains': {
'hill_height': '12',
'max_trees': '4000',
'hill_height': 12,
'max_trees': 4000,
},
'snow': {
'hill_height': '4',
'max_trees': '1500',
'hill_height': 4,
'max_trees': 1500,
}
}
DEFAULT_TERRAIN_CHOICE = 'plains'
TERRAIN_CHOICE = DEFAULT_TERRAIN_CHOICE
TERRAIN = TERRAIN_CHOICES[DEFAULT_TERRAIN_CHOICE]


#
Expand All @@ -108,7 +153,8 @@
'long': 60.0 * 2.0
}
DEFAULT_DRAW_DISTANCE_CHOICE = 'short'
DRAW_DISTANCE = DRAW_DISTANCE_CHOICES[DEFAULT_DRAW_DISTANCE_CHOICE]
DRAW_DISTANCE_CHOICE = DEFAULT_DRAW_DISTANCE_CHOICE
DRAW_DISTANCE = DRAW_DISTANCE_CHOICES[DRAW_DISTANCE_CHOICE]

FOV = 65.0 # TODO: add menu option to change FOV
NEAR_CLIP_DISTANCE = 0.1 # TODO: make min and max clip distance dynamic
Expand Down Expand Up @@ -146,9 +192,11 @@
# Global files & directories
#

config = ConfigParser()
LAUNCH_OPTIONS = argparse.Namespace()

game_dir = get_settings_path(APP_NAME)
if not os.path.exists(game_dir):
os.makedirs(game_dir)

config = ConfigParser()
config_file = os.path.join(game_dir, 'game.cfg')
config.read(config_file)
LAUNCH_OPTIONS = argparse.Namespace()
13 changes: 6 additions & 7 deletions gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,8 @@ def __init__(self, parent, player, model, *args, **kwargs):
self.current_index = 0
self.icon_size = self.model.group.texture.width / globals.TILESET_SIZE
self.visible = True
self.num_keys = [
key._1, key._2, key._3, key._4, key._5,
key._6, key._7, key._8, key._9, key._0]
self.num_keys = [getattr(globals, 'INVENTORY_%d_KEY' % i)
for i in range(1, 10)]

image = pyglet.image.load(os.path.join('resources', 'textures', 'slots.png'))
heart_image = pyglet.image.load(os.path.join('resources', 'textures', 'heart.png'))
Expand Down Expand Up @@ -272,7 +271,7 @@ def on_key_press(self, symbol, modifiers):
index = (symbol - self.num_keys[0])
self.set_index(index)
return pyglet.event.EVENT_HANDLED
elif symbol == key.ENTER:
elif symbol == globals.VALIDATE_KEY:
current_block = self.get_current_block_item_and_amount()
if current_block:
if not self.player.inventory.add_item(
Expand Down Expand Up @@ -741,10 +740,10 @@ def on_mouse_drag(self, x, y, dx, dy, button, modifiers):

def on_key_press(self, symbol, modifiers):
if self.visible:
if symbol == key.ESCAPE:
if symbol == globals.ESCAPE_KEY:
self.toggle()
return pyglet.event.EVENT_HANDLED
elif symbol == key.ENTER:
elif symbol == globals.VALIDATE_KEY:
return pyglet.event.EVENT_HANDLED

def on_resize(self, width, height):
Expand Down Expand Up @@ -864,7 +863,7 @@ def on_key_press(self, symbol, modifier):

def on_key_release(self, symbol, modifier):
if self.visible:
if symbol == key.ESCAPE:
if symbol == globals.ESCAPE_KEY:
self.toggle()
self.parent.window.pop_handlers()
if self._key_released:
Expand Down
108 changes: 54 additions & 54 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
from ConfigParser import NoSectionError, NoOptionError
import argparse
from binascii import hexlify
import datetime
import operator
import os
import cPickle as pickle
import random
import time

import pyglet
# Disable error checking for increased performance
pyglet.options['debug_gl'] = False
from pyglet.gl import *
from pyglet.window import key

#import kytten
from blocks import *
Expand All @@ -20,40 +18,52 @@
from controllers import *


config_file = os.path.join(globals.game_dir, 'game.cfg')
if not os.path.lexists(config_file):
globals.config.add_section('World')

world_type = globals.DEFAULT_TERRAIN_CHOICE # FIXME: Unify names!
globals.config.set('World', 'type', world_type)
terrain = globals.TERRAIN_CHOICES[world_type]
for k, v in terrain.items():
globals.config.set('World', k, v)

globals.config.set('World', 'flat', 'false') # dont make mountains, make a flat world
globals.config.set('World', 'size', '64')
globals.config.set('World', 'show_fog', 'true')

globals.config.add_section('Controls')
globals.config.set('Controls', 'move_forward', str(key.W))
globals.config.set('Controls', 'move_backward', str(key.S))
globals.config.set('Controls', 'move_left', str(key.A))
globals.config.set('Controls', 'move_right', str(key.D))
globals.config.set('Controls', 'jump', str(key.SPACE))
globals.config.set('Controls', 'inventory', str(key.E))
globals.config.set('Controls', 'sound_up', str(key.PAGEUP))
globals.config.set('Controls', 'sound_down', str(key.PAGEDOWN))

def safe_add_to_config(section, option, default_value):
try:
with open(config_file, 'wb') as handle:
globals.config.write(handle)
except:
print "Problem: Configuration file (%s) doesn't exist." % config_file
sys.exit(1)
else:
globals.config.read(config_file)
user_value = globals.config.get(section, option)
except NoSectionError:
globals.config.add_section(section)
except NoOptionError:
pass
else:
# If no exception (meaning that the option is already set), do nothing.
return user_value
globals.config.set(section, option, default_value)
return default_value


class InvalidKey(Exception):
pass


def get_key(key_name):
key_code = getattr(pyglet.window.key, key_name, None)
if key_code is None:
# Handles cases like pyglet.window.key._1
key_code = getattr(pyglet.window.key, '_' + key_name, None)
if key_code is None:
raise InvalidKey('%s is not a valid key.' % key_name)
return key_code


def initialize_config():
safe_add_to_config('World', 'flat', 'false') # dont make mountains, make a flat world
safe_add_to_config('World', 'size', '64')
safe_add_to_config('World', 'show_fog', 'true')

# Adds missing keys to configuration file and converts to pyglet keys.
for control, default_key_name in globals.KEY_BINDINGS.items():
key_name = safe_add_to_config('Controls', control, default_key_name)
try:
pyglet_key = get_key(key_name)
except InvalidKey:
pyglet_key = get_key(default_key_name)
globals.config.set('Controls', control, default_key_name)
setattr(globals, control.upper() + '_KEY', pyglet_key)

with open(globals.config_file, 'wb') as handle:
globals.config.write(handle)

####

class Window(pyglet.window.Window):
def __init__(self, width, height, launch_fullscreen=False, show_gui=True,**kwargs):
Expand Down Expand Up @@ -82,10 +92,10 @@ def switch_controller(self, new_controller):

def on_key_press(self, symbol, modifiers):
if self.exclusive:
if symbol == key.ESCAPE and not self.fullscreen:
if symbol == globals.ESCAPE_KEY and not self.fullscreen:
self.set_exclusive_mouse(False)
elif symbol == key.Q and self.fullscreen:
pyglet.app.exit() # for fullscreen
elif symbol == key.Q and self.fullscreen: # FIXME: Better fullscreen mode.
pyglet.app.exit() # for fullscreen

def on_draw(self):
if self.exclusive:
Expand Down Expand Up @@ -115,18 +125,13 @@ def main(options):
for name, val in options._get_kwargs():
setattr(globals.LAUNCH_OPTIONS, name, val)

if options.draw_distance:
globals.DRAW_DISTANCE = globals.DRAW_DISTANCE_CHOICES[options.draw_distance]
globals.DRAW_DISTANCE = globals.DRAW_DISTANCE_CHOICES[options.draw_distance]

if options.terrain:
world_type = options.terrain # FIXME: Unify names!
globals.config.set('World', 'type', world_type)
terrain = globals.TERRAIN_CHOICES[world_type]
for k, v in terrain.items():
globals.config.set('World', k, v)
globals.TERRAIN_CHOICE = options.terrain
globals.TERRAIN = globals.TERRAIN_CHOICES[options.terrain]

if options.flat:
globals.config.set('World', 'flat', 'true')
safe_add_to_config('World', 'flat', 'true')

if options.fast:
globals.TIME_RATE /= 20
Expand Down Expand Up @@ -162,12 +167,6 @@ def main(options):

pyglet.clock.set_fps_limit(globals.MAX_FPS)
pyglet.app.run()
if options.save_config:
try:
with open(config_file, 'wb') as handle:
globals.config.write(handle)
except:
print "Problem: Write error."


if __name__ == '__main__':
Expand All @@ -190,10 +189,11 @@ def main(options):
save_group.add_argument("--disable-auto-save", action="store_false", default=True, help="Do not save world on exit.")
save_group.add_argument("--save", default=globals.SAVE_FILENAME, help="Type a name for the world to be saved as.")
save_group.add_argument("--disable-save", action="store_false", default=True, help="Disables saving.")
save_group.add_argument("--save-config", action="store_true", default=False, help="Saves the choices as the default config.")
save_group.add_argument("--save-mode", choices=globals.SAVE_MODES, default=globals.SAVE_MODE, help="Flatfile Struct (flatfile) is the smallest and fastest")

parser.add_argument("--seed", default=None)
parser.add_argument("--motion-blur", action="store_true", default=False)

options = parser.parse_args()
initialize_config()
main(options)
Loading

0 comments on commit 3b66650

Please sign in to comment.