Search code examples
keyboardpascalfreepascal

Keyboard Management in Pascal


I'm a beginner in Pascal and I'm working on a small WIngraph game. At some point on the game, the character (which is a block) has to lay down (the block gets half of its original height). I want this to happen while holding the arrow-down key but the way I implemented it is not actually working. Another problem I have is I don't know how to read keys simultaneously (that would be needed when, for example, running to the right and jumping).

That's how I tried to write it:

procedure joystick;
begin
  key:=readkey;
  case key of 
  #0:begin  
  key:=readkey;  
    case key of  
    #80:with block do  
       begin  
        y1:=y2-100; //make it get half of its height  
        repeat  
         moveblock; //these are the drawing routines.   
         moveball;  //they are in another procedure, which is the 'main loop'   
         collisioncheck;  
         draw;      //i expected the code to run inside here with the block's  
         alternateball; //height changed, and as soon as the arrow key gets released  
         updateGraph(updateNow);  //it should go back to the 'main loop'  
         killball;  
         delay(10);  
        until keypressed = false; //<--thats what i think is not working  
        y1:=y2-200; //this would make the block get normal again  
       end;  
     end;  
   end;      
 end;  

I expected the code to run fine while the key was pressed and as soon as its released, the block should get its normal height and then the program would run based on its main loop, but outside of this procedure.

Everything is working, except that key-holding thing.


Solution

  • It does not work because after each keypressed() you should have a readkey(). The function keypressed() returns true until you call readkey() again.

    Demo:

    uses crt;
    var c:char;
        i:longint;
    begin
    while c<>#27 do
      begin
      while not keypressed() do
        begin
        clrscr;
        writeln('not pressing anything');
        delay(500);
        end;
      i:=0;
      while keypressed() do
        begin
        clrscr;
        c:=readkey();
        if(c=#0) then
          c:=readkey();
        inc(i);
        writeln(c,' ',i);
        delay(300);
        end;
      end
    end.