Tutorial: using keys, difference between LONGKEY and SHORTKEY
=============================================================

We want to move a white pixel with the arrow keys (cursor keys).
The arrow keys "left" and "right" use LONGKEY, which means they are considered
as pressed as long you press them.
The arrow keys "up" and "down" use SHORTKEY, which means they are considered
as pressed only when you press down the keys, after that you have to release
and press them again.
End the program with space key.


step 1
At first we have to initialize VgaGames
and open a window or switch to graphical screen.

==>
int main(int argc, char ** argv) {
  char * arg0;  // for the name of the program
  int x,y;  // for position of white pixel

  /* initialize vgagames, always pass argv[0] */
  if (vg_init_vgagames(argv[0],0,NULL) < 0) {exit(1);}

  /* open window */
  if ((arg0=strrchr(argv[0],'/'))==NULL) {arg0=argv[0];} else {arg0++;}
  if (vg_window_open(arg0,0,0) < 0) {exit(1);}

  /* to begin set pixel into midth of window */
  x=SC_WIDTH/2;   // SC_WIDTH is width of window=320 pixels
  y=SC_HEIGHT/2;  // SC_HEIGHT is height of window=200 pixels
<== step 2 Now we begin our program loop. It has to check the key input, to move the pixel according to the pressed keys, and to wait a little time. At first we clear the window. At the visible screen any change to the window is not shown until vg_window_flush() is called. ==>
  /* program loop */
  for (;;) {

    /* clear the window (not visible unless called vg_window_flush()) */
    vg_bitmap_clear(NULL, RGB_BLACK);
<== step 3 Now we update our information of the key- and mouse-events. ==>
    /* update key and mouse events */
    vg_key_update();
<== step 4 We move our pixel according to the pressed keys. ==>
    /* move pixel */
    if (vg_key_pressed(KEY_RCURS, LONGKEY)) {
      if (++x >= SC_WIDTH) {x=SC_WIDTH-1;}
    }
    if (vg_key_pressed(KEY_LCURS, LONGKEY)) {
      if (--x < 0) {x=0;}
    }
    if (vg_key_pressed(KEY_UCURS, SHORTKEY)) {
      if (--y < 0) {y=0;}
    }
    if (vg_key_pressed(KEY_DCURS, SHORTKEY)) {
      if (++y >= SC_HEIGHT) {y=SC_HEIGHT-1;}
    }
<== step 5 We draw the pixel and flush the background window out to the visible screen. ==>
    /* draw the pixel */
    vg_draw_pixel(NULL,x,y,RGB_WHITE);

    /* now flush window out to visible screen */
    vg_window_flush();
<== step 6 We now check for a pressed space key to end the program and then wait up to 70 milliseconds, before the loop restarts. ==>
    /* check for space key to end the program */
    if (vg_key_pressed(KEY_SPACE, SHORTKEY)) {
      break;
    }

    /* wait a little time up to 70 milliseconds */
    vg_wait_time(70);
  } // of of loop
<== step 7 The loop is ready, now we append the ending stuff: Closing the window and exit. ==>
  /* close window */
  vg_window_close();

  exit(0);
}
<== The whole program tut-window1.c
[Previous] - [Index] - [Next]