Skip to main content

News

Topic: Making use of GetKey constants to map to functions (Read 4070 times) previous topic - next topic

0 Members and 1 Guest are viewing this topic.
Making use of GetKey constants to map to functions
So, as part of my current project, I'm trying to handle my input for layered menus and such from the ground up for the sake of experimentation. As such, I have this code currently:

Code: [Select]

if(AreKeysLeft()) {
   ({ KEY_UP: startWindow.handleUp,
      KEY_DOWN: startWindow.handleDown,
      KEY_LEFT: startWindow.handleLeft,
      KEY_RIGHT: startWindow.handleRight,
      KEY_Z: startWindow.handleAccept,
      KEY_X: startWindow.handleCancel
   })[GetKey()].call(startWindow);
}


Now, this code does not currently work because the [GetKey()] step returns undefined, which is because KEY_UP, DOWN, etc. are actually numerical constants, and I can't seem to break them down within the object creation to do something like convert KEY_UP to 84, nor can I seem to get the value from GetKey() as its word form. I'm a bit stumped as to what to do here that would still result in legible code while also having equivalent functionality.
  • Last Edit: July 15, 2016, 02:24:16 am by mezzoEmrys

  • Fat Cerberus
  • [*][*][*][*][*]
  • Global Moderator
  • Sphere Developer
Re: Making use of GetKey constants to map to functions
Reply #1
You'll be able to do this in Sphere 2.0, because the built-in enumerations are two-way, which is to say: Key[Key.Enter] = "Enter"

Therefore:
Code: (javascript) [Select]

if(kb.haveKeys) {
   ({ Up: startWindow.handleUp,
      Down: startWindow.handleDown,
      Left: startWindow.handleLeft,
      Right: startWindow.handleRight,
      Z: startWindow.handleAccept,
      X: startWindow.handleCancel
   })[Key[kb.getKey()]].call(startWindow);
}


I'm unaware of a way to do this in Sphere 1.x though.
neoSphere 5.9.2 - neoSphere engine - Cell compiler - SSj debugger
forum thread | on GitHub

  • Fat Cerberus
  • [*][*][*][*][*]
  • Global Moderator
  • Sphere Developer
Re: Making use of GetKey constants to map to functions
Reply #2
It's worth noting that this would have been possible if Sphere supported ES6 using computed property names, in which case you could just wrap KEY_UP etc. constants in brackets.  Alas, ES6+ support still looks like it's a ways off for Duktape.
neoSphere 5.9.2 - neoSphere engine - Cell compiler - SSj debugger
forum thread | on GitHub

Re: Making use of GetKey constants to map to functions
Reply #3
Alright, I guess I'll just make my own reverse-enumeration function for now and call it good. Glad to know this kind of thing  won't be as much of a problem in Sphere 2.0 ;)