I am currently writing my first game (Snake) in c++ using visual Studio, I am attempting to set the blocks you eat at random areas on the screen however when I use the rand() function it says it is undefined, does anyone know why I have this error?
#include <iostream>
using namespace std;
bool gameOver;
const int WIDTH = 20;
const int HEIGHT = 20;
int x, y, foodX, foodY, score;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN};
eDirection dir;
void Setup(){
gameOver = false;
dir = STOP;
x = WIDTH /2;
y = HEIGHT /2;
//rand function below is not defined??
//I thought the function was built in
foodX = rand() % WIDTH;
foodY = rand() % HEIGHT;
}
void Draw() {
}
void Input() {
}
void Logic() {
}
int main()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
}
return 0;
}
You're missing an include
#include <cstdlib>
http://www.cplusplus.com/reference/cstdlib/rand/
rand is defined in the header cstdlib so you need to add this include:
#include <cstdlib>
Related
So I am working on a radar. I made a version for only one ship and everything worked fine. For some reason this version does not work.
Compiler:
Error: cannot convert 'ship' to 'ship*' in assignment
Code:
#include <iostream>
#include <windows.h>
#include <ctime>
#include <cstdlib>
using namespace std;
struct ship{
char name;
int x;
int y;
};
ship setPosition(ship space_ships[], int amount);
void update(ship space_ships[], char radar[][20], int x, int y);
int main () {
srand( time( NULL ) );
ship space_ships[2];
int x = 10;
int y = 20;
char radar[10][20];
update(space_ships, radar, x, y);
return 0;
}
ship setPosition(ship space_ships[], int amount){
for (int i=0; i<amount; i++){
int liczba = rand()%10;
int znak = rand()%26 + 65;
space_ships[i].x = liczba;
space_ships[i].y = 2*liczba;
space_ships[i].name = znak;
return space_ships[i];
}
}
void update(ship space_ships[], char radar[][20], int x, int y){
space_ships = setPosition (space_ships, 2);
Sleep(2000);
system("cls");
update(space_ships, radar, x, y);
}
Any ideas?
space_ships = setPosition (space_ships, 2);
This happens because your function setPosition returns value type "ship". And then you are trying to assign this to array (space_ships).
SetPosition doesn't do what you think it does. In your case it changes position of first ship in array and exits, returning that ship's object copy.
So I'm trying to create a program that mimics the Minesweeper game. I have double-checked the header files, the class names, and made sure the headers are #included in the other cpp files, but when I try to build the program, I get a LNK2019 error in the "Main" class I have.
Error in full:
Error 1 error LNK2019: unresolved external symbol "public: __thiscall
Board::Board(int,int,int)" (??0Board##QAE#HHH#Z) referenced in
function _main \fpsb\g\gathmr26\visual studio
2013\Projects\Minesweeper\Minesweeper\Main.obj Minesweeper
I've spent probably around 2 hours looking at answers here on StackOverflow and elsewhere and got nowhere. I've run down through every bullet point in this MSDN page, and every "common cause" in this popular answer, and none of them seemed to apply to my situation. I've also tried all the "Diagnosis tools" options on the MSDN page and all they've done is just confuse me more.
The closest I have to my situation (as far as I can tell) is this question except that all of my code is just in one project, not multiple. One of the people who answered that question has said "I typed this code into my Visual Studio and it worked fine", having assumed that the files were in one project. I don't understand why that answer got it working there when I have pretty much the same situation here.
So, anyway, here is the code:
Main.cpp
#include <iostream>
#include <string>
#include "Cell.h"
#include "Board.h"
int main() {
Board *bee;
bee = new Board(50, 50, 50);
std::cout << "board created";
return 0;
}
Board.cpp
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
#include "Cell.h"
#include "Board.h"
#ifndef BOARD_H
#define BOARD_H
// Board class. Used to create an array of cell objects to function as data model for Minsweeper game.
class Board
{
private:
int width; // number of columns in board
int height; // number of rows in board
int mines; // number of mines stored in board
Cell*** cells; // array storing cell objects
public:
// Constructor for board. Takes number of columns, rows, and mines as parameters
Board::Board(int cols, int rows, int numMines) {
width = cols;
height = rows;
mines = numMines;
cells = new Cell**[height];
for (int i = 0; i < height; i++) {
cells[i] = new Cell*[width];
}
int c = 0;
int r = 0;
while (r < height)
{
while (c < width)
{
setCell(c, r, CellValue::COVERED_CELL);
c++;
}
c = 0;
r++;
}
int m = 0;
while (m < numMines)
{
std::srand(std::time(nullptr));
int x = generateRandomNumberInRange(0, width - 1);
int y = generateRandomNumberInRange(0, height - 1);
if (!(getCellVal(x, y) == MINE))
{
setCell(x, y, CellValue::MINE);
m++;
}
}
}
// Accessor for width field
int Board::getWidth()
{
return width;
}
// Accessor for height field
int Board::getHeight()
{
return height;
}
// Accessor for mines field
int Board::getMines()
{
return mines;
}
// Function to access value of cell located in array where x is column parameter and y is row parameter
CellValue Board::getCellVal(int x, int y)
{
CellValue value = CellValue::INVALID_CELL;
if (!(x < 0 || x >(width - 1) || y < 0 || y >(height - 1)))
{
Cell temp = *cells[x][y];
value = temp.getValue();
}
return value;
}
// Function to set value of cell located in array where x is column parameter and y is row parameter
void Board::setCell(int x, int y, CellValue value)
{
if (!(x < 0 || x >(width - 1) || y < 0 || y >(height - 1)))
{
Cell temp = *cells[x][y];
temp.setValue(value);
}
}
// Function to determine if game is lost
// Loops through array to see if there are any UNCOVERED_MINES
// If so, returns true, game ends, as you've lost :(
// If not, returns false and game can continue
// Should run after every click action in game
bool Board::isGameLost()
{
bool isLost = false;
int c = 0;
int r = 0;
while (r < height)
{
while (c < width)
{
if (getCellVal(c, r) == UNCOVERED_MINE)
{
isLost = true;
}
c++;
}
c = 0;
r++;
}
return isLost;
}
// Function to determine if game is won
// Loops through array to determine if there are any falsely flagged mines, unflagged mines, covered cells, or uncovered mines
// If there are, returns false and game continues
// If not, returns true, games ends, you've won :)
bool Board::isGameWon()
{
bool isWon = true;
int c = 0;
int r = 0;
while (r < height)
{
while (c < width)
{
CellValue value = getCellVal(c, r);
if ((value == FLAG) ||
(value == MINE) ||
(value == COVERED_CELL) ||
(value == UNCOVERED_MINE))
{
isWon = false;
}
c++;
}
c = 0;
r++;
}
return isWon;
}
};
#endif
Board.h
#include <iostream>
#include <string>
#include "Cell.h"
#ifndef BOARD_H
#define BOARD_H
class Cell;
enum CellValue;
class Board
{
private:
int width;
int height;
int mines;
Cell*** cells;
public:
Board(int cols, int rows, int numMines);
int getWidth();
int getHeight();
int getMines();
CellValue* getCellVal(int x, int y);
void setCell(int x, int y, CellValue value);
void uncoverCell(int x, int y);
void flagCell(int x, int y);
bool isGameLost();
bool isGameWon();
};
#endif
I know this is a common error that people have and that there's more than a handful of questions about this on StackOverflow, but at this point, I've not found any that seem to match what I have here. What is the issue here?
Seems like you're mixing header and source files. Your cpp file contains a class declaration with all the functions defined inside. This is not what a cpp file looks like. It should only contain function declarations:
Board::Board(...)
{
...
}
bool Board::IsGameWon...
etc...
I'm trying to pass an instance of this (the instance in question being the GameEngine class) into my PlayerBrain.run method which takes a GameEngine * const argument corresponding to what this is. I'm curious as to what would cause such an error to be thrown in this case, especially when there are no alternative function definitions for run() or anything like that. PlayerBrain is its own class, not descending from anything. So there's no alternative definitions to run that might cause problems. Here's the relevant code:
All public methods in PlayerBrain.h
#pragma once
#include "GameEngine.h"
#include "Species.h"
#include "Neuron.h"
#include "Genome.h"
#include "GenePool.h"
#include "Gene.h"
#include <sys/stat.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;
class PlayerBrain {
private:
int popSize;
int stalenessThreshold;
int timeoutConstant;
int currentTimeout;
int maxNodes;
int farthestDistance;
bool buttons[6]; // JASON - shoot, left, right, up, down, jump in that order
GenePool p;
bool fileExists(string filename);
bool fitnessAlreadyMeasured();
void nextGenome();
void evaluateCurrent(Genome * g);
void evaluateNetwork(vector<Neuron*> * network, vector<int> inputs);
void loadPool(string filename);
double sigmoid(double sum);
vector<int> getInputs();
Genome templateGenome();
void pressAKey();
void unPressAKey();
vector<INPUT *> oldbuttons;
public:
PlayerBrain();
void intialize();
void run(GameEngine const *);
void close();
};
The actual implementation in its .cpp
void PlayerBrain::run(GameEngine const * g) {
Genome * current = p.getCurrentGenome();
int xPos = 0;
int bossLives = 0;
double fitness;
double timeoutBonus;
unPressAKey();
if ((p.getCurrentFrame() % 5) == 0)
evaluateCurrent(current);
pressAKey();
xPos = g->getXPosAckVar();
bossLives = g->getBossLivesAckVar();
if (xPos > farthestDistance) { farthestDistance = xPos; currentTimeout = timeoutConstant; }
currentTimeout--;
timeoutBonus = p.getCurrentFrame() / 4;
if ((currentTimeout + timeoutBonus) <= 0) {
fitness = (farthestDistance - (p.getCurrentFrame() / 2)) + 2000 * bossLives;
if (fitness == 0) { fitness = -1; }
current->setFitness(fitness);
if (fitness > p.getMaxFitness()) { p.setMaxFitness(fitness); }
p.setCurrentSpecies(0);
p.setCurrentGenome(0);
while (fitnessAlreadyMeasured()) { nextGenome(); }
}
p.setCurrentFrame(p.getCurrentFrame() + 1);
}
The function call in GameEngine.cpp`
while (true)
{
......//irrelevant stuff
if (tickTimeNow > tickTimeTrigger)
{
if (dTimeTrigger > m_PaintTimeTrigger)
{
....
brain->run(this);
....
}
else Sleep(1);
}
else WaitMessage();
}
}
The error I get is as follows:
Error C2660 'PlayerBrain::run': function does not take 1 arguments
Okay, I've been running into some inconsistency and it's driving me towards a fist-sized hole in my moniter I'd rather avoid.
I'm going through an SDL tutorial on www.sdltutorials.com (the sdl-tutorial-basics tutorial I'm sure more than a few people have gone through by Tim Jones) and I ran into an error: ‘Surf_Display’ was not declared in this scope.
So, trying to figure out what's going wrong I wrote similar pointer code into an old rectangle program I used to refresh myself with the basics of C++ classes, saw the same error with an int pointer, and then tried to isolate the issue in something more specific.
Well, the more specific program compiles fine while the others explode so I'm guessing it's something pretty basic I'm missing, but GISing "C++ pointer class", etc, does nothing and I don't know how to get more specific.
Anyway...some code.
The program that works...
ct.h
#ifndef _CT_H_
#define _CT_H_
class Classtest2
{
private:
int *p_x;
public:
Classtest2();
void set_x(int);
int get_x();
};
#endif
ct.cpp
#include "ct.h"
#include <cstddef>
Classtest2::Classtest2()
{
p_x = 0;
}
void Classtest2::set_x(int x)
{
//do something neat here
}
int Classtest2::get_x()
{
return *p_x;
}
classtest2.cpp
#include "ct.h"
int main (int argc, char *argv[])
{
Classtest2 ct2;
return 0;
}
compiled with
g++ classtest2.cpp ct.h ct.cpp -o bin/classtest2
Now...the program that doesn't...
The classic...
#ifndef _RECTANGLE_H
#define _RECTANGLE_H
namespace shapes
{
class rectangle
{
public:
int height;
int width;
int *weight;
rectangle (int, int);
rectangle ();
int area ();
void setHeight(int);
void setWidth(int);
void setDimensions(int, int);
};
}
#endif
The classic cpp with weight...
#include "Rectangle.h"
#include <cstddef>
using namespace shapes;
rectangle::rectangle(int h, int w)
{
height = h;
width = w;
weight = NULL;
}
rectangle::rectangle()
{
height = 0;
width = 0;
weight = NULL;
}
int rectangle::area ()
{
return height * width;
}
void rectangle::setHeight(int h)
{
height = h;
}
void rectangle::setWidth(int w)
{
width = w;
}
void rectangle::setDimensions(int h, int w)
{
height = h;
width = w;
}
And the classic "do something simple" main...
#include "Rectangle.h"
#include <iostream>
using namespace std;
using namespace shapes;
int main(int argc, char* argv[])
{
rectangle tr(5,8);
cout << tr.height << endl;
cout << tr.width << endl;
return 0;
}
The first program compiles fine, but of course it doesn't actually do anything so that's not too surprizing. The second one (the rectangle program that also doesn't actually do anything) doesn't compile. I get the following...
g++ classtest1.cpp Rectangle.h Rectangle.cpp -o bin/classtest1
Rectangle.cpp: In constructor ‘shapes::rectangle::rectangle(int, int)’:
Rectangle.cpp:10: error: ‘weight’ was not declared in this scope
Rectangle.cpp: In constructor ‘shapes::rectangle::rectangle()’:
Rectangle.cpp:17: error: ‘weight’ was not declared in this scope
So, why can the first program "see" int *p_x while the second cannot see int *weight? I've been trying to figure out what I'm doing different and getting nowhere.
The right syntax for Rectangle.cpp is this:
#include "Rectangle.h"
#include <cstddef>
namespace shapes {
rectangle::rectangle(int h, int w)
{
height = h;
width = w;
weight = NULL;
}
rectangle::rectangle()
{
height = 0;
width = 0;
weight = NULL;
}
int rectangle::area ()
{
return height * width;
}
void rectangle::setHeight(int h)
{
height = h;
}
void rectangle::setWidth(int w)
{
width = w;
}
void rectangle::setDimensions(int h, int w)
{
height = h;
width = w;
}
} // namespace shapes
My GCC-4.4.5 and MSVC process your using namespace variant OK too. But it is not correct according to the current standard (you specify ::rectangle::area(), etc. instead of ::shapes::rectangle::area(), etc.).
You don't have errors in the code you've shown. Maybe you have a typo in int *wight declaration in Rectangle.h on your machine, but you've posted the correct code here.
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);