first version: three types of field with randomness
[colorflood] / colorflood / src / field.cpp
1 /*
2   Copyright 2010 Serge Ziryukin <ftrvxmtrx@gmail.com>
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; version 2 of the License.
7
8   This program is distributed in the hope that it will be useful,
9   but WITHOUT ANY WARRANTY; without even the implied warranty of
10   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11   GNU General Public License for more details.
12 */
13
14 #include <QtGui>
15 #include "field.hpp"
16
17 static const int fieldWidth = 420;
18
19 const int Field::rects[Field::NUM_SIZES] = { 14, 21, 28 };
20 const int Field::turns[Field::NUM_SIZES] = { 25, 35, 50 };
21
22 Field::Field (QWidget *parent)
23     : QWidget (parent)
24 {
25     // FIXME -- restore saved state
26 }
27
28 Field::Field (QWidget *parent, const QVector<QBrush> &brushes, FieldSize size)
29     : QWidget (parent)
30 {
31     init(brushes, size);
32 }
33
34 Field::~Field ()
35 {
36     // FIXME -- save state
37 }
38
39 Field::FieldSize Field::getSize () const
40 {
41     return size;
42 }
43
44 /*
45 =================
46 randomize
47 =================
48 */
49 void Field::randomize ()
50 {
51     Field::FieldRect rect;
52     rect.flood = false;
53
54     data.clear();
55     data = QVector<FieldRect> (rects[size] * rects[size], rect);
56
57     qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
58
59     for (QVector<Field::FieldRect>::iterator rect = data.begin();
60          rect != data.end();
61          rect++)
62     {
63         (*rect).brush = qrand() % brushes.size();
64     }
65 }
66
67 int Field::getNumRectsOfSize (FieldSize size)
68 {
69     return rects[size];
70 }
71
72 int Field::getNumTurnsOfSize (FieldSize size)
73 {
74     return turns[size];
75 }
76
77 void Field::init (const QVector<QBrush> &brushes, FieldSize size)
78 {
79     this->size = size;
80     this->brushes = brushes;
81
82     setFixedSize(fieldWidth, fieldWidth);
83     randomize();
84 }
85
86 int Field::getRectSize (FieldSize size)
87 {
88     return fieldWidth / rects[size];
89 }
90
91 void Field::paintEvent (QPaintEvent *event)
92 {
93     QPainter painter;
94     painter.begin(this);
95
96     QRect rect = QRect(0, 0, getRectSize(size), getRectSize(size));
97
98     for (int y = 0; y < rects[size] ;y++)
99     {
100         int n = y * rects[size];
101
102         for (int x = 0; x < rects[size] ;x++, n++)
103         {
104             rect.moveTo(x * rect.width(), y * rect.height());
105
106             if (rect.intersects(event->rect()))
107                 painter.fillRect(rect, brushes.at(data[n].brush));
108         }
109     }
110
111     painter.end();
112 }