C++ how to move Text with ncurses.h? - c++

C++ how to move Text from off screen to inside the terminal (animation 20/50 millisec.) and then stop the animation. with ncurses.h ? pls with examples
with perhaps a loop that increases the X coordinate from (x = 0-number characters text-1) to (x = 2 or 1), for each Line of text containing the color.
let me explain: the previous sentence no longer moves (it remains stationary on X2 coordinates), the sentence of now makes the entry animation, as soon as the animation ends, it becomes the still sentence together with the other preceding sentences. moves the next one, and continues the loop until it is finished.
I didn't get the result I wanted: (this is the code)
#include <iostream>
#include <windows.h>
#include <ncurses.h>
using namespace std;
void tdnVoid(short colore)
{
HANDLE a = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(a, colore);
}
int main()
{
initscr();
int b = 0;
while (b != 256)
{
b++;
refresh();
move(0, 0);
tdnVoid(b);
cout << b << ". ■ ";
cout << "\n";
if (b % 16 == 0)
{
cout << "\n";
}
Sleep(100);
}
return 0;
}
☑️the result I wanted (GIF):
Gif Hello World example - GIF
❌the result I got: Gif C++ Program execution, pls help me solve it
NEW EDIT:
according to the documentation, you can use this:
mvprintw(y,x,"your string",); refresh(); but i use and try for like 2 hours, having errors;
pls if someone can help me, you will really help me!
this program may seem useless, but I am using it to learn C ++, once I have learned this, I can use the same function and complicate and do more interesting things. hope you understand me (there are those who created Nokia's Snake game with ncurses, there are those who 3D things that rotate in space) thank pls help me to understand :)

stackoverflow guys. i started stackoverflow bad. sorry for my wrong attitude
(that's why I didn't get an answer)
but luckily I managed to get the result I wanted! I can be of help for you! in the documentation it won't say, but through a while () loop I managed to do it!
int main()
{
initscr();
int x = -1;
while (x < 22)
{
x++;
refresh();
mvprintw(0, x, " C++ colori", 10);
Sleep(300);
}
//other my code
}
before putting refresh (); which is important to update, then mvprintw() which is like a cout << /*from <iostream> library*/ but with mv (mv is move()) ... which is what I wanted !! the first attribute is the Y which are the vertical, and the second attribute is the X that is to move in the same horizontal line.
all separated by commas, attention: I put the x as a variable and not as a number because I made it move through the while loop.
after put the string of characters, remember: put a space before if not you have a result like this
❌output: CCCCCCCCCCCCCC++ colori
with a space before, it appears to be invisible, so it works.
☑️output:                                    C++ colori
after I put Sleep(/*milliseconds*/); remember to put the <windows.h> library
10 is the number of characters, I know you could have done better by automating it with char [] =" your string " and make the program count, but it was was a beta.
===========
remember: if you don't put endwin (); at the end of the loop what you saw in the GIF will happen. on all your next normal code. here my first Bug

Related

How to generate random fruit for C++ 2D Snake game

I am having trouble generating random fruit for my Snake game. (I am very new to programming and this is my first language).
When I run my code all works fine so far (except from some minor issues). I'm using Visual Studio C++ in an empty project. Here is my full code (I'm not displaying my #includes):
using namespace std;
bool gameOver = false;
int gameScore;
int fruitX;
int fruitY;
string bGameW = "###########";
string bGameL = "# #\n";
class gameStart
{
public:
void start()
{
cout << bGameW;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameW;
}
void generateFruit()
{
srand(time(NULL));
fruitX = rand() % 21;
fruitY = rand() % 21;
bGameW.insert(fruitX, "F");
bGameL.insert(fruitY, "F");
}
void clearscreen()
{
system("cls");
}
private:
};
int main ()
{
gameStart gameObj;
gameObj.generateFruit();
gameObj.clearscreen();
gameObj.start();
return 0;
}
To generate the random the random fruit for the string. I use a string to make the game board, then I create random values for the fruit (X and Y) then I append them into my game board.
But the issue is: I want to make only one fruit with a random X and Y and append it into my game board to display it. But my current code is this:
bGameW.insert(fruitX, "F");
bGameL.insert(fruitY, "F");
This code makes 2 fruits with 1 at a random X and 1 at a random Y. I want to turn these 2 fruits into 1 fruit, with 1 random X and 1 random Y.
There's a whole host of things worth commenting on. Here goes:
bGameW has no \n
bGameW and bGameL are 10 and 11 characters long (both with be 11 after you add the other \n). Your RNG is generating numbers between 0 and 20... if you ever generate a number > 11 (and you will), Bad Things will happen (and probably have).
Snake games like this let you eat multiple fruit, which is why people brought up the whole "don't call srand more than once" thing, as you'll be calling generate fruit every time someone eats the old one. OTOH, that mostly removes the "calling srand multiple times per second can return the same value" problem too.
Rather than writing out those two lines, bGameW and bGameL, I recommend that you build a character array that holds your entire game display (NOT your game state, just the display of that state). You then clear it and redraw it every move. You'll need a game area, walls, something that tracks where your snake is, and the current fruit. You then 'render' all these things into your character-array-game-display. Don't forget to clear it every time you redraw it or you'll get all kinds of problems.
Rather than redrawing everything, you could use something like the "curses" library to clear and redraw specific character locations on the screen. You'd then face problems 'clearing' and redrawing different spots.
As far as programming style goes, you will find that so called "magic numbers" (like 21 in your case) can lead to bugs. What people generally do instead is to define a const with the appropriate value, and then define things in terms of that const.
// constants are often named in ALL_UPPER_CASE_WITH_UNDERSCORES
// to help you recognize them.
const int PLAY_AREA_HEIGHT = 10;
const int PLAY_AREA_WIDTH = 10;
const char EMPTY_PLAY_SQUARE = '.';
// have you learned about 2d arrays yet? Arrays at all?
char playAreaDisplay[PLAY_AREA_HEIGHT][PLAY_AREA_WIDTH];
void wipePlayArea()
{
for (int heightIdx = 0; heightIdx < PLAY_AREA_HEIGHT; ++heightIdx)
{
for (int widthIdx = 0; widthIdx < PLAY_AREA_WIDTH; ++widthIdx)
{
playAreaDisplay[heightIdx][widthIdx] = EMPTY_PLAY_SQUARE;
}
}
}

How can I 'pan out' (make screen bytes smaller) of the console screen to render 2d pyramids larger?

I am using Windows 10 with code blocks to compile my code.
I wonder WHY you want to do that. This seems to be a typical homework assignment problem for practising loops and logic. That usually is restricted to numbers easily fitting on a console. Could you elaborate what causes the need to go beyond say a size of 30? – Yunnosch 10 hours ago
#Yunnosch For pure hypothetical and experimental reasons. I essentially have a dream I could write a program that renders massive 2d pyramids on a console screen, and maybe create some game out of it. I was hoping I could figure out a way to 'pan out' of the console screen thus making the screen bytes smaller. Somebody has to know more than me, and can lead me in the right direction to accomplishing this '2d pyramid rendering' program. Thanks in advance! – Fibonacci 3 mins ago
My goal is to be able to render massive pyramid structures onto a console output screen. The code here simply asks for a number of rows and prints out a pyramid. ex. drawPyramid(50);
#include <iostream> // include iostream
using namespace std; // include std
// Draw pyramid function here
void drawPyramid(int rows)
{
// initializes space and creates for loop to keep track of rows, I and k
int space;
for(int i = 1, k = 0; i <= rows; ++i, k=0)
{
// draws spaces required
for(space = 1; space <= rows-i; ++space)
{
cout << " ";
}
// draws matter
while(k != 2*i-1)
{
cout << "* ";
++k;
}
//prints new line based on rows
cout << endl;
}
}
//driver program
int main()
{
bool fTrue = false;
// loops until user presses '0'
while(!fTrue)
{
cout << "Press (0) to quit...\n";
int i,rows;
cout << "Enter number of rows: \n";
cin >> rows;
drawPyramid(rows); // draw function called
if(rows == 0)
{
fTrue = true;
}
}
return 0;
}
Output:
While the program works great I'd like to be able to pass in bigger values such as drawPyramid(500); or drawPyramid(1000); anything above the value 50 produces results like so.
Results:
Hopefully you can understand what I am trying to ask. I want to be able to 'pan out' and move the asterisks closer together so that I can pass in larger input values into the drawPyramid() function... Thanks in advance!
I am using Windows 10 with code blocks to compile my code.

Out of Range error

The question is:
Jay had borrowed a friend's coffee mug and somehow lost it. As his friend will be extremely angry when he finds out about it, Jay has decided to buy his friend a replacement mug to try to control the damage.
Unfortunately, Jay does not remember the color of the mug he had borrowed. He only knows that the color was one of White, Black, Blue, Red or Yellow.
Jay goes around his office asking his colleagues if they are able to recall the color but his friends don't seem to remember the color of the mug either. What they do know is what color the mug definitely was not.
Based on this information, help Jay figure out what the color of the mug was.
The way I'm going about this:
I create a vector of all possible colors: White, Black, Blue, Red or Yellow. Then ask the user to enter the number of colleagues he will be questioning. Then take the color suggestions, and for every entry I compare it against the vector. If it is in there, I pop the color out. Eventually only one color will be left in the vector which is the color of the lost mug.
My issue:
I get an out of bound error after entering the first color and I am not able to figure out why. The exact error is:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
Abort (core dumped)
My code is:
#include <iostream>
#include <string>
#include <algorithm>
#include <climits>
#include <stdio.h>
#include <vector>
using namespace std;
int main(int argv, char* argc[])
{
string color;
vector<string> colorVector;
colorVector.push_back("White");
colorVector.push_back("Black");
colorVector.push_back("Blue");
colorVector.push_back("Red");
colorVector.push_back("Yellow");
int numColleagues;
cout<< "Please enter the number of Colleagues" << endl;
cin >> numColleagues;
cout<< "Please enter each suggested color" << endl;
int counter = 0;
while (counter < numColleagues) {
getline(cin, color);
counter++;
for (int i = 0; i < 5; i++) {
if (colorVector.at(i) == color) {
colorVector.erase(colorVector.begin() + i);
}
}
}
return 0;
}
You are erasing elements of your vector, but you wish to access all five elements (the loop runs from 0 to 5). So, let's say you remove the first and then you try to access the element at position 4. Out of bounds!
So change your loop to this:
colorVector.erase(std::remove(colorVector.begin(),
colorVector.end(), color), colorVector.end());
More on erase-remove idiom.
When you call vector::erase, it will return an iterator pointing to the new location of the element that followed the erased element. So if we erase this element:
1 2 3 4 5 6
^
Our iterator will automatically update to point to the 5. So we don't have to increment the iterator again, it's already sort of incremented. With that in mind:
auto it = colorVector.begin();
for (; it != colorVector.end(); /* do not increment it */ )
{
if (*it == color)
{
it = colorVector.erase(it); // erase and update
}
else
{
++it; // just update
}
}
Of course even better to just use the algorithms which are less error prone
colorVector.erase(
std::remove(colorVector.begin(), colorVector.end(), color),
colorVector.end()
);
You are modifying colorVector during an iteration.
As soon as you remove one of the colors, the vector is suddenly only 4 items in length. Now when you try to go to the 5th item (which was safe to do before the deletion) - it crashes
Try this:
for (int i = 0; i < colorVector.size(); i++) {
if (colorVector.at(i) == color) {
colorVector.erase(colorVector.begin() + i);
--i;
}
}
By stopping at colorVector.size instead of a hard-coded 5 you are ensured that the list never goes out of bounds.
Edit:
Added --i statement to avoid skipping next one
Edit2:
As the comments below state, it is generally a bad idea to remove items from the array you're currently iterating from.

c++ stack maze solving program

I wrote a program to generate a maze and to solve it, however it has some bug in the solving part.
It forms a square maze like 5*5 or 16*16.
The maze starts at (0,0 in a 2D array, and ends at (size()-1, size()-1).
I use '1' to indicate the path to end.
You can see from the picture below there are some unwanted '1' although the program can find the exit.
Excuse me everyone, I really can't debug this. Can anyone help me or guide me?
Much appreciated!
The screencapure is here. Im not allowed to post image directly
https://photos-1.dropbox.com/t/0/AADjdwSgmLdVKCZrI1C-gDvwZ9ORj0rGbv3UJ7AYqXWeuA/10/7014161/png/2048x1536/2/1355295600/0/2/bug.png/5sQR3E_jcow4lWIy9cFf2FYbmwl0C_sd2cfCyMPe0MU
My code is in here
https://www.dropbox.com/s/vldkcv4fy6bp1ff/Source.cpp
PROBLEM SOLOVED
Thanks everyone
my original code for solving the maze was
`else if (randomNum==1) {
if (y+1<myMaze.size() && !myMaze[x][y+1].left && !myMaze[x][y+1].visited)
{
y++;
myMaze[x][y].truePath=true;
myMaze[x][y].visited=true;
s1.push(myMaze[x][y]);
randomNum=rand()%4;
}
else
{
rightBusted=true;
randomNum=rand()%4;
}`
Then I just add these codes inside the if-statement to reset the bool variables to false, then the problem solved
downBusted=false;
rightBusted=false;
topBusted=false;
leftBusted=false;
You can debug this, man. Here's how. You already have the tools you need to do it; all they need is a little tweaking.
Your best tool for debugging this is your displayMaze() routine. You just need to add two optional parameters to it to turn it into a powerful debugging tool:
void displayMaze(const vector < vector<Cell> >& arr, int curX=-1, int curY=-1)
{
.
.
.
Now if a caller omits curX & curY, the compiler fills in the defaults of -1. Now later on in that function, print a different character to indicate the "current maze position". Here's how I did it, which "seems to work" but I'm not guaranteeing it because I didn't bother to actually understand your logic:
if (curX>=0 && curY>=0 && curX==i/2 && curY==j) // ++++++++++++
cout << " * "; // * means "current position" // ++++++++++++
else if (!arr[i/2][j].truePath)
cout << " ";
else
cout << " 1 ";
Now you have a formidable debugging tool built into your program. When main() calls it without the two extra parameters, no asterisk is printed. But when you call it from solveMaze(), you can specify the "current location" so it will flag that location with '*'. In solveMaze(), add a couple variables for keeping track of the "current location"...
int x=0, y=0;
int curX=x, curY=y; // ++++++++++++++++
...then, at the top of your loop, just call your formidable debugging tool so you get the current status of your overall solution as it progresses, step-by-step:
int i=0;
while (!exitFound)
{
displayMaze(myMaze, curX, curY); // +++++++++++++++++
.
.
.
Now, wherever you change what you consider to be the "current location", just update curX and curY accordingly, and your debug tool will keep you updated so you can see the solution as it unfolds graphically (well, pseudo-graphically). You might even add debug cout messages at key logic decision points, so you can correlate those decision points with the solution you see unfolding, so you can see if/when there's a problem. And if you find a problem, you can scroll back up in your output to see where things went wrong.
Good luck!

C++ selecting a number of random items without repeating

Write a program that randomly selects from a bag of eight objects.
Each object can be red, blue, orange, or green, and it can be a ball or a cube.
Assume that the bag contains one object for each combination (one red ball, one
red cube, one orange ball, one orange cube, and so on). Write code similar to
Example 5.3, using two string arrays—one to identify colors and the other to
identify shapes.
I am trying to write a program to carry out the above exercise - the problem I am having is the same object can be selected more than once each time.
This is the code so far
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
int rand_0toN1(int n);
void choose_object();
char *colour[4] =
{"Red", "Blue", "Orange", "Green"};
char *object[2] =
{"Ball", "Cube"};
int main()
{
int n, i;
srand(time(NULL)); // Set seed for randomizing.
while (1) {
cout << "Enter no. of objects to draw ";
cout << "(0 to exit): ";
cin >> n;
if (n == 0)
break;
for (i = 1; i <= n; i++)
choose_object();
}
return 0;
}
void choose_object() {
int c; // Random index (0 thru 4) into
// colours array
int o; // Random index (0 thru 2) into
// object array
c = rand_0toN1(4);
o = rand_0toN1(2);
cout << colour[c] << "," << object[o] << endl;
}
int rand_0toN1(int n) {
return rand() % n;
}
Let's try to solve this by making a real world analogy:
Let's say you have a massive jar of marbles, of the colors listed above. It's so massive (infinite size!) that you always have the same chance to draw a marble of a given color, always 1/4 each time.
How would you do this in real life? Would you just keep picking randomly, chucking the marble away as you draw it? Or would you maybe keep a little list of things you've drawn already?
Or maybe you only have one of each in the jar... You wouldn't put it back in would you? Because that's kind of what you're doing here.
Each of these thought paths will lead you to a good solution. I don't want to provide a code or anything because this kind of assignment is one that teaches you how to think like a computer.
Since this is homework, I'm not going to give an exact answer, but describe what you could do:
Keep a list of objects you've already chosen.
After you choose an object, compare that object to the list of objects you've already chosen. If it's in the list, choose another object. If it's not in the list, add it to the list.
Make sure that you don't try to choose more than 8 objects, or else you'll end up in an infinite loop in part 2.
These would go in your choose_object() subroutine. You could do it in a while() loop, something like:
int seen_before = 0;
while(!seen_before) {
pick your random numbers
if(numbers not in list) {
add to list
break
}
}