0

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 getcharusing 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.

Mike ODell
  • 37
  • 9
  • It's not very clear what you are asking. Perhaps edit your question to be less of a story and more of a question. It doesn't matter that you're new at coding, don't know the difference between curses and ncurses, or how you indent your code. – Retired Ninja Dec 06 '18 at 06:01
  • In your only do is there where is while condition at the end. – Ramya Muralidharan Dec 06 '18 at 06:32
  • @RetiredNinja, I am trying to make a game with curses and I just created to draw a box on the screen and the codes works fine and then I just got an idea I wanted to added a game inside the box into a mini game called "Guess the right number" so inside the box you just put the right number and the message ("Right number or try again") should be appear outside of box with how many times you have guessed the right number. Which I am trying to explain because I'm not good with English, BTW. I am just trying to practice and learn more C program code stuff. Hope this make sense. – Mike ODell Dec 06 '18 at 06:45

1 Answers1

1

Here is my two cents to help you but please take all in this solution with grain of salt because this solution might contain some stupid stuff...

Maybe you can pick parts or at least learn something how not to do from this one. Example is for 0-10 for easier testing... change them how you like by changing MAXVALUE and MINVALUE definitions / constant strings to match those...

Good luck and have a nice day.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ncurses.h>


// PREDEFINED VALUES FOR DEFINING NON CHANGING VALUES IN CODE THIS CASE
#define WINDOWHEIGHT 20
#define WINDOWWIDTH 60
#define WINDOWSTARTX 0
#define WINDOWSTARTY 0
#define CORRECT 1
#define INCORRECT 0
#define START 2
#define WRONGFORMAT 3
#define MAXVALUE 10
#define MINVALUE 0
// PREDEFINED VALUES FOR DEFINING NON CHANGING VALUES IN THIS CASE


// initialising global structure for saving amount of right and wrong guesses and number to compare with.
struct game {
        int rightGuesses;
        int wrongGuesses;
        int rightNumber;
} myGame;

void initializeGame()
{

        // Returns a pseudo-random integer between 0 and MAXVALUE.
        int randomNumber = rand() % MAXVALUE;
        myGame.rightGuesses=0;
        myGame.rightNumber=randomNumber;
}

WINDOW *create_newwin(int height, int width, int starty, int startx)
{
        WINDOW *local_win;
        local_win = newwin(height, width, starty, startx);
        box(local_win, 0, 0);
        wrefresh(local_win);
        return local_win;
}


int getGuess()
{
        int guess=0;
        char guessString[32];
        scanf("%s", guessString);

        // Read number as string by using scanf, but convert to int for comparison with atoi()
        guess= atoi(guessString);
        size_t allowedEntries = strspn(guessString, "0123456789");

        // Some checking if guess was between allowed range + its a number + checking if answer is correct or not
        if(guess>=MINVALUE && guess<=MAXVALUE && guessString[allowedEntries] == '\0')
        {
                if(guess==myGame.rightNumber)
                        return CORRECT;
                else
                        return INCORRECT;
        }
        else
                return WRONGFORMAT;

}

/**
    Function for updating views regarding the input values...
 **/

void updateWindowTexts(WINDOW* window, int state)
{

        char* greetingsString = "Guess the correct number!";
        char* instructionsString = "Enter number 0-10 and press enter";
        char* correctGuess = "That was correct! Lets play again";
        char* incorrectGuess = "Sorry that was not right";
        char* wrongFormat = "incorrect number, please enter number between 0-10";
        char* correctAnswersString = "Correct answers:";
        char correctAnswers[32];
        char wrongAnswers[32];
        const char rightAnswersBase[] = "Right numbers so far: ";
        sprintf(correctAnswers, "%s%d", rightAnswersBase, myGame.rightGuesses);
        const char wrongAnswersBase[] = "Wrong numbers so far: ";
        sprintf(wrongAnswers, "%s%d", wrongAnswersBase, myGame.wrongGuesses);


        wclear(window);
        box (window, 0, 0);

        mvwprintw (window, 1, (WINDOWWIDTH/2)-(strlen(greetingsString)/2), greetingsString);
        mvwprintw (window, (WINDOWHEIGHT-3), (WINDOWWIDTH/2)-(strlen(correctAnswers)/2), correctAnswers);
        mvwprintw (window, (WINDOWHEIGHT-2), (WINDOWWIDTH/2)-(strlen(wrongAnswers)/2), wrongAnswers);
        mvwprintw (window, (WINDOWHEIGHT/2), (WINDOWWIDTH/2)-(strlen(instructionsString)/2), instructionsString);


        switch (state) {
        case START:
                break;
        case CORRECT:
                mvwprintw (window, WINDOWHEIGHT-5, (WINDOWWIDTH/2)-(strlen(correctGuess)/2), correctGuess);
                myGame.rightGuesses++;
                break;
        case INCORRECT:
                mvwprintw (window, (WINDOWHEIGHT-5), (WINDOWWIDTH/2)-(strlen(incorrectGuess)/2), incorrectGuess);
                myGame.wrongGuesses++;
                break;
        case WRONGFORMAT:
                mvwprintw (window, (WINDOWHEIGHT-5), (WINDOWWIDTH/2)-(strlen(wrongFormat)/2), wrongFormat);
                break;

        }
        wrefresh (window);

}

int main (int argc, char **argv)
{
        WINDOW *my_win;
        initscr();
        // Here we call crea_newwin to make new window, paremeters are static and defined at the top of file
        // You can try to play with these numbers
        my_win = create_newwin(WINDOWHEIGHT, WINDOWWIDTH, WINDOWSTARTY, WINDOWSTARTX);
        // Initialization of random generator, should only be called once.
        srand(time(NULL));

        initializeGame();
        // Update window once before enteringing loop
        updateWindowTexts(my_win,START);
        while(1)
        {
                updateWindowTexts(my_win,getGuess());
        }
        return 0;
}
JuhoR
  • 64
  • 3
  • Good answer, You need to `#include ` in order to call: `srand (time (NULL));` but the other error about the answer variable does not occur in the file you posted?? – Mike ODell Dec 07 '18 at 04:10
  • Oh sorry yeah forgot to include that one in answer also. I'm sorry but I don't quite understand this : "but the other error about the answer variable does not occur in the file you posted??" – JuhoR Dec 07 '18 at 10:39