вывод — Почему моя программа на С ++ блэкджек работает только большую часть времени?

Моя игра в блэкджек работает примерно в 95% случаев, но иногда мне сообщают, что у меня есть туз, а я не получаю, и он будет постоянно говорить мне, что у меня есть туз в следующем цикле игры, даже когда я не играю т. Кроме того, иногда у меня в руке будет что-то вроде 8 и 2, и он скажет мне, что моя общая сумма равна 10, тогда я возьму другую карту, и она скажет мне, что моя новая общая сумма равна 40. Это просто Например, но я думаю, что тузы и общее количество ошибок иногда являются единственными проблемами, которые необходимо решить. Я также прошу прощения за неправильную загрузку, я только что присоединился к этому сайту сегодня. Вот программа:

/**
* File: blackjack blackjack.cpp
* Author: Rory Hector
* Date: 2014-04-15
* Description: Text-based blackjack game.
*/

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;

struct CardInfo
{
string cardname;
int cardvalue;
};

int main()
{
const int NUM_CARDS = 52;      // max size of the deck
CardInfo deck[NUM_CARDS];      // array of card structures
int i1, i2, oi1, oi2, g, og;   // indexes
int total, oppTotal;           // total values in your hands
int aces=0;                    // number of aces drawn by user
int maxcards = 2;              // number of cards drawn by user
char option;                   // choice to hit or stay
char cont;                     // choice to continue playing or quit
char add10;                    // changes ace value from 1 to 11
g = 0;                         // starting point for array
og = 0;                        // starting point for opponent's array
int j[8];                      // array for cards after hitting
int oj[8];                     // opponent's array for cards after hitting
int intermediate1;             // intermediate between rand # and array
int intermediate2;             // intermediate between rand # and array
int wins=0, losses=0;          // times won and times lost with initialization

srand( static_cast<unsigned int> (time(NULL)) ); // seed random number generator

deck[0].cardname = "2 of Hearts";
deck[0].cardvalue = 2;
deck[1].cardname = "2 of Diamonds";
deck[1].cardvalue = 2;
deck[2].cardname = "2 of Spades";
deck[2].cardvalue = 2;
deck[3].cardname = "2 of Clubs";
deck[3].cardvalue = 2;
deck[4].cardname = "3 of Hearts";
deck[4].cardvalue = 3;
deck[5].cardname = "3 of Diamonds";
deck[5].cardvalue = 3;
deck[6].cardname = "3 of Spades";
deck[6].cardvalue = 3;
deck[7].cardname = "3 of Clubs";
deck[7].cardvalue = 3;
deck[8].cardname = "4 of Hearts";
deck[8].cardvalue = 4;
deck[9].cardname = "4 of Diamonds";
deck[9].cardvalue = 4;
deck[10].cardname = "4 of Spades";
deck[10].cardvalue = 4;
deck[11].cardname = "4 of Clubs";
deck[11].cardvalue = 4;
deck[12].cardname = "5 of Hearts";
deck[12].cardvalue = 5;
deck[13].cardname = "5 of Diamonds";
deck[13].cardvalue = 5;
deck[14].cardname = "5 of Spades";
deck[14].cardvalue = 5;
deck[15].cardname = "5 of Clubs";
deck[15].cardvalue = 5;
deck[16].cardname = "6 of Hearts";
deck[16].cardvalue = 6;
deck[17].cardname = "6 of Diamonds";
deck[17].cardvalue = 6;
deck[18].cardname = "6 of Spades";
deck[18].cardvalue = 6;
deck[19].cardname = "6 of Clubs";
deck[19].cardvalue = 6;
deck[20].cardname = "7 of Hearts";
deck[20].cardvalue = 7;
deck[21].cardname = "7 of Diamonds";
deck[21].cardvalue = 7;
deck[22].cardname = "7 of Spades";
deck[22].cardvalue = 7;
deck[23].cardname = "7 of Clubs";
deck[23].cardvalue = 7;
deck[24].cardname = "8 of Hearts";
deck[24].cardvalue = 8;
deck[25].cardname = "8 of Diamonds";
deck[25].cardvalue = 8;
deck[26].cardname = "8 of Spades";
deck[26].cardvalue = 8;
deck[27].cardname = "8 of Clubs";
deck[27].cardvalue = 8;
deck[28].cardname = "9 of Hearts";
deck[28].cardvalue = 9;
deck[29].cardname = "9 of Diamonds";
deck[29].cardvalue = 9;
deck[30].cardname = "9 of Spades";
deck[30].cardvalue = 9;
deck[31].cardname = "9 of Clubs";
deck[31].cardvalue = 9;
deck[32].cardname = "10 of Hearts";
deck[32].cardvalue = 10;
deck[33].cardname = "10 of Diamonds";
deck[33].cardvalue = 10;
deck[34].cardname = "10 of Spades";
deck[34].cardvalue = 10;
deck[35].cardname = "10 of Clubs";
deck[35].cardvalue = 10;
deck[36].cardname = "Jack of Hearts";
deck[36].cardvalue = 10;
deck[37].cardname = "Jack of Diamonds";
deck[37].cardvalue = 10;
deck[38].cardname = "Jack of Spades";
deck[38].cardvalue = 10;
deck[39].cardname = "Jack of Clubs";
deck[39].cardvalue = 10;
deck[40].cardname = "Queen of Hearts";
deck[40].cardvalue = 10;
deck[41].cardname = "Queen of Diamonds";
deck[41].cardvalue = 10;
deck[42].cardname = "Queen of Spades";
deck[42].cardvalue = 10;
deck[43].cardname = "Queen of Clubs";
deck[43].cardvalue = 10;
deck[44].cardname = "King of Hearts";
deck[44].cardvalue = 10;
deck[45].cardname = "King of Diamonds";
deck[45].cardvalue = 10;
deck[46].cardname = "King of Spades";
deck[46].cardvalue = 10;
deck[47].cardname = "King of Clubs";
deck[47].cardvalue = 10;
deck[48].cardname = "Ace of Hearts";
deck[48].cardvalue = 1;
deck[49].cardname = "Ace of Diamonds";
deck[49].cardvalue = 1;
deck[50].cardname = "Ace of Spades";
deck[50].cardvalue = 1;
deck[51].cardname = "Ace of Clubs";
deck[51].cardvalue = 1;

cout<<"BlackJack by Rory Hector"<<endl;
cout<<"----------------------------------------------------------------------"<<endl;
cout<<"RULES: "<<endl;
cout<<"Aces have default values of 1."<<endl;
cout<<"After choosing to stay, you have the "<<endl;
cout<<"option of adding 10 to your hand value. "<<endl;
cout<<"As usual, dealer has slight upper hand, but "<<endl;
cout<<"the dealer loses part of his upper hand by losing"<<endl;
cout<<"immediately when busting, instead of"<<endl;
cout<<"waiting to see if you busted too."<<endl;
cout<<"There is no immediate blackjack win."<<endl;
cout<<"Even with a blackjack, the game still plays out."<<endl;
cout<<"----------------------------------------------------------------------"<<endl;
cout<<"Press Q after a game to quit playing. Press anything else to continue. "<<endl;
cout<<"----------------------------------------------------------------------"<<endl;
cout<<"Good luck! "<<endl;
cout<<endl;
while (cont != 'Q' || cont != 'q')
{
cin>>cont;
if (cont == 'Q' || cont == 'q')
{
cout<<endl<<"Thank you for playing. "<<endl;
cout<<"You won "<<wins<<" times and lost "<<losses<<" times.";
cout<<endl;
if (wins >= (losses*2))
cout<<"Great Job!";
else if (wins > losses)
cout<<"Good Job!";
else if (wins == losses)
cout<<"Good enough.";
else if (wins <= (losses/2))
cout<<"You're pretty terrible at this game.";
else
cout<<"Better luck next time.";
cout<<endl<<endl;
return 0;
}
cout<<endl;
cout<<"GAME START"<<endl<<endl;
cout<<"Your first card is: ";
i1 = rand() % 52;
cout<<deck[i1].cardname<<endl;
total = deck[i1].cardvalue;
cout<<"Your second card is: ";
i2 = rand() % 52;
cout<<deck[i2].cardname<<endl;
total += deck[i2].cardvalue;
cout<<"You have "<<total<<" in your hand. "<<endl;
cout<<endl;
oi1 = rand() % 52;
oi2 = rand() % 52;
oppTotal = deck[oi1].cardvalue + deck[oi2].cardvalue;
cout<<"Dealer has "<<deck[oi2].cardvalue<<" showing. "<<endl;
cout<<endl;

do
{
cout<<"Would you like to hit or stay? (H/S): ";
cin>> option;
if (option == 'h' || option == 'H')
{

cout<<"Your next card is: ";
intermediate1 = rand() % 52;
j[g] = intermediate1;
cout<<deck[j[g]].cardname<<endl;
total += deck[j[g]].cardvalue;
cout<<"Your new total is: "<<total<<endl;
cout<<endl;
g++;
maxcards = g+3;
}
else
total = total;

if (oppTotal<15)
{
intermediate2 = rand() % 52;
oj[og] = intermediate2;
cout<<"Dealer drew: "<<deck[oj[og]].cardname<<endl;
oppTotal  += deck[oj[og]].cardvalue;
cout<<"Dealer has "<<(oppTotal - deck[oi1].cardvalue)<<" showing. "<<endl;
cout<<endl;
og++;
}

} while (option == 'h' || option == 'H');

if (oppTotal<15)
{
cout<<"The dealer is continuing to draw."<<endl;
oj[og] = rand() % 52;
cout<<"Dealer drew: "<<deck[oj[og]].cardname<<endl;
oppTotal  += deck[oj[og]].cardvalue;
cout<<"Dealer has "<<(oppTotal - deck[oi1].cardvalue)<<" showing. "<<endl;
cout<<endl;
og++;
}
else
oppTotal = oppTotal;

//aces section
aces=0;
if (i1==48||i1==49||i1==50||i1==51)
aces++;
if (i2==48||i2==49||i2==50||i2==51)
aces++;
for (g=0;g<maxcards;g++)
{
if (j[g]==48||j[g]==49||j[g]==50||j[g]==51)
aces++;
}

if (aces==1)         // was if (aces==1)
{
cout<<"You have an ace."<<endl;
cout<<"Would you like to add 10 to your hand value? (Y/N) ";
cin>>add10;
cout<<endl;
if (add10=='y'||add10=='Y')
total+=10;

}
else if (aces>1)
{
cout<<"You have "<<aces<<" aces."<<endl;
cout<<"Would you like to add 10 to your hand value? (Y/N) ";
cin>>add10;
cout<<endl;
if (add10=='y'||add10=='Y')
total+=10;
else if (add10!='n'||add10!='N')
cout<<"Value of aces left at 1. "<<endl;
}
//end of aces section

cout<<"You stayed at: "<<total<<endl;
cout<<"The dealer had: "<<oppTotal<<endl;
cout<< endl;

if (total > 21)
{
cout<<"You busted!"<<endl<<"You lose."<<endl;
losses++;
}
else if (oppTotal>21)
{
cout<<"The dealer busted. "<<endl;
cout<<"You win!"<<endl;
wins++;
}
else if (oppTotal<=21 && total<=21 && oppTotal==total)
{
cout<<"Push"<<endl;
}
else if (oppTotal<=21 && total<=21 && oppTotal > total)
{
cout<<"You lose. "<<endl;
losses++;
}
else
{
cout<<"You win!"<<endl;
wins++;
}
cout<<endl;
}

return 0;
}

-20

Решение

Ваша проблема, скорее всего, что вы не сбрасываете g, og а также maxcards каждый раз вокруг петли. Это приводит к тому, что вы получаете доступ (и пишете) за пределы массивов j и oj.

Вы должны запустить программу через отладчик и взглянуть на переменные в каждой точке. Если вы еще не научились использовать отладчик, сделайте это — это одна из самых важных вещей для обучения программированию.

Другая вещь, которую вы должны сделать, это переставить вашу программу в функции (и классы тоже со временем). Когда ваша программа разбита на более мелкие фрагменты, гораздо проще протестировать каждый блок, чтобы убедиться, что он работает так, как вы ожидали.

3

Другие решения