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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
|
//David Chen
//Home Project 8
#include "Map.h"
#include <iostream>
#include <fstream>
/*
This was coded for the map below (assuming '*' = wall, 'u' = hero):
9
5
*********
** ****
** ******
** u ***
*********
Map(); //constructor
Map(string filename); //loads txt from filename and creates a map
int Display() const; //displays map
int Get(int row, int column) const; //gets row, col of character pos
void Set(int row, int column, int new_value); //sets character from row,col to new value
*/
Map::Map() //default constructor that creates size of 0
{
row = 0; //row/col for vector
col = 0;
char_pos_row = 0;
char_pos_col = 0;
}
Map::Map(std::string filename) //loads txt from filename and creates a map
{
std::ifstream fs;
fs.open(filename);
//checks to see if file exists
if (fs.fail())
{
std::cerr << "Opening file failed.\n";
}
//inputs map into vector
int r,c;
std::cout << "map:" << std::endl;
fs >> c;
fs >> r;
fs >> std::noskipws;
fs.ignore(1);
row = r;
col = c;
map2d.resize(c, std::vector<char>(r));
map2d[row][col];
/*
5x9
*********
** ****
** ******
** u ***
*********
*/
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col+1; j++)
{
char ch;
fs >> ch;
map2d[i][j] = ch;
// std::cout << ch;
}
}
std::cout << map2d[0][0];
fs.close(); //finished
}
void Map::Display() const//displays map
{
std::cout << std::endl;
for(int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
std::cout << map2d[i][j];
}
std::cout << std::endl;
}
}
char Map::Get(int r, int c)//method that returns the character at (row, column) position
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; i++)
{
if(map2d[i][j] == 'u')
map2d[i][j] = ' '; //deletes hero's old position.
}
}
return map2d[r][c];
}
bool Map::is_char_pos_possible (int r, int c) //is the character position possible?
{
if (char_pos_row > r || r < 0)
{
return false;
}
else if (char_pos_col > c || c < 0)
{
return false;
}
else if (map2d[r][c] == '*')
{
return false;
}
else
{
return true;
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (map2d[r][c] == '*') //checks to see if char is trying to stand on the wall.
{
return false;
}
}
}
}
void Map::Set(int r, int c, int new_value)//sets character from row,col to new value
{
if (is_char_pos_possible(r,c) == true)
{
char_pos_row = r;
char_pos_col = c;
map2d[r][c] = new_value;
}
}
Map::~Map(){} //deconstructor
|