-
Notifications
You must be signed in to change notification settings - Fork 0
/
layer.cpp
executable file
·89 lines (79 loc) · 1.75 KB
/
layer.cpp
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
#include<stdio.h>
#include <SDL.h>
#include "game.h"
#include "tile.h"
#include "layer.h"
Layer::Layer(Tile *tile) {
this->tile=tile;
tileMap=0;
th=0;
tw=0;
}
Layer::~Layer() {
}
void Layer::load(const char *filename)
{
tw=0;
th=0;
if(tileMap) delete tileMap;
tileMap=0;
// pass 1, measure size
FILE *file=fopen(filename,"r");
if(!file) {
D("Fatal: file not found '%s'\n",filename);
return;
}
int ch;
int pos=0;
while((ch=getc(file))!=EOF) {
if(th==0) {
if(ch>='0' && ch<='9' && tw==0) tw++;
else if(ch==',') tw++;
}
if(ch!='\n' && ch!=' ' && ch!='\t') {
pos++;
} else if(ch=='\n') {
pos=0;
th++;
}
}
fseek(file,0,SEEK_SET);
tileMap=new int[tw*th];
char buf[64];
pos=0;
int x=0,y=0;
while((ch=getc(file))!=EOF) {
if((ch>='0' && ch<='9')||ch=='-') {
buf[pos++]=ch;
buf[pos]=0;
} else if(ch==',' || ch=='\n') {
int id=0;
pos=0;
sscanf(buf,"%d",&id);
setTile(x,y,id);
x++;
if(ch=='\n') {
x=0;
y++;
}
}
}
fclose(file);
}
void Layer::draw()
{
if(!tileMap) return;
for(int y=0;y<th;y++) {
for(int x=0;x<tw;x++) {
tile->draw(getTile(x,y),x,y);
}
}
}
int Layer::getTile(int x,int y) {
if(x<0 || y<0 || x>=tw || y>=th) return -1;
return tileMap[x+y*tw];
}
void Layer::setTile(int x,int y,int value) {
if(x<0 || y<0 || x>=tw || y>=th) return;
tileMap[x+y*tw]=value;
}