I DONT WANT TO CONVERT ANYTHING :)
I'm making a small copy of poker for myself.
#include <iostream>
#include <ctime>
#include <string>
#include <cstdlib>
#include <windows.h>
using namespace std;
void welcome();
void rules();
void game();
void rateDeck(string deck[], int decksize);
bool findCard(string deck[], string card);
int main(){
srand(time(NULL));
welcome();
rules();
getchar();
game();
return 0;
}
void welcome(){
cout << "\t WELCOME \t" << endl;
cout << " TO THE POKER SIMULATOR" << endl;
cout << "\t KIND OF \t" << endl << endl;
}
void rules(){
cout << " \t RULES" << endl;
cout << "1. You get 5 cards at the beginning." << endl << "2. You can always pick more cards." << endl << "3. It's not a game. You just look at your cards and pick more." << endl << endl << "Have fun :)" << endl;
cout << endl << "PRESS ANYTHING TO START A GAME" << endl;
}
void game(){
// 24 cards
// Tr - trefl, Ka - Karo, Ki - Kier, Pi - Pik
// A - As, K - Krol, D - Dama, W - Walet, 10, 9
string cards[] = {
"TrA", "TrK", "TrD", "TrW", "Tr10", "Tr9",
"KaA", "KaK", "KaD", "KaW", "Ka10", "Ka9",
"KiA", "KiK", "KiD", "KiW", "Ki10", "Ki9",
"PiA", "PiK", "PiD", "PiW", "Pi10", "Pi9" };
string randomCard, lastCard;
bool repeat;
int decksize = 5;
string mydeck[] = {"KaA", "PiD", "KiW", "Ka10", "Pi9"};
system("cls");
cout << "My deck: " << endl;
for (int i=0; i<decksize; i++){
randomCard = cards[rand() % 24];
mydeck[i] = randomCard;
for (int j=0; j<=i-1; j++){
do{
mydeck[i] = randomCard;
if (mydeck[i]!=mydeck[j]) repeat=false;
} while(mydeck[j]==mydeck[i] && i!=0 && repeat==true);
}
if (i==0) cout << "karta nr: " << i << " " << mydeck[i] << endl;
else cout << "karta nr: " << i << " " << mydeck[i] << " Last Card:" << lastCard << endl;
lastCard = mydeck[i];
}
rateDeck(mydeck, decksize);
}
void rateDeck(string deck[], int decksize){
int royalFlush = 0;
int straightFlush = 0;
int fourOfKind = 0;
int fullHouse = 0;
int flush = 0;
int streigh = 0;
int threeOfKind = 0;
int twoPairs = 0;
int onePair = 0;
for (int i=0; i<decksize; i++){
string card[i] = { deck[i] };
if (i==decksize-1){
if( findCard(deck, decksize, "TrA") == true ) royalFlush+=1;
//&& findCard(deck, decksize, "TrK") && findCard(deck, decksize, "TrQ") && findCard(deck, decksize, "TrJ") && findCard(deck, decksize, "Tr10") ) royalFlush+=1;
}
}
}
bool findCard(string deck[], int decksize, string card){
for(int i=0; i<decksize; i++){
if(deck[i]==card) return true;
else return false;
}
}
void rateDeck(string deck[], int decksize){
for (int i=0; i<decksize; i++){
string card[i] = { deck[i] };
if (i==decksize-1){
if( findCard(deck, decksize, "TrA") == true ) royalFlush+=1;
}
}
}
Function findCard() goes through the deck and looks for a card. If it exists it return true, otherwise false. The problem is in the last line - if statement.
Result:
error: could not convert 'decksize' from 'int' to 'std::__cxx11::string' {aka'std::__cxx11::basic_string<char>'}|
Btw. function is called in another function where "deck" is "string deck[]" and "decksize" is "int decksize".
Edit1: rateDeck func is used to describe the deck. If there is a Flush or Full House (Poker names) it should show it.
Related
The requirements for the program state that the try/catch must be placed in the main.cpp as below:
cout << "printing the array element by element using: int getElement(int);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
try{
elementResult = mylist.getElement(i);
cout << elementResult << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
When it accesses the method:
int MyList::getElement(int passedIndex){
if((passedIndex < 0) || (passedIndex > length -1)){
throw 0;
}
return array[passedIndex];
}
It doesn't seem to matter which variation of throwing I use, my array gets destroyed afterward. It works fine if it stays within bounds, or I work it to not throw from the method (doing the error checking elsewhere), but the requirements state that it has to be that way, so I must be missing something. Full code below:
main.h:
#ifndef MAIN_H
#define MAIN_H
/***********************************
* DO NOT MODIFY THIS FILE OTHER THAN
* TO ADD YOUR COMMENT HEADER
***********************************/
#include <iostream> /* cout, endl */
#include "mylist.h"
#include <stdexcept>
#define LISTSIZE 10
using std::cout;
using std::endl;
int elementResult;
#endif /* MAIN_H */
main.cpp:
#include "main.h"
int main(int argc, char** argv) {
/***********************************
* DO NOT MODIFY THIS FILE OTHER THAN
* TO ADD YOUR COMMENT HEADER AND
* UNCOMMENT THINGS AS YOU COMPLETE
* THE FUNCTIONALITY OF YOUR LIST OBJECT
***********************************/
/* This will create a "list" of size LISTSIZE
* and initialize it to all zeros */
cout << "create and initialize mylist" << endl;
MyList mylist(LISTSIZE);
mylist.printArray();
cout << endl;
/* This will set the list to all 50 */
cout << "set mylist to all 50" << endl;
mylist.setArray(50);
mylist.printArray();
cout << endl;
/* This will fail and set the array to the
* default random 1-10 values */
cout << "attempt to set to random numbers -2 to 4" << endl;
mylist.setRandom(-2,4);
mylist.printArray();
cout << endl;
/* This will fail and set the array to the
* default random 1-10 values */
cout << "attempt to set to random numbers 4 to 4" << endl;
mylist.setRandom(4,4);
mylist.printArray();
cout << endl;
/* This will succeed and set the array to the
* random 1-100 values */
cout << "attempt to set to random numbers 1 to 100" << endl;
mylist.setRandom(1,100);
mylist.printArray();
cout << endl;
/* This will succeed and set the array to the
* random 500-1000 values */
cout << "attempt to set to random numbers 500 to 1000" << endl;
mylist.setRandom(1000,500);
mylist.printArray();
cout << endl;
/* These next two sets will succeed and set the 1st and last
* elements to 1000 and 2000 respectively */
if(mylist.setElement(1000, 0)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
if(mylist.setElement(2000, LISTSIZE-1)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
mylist.printArray();
cout << endl;
/* These next two sets will fail and leave the array unmodified */
if(mylist.setElement(9999, -1)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
if(mylist.setElement(9999, LISTSIZE)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
mylist.printArray();
cout << endl;
cout << "Testing new and/or modified code..." << endl << endl;
cout << "printing the array element by element using: int getElement(int);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
try{
elementResult = mylist.getElement(i);
cout << elementResult << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
mylist.printArray();
cout << "attempting to get element 4000 using: int getElement(int);" << endl;
try{
cout << mylist.getElement(4000) << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
cout << endl;
cout << "printing the array element by element using: int getElement(int,int*);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
if(mylist.getElement(i, &elementResult)){
cout << elementResult << endl;
} else {
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
cout << "attempting to get element 4000 using: int getElement(int,int*);" << endl;
if(mylist.getElement(4000, &elementResult)){
cout << elementResult << endl;
} else {
cout << "Error: Index out of range." << endl;
}
return 0;
}
mylist.h:
#ifndef MYLIST_H
#define MYLIST_H
#include <iostream> /* cout, endl */
#include <stdlib.h> /* srand, rand, atoi */
#include <time.h> /* time */
#include <stdexcept>
// you can add libraries if you need them, but you shouldn't
// DO NOT MODIFY THESE DEFINES
#define RMIN 1
#define RMAX 10
#define DEFAULT_SIZE 10
using std::cout;
using std::endl;
class MyList {
public:
// DO NOT MODIFY THESES NEXT TWO
MyList(int); // constructor
~MyList(); // destructor
int getElement(int);
void setArray(int);
bool setElement(int, int);
void setRandom(int, int);
void printArray();
bool getElement(int, int*);
private:
// these are the only attributes allowed
// DO NOT ADD OR MODIFY THEM
int length;
int *array;
};
#endif //MYLIST_H
mylist.cpp:
#include "mylist.h"
// constructor
MyList::MyList(int size) {
srand(time(NULL)); // call only once!
if(size < 1){
size = DEFAULT_SIZE;
}
MyList::length = size;
MyList::array = new int(size);
setArray(0);
}
// destructor
MyList::~MyList() {
//delete[] MyList::array;
}
void MyList::printArray() {
cout << "[";
for (int i = 0; i < length; i++){
if (i == length - 1){
cout << array[i];
}else{
cout << array[i] << " ";
}
}
cout << "]" << endl;
}
void MyList::setArray(int setArrayTo){
for (int i = 0; i < length; i++){
MyList::array[i] = setArrayTo;
}
}
void MyList::setRandom(int numOne, int numTwo){
bool isValidRandom = true;
int randMin, randMax;
if((numOne < RMIN) || (numTwo < RMIN) || (numOne == numTwo)){ isValidRandom = false; }
if(isValidRandom == true){
if(numTwo < numOne){
randMin = numTwo;
randMax = numOne;
} else {
randMin = numOne;
randMax = numTwo;
}
} else {
randMin = RMIN;
randMax = RMAX;
}
for(int i = 0;i < length; i++){
MyList::array[i] = rand() % randMax + randMin;
}
}
bool MyList::setElement(int passedValue, int arrayIndex){
bool isInRange = true;
if ((arrayIndex < 0)||(arrayIndex > length - 1)){
isInRange = false;
}
if (isInRange == true){
MyList::array[arrayIndex] = passedValue;
}
return isInRange;
}
int MyList::getElement(int passedIndex){
if((passedIndex < 0) || (passedIndex > length -1)){
throw 0;
}
return array[passedIndex];
}
bool MyList::getElement(int passedIndex, int *iPtr){
bool isItValid = true;
if((passedIndex >= 0) && (passedIndex < length)){
*iPtr = MyList::array[passedIndex];
} else {
isItValid = false;
}
return isItValid;
}
Output
I am implementing class of wizards in this code but I have a serious problem with finding relation in wizards family tree. I am using a back tracking method to find all relation between two nodes but memory will start to being messed up in the middle of the task and I have no idea what should I do.
Here you can see implementation of this class using C++.
#include "Wizard.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
Wizard::Wizard(string first_name, string surname, string occupation, string organization, string wand)
: first_name(first_name),surname(surname), occupation(occupation), organization(organization), wand(wand)
{
this->married=0;
this->wand="Dragon Hearstring";
this->occupation="Auror";
this->organization="Dumbledore Army";
};
void Wizard::set_first_name(string _name){
this->first_name = _name;
}
void Wizard::set_surname(string _surname){
this->surname = _surname;
}
void Wizard::set_occupation(string _occupation){
this->occupation = _occupation;
}
void Wizard::set_organization(string _organization){
this->organization = _organization;
}
void Wizard::set_wand(string _wand){
this->wand = _wand;
}
string Wizard::get_name(){
string name;
name = first_name + " " + surname;
return name;
}
string Wizard::get_occupation(){
return occupation;
}
string Wizard::get_organization(){
return organization;
}
string Wizard::get_wand(){
return wand;
}
void Wizard::print_parents(){
cerr << "Parents: ";
for (int i=0; i<parents.size(); i++){
cout << parents[i]->get_name();
if ( i!= parents.size() -1){
cout << " & ";
}
}
cout << endl;
}
void Wizard::print_siblings(){
cerr <<"Siblings: ";
for (int i=0; i<siblings.size(); i++){
cout << siblings[i]->get_name();
if ( i < siblings.size() -1){
cout << " & ";
}
}
cout << endl;
}
void Wizard::print_spouse(){
cerr <<"Spouse: ";
if (married==1)
cout << spouse->get_name();
cout << endl;
}
void Wizard::print_children(){
cerr <<"Children: ";
for (int i=0; i<children.size(); i++){
cout << children[i]->get_name();
if ( i < children.size() - 1){
cout << " & ";
}
}
cout << endl;
}
void Wizard::operator*(Wizard& _spouse){
this->married=1;
_spouse.married=1;
cout << this->get_name() << " and " << _spouse.get_name() << endl;
this->spouse = &_spouse;
_spouse.spouse = this;
_spouse.print_spouse();
vector< Wizard* > these_two;
these_two.push_back(this);
these_two.push_back(&_spouse);
for (int i=0; i<this->children.size(); i++)
children[i]->parents = these_two;
for (int i=0; i<_spouse.children.size(); i++)
children[i]->parents = these_two;
}
void Wizard::operator+(Wizard& _child){
if (!search_in_vector(this->children,&_child))
this->children.push_back(&_child);
if (!search_in_vector(this->spouse->children,&_child))
this->spouse->children.push_back(&_child);
vector< Wizard* > these_two;
these_two.push_back(this);
these_two.push_back(this->spouse);
_child.parents=these_two;
_child.surname = this->surname;
for (int i=0; i<this->children.size(); i++){
if(!search_in_vector(_child.siblings,children[i]) && (children[i]!=&_child)){
_child.siblings.push_back(children[i]);
children[i]->siblings.push_back(&_child);
}
}
}
void Wizard::print_relation_with(Wizard& john_doe){
vector<string> path2;
vector< vector< string > > path1;
vector<Wizard*> nodes_in_the_way;
nodes_in_the_way.push_back(this);
if (this->get_name() == john_doe.get_name()){
cout << this->get_name() << " is " << john_doe.get_name() << endl;
return;
}
this- >search_for_relation(*this,john_doe,path1,path2,nodes_in_the_way);
if (path1.size() == 0){
cout << "no relation" << endl;
return;
}
path2=path1[0];
for (int i=1;i<path1.size();i++){
if (path1[i].size() < path2.size())
path2=path1[i];
}
cout << this->get_name() << " is ";
for (int i=0; i<path2.size(); i++)
cout << path2[i] << " of ";
cout << john_doe.get_name() << endl;
}
void Wizard::search_for_relation(Wizard& a,Wizard& b,vector< vector<string> > &path1,vector<string> &path2,vector< Wizard* > &nodes_in_the_way){
cerr << "////////////" << endl;
cerr << "IM INSIDE " << a.get_name() << " , SEARCHING FOR " << b.get_name() << " - " << path2.size() << endl;
cout << "PATH: ";
for (int i=0;i<nodes_in_the_way.size();i++)
cout << nodes_in_the_way[i]->get_name() << " ";
cout << endl;
a.print_spouse();
a.print_children();
a.print_parents();
if (a.get_name() == b.get_name() && path2.size()==0){
return;
}
if (a.get_name() == b.get_name() ){
path1.push_back(path2);
return;
}
if (a.married){
if (!search_in_vector(nodes_in_the_way,a.spouse)){
path2.push_back("spouse");
nodes_in_the_way.push_back(a.spouse);
search_for_relation(* (a.spouse),b,path1,path2,nodes_in_the_way);
path2.pop_back();
nodes_in_the_way.pop_back();
}
}
// parents
for (int i=0;i<a.parents.size();i++){
if (!search_in_vector(nodes_in_the_way,a.parents[i])){
path2.push_back("child");
nodes_in_the_way.push_back(a.parents[i]);
search_for_relation(* (a.parents[i]),b,path1,path2,nodes_in_the_way);
path2.pop_back();
nodes_in_the_way.pop_back();
}
}
// children
for (int i=0;i<a.children.size();i++){
if (!search_in_vector(nodes_in_the_way,a.children[i])){
path2.push_back("parent");
nodes_in_the_way.push_back(a.children[i]);
search_for_relation(* (a.children[i]),b,path1,path2,nodes_in_the_way);
path2.pop_back();
nodes_in_the_way.pop_back();
}
}
}
///////////// NON-METHOD FUNCITONS ///////////////
bool search_in_vector(vector< Wizard* > a,Wizard* b){
for (int i=0; i<a.size(); i++)
if (a[i]->get_name() == b->get_name())
return true;
return false;
}
So that was the code.
Here you can see the output after some back_tracking:
Here you see that Harry's information has been messed up during last recursion and the executable file can't print his parents.
Please let me know that I'm doing wrong! Thanks!
I'm at a bit of a roadblock and I just can't seem to figure out where I went wrong. Essentially, I just want to pass the values from the array in the test code to a vector via constructor and then print the contents of the vector. For whatever reason, I can't even hit the for loop that starts to add the array values to the vector.
header code:
#pragma once
#ifndef BoxOfProduce_H
#define BoxOfProduce_H
#include <vector>
#include <iostream>
#include <cstdlib> //for exit
using namespace std;
class BoxOfProduce
{
public:
BoxOfProduce();
BoxOfProduce(string customerId, int size, bool doRandom, bool okDuplicates, std::string productList[], int listSize);
void addBundle(string productList);
void displayBox();
private:
string customerID;
vector<string> test;
vector<string> bundles;
bool allowDuplicates;
bool buildRandom;
int size;
};
#endif
// End of dayOfYear.h
BocOfProduce.cpp
#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <algorithm>
#include <cstdlib> //for exit
using namespace std;
#include "BoxOfProduce.h"
vector<string> tempbundles;
bool isInVect = false;
BoxOfProduce::BoxOfProduce()
{
customerID = "No Name";
allowDuplicates = true;
buildRandom = false;
}
BoxOfProduce::BoxOfProduce(string customerId, int size, bool doRandom, bool okDuplicates, string productList[], int listSize)
{
customerID = customerId;
buildRandom = doRandom;
allowDuplicates = okDuplicates;
size = size;
for (int k = 0; k > listSize; k++)
{
tempbundles.push_back(productList[k]);
cout << "added to temp" << endl;
}
if (allowDuplicates == false)
{
for (int k = 0; k > listSize; k++)
{
tempbundles.push_back(productList[k]);
cout << "added to temp" << endl;
}
for (int i = 0; i < listSize; i++)
{
for (int j = 0 + 1; j < listSize; j++)
{
if (tempbundles[i] == bundles[j])
{
isInVect = true;
}
if (isInVect == false)
{
bundles.push_back(tempbundles[i]);
cout << "added to isinvect bundle" << endl;
}
}
}
}
else if (allowDuplicates == true)
{
for (int k = 1; k > listSize; k++)
{
bundles.push_back(productList[k]);
cout << "added to normal bundle" << endl;
}
}
}
void BoxOfProduce::addBundle(string productList)
{
for (int k = 1; k > 100; k++)
{
bundles.push_back(productList);
}
}
void BoxOfProduce::displayBox()
{
cout << "custome ID is: " << customerID << "\n" << endl;
std::cout << std::boolalpha;
cout << "-buildRandom set to " << buildRandom << endl;
cout << "-allowDuplicates set to " << allowDuplicates << endl;
cout << "Contents of box: " << customerID << " with size: " << size << endl;
test.push_back("test");
for (int i = 0; i < bundles.size(); i++)
{
cout << bundles[i] << "\n";
}
cout << "\n" << endl;
}
Test code:
#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <algorithm>
#include <cstdlib> //for exit
#include "BoxOfProduce.h"
using namespace std;
int main()
{
srand(1234); // Seed random generator for random additions of products
const int LISTSIZE = 12;
string produceList[] = { "Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo",
"Mango", "Spinach", "Cucumber", "Radish", "Chard", "Spinach", "Mango" };
cout << "Original list of produce:" << endl;
for (int i = 0; i < LISTSIZE; i++)
{
cout << "item[" << i << "] = " << produceList[i] << endl;
}
// Test BoxOfProduce class
cout << endl << "Start with empty box0" << endl;
BoxOfProduce box0; // Default constructor creates empty box
cout << "Display box0:" << endl;
box0.displayBox(); // Display the empty box
cout << endl; // Skip a line
cout << "Add all products from the produceList[] to box0 allowing duplicates:"
<< endl;
for (int i = 0; i < LISTSIZE; i++)
box0.addBundle(produceList[i]); // Duplicates allowed in box
cout << "Display box0 again after loading with products:" << endl;
box0.displayBox();
cout << endl;
BoxOfProduce box1("Box-1", 4, false, true, produceList, LISTSIZE);
box1.displayBox();
BoxOfProduce box2("Box-2", 4, true, false, produceList, LISTSIZE);
box2.displayBox();
BoxOfProduce box3("Box-3", 8, true, true, produceList, LISTSIZE);
box3.displayBox();
BoxOfProduce box4("Box-4", 12, true, true, produceList, LISTSIZE);
box4.displayBox();
BoxOfProduce box5("Box-5", 12, true, false, produceList, LISTSIZE);
box5.displayBox(); // This box produces an error message
}
Thank you for any and all help!
your problem is that in case of duplicate you use the list size for bundle and tempbundle which is not the case this should fix check the code for BocOfProduce.cpp
vector<string> tempbundles;
bool isInVect = false;
BoxOfProduce::BoxOfProduce()
{
customerID = "No Name";
allowDuplicates = true;
buildRandom = false;
}
BoxOfProduce::BoxOfProduce(string customerId, int size, bool doRandom, bool okDuplicates, string productList[], int listSize)
{
customerID = customerId;
buildRandom = doRandom;
allowDuplicates = okDuplicates;
size = size;
tempbundles = vector<int>() ; // set temp bundles to empty vector
for (int k = 0; k < listSize; k++) //k was >listSize it should be <
{
tempbundles.push_back(productList[k]);
cout << "added to temp" << endl;
}
if (allowDuplicates == false)
{
for (int k = 0; k < listSize; k++)
{
tempbundles.push_back(productList[k]);
cout << "added to temp" << endl;
}
for (int i = 0; i < listSize; i++)
{
isInVect = false;
for (int j = 0 + 1; j < bundles.size(); j++)
{
if (tempbundles[i] == bundles[j])
{
isInVect = true;
}
}
if (isInVect == false)
{
bundles.push_back(tempbundles[i]);
cout << "added to isinvect bundle" << endl;
}
}
}
else if (allowDuplicates == true)
{
for (int k = 1; k < listSize; k++)
{
bundles.push_back(productList[k]);
cout << "added to normal bundle" << endl;
}
}
}
void BoxOfProduce::addBundle(string productList)
{
for (int k = 1; k > 100; k++)
{
bundles.push_back(productList);
}
}
void BoxOfProduce::displayBox()
{
cout << "custome ID is: " << customerID << "\n" << endl;
std::cout << std::boolalpha;
cout << "-buildRandom set to " << buildRandom << endl;
cout << "-allowDuplicates set to " << allowDuplicates << endl;
cout << "Contents of box: " << customerID << " with size: " << bundles.size() << endl;
test.push_back("test");
for (int i = 0; i < bundles.size(); i++)
{
cout << bundles[i] << "\n";
}
cout << "\n" << endl;
}
I'm having problems with my program's output. It keeps spitting out 12345.
Here's the details:
It's split in three files: program8.cpp (the part that runs tests), myRandom.cpp (implementation of the class), and myRandom.h (specification of the class).
myRandom.h:
#ifndef MYRANDOM_H_
#define MYRANDOM_H_
class myRandom
{
public:
myRandom(); //Constructor
~myRandom(); //Destructor
void seed(unsigned long theSeed); //Mutator for current
unsigned long next(); //Mutator or Accessor for current
int randInt(int start, int end); //Scales result to a range
double randNormal(); //Future expansion
private:
unsigned long current; //Current random #
static const unsigned long a = 1103515245; //Multiplier for LGC
static const unsigned long c = 12345; //Increment for LGC
static const unsigned long m = 2147483648; //Modulus for LGC
};
#endif /* MYRANDOM_H_ */
myRandom.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
myRandom::myRandom() //Constructor
{
current = 0;
}
myRandom::~myRandom() //Destructor
{
}
void myRandom::seed(unsigned long theSeed) //Mutator for current
{
if (theSeed < 0 || theSeed > m-1)
{
// ERROR
return;
}
else
current = theSeed;
}
unsigned long myRandom::next() //Mutator or Accessor for current
{
if (current < 0)
{
cout << "Error: cannot set seed to a negative number" << endl;
return 0;
}
else
{
current = (m*current+c)%m; //Formula
return current;
}
}
int myRandom::randInt(int start, int end) //Scales result to a range
{
if (start >= end)
{
cout << "Error: cannot set start greater than or equal to end" << endl;
return 0;
}
else
{
return ((this->next() % (end - start)) + start);
}
}
double myRandom::randNormal() //Future expansion
{
cout << "Warning: randNormal not implemented" << endl;
return 0;
}
program8.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
int main()
{
myRandom theRand;
unsigned long theSeed;
cout << "Verify that the sequence generated by next() is the same on each run" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.next() << endl;
}
cout << "Verify that you can set the seed to 0 and 1" << endl;
theSeed = 0;
cout << theRand.next() << endl;
theSeed = 1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to -1 generates an error" << endl;
theSeed = -1;
cout << theRand.next() << endl;
cout << "Verify that you can set the seed to m-2 and m-1" << endl;
theSeed = 2147483648-2;
cout << theRand.next() << endl;
theSeed = 2147483648-1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to m generates and error" << endl;
theSeed = 2147483648;
cout << theRand.next() << endl;
cout << "Verify that next() produces a sequence predicted by hand/calc for the chosen seed" << endl;
cout << "Please enter a seed: ";
cin >> theSeed;
cout << theRand.next() << endl;
cout << "Verify that using start == end generates and error. Set both to 10." << endl;
theRand.randInt(10,10);
cout << theRand.next() << endl;
cout << "Verify that using start > end generates and error. Set start to 10 and end to 5." << endl;
theRand.randInt(10,5);
cout << theRand.next() << endl;
theRand.seed(theSeed);
cout << "Testing randInt for start=0 end=1,000" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.randInt(0 , 1000) << endl;
}
return 0;
}
I think the problem lies in the next() function, since that's what gets called all those times in program8.cpp cout statements. I could understand getting 12345 once, but it should be updated once that function runs successive times. I apologize if it's a dumb question. Thank you for your time and patience.
Your problem isn't a code specific one - it is Math-related from here:
current = (m*current+c)%m;
This always returns the value of c if c < m, otherwise (or more generally) it returns c % m. Why? From this theorem:
(m*n + a)%m = a
Example:
m = 10
n = 3
a = 7
(10*3 + 7)%10 = 7
See this for more:
http://en.wikipedia.org/wiki/Modulo_operation
I've been using this code for my TicTacToe game but I want to make some changes:
first I want to introduce the name of the players, and when one of them wins, it appears on the message.
second, I want to introduce a ranking table of records, winning games and tied ones
third I want the table to be static, doesn't change in every move.
forth I want the table to have always the numbers in the square that each of them represent, and when someone chooses that position, it replaces the number for the pieace, X or O.
Now I'll post the code above of every file:
Player.h
#ifndef PLAYER_H
#define PLAYER_H
class Board;
class Player
{
public:
Player();
char GetPiece() const;
void MakeMove(Board& aBoard) const;
private:
static const int NUM_PIECES = 2;
static const char PIECES[NUM_PIECES];
static int current;
char m_Piece;
};
#endif
Player.cpp
#include "player.h"
#include "board.h"
#include <iostream>
using namespace std;
const char Player::PIECES[NUM_PIECES] = {'X', 'O'};
int Player::current = 0;
Player::Player()
{
m_Piece = PIECES[current];
current = (current + 1) % NUM_PIECES;
}
char Player::GetPiece() const
{
return m_Piece;
}
void Player::MakeMove(Board& aBoard) const
{
int move;
do
{
cout << "Player " << GetPiece();
cout << ", where would you like to move? (0-8): ";
cin >> move;
} while (!aBoard.IsLegalMove(move));
aBoard.ReceiveMove(GetPiece(), move);
}
Board.h
#ifndef BOARD_H
#define BOARD_H
class Board
{
public:
Board();
bool IsFull() const;
bool IsLegalMove(int move) const;
bool IsWinner(char piece) const;
void Display() const;
void Reset();
void ReceiveMove(char piece, int move);
static const int NUM_SQUARES = 9;
static const char EMPTY = ' ';
private:
static const int NUM_COMBOS = 8;
static const int NUM_IN_COMBO = 3;
static const int WINNING_COMBOS[NUM_COMBOS]
[NUM_IN_COMBO];
char m_Squares[NUM_SQUARES];
};
#endif
Board.cpp
#include "board.h"
#include <iostream>
using namespace std;
const int Board::WINNING_COMBOS[NUM_COMBOS]
[NUM_IN_COMBO] = { {0, 1, 2},{3, 4, 5},{6, 7, 8},{0, 3, 6},{1, 4, 7},{2, 5, 8},{0, 4, 8}, {2, 4, 6} };
Board::Board()
{
Reset();
}
bool Board::IsFull() const
{
bool full = true;
int i = 0;
while (full && i < NUM_SQUARES)
{
if (m_Squares[i] == EMPTY)
{
full = false;
}
++i;
}
return full;
}
bool Board::IsLegalMove(int move) const
{
return (move >= 0 && move < NUM_SQUARES && m_Squares[move] == EMPTY);
}
bool Board::IsWinner(char piece) const
{
bool winner = false;
int i = 0;
while (!winner && i < NUM_COMBOS)
{
int piecesInCombo = 0;
for (int j = 0; j < NUM_IN_COMBO; ++j)
{
if (m_Squares[WINNING_COMBOS[i][j]] == piece)
{
++piecesInCombo;
}
}
if (piecesInCombo == NUM_IN_COMBO)
{
winner = true;
}
++i;
}
return winner;
}
void Board::Display() const
{
cout << endl << "\t" << m_Squares[0] << " | " << m_Squares[1];
cout << " | " << m_Squares[2];
cout << endl << "\t" << "---------";
cout << endl << "\t" << m_Squares[3] << " | " << m_Squares[4];
cout << " | " << m_Squares[5];
cout << endl << "\t" << "---------";
cout << endl << "\t" << m_Squares[6] << " | " << m_Squares[7];
cout << " | " << m_Squares[8];
cout << endl << endl;
}
void Board::Reset()
{
for (int i=0; i<NUM_SQUARES; ++i)
{
m_Squares[i] = EMPTY;
}
}
void Board::ReceiveMove(char piece, int move)
{
m_Squares[move] = piece;
}
Game.h
#ifndef GAME_H
#define GAME_H
#include "board.h"
#include "player.h"
class Game
{
public:
Game();
bool IsPlaying() const;
bool IsTie() const;
void DisplayInstructions() const;
void NextPlayer();
void AnnounceWinner() const;
void Play();
private:
static const int NUM_PLAYERS = 2;
static const int FIRST = 0;
static const int SECOND = 1;
Board m_Board;
Player m_Players[NUM_PLAYERS];
int m_Current;
};
#endif
Game.cpp
#include "game.h"
#include <iostream>
using namespace std;
Game::Game():
m_Current(FIRST)
{}
bool Game::IsPlaying() const
{
return ( !m_Board.IsFull() &&!m_Board.IsWinner(m_Players[FIRST].GetPiece()) &&
!m_Board.IsWinner(m_Players[SECOND].GetPiece()) );
}
bool Game::IsTie() const
{
return ( m_Board.IsFull() &&!m_Board.IsWinner(m_Players[FIRST].GetPiece()) &&
!m_Board.IsWinner(m_Players[SECOND].GetPiece()) );
}
void Game::DisplayInstructions() const
{
cout << "\tWelcome to the ultimate intellectual
showdown: Tic-Tac-Toe.";
cout << endl << endl;
cout << "Make your move by entering a number,
0 - 8. The number" << endl;
cout << "corresponds with board position, as
illustrated:" << endl << endl;
cout << endl << "\t" << "0 | 1 | 2";
cout << endl << "\t" << "---------";
cout << endl << "\t" << "3 | 4 | 5";
cout << endl << "\t" << "---------";
cout << endl << "\t" << "6 | 7 | 8";
cout << endl << endl << "Prepare yourself. The
battle is about to begin.";
cout << endl << endl;
}
void Game::NextPlayer()
{
m_Current = (m_Current + 1) % NUM_PLAYERS;
}
void Game::AnnounceWinner() const
{
cout << "The raging battle has come to a fi nal end.";
cout << endl;
if (IsTie())
{
cout << "Sadly, no player emerged victorious.";
cout << endl;
}
else
{
cout << "The winner of this climatic ";
cout << "confrontation is Player ";
if (m_Board.IsWinner(m_Players[FIRST].
GetPiece()))
{
cout << m_Players[FIRST].GetPiece() << "!";
cout << endl;
}
else
{
cout << m_Players[SECOND].GetPiece() << "!";
cout << endl;
}
}
}
void Game::Play()
{
m_Current = FIRST;
m_Board.Reset();
while (IsPlaying())
{
m_Board.Display();
m_Players[m_Current].MakeMove(m_Board);
NextPlayer();
}
m_Board.Display();
AnnounceWinner();
}
main.cpp
#include "game.h"
#include <iostream>
using namespace std;
int main()
{
Game ticTacToe;
ticTacToe.DisplayInstructions();
char again;
do
{
ticTacToe.Play();
cout << endl << "Play again? (y/n): ";
cin >> again;
} while (again != 'n');
return 0;
}
I'm not going to write code for you, but I'm slightly bored at the moment so I will structure it somewhat so you have an idea.
You need to store the name per player, and some way to retrieve it for the winning playerwhen the game is finished.
You need to keep track of scores, store between sessions which means file i/o.
I don't understand what you want with 3 or 4.
Mi version en español y ademas lo mejoré un poquito
main.cpp
#include "Arbitro.h"
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
system("color 09");
Arbitro Triqui;
Triqui.mostrarInstrucciones();
string continuar;
cout<<"\t\t\t\t presione cualquier tecla para continuar";
continuar = (char)getch();
system("cls");
char deNuevo;
do
{
Triqui.jugar();
cout << endl << "\t\t\tQuieres jugar otra vez? (s/n): ";
cin >> deNuevo;
system ("cls");
} while (deNuevo != 'n');
cout << endl;
cout << "\t\t\t\t/////////////////////////////////////////////////////\n";
cout << "\t\t\t\t// Autor: //\n";
cout << "\t\t\t\t// //\n";
cout << "\t\t\t\t// Camilo Andres Granda Codigo: 201759710 //\n";
cout << "\t\t\t\t// //\n";
cout << "\t\t\t\t/////////////////////////////////////////////////////\n";
cout << endl;
return 0;
}
Arbitro.h
#ifndef ARBITRO_H
#define ARBITRO_H
#include "Tablero.h"
#include "Jugador.h"
class Arbitro
{
public:
Arbitro();
bool enJuego() const;
bool empate() const;
void mostrarInstrucciones() const;
void siguienteJugador();
void anunciarGanador() const;
void jugar();
private:
static const int numero_de_jugadores = 2;
static const int primero = 0;
static const int segundo = 1;
Tablero m_Tablero;
Jugador m_Jugadores[numero_de_jugadores];
int m_Actual;
};
#endif
Arbitro.cpp
#include "Arbitro.h"
#include <iostream>
using namespace std;
Arbitro::Arbitro():
m_Actual(primero)
{}
bool Arbitro::enJuego() const
{
return ( !m_Tablero.estaLleno()
&&!m_Tablero.ganador(m_Jugadores[primero].getPieza()) &&
!m_Tablero.ganador(m_Jugadores[segundo].getPieza()) );
}
bool Arbitro::empate() const
{
return ( m_Tablero.estaLleno()
&&!m_Tablero.ganador(m_Jugadores[primero].getPieza()) &&
!m_Tablero.ganador(m_Jugadores[segundo].getPieza()) );
}
void Arbitro::mostrarInstrucciones() const
{
cout << "\t\t\t
///////////////////////////////////////////////////////\n";
cout << "\t\t\t // Bienvenidos
//\n";
cout << "\t\t\t
///////////////////////////////////////////////////////\n";
cout << endl << endl;
cout << "\t\t\tHaga su movimiento ingresando un numero, [1 - 9]. El numero"
<< endl;
cout << "\t\t\tcorresponde con la posicion de la tabla, como se ilustra:" <<
endl << endl;
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| 1 | 2 | 3 |";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| 4 | 5 | 6 |";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| 7 | 8 | 9 |";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << endl << "\t\t\t\tPreparate. La partida esta a punto de
comenzar.";
cout << endl << endl;
}
void Arbitro::siguienteJugador()
{
m_Actual = (m_Actual + 1) % numero_de_jugadores;
}
void Arbitro::anunciarGanador() const
{
if (empate())
{
cout << "\t\t\tEmpate, ningun jugador gano.";
cout << endl;
}
else
{
cout << "\t\t\tEl ganador de esta partida es el jugador ";
if (m_Tablero.ganador(m_Jugadores[primero].
getPieza()))
{
cout << m_Jugadores[primero].getPieza() << "!";
cout << endl;
}
else
{
cout << m_Jugadores[segundo].getPieza() << "!";
cout << endl;
}
}
}
void Arbitro::jugar()
{
m_Actual = primero;
m_Tablero.reiniciarTablero();
while (enJuego())
{
m_Tablero.mostrarTablero();
m_Jugadores[m_Actual].hacerMovimiento(m_Tablero);
siguienteJugador();
}
m_Tablero.mostrarTablero();
anunciarGanador();
}
Jugador.h
#ifndef JUGADOR_H
#define JUGADOR_H
#include <iostream>
#include <string> // string, stoi
#include <cctype> // isdigit
#include <cstdlib> // atoi
class Tablero;
class Jugador
{
public:
Jugador();
char getPieza() const;
void hacerMovimiento(Tablero& unTablero) const;
private:
static const int numero_de_fichas = 2;
static const char fichas[numero_de_fichas];
static int actual;
char m_Ficha;
};
#endif
Jugador.cpp
#include "Jugador.h"
#include "Tablero.h"
#include <iostream>
using namespace std;
const char Jugador::fichas[numero_de_fichas] = {'N', 'B'};
int Jugador::actual = 0;
Jugador::Jugador()
{
m_Ficha = fichas[actual];
actual = (actual + 1) % numero_de_fichas;
}
char Jugador::getPieza() const
{
return m_Ficha;
}
void Jugador::hacerMovimiento(Tablero& unTablero) const
{
string linea;
int move;
do
{
cout << "\t\t\tJugador " << getPieza() << ", Donde te gustaria hacer el movimiento? [1 - 9]: ";
cin >> linea;
if (unTablero.esNumerico(linea)) {
move = atoi(linea.c_str());
} else {
cout << "\n\t\t\t\t\tError!, ingrese valor valido\n\n";
move=0;
}
} while (!unTablero.movimientoValido(move));
unTablero.recibirMovimiento(getPieza(), move);
}
Tablero.h
#ifndef TABLERO_H
#define TABLERO_H
#include <iostream>
#include <string> // string, stoi
using namespace std;
class Tablero
{
public:
Tablero();
bool esNumerico(string linea);
bool estaLleno() const;
bool movimientoValido(int move) const;
bool ganador(char ficha) const;
void mostrarTablero() const;
void reiniciarTablero();
void recibirMovimiento(char pieza, int mover);
static const int numero_de_cuadros = 10;
static const char vacio = ' ';
private:
static const int numero_de_combos = 8;
static const int numero_en_combo = 3;
string linea;
static const int combos_ganadores[numero_de_combos] [numero_en_combo];
char m_Cuadrados[numero_de_cuadros];
};
#endif
Tablero.cpp
#include "Tablero.h"
#include <iostream>
using namespace std;
const int Tablero::combos_ganadores[numero_de_combos]
[numero_en_combo] = { {1, 2, 3},{4, 5, 6},{7, 8, 9},{1, 4, 7},{2, 5, 8},{3, 6, 9},{1, 5, 9}, {3, 5, 7} };
Tablero::Tablero()
{
reiniciarTablero();
}
bool Tablero::estaLleno() const
{
bool lleno = true;
int i = 1;
while (lleno && i < numero_de_cuadros)
{
if (m_Cuadrados[i] == vacio)
{
lleno = false;
}
++i;
}
return lleno;
}
bool Tablero::movimientoValido(int mover) const
{
return (mover >= 1 && mover < numero_de_cuadros && m_Cuadrados[mover] ==
vacio);
}
bool Tablero::ganador(char ficha) const
{
bool ganador = false;
int i = 0;
while (!ganador && i < numero_de_combos)
{
int fichasEnCombo = 0;
for (int j = 0; j < numero_en_combo; ++j)
{
if (m_Cuadrados[combos_ganadores[i][j]] == ficha)
{
++fichasEnCombo;
}
}
if (fichasEnCombo == numero_en_combo)
{
ganador = true;
}
++i;
}
return ganador;
}
void Tablero::mostrarTablero() const
{
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| " << m_Cuadrados[1] << " | " << m_Cuadrados[2]; cout << " | " << m_Cuadrados[3]; cout << " | ";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| " << m_Cuadrados[4] << " | " << m_Cuadrados[5]; cout << " | " << m_Cuadrados[6]; cout << " | ";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| " << m_Cuadrados[7] << " | " << m_Cuadrados[8]; cout << " | " << m_Cuadrados[9]; cout << " | ";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << endl;
}
void Tablero::reiniciarTablero()
{
for (int i=0; i<numero_de_cuadros; ++i)
{
m_Cuadrados[i] = vacio;
}
}
void Tablero::recibirMovimiento(char pieza, int mover)
{
m_Cuadrados[mover] = pieza;
}
bool Tablero::esNumerico(string linea)
{
bool b = true;
int longitud = linea.size();
if (longitud == 0) { // Cuando el usuario pulsa ENTER
b = false;
} else if (longitud == 1 && !isdigit(linea[0])) {
b = false;
} else {
int i;
if (linea[0] == '+' || linea[0] == '-')
i = 1;
else
i = 0;
while (i < longitud) {
if (!isdigit(linea[i])) {
b = false;
break;
}
i++;
}
}
return b;
}