PA6

main.c

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Author:	Nathan Scott
//Class:	CptS 121, Fall  2015, Section 01, Lab Section 11.
//PA#:		6
//Due:		19NOV2015
//Type:		program entrance file.
//Purpose:	to performance Battleship game.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Write a program that simulates the game of Battleship.The game will be completely text - based(see Sample Execution).Battleship is a two player Navy game.The objective of the game is to sink all ships in your enemy's fleet. The Player to sink his/her enemy's fleet first wins.Both players' fleets consist of 5 ships that are hidden from the enemy. Each ship may be differentiated by its "size" (besides the Cruiser and Submarine) or number of cells it expands on the game board. The Carrier has 5 cells, Battleship has 4 cells, Cruiser has 3 cells, Submarine has 3 cells, and the Destroyer has 2 cells.
//The program should be built such that the user is Player1 and the computer is Player2.Two boards exist within the game.Hint: each board should be implemented as a 2 - dimensional array.Each 2 - dimensional array should be 10 X 10. One represents Player1's board and one represents Player2's board.At the beginning of the game each Players' game board should be initialized to all ' - ' indicating that no ships have been placed on either board. Before the game starts, Player1 should have the option to either manually place each of the 5 ships in his/her fleet or to have them randomly placed on the board. If Player1 decides to place the ships manually, then he/she should be prompted to place the Carrier first, Battleship second, Cruiser third, Submarine fourth, and the Destroyer last. Note that ships cannot be placed diagonally on the board, they can only be placed vertically or horizontally. You program must check to see if the user tries to place a ship outside the boundaries of the board or on top of a ship that has already been placed. Each cell on the board that contains part of the ship must be indicated by 'c' for Carrier, 'b' for Battleship, 'r' for Cruiser, 's' for Submarine, or 'd' for Destroyer. For example, if the Carrier was placed then the board should contain 5 'c' s for each cell on the board that has a piece of the Carrier, etc. Once Player1's ships have been placed, Player2's ships must be randomly placed. Note that the placement of Player2's ships must be unknown.Thus, Player2's board will only display ' - ' in each cell after the placement of each ship. The program should randomly select Player1 or Player2 to go first.
//Once it has been decided on which player goes first, the game starts.Whenever it's Player1's turn, a prompt should be displayed asking for a position to target(specifying where to "shoot") on the enemy's (Player2's) board(2 - dimensional array).The position should be specified in terms of a row and a column on the board.The row and column should always be displayed along with the board.If the position specified happens to hit a ship, then a '*' should replace the '-' on Player2's board. If the positioned specified misses any one of the ships in the fleet, then a 'm' should replace the ' - ' on Player2's board.Note that from turn - to - turn each player should NOT be allowed to enter the same position.Also, between turns clear the screen(system("cls")).In one turn, a player can only take one shot at the enemy's (other player's) fleet.When Player2 takes a shot at Player1's board, each hit should be specified with a '*' and each miss with a 'm' on Player1's board.The game is over win Player1 or Player2 has sunk all of the ships in the fleet of the enemy.
//For each move made by Player1 and Player2, the results should be echoed to a file called "battleship.log".In this file, you should log the targeted position by each player on each move and whether it was a hit on one of the ships in the fleet.Also, if one of the ships happens to sink, then note this in the log file.For more information about the rules of Battleship visit : Rules of Battleship.
//At the end of the game, Player1's and Player2's statistics should be written to "battleship.log".The stats include total number of hits, total number of misses, total number of shots, hits to misses ratio(as a percentage), and won or lost the game.Note that the statistics should be placed into a structure called Stats.You need two variables of type Stats, one for Player1 and one for Player2.Once the game has ended you should write the contents of each struct variable to the "battleship.log" file.
//*   A main function that does the following :
//o   Opens an output file battleship.log for writing;
//o   Simulates the game of Battleship
//o   Outputs data to logfile
//o   Outputs stats to logfile
//o   Closes logfile
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "header.h"

