В настоящее время я работаю над проектом CMSC под названием Blackjack для моего курса в колледже. Я пытаюсь добавить класс с именем Card в векторный объект в другом классе с именем Hand. Класс Hand хранится как объект в другом векторе класса Player.
Моя проблема заключается в том, что я пытаюсь вызвать метод OutputPlayerHand в классе с именем Blackjack, но я получаю ошибку сегментации.
Вот мой код для класса Blackjack.cpp.
#include "Blackjack.h"#include <iostream>
Blackjack::Blackjack()
{
// Initialize the dealer
Player dealer((char *) "Dealer", 100);
m_dealer = dealer;
// Initialize a player 'Jane' with 100 funds
Player player((char *) "Jane", 100);
m_players.push_back(player);
}
Blackjack::Blackjack(char *names[], int numPlayers)
{
// Initialize the dealer
Player dealer((char *) "Dealer", 100);
m_dealer = dealer;
// Loop through all passed player names
for(int i = 0; i < numPlayers; i++)
{
// Initialize a player 'names[i]' with 100 funds
Player player(names[i], 100);
m_players.push_back(player);
}
}
int Blackjack::GetNumPlayers()
{
// Return the size of the players vector
return m_players.size();
}
char *Blackjack::GetPlayerName(int player)
{
// Return the requested player's name
return m_players[player].GetName();
}
int Blackjack::GetPlayerFunds(int player)
{
// Return the requested player's funds
return m_players[player].GetFunds();
}
void Blackjack::SetPlayerFunds(int player, int amt)
{
// Set the requested player's funds
m_players[player].SetFunds(amt);
}
bool Blackjack::SetPlayerBet(int player, int amt)
{
// If the player has insufficient funds
if(m_players[player].GetFunds() < amt)
{
// Return false
return false;
}
// Subtract the amount from the player funds
m_players[player].SetFunds(m_players[player].GetFunds() - amt);
// Add the amount to the player bet
m_players[player].SetBet(amt);
// Return true
return true;
}
void Blackjack::NewDeal()
{
// Create a new unsorted 52 card deck
Deck deck;
// Initialize m_deck to the new deck
m_deck = deck;
// Shuffle m_deck
m_deck.Shuffle();
// 2 cards for dealer, 2 cards for each player
int cardsToDeal = 2 + (2 * m_players.size());
// While we still have cards to deal
while(cardsToDeal > 0)
{
// Deal to each player
for(unsigned int i = 0; i < m_players.size(); i++)
{
std::cout << "Deal Player Card" << std::endl;
// Deal one card to the player
m_players[i].GetHand().AddCard(m_deck.DealCard());
// Decrement the number of cards to deal
cardsToDeal--;
}
std::cout << "Deal Dealer Card" << std::endl;
// Deal the dealer one card
m_dealer.GetHand().AddCard(m_deck.DealCard());
// Decrement the number of cards to deal
cardsToDeal--;
}
}
void Blackjack::OutputPlayerHand(int player)
{
std::cout << "Player Output Card." << std::endl;
m_players[player].GetHand().GetCard(0).OutputCard();
}
void Blackjack::OutputDealerHand()
{
// TODO: Code Method
}
bool Blackjack::HitPlayer(int player)
{
// TODO: Code Method
return false;
}
void Blackjack::DealerPlay()
{
// TODO: Code Method
}
int Blackjack::SettlePlayerBet(int player)
{
// TODO: Code Method
return -1;
}
Вот мой код для класса Player.cpp.
#include "Player.h"
Player::Player()
{
m_name = (char *) "Jane";
m_funds = 100;
m_bet = 0;
}
Player::Player(char *name, int funds)
{
m_name = name;
m_funds = funds;
m_bet = 0;
}
char *Player::GetName()
{
return m_name;
}
void Player::SetName(char *name)
{
m_name = name;
}
int Player::GetFunds()
{
return m_funds;
}
void Player::SetFunds(int funds)
{
m_funds = funds;
}
int Player::GetBet()
{
return m_bet;
}
void Player::SetBet(int bet)
{
m_bet = bet;
}
Hand Player::GetHand()
{
return m_hand;
}
Вот мой код для класса Hand.cpp.
#include "Hand.h"
void Hand::AddCard(Card card)
{
m_cards.push_back(card);
}
Card Hand::GetCard(int card)
{
return m_cards[card];
}
int Hand::Size()
{
return m_cards.size();
}
void Hand::Clear()
{
m_cards.clear();
}
Вот мой код для основного класса Proj2.cpp.
/*
* CHANGES TO Blackjack.h SPEC:
* added new member funcs:
* char *GetPlayerName(int)
* int GetNumPlayers()
* void OutputDealerHand()
*
* HitPlayer() should print out the card that was dealt.
*/
#include <cstdlib>
#include <iostream>
#include "Blackjack.h"
using namespace std;
Blackjack *CreateGame(int argc, char *argv[]);
int ProcessArgs(int argCnt, char *args[], char **&names, int *&funds);
void DoNewDeal(Blackjack &game);
void ProcAllBets(Blackjack &game);
void DoAllPlays(Blackjack &game);
void PlayOnePlayer(Blackjack &game, int player);
void SettleAllPlayers(Blackjack &game);
void ShowAllPlayerFunds(Blackjack &game);
bool QueryAnotherRound();int main(int argc, char *argv[]) {
Blackjack *game;
int round;
cout << "Welcome to CMSC 202 Blackjack!\n";
game = CreateGame(argc, argv);
round = 0;
do {
cout << "\nRound " << ++round << ":\n";
ProcAllBets(*game);
DoNewDeal(*game);
DoAllPlays(*game);
SettleAllPlayers(*game);
ShowAllPlayerFunds(*game);
} while (QueryAnotherRound());
cout << "\nGoodbye!\n";
return 0;
}Blackjack *CreateGame(int argc, char *argv[]) {
char **names;
int *funds;
int numPlayers;
Blackjack *game;
numPlayers = ProcessArgs(argc - 1, &argv[1], names, funds);
game = new Blackjack(names, numPlayers);
for (int p = 0; p < numPlayers; p++) {
game->SetPlayerFunds(p, funds[p]);
}
return game;
}int ProcessArgs(int argCnt, char *args[], char **&names, int *&funds) {
int i, p;
int numRecs = argCnt / 2;
names = static_cast<char **>(calloc(numRecs, sizeof(char *)));
funds = static_cast<int *>(calloc(numRecs, sizeof(int)));
for (p = 0, i = 0; p < numRecs; p++) {
names[p] = args[i++];
funds[p] = atoi(args[i++]);
}
return p;
}void ProcAllBets(Blackjack &game) {
int numPlayers = game.GetNumPlayers();
int bet;
for (int p = 0; p < numPlayers; p++) {
cout << "How much does " << game.GetPlayerName(p) << " bet? ";
cin >> bet;
cout << endl; // For neat scripting
if (!game.SetPlayerBet(p, bet)) {
cout << "Illegal bet--changing to $0\n";
game.SetPlayerBet(p, 0);
}
}
}void DoNewDeal(Blackjack &game) {
int numPlayers = game.GetNumPlayers();
game.NewDeal();
cout << "The players' hands:\n";
for (int p = 0; p < numPlayers; p++) {
cout << game.GetPlayerName(p) << ": ";
game.OutputPlayerHand(p);
cout << endl;
}
cout << "Dealer: ";
game.OutputDealerHand(); // This hides dealer's hole card
cout << "\n\n";
}void DoAllPlays(Blackjack &game) {
int numPlayers = game.GetNumPlayers();
int p;
for (p = 0; p < numPlayers; p++) {
PlayOnePlayer(game, p);
}
game.DealerPlay();
}
void PlayOnePlayer(Blackjack &game, int player) {
char *name = game.GetPlayerName(player);
string answer;
bool hit, busted;
cout << ">>" << name << "'s turn:\n";
busted = false;
do {
cout << "Hand: ";
game.OutputPlayerHand(player);
cout << endl;
cout << name << "'s play: ";
cin >> answer;
cout << endl; // For neat scripting
answer[0] == 'y' || answer[0] == 'Y';
hit = (answer[0] == 'h' || answer[0] == 'H');
if (hit) {
busted = game.HitPlayer(player);
}
} while (hit && !busted);
if (busted) {
cout << "Busted!\n";
}
cout << endl;
}
void SettleAllPlayers(Blackjack &game) {
int numPlayers = game.GetNumPlayers();
int p;
for (p = 0; p < numPlayers; p++) {
game.SettlePlayerBet(p);
// Above should print out:
// Joe has busted--Dealer wins", or "Sally has 15--Dealer loses"}
cout << endl;
}
void ShowAllPlayerFunds(Blackjack &game) {
int numPlayers = game.GetNumPlayers();
int p;
for (p = 0; p < numPlayers; p++) {
cout << game.GetPlayerName(p) << " now has $"<< game.GetPlayerFunds(p) << endl;
}
cout << endl;
}
bool QueryAnotherRound() {
string answer;
cout << "Another round? ";
cin >> answer;
cout << endl; // For neat scripting
return answer[0] == 'y' || answer[0] == 'Y';
}
Может кто-нибудь сказать мне, что я делаю не так? Мне запрещено редактировать класс Proj2.cpp. Если вам нужна дополнительная информация, пожалуйста, не стесняйтесь спрашивать. Если вам нужно увидеть проект целиком Вот пока что ссылка на репозиторий Github для всего проекта. Если вам нужно увидеть мои правила проекта и разъяснения, Вот это ссылка на мой сайт описания проекта курсов.
Любая помощь очень ценится в этом вопросе, заранее спасибо за ваше время.
Hand
пустой.
Эта строка: m_players[i].GetHand().AddCard(m_deck.DealCard())
добавляет карту только во временную копию
Делать GetHand()
верните ссылку, и ваши игроки действительно получат карты.
Кроме того, вы не должны включать исполняемые файлы, такие как Prog2.out в репозитории.
Других решений пока нет …