// Battleship.cpp -- This program plays the board game Battleship
// CSCI 111-03
// Source -- Open Source

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;


const int ROWS = 25;
const int COLS = 25;
typedef char playboard[ROWS][COLS];

//prototypes
void printboard(playboard);
bool fleetsunk(playboard);
void fire(int, int);

//global variables
playboard display;
playboard ships;

int main() {
	//lab name and number
	cout << "Dylan Brucki -- Lab 8" << endl << endl;

	//create infile
	ifstream infile;
	char letter;
	int number;

	infile.open("ships.txt");
	if (!infile){
		cout << "FILE OPENING ERROR!" << endl;
		system("pause");
		return 0;
	}
		
	for (int row = 0; row < ROWS; row++){
		for (int col = 0; col < COLS; col++){
			infile >> ships[row][col];
		}
	}

	for (int row = 0; row < ROWS; row++){
		for (int col = 0; col < COLS; col++){
			display[row][col] = '~';
		}
	}

	printboard(display);

	while (fleetsunk(ships)){
		cout << "Please enter a coordinate (Hint: [A-Y][1-25], Example: A1): ";
		cin >> letter >> number;
		cout << endl << endl;
		fire(letter-64, number);
		printboard(display);
	}

	cout << "HOORAY!! You have won the game by destroying all ships!" << endl << endl;

	// pause command window and then return 0
	system("pause");
	return 0;
}

void printboard(playboard board){
	for (int r = 0; r < ROWS; r++){
		for (int c = 0; c < COLS; c++){
			cout << board[r][c];
		}
		cout << endl;
	}
}

bool fleetsunk(playboard board){
	bool shipremain = false;

	for (int r = 0; r < ROWS; r++){
		for (int c = 0; c < COLS; c++){
			if (board[r][c] == '#'){
				shipremain = true;
			}
		}
	}

	return shipremain;
}

void fire(int row, int col){
	if (ships[row-1][col-1] == '#'){
		cout << "You hit the ship!" << endl;
		ships[row-1][col-1] = 'H';
		display[row-1][col-1] = 'H';
	}
	else if (ships[row-1][col-1] == '~'){
		cout << "Haha the ship is still okay! You have missed." << endl;
		ships[row-1][col-1] = 'M';
		display[row-1][col-1] = 'M';
	}
	else if (ships[row-1][col-1] == 'H'){
		cout << "You already hit this ship!!" << endl;
	}
	else if (ships[row-1][col-1] == 'M'){
		cout << "You have failed again! You already tried this.  PS it is still a miss." << endl;
	}
	else {
		cout << "This input is not a coordinate. Please try again" << endl;
	}
}