int main(void){
	srand((unsigned)time(0));//generate seed for rand().
	//declare variables.
	char board0[SIZE_ROWS][SIZE_COLS] = { { '~', '~' }, { '~', '~' } };//board1 for first player.
	char board1[SIZE_ROWS][SIZE_COLS] = { { '~', '~' }, { '~', '~' } };//board2 for second player.
	char shipType[2][5] = { { 'd', 'r', 's', 'b', 'c' }, { 'd', 'r', 's', 'b', 'c' } };//initialized each type of ship.'d', 'r', 's', 'b', 'c'.
	char str[] = "\0";//hold the information and write to log file.

	int menu = 0;
	int dock[2][5] = { { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 } };//mark which ship has been placed.
	int points[2][1] = { 17, 17 };//[2] two players, [1] how many ship leftover.
	int computer = 0;//0 means computer.
	int player = 1;//1 means player.
	int who = NULL;//1 mean player goes first by default.
	int MorR = 0;//0 means manually, 1 means randomly.
	int target[2][2] = { 0 };//target x, y value.

	int playerScore[2][1] = { 17, 17 };//[2] means player's number, [1] means score ship points.

	system("mode con cols=140 lines=50");//define window size.
	system("color 5f");//change window color.

	do{//do while loop start.
		system("cls");//clean screen.
		printMenu();//Prints out the menu.
		fflush(stdin);//clear scanf buffer.

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//3.0. If option 1 is entered, then print the game rules stated above and repeat step (1)
		//otherwise if option 2 is entered, then continue on to step(4); player 1 starts the game
		//otherwise if option 3 is entered, then print a goodbye message and quit the program
		//otherwise repeat step(1)
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		if (scanf("%d", &menu) != 1 || menu > 2){//determine user enter is valid or not.
			system("cls");
			printf("\n***************************************\nError: please enter a valid choice!\n***************************************\n\n");
			system("pause");
			system("cls");
		}
		else
		{//if user input is valid then enter else clause.
			if (menu == 1){
				welcome_screen();
			}
			if (menu == 2){
				srand((unsigned)time(0));//generate seed for rand().
				do{
					initialize_game_board(board0);//initialize_game_board() that sets each cell in a game board to '~'.
					initialize_game_board(board1);//initialize_game_board() that sets each cell in a game board to '~'.
					randomly_place_ships_on_board(board0, dock, points, shipType, computer);//randomly_place_ships_on_board() that randomly to place each of the 5 types of ships on the player's game board.
					
					MorR = select_manually_or_randomly(MorR, player); //select_who_starts_first() that determines if Player1 or Player2 goes first in the game.
					switch (MorR){//determine which method should use to place the ships.
					case 0:manually_place_ships_on_board(board1, dock, points, shipType, player); break;//manually_place_ships_on_board() that manually to place each of the 5 types of ships on the player's game board.
					case 1:randomly_place_ships_on_board(board1, dock, points, shipType, player); break;//randomly_place_ships_on_board() that randomly to place each of the 5 types of ships on the player's game board.
					}

					who = select_who_starts_first(who); //select_who_starts_first() that determines if Player1 or Player2 goes first in the game.

					while (points[0][0] > 0 && points[1][0] > 0){
						if (who % 2 == 0){//0 means computer goes first.
							check_shot(board1, dock, points, shipType, computer, playerScore);//that determines if the shot taken was a hit or a miss.
							display_board(board0, board1, points, who);//prints out computer and player's board.
							who += 1;
							if (DEBUG == 1){
								printf("\nwho = %d\n", who);
								system("pause");
							}
						}
						if (who % 2 == 1){//1 means player goes first.
							check_shot(board0, dock, points, shipType, player, playerScore);//that determines if the shot taken was a hit or a miss.
							display_board(board0, board1, points, who);//prints out computer and player's board.
							who += 1;
							if (DEBUG == 1){
								printf("\nwho = %d\n", who);
								system("pause");
							}
						}
						display_board(board0, board1, points, who);//that displays a board to the screen. Note that Player1's board should be displayed differently than Player2's board (see above).
					}
					
				} while (points[0][0] > 0 && points[1][0] > 0);//any player score below 0 will terminate the game.

				is_winner(points);//that determines if a winner exists.
				//output_stats();
			}
		}
	} while (menu != 0);//end do while loop when menu == 0.
	system("cls");
	printf("\n\nGood Bye!\n\n");

	system("pause");
	return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//THE END
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

header.h

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Author:	Nathan Scott
//Class:	CptS 121, Fall  2015, Section 01, Lab Section 11.
//PA#:		6
//Due:		19NOV2015
//Type:		header file.
//Purpose:	include lib and pre-define functions.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#ifndef _HEADERNAME_H 
#define _HEADERNAME_H
#define _CRT_SECURE_NO_WARNINGS
#define SIZE_ROWS 10 //set rows for array, total 10 rows.
#define SIZE_COLS 10 //set cols for array, total 10 cols.
#define DEBUG 1 //switch on(1)/off(0) debug mode.

void printMenu(void);
void welcome_screen(void);

int select_who_starts_first(int who);
int select_manually_or_randomly(int MorR, int role);

void initialize_game_board(char board[SIZE_ROWS][SIZE_COLS]);
void print_board(char board[SIZE_ROWS][SIZE_COLS], int points[][1], int role);
void manually_place_ships_on_board(char board[SIZE_ROWS][SIZE_COLS],int dock[][5], int points[][1], char shipType[][5],int role);
void randomly_place_ships_on_board(char board[SIZE_ROWS][SIZE_COLS], int dock[][5], int points[][1], char shipType[][5], int role);

void check_shot(char board[SIZE_ROWS][SIZE_COLS], int dock[][1], int points[][1], int target[][2], int role, int playerScore[][1]);
void update_board(char board[SIZE_ROWS][SIZE_COLS], int points[][1], int role, int target[][2]);
void display_board(char board0[SIZE_ROWS][SIZE_COLS], char board1[SIZE_ROWS][SIZE_COLS], int points[][1], int who);

void check_if_sunk_ship(char board[SIZE_ROWS][SIZE_COLS], int dock[][5], int target[][2], int role);
void output_current_move(char board[SIZE_ROWS][SIZE_COLS], int dock[][5], int role);
void output_stats(char str[], int points, int role);

void is_winner(int points[][1]);

int nonRepeatRand(int num, int array[]);
void playerScore(int playerNum, int score[][12], int finalScore[][12]);

#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//THE END
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

func.c

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Author:	Nathan Scott
//Class:	CptS 121, Fall  2015, Section 01, Lab Section 11.
//PA#:		6
//Due:		19NOV2015
//Type:		source file.
//Purpose:	define functions and logics.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "header.h"

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//*       Create a function select_who_starts_first() that determines if Player1 or Player2 goes first in the game.
//*       Create a function manually_place_ships_on_board() that allows the user to place each of the 5 types of ships on his / her game board.
//*       Create a function randomly_place_ships_on_board() that randomly places the 5 types of ships on a given board.
//*       Create a function check_shot() that determines if the shot taken was a hit or a miss.
//*       Create a function is_winner() that determines if a winner exists.
//*       Create a function update_board() that updates the board every time a shot is taken. '*' indicates a hit and 'm' indicates a miss.
//*       Create a function display_board() that displays a board to the screen.Note that Player1's board should be displayed differently than Player2's board(see above).
//Hint: pass in a flag(int) that stores whether or not you just passed in Player1's or Player2's board.Then perform the different logic for Player1's board versus Player2's board.
//	  *       Create a function output_current_move() that writes the position of the shot taken by the current player to the log file.It also writes whether or not it was a hit, miss, and if the ship was sunk.
//	  *       Create a function check_if_sunk_ship() that determines if a ship was sunk.
//	  *       Create a function output_stats() that writes the statistics collected on each player to the log file.
//	  *       Other functions that you think are necessary!
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//welcome_screen() that displays an initial program welcome message along with the rules of Battleship.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void printMenu(void){
	printf("\n\n\
	                                       |\n\
	                                       |\\ \n\
	                                       | |\n\
	                                       ---\n\
	                                      / | [\n\
	                              |       | |||\n\
	                            _/|     _/|-++'\n\
	                        +  +--|    |--|--|_ |-\n\
	                     {_/|__|  |/\\__|  |--- |||__}\n\
	                    +---------------___[}-_===_.'____\n\
	                ____`-' ||___-{]_| _[}-__|_____|_[___\\==--\n\
	__...._____--==/___]_|__|_____________________________[___\\==--____,--------|\n\
	| o     USN 121                                                 BATTLESHIP  /\n\
	 \\_________________________________________________________________________|\n\
\n\
	~ ~      ~ ~ ~ ~ ~ ~ ~ ~      ~ ~ ~ ~ ~      ~ ~ ~ ~ ~ ~ ~         ~ ~ ~ ~ ~ ~ \n\
	 ~ ~ ~ ~ ~ ~ ~ ~      ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~        ~ ~ ~ ~ ~ ~ ~ ~ ~ \n\
	~ ~ ~ ~      ~ ~ ~ ~ ~ ~ ~ ~ ~       ~ ~ ~ ~    ~ ~ ~ ~ ~ ~ ~       ~ ~    ~ ~ \n\
\n\n\
Author: Nathan Scott\n\
Version: 6.28\n\n\
--------------------------------------------MENU--------------------------------------------\n\
1. Welcome and rules\n\
2. Start the Battleship\n\
0. Exit\n\
--------------------------------------------------------------------------------------------\n\n\
Enter: ");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//welcome_screen() that displays an initial program welcome message along with the rules of Battleship.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void welcome_screen(void){
	system("cls");
	printf("Function: welcome_screen()\n\
\nThe Rules of Battleship\n\
\n\
The game is played on four grids, two for each player. \n\
The grids are typically square – usually 10×10 – and the individual squares in the grid are identified by letter and number.\n\
On one grid the player arranges ships and records the shots by the opponent.\n\
On the other grid the player records his/her own shots.\n\
Before play begins, each player secretly arranges their ships on their primary grid.\n\
Each ship occupies a number of consecutive squares on the grid, arranged either horizontally or vertically.\n\
The number of squares for each ship is determined by the type of the ship.\n\
The ships cannot overlap(i.e., only one ship can occupy any given square in the grid).\n\
The types and numbers of ships allowed are the same for each player.These may vary depending on the rules.\n\
There are two typical complements of ships, as given in the Milton Bradley version of the rules : \n\
\n\
See the table provided below :\n\
\n\
+-------------------------------------------------------------------------------------------------------+\n\
| TYPE OF SHIP						| SIZE							|\n\
|-------------------------------------------------------------------------------------------------------|\n\
| Aircraft Carrier					| 5							|\n\
|-------------------------------------------------------------------------------------------------------|\n\
| Battleship						| 4							|\n\
|-------------------------------------------------------------------------------------------------------|\n\
| Submarine						| 3							|\n\
|-------------------------------------------------------------------------------------------------------|\n\
| Cruiser						| 3							|\n\
|-------------------------------------------------------------------------------------------------------|\n\
| Destroyer						| 2							|\n\
+-------------------------------------------------------------------------------------------------------+\n\
\n");
	system("pause");
	system("cls");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//select_who_starts_first() that determines if Player1 or Player2 goes first in the game.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int select_who_starts_first(int who){
	if (DEBUG == 1){
		printf("\nFunction: select_who_starts_first()\n");
		printf("Debug = %d\n\n", DEBUG);
	}

	printf("Which Player goes first: 0. Computer | 1. Player\n\nEnter: ");
	if (scanf("%d", &who) != 1 || who < 0 || who >1){
		system("cls");
		printf("\n***************************************\nselect_who_starts_first()\nplayerNum error!\nPlease enter a valid value!\n***************************************\n\n");
		system("pause");
		system("cls");
	}

	return who;
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//select_manually_or_randomly() that determines manually or randomly place the ship.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int select_manually_or_randomly(int MorR, int role){
	if (DEBUG == 1){
		printf("\nFunction: select_manually_or_randomly()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Role = %d\n\n", role);
		printf("How would you place the ships: 0. Manually | 1. Randomly\n\nEnter: ");
	}
	if (scanf("%d", &MorR) != 1 || MorR < 0|| MorR > 1){
		system("cls");
		printf("\n***************************************\nselect_manually_or_randomly()\nMorR error!\nPlease enter a valid value!\n***************************************\n\n");
		system("pause");
		system("cls");
	}
	if (DEBUG == 1){
		printf("MorR = %d\n", MorR);
		system("pause");
	}

	return MorR;
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//initialize_game_board() that sets each cell in a game board to '~'.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void initialize_game_board(char board[SIZE_ROWS][SIZE_COLS]){
	int counter = 0, input = 0;
	for (int i = 0; i < SIZE_ROWS; i++){
		for (int j = 0; j < SIZE_COLS; j++){
			board[i][j] = '~';
		}
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//print_board() prints out the status of the board.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void print_board(char board[SIZE_ROWS][SIZE_COLS], int points[][1], int role){
	//system("cls");
	if (DEBUG == 1){
		printf("\nFunction: print_board()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Role = %d\n\n", role);
		printf("Points: %d\n\n", points[role][0]);
	}
	printf("  x 0  1  2  3  4  5  6  7  8  9\ny\n");
	for (int i = 0; i < SIZE_ROWS; i++)//rows.
	{
		printf("%d ", i);
		for (int j = 0; j < SIZE_COLS; j++)//columns.
		{
			if (j == 0){
				printf("  %c ", board[i][j]);
			}
			else{
				printf(" %c ", board[i][j]);
			}
		}
		printf("\n");
	}
	printf("\n");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//manually_place_ships_on_board() that allows the user to place each of the 5 types of ships on his/her game board.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void manually_place_ships_on_board(char board[SIZE_ROWS][SIZE_COLS], int dock[][5], int points[][1], char shipType[][5], int role){
	int xStart = 0, yStart = 0,//starting point coordinate.
		HorV = 0,//HorV means Horizontally(0) or Vertically(1).
		overlap = 0,//0 means there is no overlap ship.
		input = 0,//select which ship type.
		shipLength = 0;
	if (DEBUG == 1){
		printf("\nFunction: manually_place_ships_on_board()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Role = %d\n\n", role);
		printf("Points: %d\n\n", points[role][0]);
	}
	print_board(board, points, role);

	do{
		//get ship type.
		printf("Please chose a ship type: \n1.Destroyer (%d) | 2.Cruiser (%d) | 3.Submarine (%d) | 4.Battleship (%d) | 5.Aircraft Carrier (%d)\nEnter: ", dock[role][0], dock[role][1], dock[role][2], dock[role][3], dock[role][4]);
		if (scanf("%d", &input) != 1 || dock[role][input - 1] == 0 || input < 1 || input > 5 || points < 0){
			system("cls");
			printf("\n***************************************\nmanually_place_ships_on_board()\ninput/dock error!\nPlease enter a valid value!\n***************************************\n\n");
			system("pause");
			system("cls");
			print_board(board, points, role);
		}
		else{
			fflush(stdin);//clear scanf buffer.
			printf("\n\n");

			//input value adjustment.
			switch (input){
			case 1: shipLength = 2; break;
			case 2: shipLength = 3; break;
			case 3: shipLength = 3; break;
			case 4: shipLength = 4; break;
			case 5: shipLength = 5; break;
			}

			//get direction.
			printf("Would you like to place your ship Horizontally (0) or Vertically (1) ?\nEnter: ");
			if (scanf("%d", &HorV) != 1 || HorV < 0 || HorV > 1){
				system("cls");
				printf("\n***************************************\nmanually_place_ships_on_board()\nHorV error!\nPlease enter a valid value!\n***************************************\n\n");
				system("pause");
				system("cls");
				print_board(board, points, role);
			}
			else{
				fflush(stdin);//clear scanf buffer.
				printf("\n\n");

				//get starting point.
				printf("Where is the starting point coordinate (x, y) ?\nEnter: ");
				if (scanf("%d%d", &xStart, &yStart) != 2){
					system("cls");
					printf("\n***************************************\nmanually_place_ships_on_board()\nxStart/yStart error!\nPlease enter a valid value!\n***************************************\n\n");
					system("pause");
					system("cls");
					print_board(board, points, role);
				}
				else{
					fflush(stdin);//clear scanf buffer.
					printf("\n\n");

						//check the ship placement must in the same row.
					if (HorV == 0 && (xStart + shipLength) <= SIZE_ROWS && dock[role][input - 1] == 1){//horizontally.
							for (int i = 0; i < shipLength; i++){
								if (board[yStart][xStart + i] != '~'){
									overlap += 1;
								}
							}
							if (overlap < 1){//check the placement is not overlap.
								printf("Your ship starting point at (%d,%d)\n", xStart, yStart);
								for (int i = 0; i < shipLength; i++)
								{
									board[yStart][xStart + i] = shipType[role][input - 1];
								}
								points[role][0] = points[role][0] - shipLength;//subtract the ship pts from 17.
								dock[role][input - 1] = 0;//change dock status mark it as has been used.
								input = 0;//reset input value.
								print_board(board, points, role);
							}
							else{
								overlap = 0;//reset overlap value.
								system("cls");
								printf("\n***************************************\nmanually_place_ships_on_board()\noverlap error!\nPlease enter a valid value!\n***************************************\n\n");
								system("pause");
								system("cls");
							}
						}
					else if (HorV == 1 && (yStart + shipLength) <= SIZE_ROWS && dock[role][input - 1] == 1){//vertically.
							for (int i = 0; i < shipLength; i++){//check the placement is not overlap.
								if (board[yStart + i][xStart] != '~'){
									overlap += 1;
								}
							}
							if (overlap < 1){//check the placement is not overlap.
								printf("Your ship starting point and ending point is (%d,%d)\n", xStart, yStart);
								for (int i = 0; i < shipLength; i++)
								{
									board[yStart + i][xStart] = shipType[role][input - 1];
								}
								points[role][0] -= shipLength;//subtract the ship pts from 17.
								dock[role][input - 1] = 0;//change dock status mark it as has been used.
								input = 0;//reset input value.
								print_board(board, points, role);
							}
							else{
								overlap = 0;//reset overlap value.
								system("cls");
								printf("\n***************************************\nmanually_place_ships_on_board()\noverlap error!\nPlease enter a valid value!\n***************************************\n\n");
								system("pause");
								system("cls");
							}
					}
					else{
						overlap = 0;//reset overlap value.
						system("cls");
						printf("\n***************************************\nmanually_place_ships_on_board()\nstart coordinate + shipLength out of boundary error!\nPlease enter a valid value!\n***************************************\n\n");
						system("pause");
						system("cls");
					}
					print_board(board, points, role);
				}
			}
			//print_board(board, ship, playerNum);
		}
	} while (points[role][0] > 0);//check how many ship still leftover.

	points[role][0] = 17;//reset total ship points.

	for (int i = 0; i < 5; i++){//reset dock value.
		dock[role][i] = 1;
	}

	system("pause");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//randomly_place_ships_on_board() that randomly places the 5 types of ships on a given board.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void randomly_place_ships_on_board(char board[SIZE_ROWS][SIZE_COLS], int dock[][5], int points[][1], char shipType[][5], int role){
	int xStart = 0,//x starting point coordinate.
		yStart = 0,//y starting point coordinate.
		HorV = 0,//HorV means Horizontally(0) or Vertically(1).
		overlap = 0,//0 means there is no overlap ship.
		input = 1,//select which ship type.
		shipLength = 0;//how long is the ship.
	
	if (DEBUG == 1){
		printf("\nFunction: randomly_place_ships_on_board()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Role = %d\n\n", role);
		printf("Points: %d\n\n", points[role][0]);
	}
	print_board(board, points, role);

	do{
		HorV = rand() % 2;//HorV means Horizontally(0) or Vertically(1).
		xStart = rand() % 10;//x starting point coordinate.
		yStart = rand() % 10;//y starting point coordinate.

			//input value adjustment.
			switch (input){
			case 1: shipLength = 2; break;
			case 2: shipLength = 3; break;
			case 3: shipLength = 3; break;
			case 4: shipLength = 4; break;
			case 5: shipLength = 5; break;
			}

		//check the ship placement must in the same row.
			if (HorV == 0 && (xStart + shipLength) <= SIZE_ROWS && dock[role][input - 1] == 1 && points > 0){//horizontally.
			for (int i = 0; i < shipLength; i++){//check the placement is not overlap.
				if (board[yStart][xStart + i] != '~'){
					overlap += 1;
				}
			}
			if (overlap < 1){
				//system("cls");
				for (int i = 0; i < shipLength; i++)
				{
					board[yStart][xStart + i] = shipType[role][input - 1];
				}
				points[role][0] = points[role][0] - shipLength;//subtract the ship pts from 17.
				dock[role][input - 1] = 0;//change dock status mark it as has been used.
				input += 1;//select which ship type from (1~5).
				if (DEBUG == 1){ printf("H = %d\n\n", HorV); }
				print_board(board, points, role);
			}
			else{
				overlap = 0;//reset overlap value.
				if (DEBUG == 1){ printf("H-overlapped\n\n"); }
			}
		}
			else if (HorV == 1 && (yStart + shipLength) <= SIZE_ROWS && dock[role][input - 1] == 1 && points > 0){//vertically.
				//system("cls");
			for (int i = 0; i < shipLength; i++){//check the placement is not overlap.
				if (board[yStart + i][xStart] != '~'){
					overlap += 1;
				}
			}
			if (overlap < 1){//check the placement is not overlap.
				for (int i = 0; i < shipLength; i++)
				{
					board[yStart + i][xStart] = shipType[role][input - 1];
				}
				points[role][0] -= shipLength;//subtract the ship pts from 17.
				dock[role][input - 1] = 0;//change dock status mark it as has been used.
				input += 1;//select which ship type from (1~5).
				if (DEBUG == 1){ printf("V = %d\n\n", HorV); }
				print_board(board, points, role);
			}
			else{
				overlap = 0;//reset overlap value.
				if (DEBUG == 1){ printf("V-overlapped!\n\n"); }
			}
		}
		else{
			if (DEBUG == 1){ printf("error: %d > %d\n", xStart + yStart + shipLength, SIZE_ROWS); }
		}
		if (DEBUG == 1){ printf("ship = %d\n", points[role][0]); }

	} while (points[role][0] > 0);//check how many ship still leftover.

	points[role][0] = 17;//reset total ship points.

	for (int i = 0; i < 5; i++){//reset dock value.
		dock[role][i] = 1;
	}

	system("pause");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//check_shot() that determines if the shot taken was a hit or a miss.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void check_shot(char board[SIZE_ROWS][SIZE_COLS], int dock[][1], int points[][1], int target[][2], int role, int playerScore[][1]){
	int exitCon = 0;//exit condition.
	if (DEBUG == 1){
		printf("\nFunction: check_shot()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Role = %d\n\n", role);
	}

	//computer enter target coordinate.
	while (role % 2 == 0 && exitCon == 0){
		exitCon = 1;
		target[role][0] = rand() % 10;
		target[role][1] = rand() % 10;

		//computer would not hit same target coordinate again.
		while (board[target[role][1]][target[role][0]] == 'm' || board[target[role][1]][target[role][0]] == '*'){
			target[role][0] = rand() % 10;//reassign xStart value.
			target[role][1] = rand() % 10;//reassign yStart value.
		}

		//check continue.
		if (board[target[role][1]][target[role][0]] != '~' && board[target[role][1]][target[role][0]] != 'm' && board[target[role][1]][target[role][0]] != '*'){//continue if use computer his anything.
			update_board(board, points, role, target);
			printf("Continue, you hit player's ship!\n\n");
			system("pause");
			exitCon = 0;
		}
		update_board(board, points, role, target);//that updates the board every time a shot is taken. '*' indicates a hit and 'm' indicates a miss.
		check_if_sunk_ship(board, dock, target, role);//that determines if a ship was sunk.
		output_current_move(board, dock, target, role);//that writes the position of the shot taken by the current player to the log file. It also writes whether or not it was a hit, miss, and if the ship was sunk.
	}

	//player enter target coordinate.
	while (role % 2 == 1 && exitCon == 0){
		exitCon = 1;
		printf("Please enter computer target's x, y coordinate:\nEnter: ");
		if (scanf("%d%d", &target[role][0], &target[role][1]) == 2){
			update_board(board, points, role, target);
			check_if_sunk_ship(board, dock, target, role);//that determines if a ship was sunk.
			output_current_move(board, dock, target, role);//that writes the position of the shot taken by the current player to the log file.It also writes whether or not it was a hit, miss, and if the ship was sunk.
			printf("Continue, you hit something!\n\n");
			system("pause");

			//check continue.
			if (board[target[role][1]][target[role][0]] != '~' && board[target[role][1]][target[role][0]] != 'm' && board[target[role][1]][target[role][0]] != '*'){//continue if use computer his anything.
				update_board(board, points, role, target);
				printf("Continue, you hit computer's ship!\n\n");
				system("pause");
				exitCon = 0;
			}
		}
		else{
			system("cls");
			printf("\n***************************************\ncheck_shot()\ntarget coordinate error!\nPlease enter a valid value!\n***************************************\n\n");
			system("pause");
			system("cls");
		}
	}

	if (DEBUG == 1){
		printf("target[%d][0]:x = %d\ntarget[%d][0]:y = %d\n\n", role, target[role][0], role, target[role][1]);
		system("pause");
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//update_board() that updates the board every time a shot is taken. '*' indicates a hit and 'm' indicates a miss.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void update_board(char board[SIZE_ROWS][SIZE_COLS], int points[][1], int role, int target[][2]){
	if (DEBUG == 1){
		printf("\nFunction: update_board()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Role = %d\n\n", role);
	}

	if (board[target[role][1]][target[role][0]] == '~'){//0 means xStart, 1 means yStart.
		board[target[role][1]][target[role][0]] = 'm';
	}

	if (board[target[role][1]][target[role][0]] == 'd' || \
		board[target[role][1]][target[role][0]] == 'r' || \
		board[target[role][1]][target[role][0]] == 's' || \
		board[target[role][1]][target[role][0]] == 'b' || \
		board[target[role][1]][target[role][0]] == 'c'){
		
		board[target[role][1]][target[role][0]] = '*';
		points[role][0] -= 1;//deduct points.
	}
	

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//display_board() that displays a board to the screen. Note that Player1's board should be displayed differently than Player2's board (see above).
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void display_board(char board0[SIZE_ROWS][SIZE_COLS], char board1[SIZE_ROWS][SIZE_COLS], int points[][1], int who){
	system("cls");
	if (DEBUG == 1){
		printf("\nFunction: display_board()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Round = %d\n\n", who);
	}
	
	print_board(board0, points, 0);
	print_board(board1, points, 1);

	system("pause");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//is_winner() that determines if a winner exists.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void is_winner(int points[][1]){
	system("cls");
	if (DEBUG == 1){
		printf("\nFunction: display_board()\n");
		printf("debug = %d\n\n", DEBUG);
	}

	if (points[0][0] == 0 && points[1][0] > 0){
		printf("The winner is : Player1\n\n");
	}

	if (points[1][0] == 0 && points[0][0] > 0){
		printf("The winner is : Player0\n\n");
	}

	system("pause");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//check_if_sunk_ship() that determines if a ship was sunk.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void check_if_sunk_ship(char board[SIZE_ROWS][SIZE_COLS], int dock[][5], int target[][2], int role){
	if (DEBUG == 1){
		printf("\nFunction: check_if_sunk_ship()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Role = %d\n\n", role);
	}

	if (board[target[role][1]][target[role][0]] == 'd'){//0 means xStart, 1 means yStart.
		dock[role][0] = 0;
	}
	if (board[target[role][1]][target[role][0]] == 'r'){//0 means xStart, 1 means yStart.
		dock[role][1] = 0;
	}
	if (board[target[role][1]][target[role][0]] == 's'){//0 means xStart, 1 means yStart.
		dock[role][2] = 0;
	}
	if (board[target[role][1]][target[role][0]] == 'b'){//0 means xStart, 1 means yStart.
		dock[role][3] = 0;
	}
	if (board[target[role][1]][target[role][0]] == 'c'){//0 means xStart, 1 means yStart.
		dock[role][4] = 0;
	}

	system("pause");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//output_current_move() that writes the position of the shot taken by the current player to the log file. It also writes whether or not it was a hit, miss, and if the ship was sunk.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void output_current_move(char board[SIZE_ROWS][SIZE_COLS], int dock[][5], int target[][2], int role){
	if (DEBUG == 1){
		printf("\nFunction: output_current_move()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Role = %d\n\n", role);
	}

	FILE *fPtr, *fPtrOut = NULL; //NULL ptr
	fPtr = fopen("battleship.log", "a+");
	if (fPtr == NULL){//relative path for filename, and determine file can be open or not.
		printf("\nError: file battleship.log cannot be open!\n\n");
	}
	else{
		if (role % 2 == 0){
			if (board[target[role][1]][target[role][0]] == 'm'){
				fprintf(fPtr, "Computer: %d,%d \"Miss!\"\n\n", target[role][1], target[role][0]);
			}
			if (board[target[role][1]][target[role][0]] == '*'){
				fprintf(fPtr, "Computer: %d,%d \"Hit!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][0] == 0){
				fprintf(fPtr, "Computer: %d,%d \"Destroyer sunk!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][1] == 0){
				fprintf(fPtr, "Computer: %d,%d \"Cruiser sunk!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][2] == 0){
				fprintf(fPtr, "Computer: %d,%d \"Submarine sunk!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][3] == 0){
				fprintf(fPtr, "Computer: %d,%d \"Battleship sunk!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][4] == 0){
				fprintf(fPtr, "Computer: %d,%d \"Aircraft sunk!\"\n\n", target[role][1], target[role][0]);
			}
		}

		if (role % 2 == 1){
			if (board[target[role][1]][target[role][0]] == 'm'){
				fprintf(fPtr, "Player: %d,%d \"Miss!\"\n\n", target[role][1], target[role][0]);
			}
			if (board[target[role][1]][target[role][0]] == '*'){
				fprintf(fPtr, "Player: %d,%d \"Hit!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][0] == 0){
				fprintf(fPtr, "Player: %d,%d \"Destroyer sunk!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][1] == 0){
				fprintf(fPtr, "Player: %d,%d \"Cruiser sunk!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][2] == 0){
				fprintf(fPtr, "Player: %d,%d \"Submarine sunk!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][3] == 0){
				fprintf(fPtr, "Player: %d,%d \"Battleship sunk!\"\n\n", target[role][1], target[role][0]);
			}
			if (dock[role][4] == 0){
				fprintf(fPtr, "Player: %d,%d \"Aircraft sunk!\"\n\n", target[role][1], target[role][0]);
			}
		}
	}

	printf("\n\n%d files were saved and closed!\n\n", fcloseall());//output how many open files has been closed.
	system("pause");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//output_stats() that writes the statistics collected on each player to the log file.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void output_stats(char str[], int points, int role){
	if (DEBUG == 1){
		printf("\nFunction: output_stats()\n");
		printf("Debug = %d\n", DEBUG);
		printf("Role = %d\n\n", role);
	}

	FILE *fPtr, *fPtrOut = NULL; //NULL ptr
	fPtr = fopen("battleship.log", "a+");
	if (fPtr == NULL){//relative path for filename, and determine file can be open or not.
		printf("\nError: file battleship.log cannot be open!\n\n");
	}
	else{

		fprintf(fPtr, "Player%d : %d,%d \"%c\"");
		fprintf(fPtr, "Player%d wins, Player%d loses");
		fprintf(fPtr, "\n\n");

		fprintf(fPtr, "*** Player1 Stats ***");
		fprintf(fPtr, "Number Hits: %d");
		fprintf(fPtr, "Number Misses: %d");
		fprintf(fPtr, "Total Shots: %d");
		fprintf(fPtr, "Hit/Miss Ratio: %d");
		fprintf(fPtr, "\n\n");

		fprintf(fPtr, "*** Player2 Stats ***");
		fprintf(fPtr, "Number Hits: %d");
		fprintf(fPtr, "Number Misses: %d");
		fprintf(fPtr, "Total Shots: %d");
		fprintf(fPtr, "Hit/Miss Ratio: %d");
	}

	printf("\n\n%d files were saved and closed!\n\n", fcloseall());//output how many open files has been closed.
	system("pause");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//nonRepeatRand().
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int nonRepeatRand(int num, int array[]){
	int x, p;
	int count;
	int i = 0;

	srand(time(NULL));

	for (count = 0; count < num; count++){
		array[count] = rand() % num + 1;
	}

	while (i < num){
		int r = rand() % num + 1;

		for (x = 0; x < i; x++)
		{
			if (array[x] == r){
				break;
			}
		}
		if (x == i){
			array[i++] = r;
		}
	}
	for (p = 0; p < num; p++){
		printf("%d ", array[p]);
	}
	return array;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//THE END
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////