1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
//
// main.cpp
// battleship
//
// Created by Home on 3/30/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <exception>
#include <ctype.h>
void printinfo();
void printfield(char array[6][6]);
void printlane(int i, char array[6][6]);
bool check(int i, int j, char map[6][6]);
int charcovert(char c);
int main(){
char c;
int row, collumn = 7, ship = 0, quess = 0;
bool sunk = false;
std::ifstream ship_location;
ship_location.exceptions(std::ifstream::failbit | std::ifstream::badbit);
// [row] [collumn]
char field[6][6], player[6][6] = {};
//open file
try{
ship_location.open("/Users/home/Desktop/battleship/battleship/ship.txt");
}
//catch error
catch (std::ofstream::failure &e){
std::cout << "An error has occured";
return 1;
}
//upload array
for(int j = 0; j < 6; j++){
for(int i = 0; i < 6; i++){
ship_location >> field[j][i];
}
}
ship_location.close();
printinfo();
//player guessing, all user input in the while loop
while(!sunk){
printfield(player);
std::cout << "enter in your location!(q to exit)";
std::cin >> c >> row;
c = tolower(c);
if(c == 'q') sunk = true;
collumn = charcovert(c);
++quess;
if(check(row, collumn, field)){
player[--row][--collumn] = 'H';
ship++;
}
else {
player[--row][--collumn] = 'M';
}
if(ship == 3) sunk = true;
}
printfield(player);
std::cout << "YOU HAVE WON!!!! it took you " << quess << " tries";
return 0;
}
int charcovert(char c){
if(c == 'a') return 1;
if(c == 'b') return 2;
if(c == 'c') return 3;
if(c == 'd') return 4;
if(c == 'e') return 5;
if(c == 'f') return 6;
if(c == 'q') return 0;
else return 7;
}
bool check(int i, int j, char field[6][6]){
if(field[i][j] == 'S') return true;
else return false;
}
void printfield(char array[6][6]){
std::cout << "\n A B C D E F\n";
for(int i = 0; i < 6; i++){
std::cout << i + 1 << " "; printlane(i, array);
std::cout << '\n';
}
}
void printlane(int i, char array[6][6]){
for(int j = 0; j < 6; j++){
std::cout << array[i][j] << " ";
}
}
void printinfo(){
std::cout << "********************";
std::cout << "\n* *";
std::cout << "\n* BATTLESUB! *";
std::cout << "\n* by me! *";
std::cout << "\n* *";
std::cout << "\n********************";
}
| |