Hey guys,
Im making an uno card game and I think so far so good, however once I compile it, my program doesnt read any errors, but a box pops up stating "vector subscript out of range" and it is confusing me a lot. I think I can identify where the problem is, I just have no idea how to go about fixing it or even trying something different.
My code is in 5 different files but I will put 3 of them here. Hopefully its not too confusing. Any help would be greatly appreciated.
Header File
#ifndef UNODECK_H
#define UNODECK_H
#include <iostream>
#include <vector>
#include "unoNumberCard.h"
using namespace std;
class UnoDeck {
vector<UnoNumberCard> draw_pile;
vector<UnoNumberCard> discard_pile;
public:
UnoDeck();
void discard(UnoNumberCard);
UnoNumberCard top_discard();
UnoNumberCard draw();
void shuffle();
};
#endif
UnoDeck Cpp file
#include <iostream>
#include <cstdlib>
#include "unoDeck.h"
using namespace std;
UnoDeck::UnoDeck() {
for (int k=0; k<2; k++) {
UnoNumberCard c1("Red",k);
draw_pile.push_back(c1);
UnoNumberCard c2("Blue",k);
draw_pile.push_back(c2);
UnoNumberCard c3("Yellow",k);
draw_pile.push_back(c3);
UnoNumberCard c4("Green",k);
draw_pile.push_back(c4);
}
UnoNumberCard c5("Red",0);
draw_pile.push_back(c5);
UnoNumberCard c6("Blue",0);
draw_pile.push_back(c6);
UnoNumberCard c7("Yellow",0);
draw_pile.push_back(c7);
UnoNumberCard c8("Green",0);
draw_pile.push_back(c8);
}
int randrange(int first, int last) {
return (rand()%(last-first))+first;
}
void UnoDeck::shuffle() {
for (int i(0); i<75; i++) {
swap(draw_pile[i],draw_pile[randrange(i+1,76)]);
}
}
void UnoDeck::discard(UnoNumberCard b){
discard_pile.push_back(b);
}
UnoNumberCard UnoDeck::top_discard() {
return discard_pile.back();
}
UnoNumberCard UnoDeck::draw(){
if (draw_pile.empty()){
UnoNumberCard temp= discard_pile.back();
discard_pile.pop_back();
while(!discard_pile.empty()){
draw_pile.push_back(discard_pile.back());
discard_pile.pop_back();
}
discard_pile.push_back(temp);
shuffle();
draw_pile.push_back(discard_pile.back());
discard_pile.pop_back();
}else{
draw_pile.back();
}
return draw_pile.back();// I have a feeling something here is affecting my program
}
Cpp file containing main which creates a UnoDeck variable, and do the following 152 times
(i.e. twice through the deck): print the top discarded card, draw a new
card, and discard it. Because the deck will be shuffled partway
through, the order of the cards the second time will be different than the first.
#include <iostream>
#include <cstdlib> // for srand
#include <ctime> // for time
#include "unoDeck.h"
#include "unoNumberCard.h"
using namespace std;
int main () {
srand((int)time(0)); // seed the random number generator with the current time
UnoDeck d;
d.shuffle();
UnoNumberCard tempo("Blue",8);//I think this will have to change eventually, but for now I put blue and 8 to test
for(int m; m=152; m++){//
tempo = d.draw();
tempo.print();
UnoNumberCard discard_pile(tempo);
}
}
Any one have any ideas?