I am trying to learn how to use graphics.h and conio.h libraries.I am developing a graphic program which i need to move a rectangle after keyboard input.ex: if player press right , rectangle should move right side.Problem is i don't know how to get user input.I need to get user input inside a loop continuous.Here is my code.Any help is appreciated(keyword,function name etc)
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
void drawrect(int left,int top,int right,int bot);
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
drawrect(5,400,40,450); // default start position
firsttime=1;//counter for if its first time in for loop
int currentl=5;
int currentt=400;
int currentr=40;
int currentb=450;
if(firsttime==1)
{
//get user input and drawrectangle with new inputs
//if player press right add 5 to currentl and current r and
//redraw the rectangle
}
getch();
closegraph();
}
void drawrect(int left,int top,int right,int bot)
{
rectangle(left,top,right,bot);
}
You can use getch() or _getch() to read codes of keys and react on it. But some things you should think over.
1) loop is needed to perform continuois action in your program.
2) keys such as "arrow left", "arrow up", etc. is given by getch() as two codes - the first -32 and the second depends on key.
Use the following programm to see the loop example and to find codes for keys:
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(void)
{
char ch;
printf("Press 'q' to exit prom program\n");
do{
ch = _getch();
printf("%c (%d)\n", ch, ch);
} while( ch != 'q');
}
Its solved this code works thanks for help
#include
#include
void drawrect(int left,int top,int right,int bot);
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
int firsttime=1;//counter for if its first time in for loop
int currentl=5;
int currentt=400;
int currentr=40;
int currentb=450;
char ch;
settextstyle(0, HORIZ_DIR, 1);
outtextxy(20, 20, "To start press 'S'");
ch = getch();
cleardevice();
drawrect(5,400,40,450); // default start position
while(ch!='q')
{
ch = getch();
switch (ch)
{
case KEY_RIGHT:currentr=currentr+5;
currentl=currentl+5;
break;
case KEY_LEFT:currentr=currentr-5;
currentl=currentl-5;
break;
}
cleardevice();
drawrect(currentl,currentt,currentr,currentb);
}
getch();
closegraph();
}
void drawrect(int left,int top,int right,int bot)
{
rectangle(left,top,right,bot);
}
Related
The following program does not work properly. It is supposed to be a calculation game which should not loop over and over. I'm not exactly sure what's going on. I tried rearranging some things but that did not help. I noticed that after the user inputs the numbers and answers the question, it just goes to mainMenu even though it should go to display.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//Declaration Statement
double num1;
double num2;
double answer;
int choice;
void pauseProgram()
{
printf("\nPress any key to continue...");
getchar();
}
//Function Title
void title(char * programTitle)
{
int len = strlen(programTitle);
system("cls");
printf("\n");
for(int i=1; i<40 - len/2;i++) printf(" ");
printf("%s\n",programTitle);
}
void intro()
{
title("Calculation Game");
printf("\nThis program will test your math abilites");
pauseProgram();
}
void userInput()
{
title("Calculation Game");
printf("\nPlease enter positive numbers only\n");
printf("Enter a number:");
scanf("%lf",&num1);
getchar();
printf("Enter another number:");
scanf("%lf",&num2);
getchar();
printf("What is %lf + %lf?",num1,num2);
scanf("%lf",&answer);
if (num1<0 or num2<0)
{
printf("\nSorry, you must enter a positive value! Please try again.");
userInput();
pauseProgram();
}
}
void display()
{
title("Calculation Game");
if (answer=num1+num2)
printf("\nWow you got the right answer\n");
else if (answer!=num1+num2)
printf("\nHmmm...maybe we should review this math concept again!\n");
pauseProgram();
}
void goodbye()
{
title("Calculation Game");
printf("\nFor further information call: 1-800-123-4567\n");
pauseProgram();
}
void mainMenu()
{
title("Calculation Game");
printf("\n1.\tPlay Game");
printf("\n2.\tExit\n");
printf("\nEnter 1 or 2:");
scanf("%d",&choice);
getchar();
if (choice==1)
userInput();
if (choice=2)
goodbye();
if (choice!=1 or choice!=2);
{
printf("\nPlease enter either 1 or 2! Please try again.");
mainMenu();
}
}
//Main program
int main()
{
do
{
intro();
mainMenu();
userInput();
if (answer==num1+num2 or answer!=num1+num2)
{
display();
}
}while(1);
goodbye();
}
As I mentionned in my comment, you can probably see the main() function enters an infinite loop:
do {
...
} while (1)
This loop will not stop until told so. For instance, you can tell the program to exit in your pauseProgram() function :
void pauseProgram()
{
printf("\nPress any key to continue...");
getchar();
exit(0);
}
or in your goodbye() function :
void goodbye()
{
title("Calculation Game");
printf("\nGame designed by David Liubart\n");
printf("\nFor further information call: 1-800-123-4567\n");
pauseProgram();
exit(0);
}
Finally, you could use a break instruction anywhere in the loop in order to exit the loop.
I am making a simple game using C++
It's just a tile game with an ASCII map.
The game itself works fine, but the console screen(map) is flickering when I move my player and I don't know how to fix this. Any help appreaciated, thanks!
Code:
#include <iostream>
#include <windows.h>
#include <conio.h>
#include <ctime>
#include <vector>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
vector<string> map;
int playerX = 10;
int playerY = 10;
int oldPlayerX;
int oldPlayerY;
bool done = false;
void loadMap();
void printMap();
void setPosition(int y, int x);
void eventHandling();
int main()
{
loadMap();
map[playerY][playerX] = '#';
printMap();
while(!done){
eventHandling();
printMap();
}
exit(1);
return 0;
}
void eventHandling(){
char command;
command = _getch();
system("cls");
oldPlayerX = playerX;
oldPlayerY = playerY;
if(command == 'w'){
playerY--;
}else if(command == 'a'){
playerX--;
}else if(command == 'd'){
playerX++;
}else if(command == 's'){
playerY++;
}
if(map[playerY][playerX] == '#'){
playerX = oldPlayerX;
playerY = oldPlayerY;
}
setPosition(playerY,playerX);
}
void setPosition(int y, int x){
map[oldPlayerY][oldPlayerX] = '.';
map[y][x] = '#';
}
void printMap(){
for(int i = 0 ; i < map.size() ; i++){
cout << map[i] << endl;
}
}
void loadMap(){
ifstream file;
file.open("level.txt");
string line;
while(getline(file, line)){
map.push_back(line);
}
}
std::cout is not intended to be used that way.
You should refer to the system specific API for the target OS and environment. For example, for Windows you should use Console API functions for your purpose. These functions are defined in Wincon.h include file.
It also helps if you use a double buffering system such that only what needs to be overwritten every frame is changed. IO operations are extremely expensive so ought to be minimized.
Cameron Gives a Very Thorough Description of How to Do this Here
But in essence, you'd use two arrays, one containing the current state of the map, one containing the previous state and only write to the specific locations that have changed.
One method to clear the screen that works on many systems is to print the form feed character, \f. The Linux console supports this, and so did MS-DOS if you loaded ansi.sys. Unix has ncurses and terminfo to abstract these functions.
So I was browsing the Internet for a project and stumbled upon this piece of code. It runs perfectly until the point you enter a website(include "www" :P) and press Enter and then boom! The program terminates, no error message, nothing.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <graphics.h>
#include <dos.h>
#include <string.h>
void initialize_graphics_mode();
int get_key();
void draw();
union REGS i, o;
main()
{
int key, i = 0, xpos, ypos, button;
char arr[200], temp[5], *ptr;
char a[] = "C:\\Progra~1\\Mozill~1\\firefox ";
strcpy(arr,a);
i = strlen(a);
initialize_graphics_mode();
draw();
while(1)
{
if(kbhit())
key = get_key();
if((key>=97&&key<=122)||(key>=65&&key<=90)||key==46||key==47||key==63)
{
arr[i] = key;
sprintf(temp,"%c",arr[i]);
outtext(temp);
if(getx()>470)
{
clearviewport();
moveto(5,2);
}
i++;
}
else if ( key == 13 )
{
arr[i] = '\0';
system(arr);
break;
}
else if ( key == 27 )
{
closegraph();
exit(EXIT_SUCCESS);
}
if(button==1&&xpos>=150&&xpos<=480&&ypos>=300&&ypos<=330)
{
system("C:\\Progra~1\\Mozill~1\\firefox programmingsimplified.com");
break;
}
key = -1;
}
closegraph();
return 0;
}
void initialize_graphics_mode()
{
int gd = DETECT, gm, errorcode;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
errorcode = graphresult();
if( errorcode != grOk )
{
printf("Graphics error : %s\n",grapherrormsg(errorcode));
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}
}
int get_key()
{
i.h.ah = 0;
int86(22,&i,&o);
return( o.h.al );
}
void draw()
{
settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2);
outtextxy(275,11,"Web Browser");
outtextxy(155,451,"<a> href=http://www.programmingsimplified.com"">www.programmingsimplified.com</a>");
outtextxy(5,105,"Enter URL : ");
rectangle(120,100,600,130);
setviewport(121,101,599,129,1);
moveto(5,1);
}
Could someone help me in understanding why this happens? and possibly a fix for this?
NOTE: + It is supposed to work if you have Mozilla Firefox. If you have any other browser, please edit the code accordingly.
I am running this on Turbo C++, what would I have to do in order to convert this code for Dev-C++?
Thanks in advance.
P.S: I'm new to C++ so elaborate as much as possible.
I am creating a console application in C. This is a game in which characters are falling down and user has to press that specific key on the keyboard. I don't know how to detect which key is pressed by the user without pausing the falling characters. When I use scanf the Program waits for input and everything pauses.
Please help me soon!
There is a function called kbhit() or _kbhit it is in the <conio.h> library it returns true or false depending whether a key was hit. So you can go with something like this:
while (1){
if ( _kbhit() )
key_code = _getch();
// do stuff depending on key_code
else
continue;
Also use getch() or _getch which reads a character directly from the console and not from the buffer. You can read more about conio.h functions here they might be very useful for what you want to do.
Note: conio.h is not a standard library and implementations may vary from compiler to compiler.
You may probably look for ncurses
ncurses (new curses) is a programming library that provides an API
which allows the programmer to write text-based user interfaces in a
terminal-independent manner. It is a toolkit for developing "GUI-like"
application software that runs under a terminal emulator.
Also check C/C++: Capture characters from standard input without waiting for enter to be pressed
#include <conio.h>
if (kbhit()!=0) {
cout<<getch()<<endl;
}
I think this might be the non-blocking keyboard input you are looking for.
void simple_keyboard_input() //win32 & conio.h
{
if (kbhit())
{
KB_code = getch();
//cout<<"KB_code = "<<KB_code<<"\n";
switch (KB_code)
{
case KB_ESCAPE:
QuitGame=true;
break;
}//switch
}//if kb
}//void
And as for the characters falling down.. here you go.
Code for if you are on Windows:
/* The Matrix falling numbers */
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
using namespace std;
#define KB_UP 72
#define KB_DOWN 80
#define KB_LEFT 75
#define KB_RIGHT 77
#define KB_ESCAPE 27
#define KB_F8 66
/* Variables*/
char screen_buffer[2000]={' '};
int y_coord[2000]={0};
int x=0, y=0,dy=0;
int XMAX=77;
int YMAX=23;
int KB_code=0;
bool QuitGame=false;
int platformX=35, platformY=23;
/* function prototypes*/
void gotoxy(int x, int y);
void clrscr(void);
void setcolor(WORD color);
void simple_keyboard_input();
void draw_falling_numbers();
void draw_platform();
/* main */
int main(void)
{
/* generate random seed */
srand ( time(NULL) );
/* generate random number*/
for(int i=0;i<XMAX;i++) y_coord[i]= rand() % YMAX;
while(!QuitGame)
{
/* simple keyboard input */
simple_keyboard_input();
/* draw falling numbers */
draw_falling_numbers();
}
/* restore text color */
setcolor(7);
clrscr( );
cout<<" \n";
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
/* functions */
void draw_falling_numbers()
{
for(x=0;x<=XMAX;x++)
{
/* generate random number */
int MatixNumber=rand() % 2 ;
/* update falling number */
y_coord[x]=y_coord[x]+1;
if (y_coord[x]>YMAX) y_coord[x]=0;
/* draw dark color */
setcolor(2);
gotoxy(x ,y_coord[x]-1); cout<<" "<<MatixNumber<<" ";
/* draw light color */
setcolor(10);
gotoxy(x ,y_coord[x]); cout<<" "<<MatixNumber<<" ";
}
/* wait some milliseconds */
Sleep(50);
//clrscr( );
}
void draw_platform()
{
setcolor(7);
gotoxy(platformX ,platformY);cout<<" ";
gotoxy(platformX ,platformY);cout<<"ÜÜÜÜÜÜ";
setcolor(7);
Sleep(5);
}
void simple_keyboard_input()
{
if (kbhit())
{
KB_code = getch();
//cout<<"KB_code = "<<KB_code<<"\n";
switch (KB_code)
{
case KB_ESCAPE:
QuitGame=true;
break;
case KB_LEFT:
//Do something
platformX=platformX-4;if(platformX<3) platformX=3;
break;
case KB_RIGHT:
//Do something
platformX=platformX+4;if(platformX>74) platformX=74;
break;
case KB_UP:
//Do something
break;
case KB_DOWN:
//Do something
break;
}
}
}
void setcolor(WORD color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color);
return;
}
void gotoxy(int x, int y)
{
static HANDLE hStdout = NULL;
COORD coord;
coord.X = x;
coord.Y = y;
if(!hStdout)
{
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
}
SetConsoleCursorPosition(hStdout,coord);
}
void clrscr(void)
{
static HANDLE hStdout = NULL;
static CONSOLE_SCREEN_BUFFER_INFO csbi;
const COORD startCoords = {0,0};
DWORD dummy;
if(!hStdout)
{
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout,&csbi);
}
FillConsoleOutputCharacter(hStdout,
' ',
csbi.dwSize.X * csbi.dwSize.Y,
startCoords,
&dummy);
gotoxy(0,0);
}
I am trying to use ncurses to get non-blocking input.
#include <iostream>
#include <ncurses.h>
int main()
{
char ch;
nodelay(stdscr, TRUE);
while(1)
{
ch= getch();
if (ch == ERR) {
printf("here \n");
usleep(100000);
}
else {
printf("---------------\n");
}
}
}
However when I run this code, irrespective of what I press I always just get "here" printed.
Sample output:
Latitude-E6430:~$ ./try
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
dhere
ddhere
dhere
here
The d's and the spaces are not detected at all.
Can someone tell me why?
Thanks.
Finally I found the answer to the question.
I need to do initscr();
After that I am able to print out correctly (the formatting is not-as-expected though).
Correct code:
#include <iostream>
#include <ncurses.h>
int main()
{
char ch;
initscr();
nodelay(stdscr, TRUE);
while(1)
{
ch= getch();
if (ch == ' ') {
// printf("here \n");
usleep(100000);
}
else {
printf("---------------\n");
}
}
}