Hello,
I'm reading this tutorial: https://hookrace.net/blog/writing-a-2d-platform-game-in-nim-with-sdl2/
He is using hardcoded keys like this:
type Input {.pure.} =
enum none, left, right, up, down, jump, restart, quit
proc toInput(key: Scancode): Input =
case key
of SDL_SCANCODE_A: Input.left
of SDL_SCANCODE_D: Input.right
# etc…
else: Input.none
proc handleInput(game: Game) =
var event = defaultEvent
while pollEvent(event):
case event.kind
of KeyDown:
game.inputs[event.key.keysym.scancode.toInput] = true
# etc…
else:
discard
Ok that's nice, but i want to be able to redefine inputs, for example SDL_SCANCODE_LEFT for Input.left.
I guess of course i have to treat this in ToInput, but what should i use to store and compare ? Tuples , Arrays, Objects … ?
Thank you.
Thank you, both techniques are interesting (array and table). I think i try the array one, even if i need to loop it entirely for getting assigned keys.
Thank you for explaining, coming from Lua i know only tables, tables and tables for solving everything !
I like this encoding for enums. Sadly Scancode is not an ordinal, if we filled the gaps to make it an ordinal, we could have an even better syntax and use sets with them:
var mapping: array[Scancode, Input]
mapping[SDL_SCANCODE_A] = left
mapping[SDL_SCANCODE_D] = right
import std/packedsets # Merged to devel today
var mappedCodes: PackedSet[Scancode]
for c in ScanCode:
if mapping[c] != none: mappedCodes.incl(c)
echo mappedCodes # prints: "{SDL_SCANCODE_A, SDL_SCANCODE_D}"
I think for these C enum compat cases we should provide a macro to fill the undefined holes with some hidden unknown_xxxx values, so we can use them as ordinals.Well it seems that it works for all of you, but not for me…
Look what i get (from INim for sample purpose, but i have the same error with a regular compilation of my source):
👑 INim 0.6.1
Nim Compiler Version 1.4.1 [Linux: amd64]
nim> import sdl2
nim> type Input {.pure.} = enum none, left, right, up, down, jump, restart, quit
nim> var mapping:array[ScanCode, Input]
Error: ordinal type expected
You can use:
var mapping: array[SDL_NUM_SCANCODES.int, Input]
and access with mapping[SDL_SCANCODE_A.int].
I don't understand why
var mapping: array[Scancode, Input]
won't work though, since it works if you try to use it in the the keymappings.nim file (where Scancode is defined). But, if you import or include keymappings.nim into another file, the compiler no longer recognizes the Scancode enum as being ordinal. Seems like a weird bug.won't work though, since it works if you try to use it in the the keymappings.nim file (where Scancode is defined). But, if you import or include keymappings.nim into another file, the compiler no longer recognizes the Scancode enum as being ordinal if you try this from within that file. Seems like a weird bug.
why does it work in keymappings.nim? its not ordinal