1 /*
2  * Copyright (C) 2004 Ivo Danihelka (ivo@danihelka.net)
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  */
9 #include "Field.h"
10 
11 #include "V2.h"
12 #include "Cube.h"
13 #include "Rules.h"
14 #include "ModelFactory.h"
15 
16 #include <string.h> // memset()
17 
18 //-----------------------------------------------------------------
19 /**
20  * Two dimensional array of Cube pointers.
21  */
Field(int w,int h)22 Field::Field(int w, int h)
23 {
24     m_w = w;
25     m_h = h;
26 
27     m_border = ModelFactory::createBorder();
28     m_border->rules()->takeField(this);
29 
30     //NOTE: [y][x] indexes
31     m_marks = new Cube**[m_h];
32     for (int y = 0; y < m_h; ++y) {
33         m_marks[y] = new Cube*[m_w];
34         memset(m_marks[y], 0, sizeof(Cube *) * m_w);
35     }
36 }
37 //-----------------------------------------------------------------
~Field()38 Field::~Field()
39 {
40     for (int y = 0; y < m_h; ++y) {
41         delete [] m_marks[y];
42     }
43     delete [] m_marks;
44     delete m_border;
45 }
46 //-----------------------------------------------------------------
47 /**
48  * Get model which occupied this location.
49  * Empty locations are NULL filled.
50  * Locations out of field are filled with border object.
51  */
52 Cube *
getModel(const V2 & loc)53 Field::getModel(const V2 &loc)
54 {
55     int x = loc.getX();
56     int y = loc.getY();
57 
58     //NOTE: hack border everywhere in outher space
59     Cube *result = m_border;
60     if ((0 <= x && x < m_w) && (0 <= y && y < m_h)) {
61         result = m_marks[y][x];
62     }
63     return result;
64 }
65 //-----------------------------------------------------------------
66 /**
67  * Mark this location as occupied by model.
68  * Locations out of field will not be filled.
69  * @param loc write location
70  * @param model model to put on given location
71  * @param toOverride allowed model to overwrite or NULL
72  */
73 void
setModel(const V2 & loc,Cube * model,Cube * toOverride)74 Field::setModel(const V2 &loc, Cube *model, Cube *toOverride)
75 {
76     int x = loc.getX();
77     int y = loc.getY();
78 
79     if ((0 <= x && x < m_w) && (0 <= y && y < m_h)) {
80         if (toOverride == NULL || m_marks[y][x] == toOverride) {
81             m_marks[y][x] = model;
82         }
83     }
84 }
85 
86 
87