Question

I'm trying to make my first game, a console tetris. I have a class Block, that contains x and y integers. Then I have a class Piece : List<Block>, and a class Pieces : List<Piece>.

I can already randomly generate pieces, and make them fall one row per second. I still didn't get to collisions detection, but I think that I already know how to work it out later. The problem is that I don't know how to control the pieces. I've read a bit about keyboard hooking and checked some tetris tutorials, but most of them are for windows forms, which really simplifies events handling and the such.

So... Could you please point me the beginning of the path to controlling the pieces on a console? Thanks!

public class Program
    {
        static void Main(string[] args)
        {
            const int limite = 60;
            Piezas listaDePiezas = new Piezas();    //list of pieces
            bool gameOver = false;
            Pieza pieza;    //piece
            Console.CursorVisible = false;
            while (gameOver != true)
            {
                pieza = CrearPieza();    //Cretes a piece
                if (HayColision(listaDePiezas, pieza) == true)   //if there's a collition
                {
                    gameOver = true;
                    break;
                }
                else
                    listaDePiezas.Add(pieza);    //The piece is added to the list of pieces
                while (true)    //This is where the piece falls. I know that I shouldn't use a sleep. I'll take care of that later
                {
                    Thread.Sleep(1000);
                    pieza.Bajar();    //Drop the piece one row.
                    Dibujar(listaDePiezas);    //Redraws the gameplay enviroment.
                }
            }
        }
Was it helpful?

Solution

What you are looking for is non-blocking console input.

Here is an example:

http://www.dutton.me.uk/2009/02/24/non-blocking-keyboard-input-in-c/

Basically, you would check Console.KeyAvailable in your while loop and then move the piece according to what key was pressed.


            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo cki = Console.ReadKey();
                switch (cki.Key)
                {
                    case ConsoleKey.UpArrow:
                        // not used in tetris game?
                        break;
                    case ConsoleKey.DownArrow:
                        // drop piece
                        break;
                    case ConsoleKey.LeftArrow:
                        // move piece left
                        break;
                    case ConsoleKey.RightArrow:
                        // move piece right
                        break;
                }
            }

OTHER TIPS

You could use a Low-Level Keyboard Hook as shown here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top