I'm trying to count how many instances or the class mole2 there are and store the number in a public static variable called mole_count.
mole2.h
#ifndef mole2_h
#define mole2_h
#include "Arduino.h"
class mole2 {
public:
mole2(int input, int output);
void popUp();
void popdown();
boolean moleBrainThinkPopUpNow();
void setUpTimer(int up_timer);
boolean didMoleGetHit();
void setRecoveryTimer(int recovery_timer);
void decrementRecoveryTimer();
boolean dosePlayerMistMole();
void moleReset();
int input, output;
static int mole_count;
static int odds_of_poping;
private:
boolean _is_popped = false;
int _up_timer = 0;
int _recovery_timer = 0;
};
#endif
mole2.cpp
#include "Arduino.h"
#include "mole2.h"
int mole2::odds_of_poping = 10;
mole2::mole2(int input, int output) {
input = input;
output = output;
int mole2::mole_count = mole2::mole_count + 1;
pinMode(input, INPUT);
pinMode(output, OUTPUT);
}
void mole2::popUp() {
_is_popped = true;
digitalWrite(input, HIGH);
}
void mole2::popdown() {
_is_popped = false;
digitalWrite(input, LOW);
}
boolean mole2::moleBrainThinkPopUpNow() {
if (_recovery_timer == 0 && _is_popped == false && rand() % odds_of_poping == 1) {
popUp();
return true;
}
else {
return false;
}
}
void mole2::setUpTimer(int up_timer) {
_up_timer = up_timer;
}
boolean mole2::didMoleGetHit() {
if (_is_popped == true && digitalRead(input) == HIGH) {
popdown();
_up_timer = 0;
return true;
}
else {
return false;
}
}
void mole2::setRecoveryTimer(int recovery_timer) {
_recovery_timer = recovery_timer;
}
void mole2::decrementRecoveryTimer() {
if (_recovery_timer > 0) {
_recovery_timer--;
}
}
boolean mole2::dosePlayerMistMole() {
if (_is_popped == true && _up_timer > 0) {
_up_timer--;
}
if (_is_popped == true && _up_timer == 0) {
popdown();
return true;
}
else {
return false;
}
}
void mole2::moleReset() {
popdown();
_up_timer = 0;
_recovery_timer = 0;
}
FullError
Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Uno"
C:\Users\Strings\Documents\Arduino\libraries\mole2\mole2.cpp: In constructor 'mole2::mole2(int, int)':
C:\Users\Strings\Documents\Arduino\libraries\mole2\mole2.cpp:9:25: error: qualified-id in declaration before '=' token
int mole2::mole_count = mole2::mole_count + 1;
^
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
First this:
int mole2::mole_count = mole2::mole_count + 1;
has no sense: you're declaring something and assigning it to its value + 1
Anyway, you already declared mole_count in your class. Since you're in the constructor, you're in the mole2 class already (the "qualified-id" bit comes from here), so you just have to do:
mole_count++;
Also, you have to declare storage for the variable in the .cpp class & initialize it:
int mole2::mole_count = 0;
You have to do the same thing as with odds_of_poping:
Definition:
int mole2::mole_count = 0; // initialization can be ommited as static variables are initialized to the default value
and later just increment: ++mole_count;
int mole2::mole_count has already been defined. This is trying to make another int mole2::mole_count. Lose the int and assign to the pre-existing variable.
You also need to allocate storage for and initialize mole_count. Place
int mole2::mole_count = 0; // replace 0 if starting with more than 0 mole2s
in somewhere around
int mole2::odds_of_poping = 10;
in mole2.cpp
Also watch out for
input = input;
output = output;
The compiler doesn't know whether you want to use the passed parameter input or the class's input so it will pick the closest defined input, the parameter, on both sides of the = . Refrain from reusing the same variable names in the same places at the same times.
This can be resolved by explicitely stating
this->input = input;
this->output = output;
Or (my favourite!) by using the member initializer list
mole2::mole2(int input, int output): input(input), output(output) {
But to prevent other confusion you should still not repeat the names.
Related
I have been reading for a while, but today I can't figure someting out and find a solution.
How to return a function pointer from a function table as parameter? All similair solutions don't work for this one and end up not compiling.
I have tried a lot of methods but the compiler always returns with errors like:
function returning function is not allowed solution (when using typedef void (*func)();)
As NO parameters have to be passed into the final routine it should be possible.
My simplified example:
void PrintOne(void) { printf("One")};
void PrintTwo(void) { printf("Two")};
struct ScanListStruct
{
int Value;
void (*Routine)(void);
}
const ScanListStruct DoList[] =
{
{1, PrintOne},
{2, PrintTwo}
}
bool GetRoutine(void *Ptr, int Nr)
{
for (int x =0; x<=1; x++)
{
if (DoList[x].Value = Nr)
{
Ptr = DoList[(x)].Routine;
//((*DoList[(x)].Routine)()); // Original Working and executing version!
return true;
}
}
return false;
}
void main(void)
{
int y = 1;
void (*RoutineInMain)(); // Define
if (GetRoutine( RoutineInMain, y) == true) // get the address
{
RoutineInMain(); // Execute the function
}
}
There a few things wrong with the code;
Syntax errors (missing ; etc.)
main must return int
GetRoutine should accept the function pointer by reference, not just a void* pointer to anything
if condition should contain an equality test, not an assignment
As follows, works as expected;
void PrintOne(void) { printf("One"); };
void PrintTwo(void) { printf("Two"); };
struct ScanListStruct
{
int Value;
void (*Routine)(void);
};
const ScanListStruct DoList[] =
{
{1, &PrintOne},
{2, &PrintTwo}
};
bool GetRoutine(void (*&Ptr)(), int Nr)
{
for (int x =0; x<=1; x++)
{
if (DoList[x].Value == Nr)
{
Ptr = *DoList[(x)].Routine;
//((*DoList[(x)].Routine)()); // Original Working and executing version!
return true;
}
}
return false;
}
int main(void)
{
int y = 1;
void (*RoutineInMain)(); // Define
if (GetRoutine( RoutineInMain, y) == true) // get the address
{
RoutineInMain(); // Execute the function
}
}
Prints One.
You have lots of errors in your code. Like here you put the comas at the wrong place:
void PrintOne(void) { printf("One")};
void PrintTwo(void) { printf("Two")};
It should be
void PrintOne(void) { printf("One");}
void PrintTwo(void) { printf("Two");}
And here you are using the wrong operator, = instead of ==.
if (DoList[x].Value = Nr)
When the argument Ptr is a pointer, and that is passed by value, so the value assigned in the function will not be available when the function returns.
This is how your code should be:
void PrintOne(void) { printf("One"); }
void PrintTwo(void) { printf("Two"); }
typedef void(*prototype)();
struct ScanListStruct
{
int Value;
prototype Routine;
};
const ScanListStruct DoList[] =
{
{ 1, PrintOne },
{ 2, PrintTwo }
};
bool GetRoutine(prototype &Ptr, int Nr)
{
for (int x = 0; x <= 1; x++)
{
if (DoList[x].Value == Nr)
{
Ptr = DoList[(x)].Routine;
return true;
}
}
return false;
}
int main()
{
int y = 1;
prototype RoutineInMain; // Define
if (GetRoutine(RoutineInMain, y) == true) // get the address
{
RoutineInMain(); // Execute the function
}
return 0;
}
I will start by explaining my issue, and then provide a good portion of the code.
I and filling a queue with a custom class called process. Using this line:
ProcessQueue.push(new Process(inputs[0], inputs[1], inputs[2], inputs[3], inputs[4]));
This all seems well and good, when the loop is done Process queue is filled with pointers.
However upon further inspection I found out they all point to the SAME object?
Finding this curious, I stepped into the constructor on each iteration of the loop.
First iteration: when the constructor is entered all instance variables are null (as expected)
Second iteration: upon entering the constructor, all instance variables contain the values given to the object in the first iteration (ie: the same object)
Furthermore later when I use the queue I have confirmed that every pointer in the queue is referring to the same process object. (I can tell this because process contains a state and if loop through the queue changing the state, I will find the state already changed for the second pointer)
I suspect I must have done something wrong with the creation of me class. so here it is in its entirety.
Process.h
#pragma once
class Process
{
public:
Process(int _processId, int _arrivalTime, int _CPUTime,
int _IOFrequency, int _IODuration);
~Process();
bool HasArrived(int time);
bool HasCompleted();
bool HasFinishedBurst();
bool HasFinishedIO();
int GetQueueNum();
int GetID();
void SetQueueNum(int i);
void SetToReady();
void Run();
void PerformIO();
};
Process.cpp
#include "stdafx.h"
#include "Process.h"
#include <string>
using namespace std;
int processId;
int arrivalTime;
int CPUTime;
int IOFrequency;
int IODuration;
int Ticks;
int CPUConsumption;
int CPUBurstSize;
int queueNumber;
int IOBurstCount;
string state;
Process::Process(int _processId, int _arrivalTime, int _CPUTime,
int _IOFrequency, int _IODuration)
{
processId = _processId;
arrivalTime = _arrivalTime;
CPUTime = _CPUTime;
IOFrequency = _IOFrequency;
IODuration = _IODuration;
IOBurstCount = 0;
CPUConsumption = 0;
Ticks = 0;
queueNumber = 0;
state = "None";
printf("%d: %s\n", processId,state.c_str());
int excess = CPUTime % IOFrequency;
if (excess == 0)
{
CPUBurstSize = CPUTime / IOFrequency;
}
else
{
CPUBurstSize = (CPUTime - excess) / (IOFrequency - 1);
}
}
Process::~Process()
{
}
bool Process::HasArrived(int time)
{
if (arrivalTime <= time)
{
if (state.compare("Newly Arrived") == 0)
{
printf("Already arrived!\n");
}
state = "Newly Arrived";
printf("%d: %s\n", processId, state.c_str());
return true;
}
else
{
return false;
}
}
bool Process::HasCompleted()
{
if (CPUConsumption == CPUTime && IOBurstCount == IOFrequency)
{
state = "Finished";
printf("%d: %s\n", processId, state.c_str());
return true;
}
else
{
return false;
}
}
bool Process::HasFinishedBurst()
{
if (Ticks == CPUBurstSize)
{
Ticks = 0;
state = "Blocked";
printf("%d: %s\n", processId, state.c_str());
return true;
}
else
{
return false;
}
}
bool Process::HasFinishedIO()
{
if (Ticks >= IODuration)
{
IOBurstCount++;
Ticks = 0;
return true;
}
else
{
return false;
}
}
void Process::SetToReady()
{
state = "Ready";
printf("%d: %s\n", processId, state.c_str());
}
void Process::Run()
{
state = "Running";
printf("%d: %s\n", processId, state.c_str());
Ticks++;
CPUConsumption++;
}
void Process::PerformIO()
{
Ticks++;
}
int Process::GetQueueNum()
{
return queueNumber;
}
void Process::SetQueueNum(int i)
{
queueNumber = i;
}
int Process::GetID()
{
return processId;
}
I suspect I have somehow created this as a static class without meaning too...
It seems you have placed all your member variables outside the class!
int processId;
int arrivalTime;
int CPUTime;
int IOFrequency;
int IODuration;
int Ticks;
int CPUConsumption;
int CPUBurstSize;
int queueNumber;
int IOBurstCount;
string state;
Should be here:
class Process
{
public:
Process(int _processId, int _arrivalTime, int _CPUTime,
int _IOFrequency, int _IODuration);
~Process();
bool HasArrived(int time);
bool HasCompleted();
bool HasFinishedBurst();
bool HasFinishedIO();
int GetQueueNum();
int GetID();
void SetQueueNum(int i);
void SetToReady();
void Run();
void PerformIO();
private:
int processId;
int arrivalTime;
int CPUTime;
int IOFrequency;
int IODuration;
int Ticks;
int CPUConsumption;
int CPUBurstSize;
int queueNumber;
int IOBurstCount;
string state;
};
You defined global variables
int processId;
int arrivalTime;
int CPUTime;
int IOFrequency;
int IODuration;
and the constructor of class Process each time when it is called overrides their values.
Process::Process(int _processId, int _arrivalTime, int _CPUTime,
int _IOFrequency, int _IODuration)
{
processId = _processId;
arrivalTime = _arrivalTime;
CPUTime = _CPUTime;
IOFrequency = _IOFrequency;
IODuration = _IODuration;
IOBurstCount = 0;
CPUConsumption = 0;
Ticks = 0;
queueNumber = 0;
//...
While the class itself has no data members.
So these global variables keep that values that were assigned to them in the last call of the constructor.
I've been looking around and haven't come up with any tangible solutions. It sounds like it is looking for a default constructor instead of the one in place but I have one below. Moving it up as the first listed constructor didn't change the error messages so I'm wrong about that. Here's the full error message (using jGRASP):
In file included from intset.h:47:0,
from IntSet.cpp:1:
IntSet.cpp:12:11: error: expected unqualified-id before 'int'
IntSet(int a, int b, int c, int d, int e) {
^
IntSet.cpp:12:11: error: expected ')' before 'int'
Here's the IntSet.cpp code:
#include "intset.h"
//#include <algorithm>
//#include <iostream>
int size;
const int MAXSIZE = 25000;
bool set[MAXSIZE];
const int SENTINEL = -1;
//Constructors
IntSet(int a, int b, int c, int d, int e) {
size = a;
if(b > size) {
size = b;
}
if(c > size) {
size = c;
}
if(d > size) {
size = d;
}
if(e > size) {
size = e;
}
set = new bool[size];
for(int i = 0; i <= size; i++) {
if(i == a || i == b || i == c || i == d || i == e) {
insert(i);
} else {
remove(i);
}
}
}
IntSet(int a, int b, int c, int d) {
IntSet(a, b, c, d, -1);
}
IntSet(int a, int b, int c) {
IntSet(a, b, c, -1, -1);
}
IntSet(int a, int b) {
IntSet(a, b, -1, -1, -1);
}
IntSet(int a) {
IntSet(a, -1, -1, -1, -1);
}
//Copy constructor
IntSet(const IntSet& x) {
size = x.size;
for (int i = 0; i <= x.size; i++ ) {
set[i] = x.set[i];
}
}
//Destructor
~IntSet()
{
//for(int i = this.length(); i >= 0; i--) {
// this[i]
//}
}
////////////////////////
bool insert(int a) {
if(a <= size && a >= 0) {
set[a] = true;
return true;
}
else if(a >= 0) {
//removed "new" from line below
IntSet temp = IntSet(a);
&this += temp;
set[a] = true;
return true;
}
return false;
}
bool remove (int a) {
if (isInSet(a)) {
set[a] = false;
return true;
}
return false;
}
bool isEmpty() {
bool retVal = true;
for (int i = 0; i <= size; i++) {
if (set[i] == true) {
retVal = false;
}
}
return retVal;
}
bool isInSet (int a) {
if (set[a]){
return true;
}
return false;
}
/////////////////////////////////////////////
IntSet operator + (IntSet a) {
IntSet c = IntSet(max(size, a.size));
for (int i = 0; i <= c.size; i++) {
if (set[i] || a.set[i]){
c.set[i] = true;
}
else {
c.set[i] = false;
}
}
return c;
}
IntSet operator * (IntSet a) {
IntSet c = IntSet(max(size, a.size));
for (int i = 0; i <= c.size; i++) {
if (set[i] && a.set[i]) {
c.set[i] = true;
}
else {
c.set[i] = false;
}
}
return c;
}
IntSet operator - (IntSet a) {
IntSet c = IntSet();
c.size = 0;
for (int i = 0; i <= size; i++) {
if (set[i] && !a.set[i]) {
c.set[i] = true;
}
else {
c.set[i] = false;
}
c.size++;
}
return c;
}
IntSet operator = (const IntSet a) {
return IntSet(a);
}
IntSet operator += (IntSet a) {
return IntSet(operator+(a));
}
IntSet operator *= (IntSet a) {
return IntSet(operator * (a));
}
IntSet operator -= (IntSet a) {
return IntSet(operator - (a));
}
IntSet operator == (const IntSet a) const{
for(int i = 0; i < size; i++) {
if(set[i] != a.set[i]) {
return false;
}
}
return true;
}
IntSet operator != (IntSet a) {
for(int i = 0; i < size; i++) {
if(set[i] != a.set[i]) {
return true;
}
}
return false;
}
IntSet operator << (IntSet a) {
cout << "{";
for(int i = 0; i < size; i++) {
if(set[i]) {
cout << " " << i;
}
}
cout << "}";
}
IntSet operator >> (IntSet a) {
int index;
while(cin >> index && index != SENTINEL) {
insert(index);
}
}
Here is the attached intset.h code:
#ifndef INTSET_H
#define INTSET_H
#include <iostream>
#include <algorithm>
using namespace std;
class IntSet {
public:
//Constructors
IntSet();
IntSet(int);
IntSet(int, int);
IntSet(int, int, int);
IntSet(int, int, int, int);
IntSet(int, int, int, int, int);
IntSet(const IntSet&); // M: Added the &; must be a pointer or reference
~IntSet();
//Overloaded Operators M: Added 'IntSet' in front of the word 'operator.'
// It was required syntax.
IntSet operator+(IntSet);
IntSet operator*(IntSet);
IntSet operator-(IntSet);
IntSet operator=(IntSet);
IntSet operator+=(IntSet);
IntSet operator*=(IntSet);
IntSet operator-=(IntSet);
IntSet operator==(IntSet);
IntSet operator!=(IntSet);
IntSet operator<<(IntSet);
IntSet operator>>(IntSet);
//Functions
bool insert(int);
bool remove(int);
bool isEmpty();
bool isInSet(int);
private:
const int MAXSIZE;
int size;
bool set[];
const int SENTINEL;
};
#include "IntSet.cpp"
#endif
I haven't had much experience with header files so it wouldn't surprise me if I formatted something incorrectly but I'm looking at plenty of other samples provided by the professor and there isn't anything unusual about mine. I thought maybe it had something to do with the order listed in the .h file and that I wasn't following the same exact order in the .cpp but nothing changed when I had everything listed in the same order.
There is a lot that is wrong with your code. We are going to have to jump around a bit between the header and the implementation. Ready?
In your header you do this:
class IntSet {
/* stuff */
private:
bool set[];
};
First of all, the name set is a bad choice: it is the name of a class in namespace stdw which you are importing by having using namespace std in your header file. This can be confusing at best.
More importantly, the syntax bool set[] isn't correct in this context. Even if your compiler allows it, it's an extension. Who knows what it does and how it will behave on other compilers? Avoid it.
If you want to declare an array, declare an array. If you want to declare a pointer, declare a pointer. Just remember: an array isn't a pointer.
Unfortunately you don't, becase later on in your code you do this:
set = new bool[size];
What is this supposed to do? set isn't a pointer, it's some kind of array, and you cannot assign a pointer to an array.
Now, we get to the second problem: you declare some member variables for your class, in your header file:
class IntSet {
/* some stuff here */
private:
const int MAXSIZE;
int size;
bool set[];
const int SENTINEL;
};
Then in your implementation you have the following code floating up at the top:
int size;
const int MAXSIZE = 25000;
bool set[MAXSIZE];
const int SENTINEL = -1;
I don't think that this does what you think it does. It seems that your intention is to initialize those variables, but that's not what happens. Remember, those variables only exist as members variables that belong to a particular instance of a class, and they are not "free-standing". So what's happening here?
Well, this declares all these variables again, so you have variables called MAXSIZE, size, set and SENTINEL that are valid anywhere in that translation unit (i.e. the .cpp file), independent of the member variables in the class.
This, of course, means that the member variables with those names aren't initialized (well, except set which you assign a pointer to, which we already know is wrong). This will cause your code to exhibit undefined behavior. After all, the value of an uninitialized variable can be anything at all.
If your intention had been to initialize the class members, then you should remove that code and initialize those variables in your constructor(s):
IntSet::IntSet(int a, int b, int c, int d, int e)
: size(a), MAXSIZE(25000), SENTINEL(-1)
{
/* whatever*/
}
Notice, by the way, how I used IntSet:: in front of the constructor name? This is called the scope resolution operator. Remember, there is no constructor called IntSet. The constructor belongs to a class, which is called IntSet, and outside of that class, it's proper name is IntSet::IntSet. A small example may help:
class Test
{
int Length;
public:
/* notice how inside the class, you only need Test
* when providing a body for the constructor. This
* makes sense. You know which class you inside of.
*/
Test()
: Length(0)
{
}
Test(int len);
};
/* Now we are outside the class. We need to help
* the compiler out and tell it what class the
* function belongs to.
*/
Test::Test(int len)
: Length(len)
{
}
A tangential point as to do with the names that you are using. What's a? Why do you use a to initialize something called size? You should choose meaningful variables names that help document the code so that when you have to read it back your head doesn't explode.
Another tangential point is that if variables like MAXSIZE and SENTINEL are going to be shared between all instances of the class, then, for future reference, you should probably consider making them static class members.
Lastly, you have this bit of code in your header file
#include "IntSet.cpp"
This is, almost certainly, not correct. You should never do this (there may be some who think that there are exceptions, but don't learn bad habits at this point. When you know enough to stumble on this legitimately, then you will know enough to determine whether it's the right thing to do or not).
What makes it worse is that your implementation file contains:
#include "IntSet.h"
Think about what you are doing here: when the compiler is processing the file IntSet.h you are telling to also process the file IntSet.cpp. The file IntSet.cpp tells the compiler to process the file IntSet.h. Which tells the compiler to process the file IntSet.cpp. And so on and so forth.
Generally speaking, implementation files (.cpp) will include header files. Header files will only include other header files.
There are a few other issues, but you should probably fix all these things, and then, if you are still having issues, post a new question and we can go from there.
Good luck!
You need to put the name of the class and :: before defining a member function.
IntSet::IntSet(int a, int b, int c, int d, int e) {
//^^^^^^^^
//here
Do the same with the other constructors, the operators and methods.
Hey so I have three 2 classes: Screen, and Sprite : that depend on each other so if i define one i can not implement the second class to be defined into it as it has not been definded yet! Is there any simple solution to this that does not require a lot of re-coding?
Heres each class definition (Map is also a class):
the Sprite Class: move() wont work without the Screen Class definition....
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// Sprite Class ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Sprite
{
public:
///////////////////// Get and SET all the privates ///////
Sprite(){};
Sprite(string a_name, char a_symbol, float a_health){
_name = a_name;
_symbol = a_symbol;
_health = a_health;};
char get_symbol() {return _symbol;};
void set_symbol(char _sym) {_symbol = _sym;};
float get_health() {return _health;};
void set_health(float _numb) {_health = _numb;};
void add_health (float _numb) {_health += _numb;};
string get_name() {return _name;};
string set_name(string _aName) {_name = _aName;};
int* get_location(){return _location;};
void set_location(int X, int Y) {
_location[0] = X;
_location[1] = Y;};
//////////////////////////////// Move ////////////
// WONT WORK UNTIL UNLESS SCEEN CLASS IS DEFINED BEFORE IT
bool move(Screen screen,int X, int Y)
{
bool OK = true;
////////////////////// check whats already there /////
char newLoc = screen.get_contents(_location[1]+Y,_location[0]+X);
if (newLoc == '|' || '/' || '_' || '=' || 'X' || 'x' )
OK = false;
if (OK == true)
{
_location[0] += X;
_location[1] += Y;
return true;
}
else
return false;
};
private:
string _name;
char _symbol;
float _health;
int _location[2];
};
And the screen class: (the sprite overloaded insert function won't work without Sprite def.
///////////////////////// SCREEN CLASS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Screen
{
private:
/////////////////////////////////////////// Screen Variables ///////////////
string _name;
vector <string> _contents;
public:
Screen(string name){_name = name;
_contents.resize(24);};
~Screen(){};
//////////////////////////////////////////// Get contents ///////////////////////////
string get_contents(int Y) {return _contents[Y];};
char get_contents(int X, int Y) {return _contents[Y][X];};
//////////////////////////////////////////// Display (1 FPS) ///////////////////////////
void Display(int numbRefreshes) //
{ //
for(int t = 0; numbRefreshes > t;) //
{ //
UL_2 = GetTickCount()+overSec-UL_1; // Get Time in Milliseconds since start //
// GATE TO GETTING INTO THE DISPLAY FUNCTION (every 1 sec)
if (UL_2 >= 1000) //
{ //
overSec += 1000 - UL_2; //
// Wait another second before update (1000 milliseconds) //
UL_1+=1000; //
UL_3+= 1; //
char UL_3_string[6]; //
itoa(UL_3, UL_3_string, 10); //
// Tell the for loop 1 render is complete (/////)
t+=1; // (///)
// Update the time counter (/)
int B = sizeof(UL_3_string); // |
for(int I = 0; I < sizeof(UL_3_string); I++)
Screen::Insert(UL_3_string[I], 38+I, 22);
/////////////////// Draw each line of the Screen
for (unsigned int I = 0; I < _contents.size(); I++)
{
cout << _contents[I];
}
//////////////// draw any empty lines NOT WORKING WTF???????
for(int emptyLines = 24-_contents.size(); emptyLines > 0; emptyLines--)
{
cout << endl;
}
}
}
};
/////////////////////////////////////////// Insert ////////////////////////
/////////////////// map
bool Insert(Map& _map)
{
for (unsigned int I = 0; I<_map.getContents().size();I++)
{
_contents[I] = _map.getContents()[I];
}
return true;
};
/////////////////// string
bool Insert(string _string, int Y)
{
_contents[Y] = _string;
return true;
};
///////////////////// char
bool Insert(char _char, int X, int Y)
{
_contents[Y][X] = _char;
return true;
};
//////////////////// sprite
bool Insert(Sprite& _sprite)
{
_contents[_sprite.get_location()[0]][_sprite.get_location()[1]] = _sprite.get_symbol();
};
};
Screen theScreen("theScreen");
Thanks for any help!! =)
I would redesign - I can't see why a sprite needs to know about a screen. And what is this:
if (newLoc == '|' || '/' || '_' || '=' || 'X' || 'x' )
supposed to be doing? That is not how you test things in C++.
Other problems - don't pass strings by value, pass them as const references, and don't begin names with underscores.
First, split your classes to .h files and .cpp files, then use forward declaration (google for it, I can't post link). There are a few other errors in your code, you might like Bjarne Stroustrup's book "Language c++"
This is for a poker game and I have class PokerTable defined in PokerTable.h
#include <iostream>
using namespace std;
class PokerTable
{
private:
int numPlayers;
int numPlaying;
int dealerPos;
int bigBlind;
int potSize;
int betSize;
bool flop;
bool turn;
bool river;
public:
//constructors
PokerTable();
PokerTable(int,int,int,int,int,bool,bool,bool);
//getters
int getNumPlayers(){return numPlayers;};
int getDealerPos(){return dealerPos;};
int getBigBlind(){return bigBlind;};
int getNumPlaying(){return numPlaying;};
int getPotSize(){return potSize;};
int getBetSize(){return betSize;};
bool getFlop(){return flop;};
bool getTurn(){return turn;};
bool getRiver(){return river;};
//void buttonShow(int);
//setters
void setBetSize(int inBetSize){betSize = inBetSize;};
void setBigBlind(int inBigBlind){bigBlind = inBigBlind;};
void setNumPlaying(int inNumPlaying){numPlaying = inNumPlaying;};
void setPotSize(int inPotSize){potSize = inPotSize;};
void setFlop(bool inFlop){flop = inFlop;};
void setTurn(bool inTurn){turn = inTurn;};
void setRiver(bool inRiver){river = inRiver;};
void setNumPlayers(int inPlayers){numPlayers = inPlayers;};
void setDealerPos(int inDealerPos){dealerPos = inDealerPos;};
};
PokerTable::PokerTable()
{
numPlayers = 9;
numPlaying = 9;
dealerPos = 1;
bigBlind = 20;
flop = false;
turn = false;
river = false;
}
PokerTable::PokerTable(int playerNum, int playingCount, int posDealer, int blindBig,int inPotSize, bool inFlop,bool inTurn,bool inRiver)
{
numPlayers = playerNum;
numPlaying = playingCount;
dealerPos = posDealer;
potSize = inPotSize;
bigBlind = blindBig;
flop = inFlop;
turn = inTurn;
river = inRiver;
}
In my watch list pokerTable.numPlayers has a random value up to 4 million before I even execute this next line of code.
PokerTable aPokerTable(9,9,1,20,30,false,false,false);
and afterwards here is pokerTable in my watch list:
- aPokerTable { numPlayers=2990892 numPlaying=9 dealerPos=9 ...} PokerTable
betSize 30 int
bigBlind 1 int
dealerPos 9 int
flop false bool
numPlayers 2990892 int
numPlaying 9 int
potSize 20 int
river false bool
turn false bool
Can anyone tell me why all the values are not what I declared them to be??!?!!
And how I can fix this?
This is Form1.h
#pragma once
#include "PokerTable.h"
#include "Card.h"
#include <time.h>
#include "PokerPlayer.h"
#include <fstream>
#include <string>
#include <sstream>
//global variables
//TODO make players start from 0
int firstPlayer;
int deck[52];
int nextCard=0;
PokerTable aPokerTable(9,9,1,20,30,false,false,false);
PokerPlayer players[9]; //however many players
ofstream gameLog;
/*
void setTable()
{
aPokerTable.setNumPlayers(9);
aPokerTable.setNumPlaying(9);
aPokerTable.setDealerPos(1);
aPokerTable.setBigBlind(20);
aPokerTable.setPotSize(30);
aPokerTable.setBetSize(20);
aPokerTable.setFlop(false);
aPokerTable.setTurn(false);
aPokerTable.setRiver(false);
}
*/
string convertInt(int number) //convert to string
{
stringstream ss;//create a stringstream
ss << number;//add number to the stream
return ss.str();//return a string with the contents of the stream
}
void createPlayers()
{
// aPokerTable.setNumPlayers(9);
for(int x=0;x<=(aPokerTable.getNumPlayers()-1);x++)
{
players[x] = *(new PokerPlayer(1000,(aPokerTable.getDealerPos())+1,false,0,1));//1000 chips, position i+1, not folded
}
}
void playRound()
{
int action;
for(int playerTurn = firstPlayer; playerTurn <= aPokerTable.getNumPlayers()+firstPlayer; playerTurn++)
{
if(players[playerTurn].getFold() == false)
{
if(aPokerTable.getNumPlaying() == 1)
{
players[playerTurn].setChipStack(players[playerTurn].getChipStack() + aPokerTable.getPotSize()); //player wins pot
}
else //there is more than one person playing
{
action = players[playerTurn].action(); //0 is check/fold, value is call/bet/raise,
if(action > aPokerTable.getBetSize())
{
aPokerTable.setBetSize(action);
aPokerTable.setPotSize(aPokerTable.getPotSize() + action);
playerTurn = playerTurn - aPokerTable.getNumPlayers();
}
else if (action == aPokerTable.getBetSize()) //call
{
aPokerTable.setPotSize(aPokerTable.getPotSize() + action);
}
else //action < aPokerTable.betSize
{
players[playerTurn].setFold(true);
aPokerTable.setNumPlaying(aPokerTable.getNumPlaying()-1); //removes player from playing tally
}
}
}
}
}
void randomDeck()
{
int random_integer;
int tempCard;
//srand((unsigned)time(0));
for(int j=0;j<=51;j++)
{
deck[j] = j;
}
for(int i=51; i>=1; i--)
{
random_integer = rand()%(i); //a random number between 0 and i
tempCard = deck[i];
deck[i] = deck[random_integer]; //put the random card from unshuffled deck into slot i of the deck
deck[random_integer] = tempCard; //put whatever was at slot i into the random slot
}
}
void dealCards()
{
for(int j=1;j<=aPokerTable.getNumPlayers();j++)
{
players[j].setCard1(deck[nextCard]);
nextCard++;
players[j].setCard2(deck[nextCard]);
nextCard++;
}
}
void playPreFlop()
{
aPokerTable.setBetSize(aPokerTable.getBigBlind());
aPokerTable.setFlop(false); //it is before the flop
aPokerTable.setTurn(false);
aPokerTable.setRiver(false);
randomDeck(); //shuffle cards
dealCards();
firstPlayer = (aPokerTable.getDealerPos() + 3)%(aPokerTable.getNumPlayers()); // first player is left of blinds between 0 and numplayers
playRound();
}
void playFlop()
{
aPokerTable.setFlop(true);
firstPlayer = (aPokerTable.getDealerPos())%aPokerTable.getNumPlayers(); // first player is left of dealer between 0 and numplayers
aPokerTable.setBetSize(0);
playRound();
}
void playTurn()
{
aPokerTable.setTurn(true);
firstPlayer = (aPokerTable.getDealerPos())%aPokerTable.getNumPlayers(); // first player is left of dealer between 0 and numplayers
aPokerTable.setBetSize(0);
playRound();
}
void playRiver()
{
aPokerTable.setRiver(true);
firstPlayer = (aPokerTable.getDealerPos())%(aPokerTable.getNumPlayers()); // first player is left of dealer between 0 and numplayers
aPokerTable.setBetSize(0);
playRound();
if(aPokerTable.getNumPlaying() >=2)
{
//showDown();
}
}
/*
void showDown()
{
}
*/
This is pokerPlayer.h
using namespace std;
class PokerPlayer
{
private:
int chipStack,position;
bool fold;
int card1,card2;
public:
//constructors
PokerPlayer();
PokerPlayer(int,int,bool,int,int);
//getters
int getChipStack() {return chipStack;}
int getPosition() {return position;}
int getCard1(){return card1;}
int getCard2(){return card2;}
bool getFold(){return fold;}
//setters
void setChipStack(int inChips){chipStack = inChips;}
void setPosition(int inPos){position = inPos;}
void setCard1(int inCard1){card1 = inCard1;}
void setCard2(int inCard2){card2 = inCard2;}
void setFold(bool inFold){fold = inFold;}
int action();
};
PokerPlayer::PokerPlayer()
{
chipStack = 1000;
position = 0;
fold=false;
card1 = 0;
card2 = 1;
}
PokerPlayer::PokerPlayer(int inChipStack,int inPos, bool inFold, int inCard1, int inCard2)
{
chipStack = inChipStack;
position = inPos;
fold = inFold;
card1 = inCard1;
card2 = inCard2;
}
int PokerPlayer::action()
{
return 0;
}
aPokerTable { numPlayers=2990892 numPlaying=9 dealerPos=9 ...}
Note that dealerPos got assigned the value 9, that's wrong as well. If you look closely, you'll see that everything is shifted by 4 bytes.
Two possible reasons. The debugger could have picked the wrong address for aPokerTable, the actual address minus 4. That's unlikely. Or there's a mismatch between the definition of the PokerTable class as seen by pokertable.cpp and the other .cpp files that #include the pokertable.h include file. Where pokertable.cpp saw an extra member before the numPlayers member. Maybe you edited the header and deleted that member but ended up not recompiling pokertable.cpp for some mysterious reason. Build + Rebuild to fix. Do panic a bit if this actually works.
It's because in C++ before the constructor is called, variable uses the value that it already contains in its memory location that is a "random" value
I cannot reconstruct it because i dont have the full code. However, a random value near 4 million sounds like a pointer. When you store or retrieve a member variable maybe you did not de-reference the pointer. Please post the rest of the code so we can check if that's the case.
players[x] = *(new PokerPlayer(...));
That is a memory leak. What you probably want is:
players[x] = PokerPlayer(1000,(aPokerTable.getDealerPos())+1,false,0,1);