だから基本的には戦艦の割り当てに取り組んでいますmain関数はループ内でfire関数を呼び出します。このループの中で、各プレイヤーのためにfire関数が一度呼び出されます。この機能が実行されるたびに、ゲームボードのパラメータが変更され(上記参照)、プレイヤーの移動結果が反映されます。また、メインでは、end_gameパラメータの値を評価して、プレーヤがゲームを終了する必要があるかどうかを判断する必要があります。この評価には、プレーヤーがゲームに勝ったかどうかの決定も含まれていなければなりません(つまり、no_hitsパラメーターが23に等しい)。ループ条件を修正するには?
でも、winner_test関数と呼ばれる関数があります。 main関数はwinner_test関数を使用して、まだ勝者が存在するかどうかを判断する必要があります。これを行うために、winner_test関数は、単にno_hits_player_1かno_hits_player_2のいずれかが23に等しいかどうかを判断します。各ボードには23のポジションがあります。だから、どちらのボードに23ヒットがあるとき、ゲームは勝ち、プログラムは終了しなければならない。
私の質問は勝者のテスト関数であり、私のループでは繰り返しを続けるための条件は、end_gameパラメータがtrueの場合はfalseです。これは、ユーザーが値10を楽しまれたことを意味します。私のループの状態が間違っている場合、どうすれば私のコードを修正することができますか?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
typedef char gameBoard[10][10];
using namespace std;
const int MAX_ROWS = 10;
const int MAX_COLS = 10;
void get_board_data(ifstream&, gameBoard, gameBoard);
void fire(gameBoard, int&, bool&);
void print_board(gameBoard);
bool winner_test(int, int);
int currentplayer = 1;
int main()
{
int no_hits;
bool end_game = true;
ifstream myfile;
myfile.open("infile.txt");
gameBoard Player1;
gameBoard Player2;
get_board_data(myfile, Player1,Player2);
//The main function calls the fire function in a loop. Inside this loop the fire function is called once for each player.
while (end_game==true) {
fire(Player2, no_hits, end_game);
if (end_game == false)
{
break;
}
fire(Player1, no_hits, end_game);
}
}
void fire(gameBoard player, int& no_hits, bool& end_game)
{
int row;
int col;
static int player1_hits=0;
static int player2_hits=0;
if (currentplayer == 1)
{
cout << "Player 1 hits:" << " " << player1_hits << " "<< "player2 hits:" << " " << player2_hits << endl;
cout << "Player 1 - enter your move" << " " << "(ie. 0 4)";
cin >> row >> col;
if (row == 10 && col == 10)
{
end_game = false;
return;
}
if (player[row][col] == '#') {
cout << "hit!!!!!" << endl;
player[row][col] = 'H';
player1_hits++;
currentplayer = 2;
}
else if (player[row][col] == '-')
{
cout << "miss!!!" << endl;
player[row][col] = '.';
}
currentplayer = 2;
}
else if (currentplayer == 2)
{
cout << "Player 2- enter your move" << " " << "(ie. 0 4)";
cin >> row >> col;
if (row == 10 && col == 10)
{
end_game = false;
}
if (player[row][col] == '#') {
cout << "hit!!!!!" << endl;
player[row][col] = 'H';
player2_hits++;
currentplayer = 1;
}
else if (player[row][col] == '-')
{
cout << "miss!!!" << endl;
player[row][col] = '.';
currentplayer = 1;
}
}
}
男性と書くと、このコードは長すぎます。私たちはこのすべてを必要としません。 – Xyzk
... [MCVE]の定義に合致するように最低限必要なものを教えてください。 –
プレイヤー2が「10 10」を入力したときに「戻る」ことを忘れたようです。繰り返しコードを避けるべき理由のもう一つの例です。変更を加えることは、他の多くの場所で同じ変更を行うことを覚えていることを意味します。 –