source: network-game/common/WorldMap.cpp@ f401cac

Last change on this file since f401cac was f401cac, checked in by dportnoy <dmp1488@…>, 12 years ago

Fixed some bugs in the player movement code

  • Property mode set to 100644
File size: 2.9 KB
Line 
1#include "WorldMap.h"
2
3#include <string>
4#include <iostream>
5#include <fstream>
6#include <sstream>
7#include <cstdlib>
8
9using namespace std;
10
11WorldMap::WorldMap(int width, int height)
12{
13 this->width = width;
14 this->height = height;
15
16 vctMap = new vector<vector<TerrainType>*>(width);
17
18 for (int x=0; x<width; x++) {
19 vector<TerrainType>* newVector = new vector<TerrainType>(height);
20
21 for (int y=0; y<height; y++)
22 (*newVector)[y] = TERRAIN_NONE;
23
24 (*vctMap)[x] = newVector;
25 }
26}
27
28WorldMap::~WorldMap()
29{
30 for (int x=0; x<width; x++)
31 delete (*vctMap)[x];
32
33 delete vctMap;
34}
35
36WorldMap::TerrainType WorldMap::getElement(int x, int y)
37{
38 return (*(*vctMap)[x])[y];
39}
40
41void WorldMap::setElement(int x, int y, TerrainType t)
42{
43 (*(*vctMap)[x])[y] = t;
44}
45
46WorldMap* WorldMap::createDefaultMap()
47{
48 WorldMap* m = new WorldMap(12l, 12);
49
50 for(int x=0; x<12; x++)
51 {
52 for(int y=0; y<12; y++)
53 {
54 if (x ==0 || y == 0 || x == 11 || y == 11)
55 m->setElement(x, y, TERRAIN_OCEAN);
56 else
57 m->setElement(x, y, TERRAIN_GRASS);
58 }
59 }
60
61 m->setElement(5, 5, TERRAIN_ROCK);
62
63 return m;
64}
65
66WorldMap* WorldMap::loadMapFromFile(string filename)
67{
68 WorldMap* m = new WorldMap(12l, 12);
69
70 ifstream file(filename.c_str());
71
72 if (file.is_open())
73 {
74 string line;
75 int width, height;
76
77 // read the map dimensions
78 getline(file, line);
79 if (line.size() > 0)
80 {
81 istringstream iss(line);
82 string token;
83 getline(iss, token, 'x');
84 width = atoi(token.c_str());
85 getline(iss, token, 'x');
86 height = atoi(token.c_str());
87 }
88
89 cout << "width: " << width << endl;
90 cout << "height: " << height << endl;
91
92 // read the map contents
93 int row = 0;
94 while ( file.good() )
95 {
96 getline(file, line);
97 if (line.size() > 0)
98 {
99 cout << "line: " << line << endl;
100
101 istringstream iss(line);
102 string token;
103 int type;
104 TerrainType terrain;
105
106 for(int x=0; x<width; x++)
107 {
108 getline(iss, token, ',');
109 cout << "token: " << token << endl;
110 type = atoi(token.c_str());
111 cout << "type: " << type << endl;
112
113 switch(type) {
114 case 1:
115 terrain = TERRAIN_GRASS;
116 break;
117 case 2:
118 terrain = TERRAIN_OCEAN;
119 break;
120 case 3:
121 terrain = TERRAIN_ROCK;
122 break;
123 }
124
125 cout << "About to set element" << endl;
126 cout << "x: " << x << endl;
127 cout << "row: " << row << endl;
128 m->setElement(x, row, terrain);
129 }
130 }
131
132 row++;
133 }
134 file.close();
135 }
136 else
137 cout << "Could not open the file" << endl;
138
139 return m;
140}
Note: See TracBrowser for help on using the repository browser.