1

I am trying to make a tetris game in java. I have made the functions to move the shapes in the matrix. But I don't know how to access those functions when a key is pressed from keyboard on runtime.

public class tetris
    {
      public static void main(String args[])throws InterruptedException
      {
        int score=0;
        int height=30;
        int width=30;
        board obj=new board(height,width);
        SquareShape sq=new SquareShape(height,width);
        while(true)
        {
          System.out.println("\t  Score: "+score);
          obj.createboard();
          board.update(sq);
          obj.dispboard();
          sq.movedown();
          Thread.sleep(1000);
          System.out.print("\033[H\033[2J");
        }
      }
    }

1 Answers1

0

Are you writing a console game? It's a bit hardcore but if you like it :)

You need to capture the input stream from the console.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
String line = br.readLine(); // or br.read(byteBuffer);

By with the default implementation of JDK the stream will give you data only after ENTER.

So if you need it to work on keypress then try that. This is a java/scala example but it can be easily changed to work for pure java: How to capture keyboard event without Enter key in java/scala? Follow the thread into the github implementation!

Alternatively if you have access to the awt package you can use that one too.

Hope that helps.

Anyhow ... my 2c: it will be much better game if code it for android or ios.

Deian
  • 1,237
  • 15
  • 31
  • I used this but it requires Enter key after my input. Is there any way I can avoid that? And this solution stops the Execution of the program to take the input. – Madhur Bansal Oct 05 '18 at 16:33