I’m still relatively new to C++ and programming, but having a good time learning. I’m writing a small, very simple ncurses program that so far should simply move a “#” around the screen using the WASD keys.
The problem is I am unable to change player.x in the first function Update().
Here is the code:
#include <iostream>
#include <ncurses.h>
using namespace std;
class Player
{
public:
int x;
int y;
};
void Update()
{
int z;
z = getch();
if(z == 97) //A key
{
player.x--;
}
if(z == 100) //D key
{
player.x++;
}
if(z == 119) //W key
{
player.y--;
}
if(z == 115) //S key
{
player.y++;
}
}
void Draw(int xPos, int yPos)
{
clear();
mvprintw(yPos,xPos,"#");
refresh();
}
int main()
{
initscr();
noecho();
int doContinue;
Player player;
do
{
Update();
Draw(player.x, player.y);
}while((doContinue=getch()) != 27);
endwin();
return 0;
}
Any input would be helpful!
All variables in c++ are associated with a scope. Think of scope as the visibility of that variable. In this case player is only visible with in the function it is declared in which is main. To update player you must either increase its scope and make it global (bad idea) or b. pass it into you function.
If your changed your
Updateto take a player reference you could accomplish what you attempted. The new declaration would look like this ‘void Update(Player &player)` then when you call your update function pass in the instance