You are here:

C++/How to move a block in c++ graphics.


I am working on my project in c++ graphics which is on making a game and I am trying to make Tetris.
I made a block by the following coordinates...:
I have uploaded the image of the block.
I want to move this block by using left and right keys and i know the ASCII code of left(75) and right(77).
But I am not able to move it as I can't understand what should i do.
So,can you Please help me out in moving this block and i want it in my syllabus  only for loop,kbhit() and I just know dos.h,conio.h,iostream.h,stdio.h,stdlib.h and graphics.h..

Hi Manan Grover

I am not sure if you are having trouble with getting keyboard data, or with drawing. I cannot help you much with drawing, but I can help you with the keyboard and the main game loop. Unfortunately, I do not have turbo C++, and I think that is what you are using.

To see how to get keyboard data, try this simple program.

#include <Windows.h> // for the Sleep function
#include <conio.h>
#include <iostream> // or iostream.h for turbo c++
using namespace std; // omit for turbo c++

int main()
       if (kbhit())
         int c = getch();
         if (c == 75)
         cout << "L";
         else if (c == 77)
         cout << "R";
       // Sleep(100);

You should see L and R printed as you hit the left and right cursor buttons. If you look at your task manager, you will see that the program is taking up a lot of CPU even though it is doing nothing. It is spinning in the while loop, constantly checking for a kbhit. You can put in a sleep statement to reduce the CPU usage. If you check the keyboard 10 times per second, that is a 100 millisecond sleep between checks, and that is probably responsive enough. Uncomment the sleep and see what difference it makes. On my machine it goes from 10% CPU to 0% CPU while still being very responsive.

Next, instead of printing out L and R, you need to update the position of you current rectangle, clear the screen, and redraw your shape. It may surprise you that you need to erase and redraw the entire screen, including all the other shapes which have not moved, but that is the simplest way.

In your program, you need to keep an object for each tetris shape which is on the screen. Each object has the shape's location. When it comes time to redraw, you go through all the objects, and redraw all of the shapes. Do you know how to allocate objects from memory? Do you know how to store pointers in an array? If you have written some code, show it to me so that I can see where you are having trouble.

Best regards


All Answers

Answers by Expert:

Ask Experts




No longer taking questions.


No longer taking questions.

No longer taking questions.

©2016 All rights reserved.