2013-09-17 2 views
3

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

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

ответ

3

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

Эта версия модифицирована для работы с текущим (09/26/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 
    ] 
] 

Эта версия использует, как-из -yet невыпущенная версия 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 
    ] 
] 
+0

Когда я впервые начал, я обсуждал использование графических или рисованных команд, но проблема, с которой я столкнулся, заключалась в записи двоичного файла на монохромный экран. Учитывая '# {11110000}', он будет писать первые четыре пикселя, а следующие четыре - нецветные. Я решил сделать коробку для каждого пикселя, казалось немного сумасшедшим, поэтому я пошел с типом данных изображения и вытолкнул пиксели в двоичном формате. Имеет ли это смысл? – kealist

Смежные вопросы