Должен ли я использовать обработчик событий или актер для добавления элементов управления клавиатуры для игры

В Rebol3 Saphir я пишу игру, и я возился с функциональностью обработчика событий, а также с актерами, и мне было интересно, будет ли лучше использовать обработчик событий для управления клавиатурой для игры или для добавить актера в один из элементов GUI.

Если я использую актера, на каком уровне? В настоящее время я использую тип image! для экрана. Могу ли я добавить актера к корневому (layout) лицу, поэтому, даже если я нажму (передам фокус) на кнопку также в графическом интерфейсе, фокус будет не на изображении, и он не будет использовать элементы управления с клавиатуры.


person kealist    schedule 17.09.2013    source источник


Ответы (1)


Ниже приведен пример того, как вы могли бы это сделать... Вы также можете использовать только встроенную функцию сочетаний клавиш, если вам не нужны события нажатия клавиш. В таком случае см. пример с сочетаниями клавиш здесь: https://github.com/saphirion/documentation/blob/master/r3/r3-gui/examples/layouts/layout-15.r3

Эта версия модифицирована для работы с текущим (26.09.13) выпуском R3-GUI.

REBOL [
    author: "[email protected]"
]

load-gui

;image for game screen
img: make image! 400x400

;just some example game object
game-object: context [
    offset: 0x0
    draw-block: [
        pen red
        fill-pen white
        line-width 5
        circle offset 20
    ]
    move: func [
        delta [pair!]
    ][
        offset: offset + delta
        img/rgb: black
        ;note: this is not optimal way how to render DRAW objects
        ;but I use image! here because the asking SO user uses image! as well
        ;better way is to just use DRAWING style for DRAW based graphics
        draw img to-draw draw-block copy []
        draw-face game-screen
        ;signal true move has been executed
        return true
    ]
]

stylize [
    ;backup the original window style to be able call the original key actor
    window-orig: window []

    ;override window style with our key actor
    window: window [
        actors: [
            on-key: [
                ;execute our key controls prior to 'system' key handling
                switch arg/type [
                    key [
                        ;here you can handle key-down events
                        moved?: switch/default arg/key [
                            up [
                                game-object/move 0x-5
                            ]
                            down [
                                game-object/move 0x5
                            ]
                            left [
                                game-object/move -5x0
                            ]
                            right [
                                game-object/move 5x0
                            ]
                        ][
                            false
                        ]
                    ]
                    key-up [
                        ;here you can handle key-up events
                    ]
                ]
                ;for example filter out faces that shouldn't get the system key events (for example editable styles)
                 unless all [
                    moved?
                    guie/focal-face
                    tag-face? guie/focal-face 'edit
                 ][
                    ;handle the system key handling
                    do-actor/style face 'on-key arg 'window-orig
                ]
            ]
        ]
    ]
]

view [
    title "Custom keyboard handling (whole window)"
    text "press cursor keys to move the box"
    game-screen: image options [min-size: 400x400 max-size: 400x400]
    text 400 "focus the field below and press to see these keys are filtered out, but other keys works normally"
    field "lorem ipsum"
    when [enter] on-action [
        ;initialize game object
        game-object/move 200x200
    set-face game-screen img
    ]
]

В этой версии используется еще не выпущенная версия R3-GUI:

REBOL [
    author: "[email protected]"
]

;image for game screen
img: make image! 400x400

;just some example game object
game-object: context [
    offset: 0x0
    draw-block: [
        pen red
        fill-pen white
        line-width 5
        circle offset 20
    ]
    move: func [
        delta [pair!]
    ][
        offset: offset + delta
        img/rgb: black
        ;note: this is not optimal way how to render DRAW objects
        ;but I use image! here because the asking SO user uses image! as well
        ;better way is to just use DRAWING style for DRAW based graphics
        draw img to-draw draw-block copy []
        draw-face game-screen
        ;signal true move has been executed
        return true
    ]
]

stylize [
    ;backup the original window style to be able call the original key actor
    window-orig: window []

    ;override window style with our key actor
    window: window [
        actors: [
            on-key: [
                ;execute our key controls prior to 'system' key handling
                switch arg/type [
                    key [
                        ;here you can handle key-down events
                        moved?: switch/default arg/key [
                            up [
                                game-object/move 0x-5
                            ]
                            down [
                                game-object/move 0x5
                            ]
                            left [
                                game-object/move -5x0
                            ]
                            right [
                                game-object/move 5x0
                            ]
                        ][
                            false
                        ]
                    ]
                    key-up [
                        ;here you can handle key-up events
                    ]
                ]
                ;for example filter out faces that shouldn't get the system key events (for example editable styles)
                 unless all [
                    moved?
                    guie/focal-face
                    tag-face? guie/focal-face 'edit
                 ][
                    ;handle the system key handling
                    do-actor/style face 'on-key arg 'window-orig
                ]
            ]
        ]
    ]
]

view [
    title "Custom keyboard handling (whole window)"
    text "press cursor keys to move the box"
    game-screen: image img options [min-size: 400x400 max-size: 400x400]
    text 400 "focus the field below and press to see these keys are filtered out, but other keys works normally"
    field "lorem ipsum"
    when [enter] on-action [
        ;initialize game object
        game-object/move 200x200
    ]
]
person Cyphre    schedule 18.09.2013
comment
Когда я только начинал, я спорил об использовании команд изображения или рисования, но проблема, с которой я столкнулся, заключалась в записи двоичного кода на монохромный экран. Учитывая #{11110000}, он запишет первые четыре пикселя окрашенными, а следующие четыре неокрашенными. Я решил, что создание рамки для каждого пикселя кажется немного безумным, поэтому я выбрал тип данных изображения и задал пиксели в двоичном формате. Имеет ли это смысл? - person kealist; 19.09.2013