I am doing this C program for three months in my spare time for learning and fun. I am trying to create a curses file in C for very first time, but I honestly don't even know what is the curses and ncurses because they're are same anyway...so I wanted to make a simple square box with guess a right number inside the box just to test it. I have created a box successfully which it is included in the below. I wanted to make character keys that I just added inside the box with the Q key for Quit and C key for clear or reset in getchar
using the while-do loops for to guess the right or wrong number including counting how many times you have guessed. BTW: I used indent
for formatted codes in Linux system.
So first I just learned how to create a box in the screen show like this (code included):
lqqqqqqqqqqqqqqqqqqk
xthis is my box x
x x
x x
x x
x x
x x
x x
x x
mqqqqqqqqqqqqqqqqqqj
Code for "This is my box":
#include <stdio.h>
#include <ncurses.h>
int
main (int argc, char **argv)
{
initscr ();
int height, width, start_y, start_x;
height = 10;
width = 20;
start_y = start_x = 10;
WINDOW *win = newwin (height, width, start_y, start_x);
refresh ();
box (win, 0, 0);
mvwprintw (win, 1, 1, "this is my box");
wrefresh (win);
int c = getch ();
endwin ();
return 0;
}
My code source I worked on for almost three days:
#include <stdio.h>
#include <ncurses.h> /*This is similar as curses file*/
//using namespace std;
int
main (int argc, char **argv)
{
initscr ();
int height, width, start_y, start_x;
int tries, num, guess;
srand(time(0)); //random number generator
num = rand() % 100 +1; //only 1 through 100
height = 10;
width = 20;
start_y = start_x = 10;
WINDOW *win = newwin (height, width, start_y, start_x);
refresh ();
box (win, 0, 0);
mvwprintw (win, 1, 1, "Guess the correct number!\n");
do {
while((ch = getch()) != ERR) {
switch(ch) {
case 'Q': shutdown();
case 'C': clear(); break;
}
printf("Enter your guess number (1-100): ");
scanf("%d", &guess);
tries++;
if (guess > num){
printf("Try Again Next Time! Press any key to exit!\n");
} else if (guess < num){
printf("Try again...\n");
} else {
printf("\nCORRECT! You got it right after %d guesses!", tries);
}
}
wrefresh (win);
endwin ();
return 0;
}
This is my expected from my idea (I copied the output and edited it for example):
lqqqqqqqqqqqqqqqqqqk
xGuess the correct x
xnumber! x
x x
xEnter your guess x
xnumber (1-100):___x
x x
xTry again... x
x x
mqqqqqqqqqqqqqqqqqqj
for expected output, I can still edit the sizes but use the current size for now. Unless you wanted to add for "auto-size" that would be sweet. Thanks for reading and help.