Change Board::get() to return a pointer.
[tagua/yd.git] / src / core / board.cpp
blob1fed6de7deb5f2a0e30ba564dc9b7c8e8ddd612e
1 /*
2 Copyright (c) 2007 Paolo Capriotti <p.capriotti@gmail.com>
3 (c) 2007 Maurizio Monge <maurizio.monge@kdemail.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9 */
11 #include "board.h"
12 #include "piece.h"
14 #include <KDebug>
16 Board::Board(const Point& size)
17 : m_size(size) {
18 m_data.resize(m_size.x * m_size.y);
21 Board::Board(const Board* other)
22 : m_size(other->m_size)
23 , m_data(other->m_data) { }
25 bool Board::equals(const Board* other) const {
26 if (m_size != other->m_size)
27 return false;
29 const unsigned int total = m_data.size();
30 for (unsigned int i = 0; i < total; i++) {
31 if (m_data[i] != other->m_data[i])
32 return false;
35 return true;
38 Point Board::size() const { return m_size; }
40 const Piece* Board::get(const Point& p) const {
41 if (valid(p)) {
42 return &m_data[p.x + p.y * m_size.x];
44 else {
45 return NULL;
49 // FIXME: solve this code duplication
50 Piece* Board::get(const Point& p) {
51 if (valid(p)) {
52 return &m_data[p.x + p.y * m_size.x];
54 else {
55 return NULL;
59 void Board::set(const Point& p, const Piece& piece) {
60 if (valid(p)) {
61 m_data[p.x + p.y * m_size.x] = piece;
63 else
64 kError() << "point is not valid" << p;
67 bool Board::valid(const Point& p) const {
68 return p.x < m_size.x &&
69 p.x >= 0 &&
70 p.y < m_size.y &&
71 p.y >= 0;
74 PathInfo Board::path(const Point& from, const Point& to) const {
75 if (!valid(from) || !valid(to))
76 return PathInfo(PathInfo::Undefined, 0);
78 Point delta = to - from;
79 PathInfo::Direction direction;
81 if (delta.x == 0)
82 direction = PathInfo::Vertical;
83 else if (delta.y == 0)
84 direction = PathInfo::Horizontal;
85 else if (delta.x == delta.y)
86 direction = PathInfo::Diagonal1;
87 else if (delta.x == -delta.y)
88 direction = PathInfo::Diagonal2;
89 else
90 direction = PathInfo::Undefined;
92 int num_obs = 0;
93 if (direction != PathInfo::Undefined) {
94 Point step = delta.normalizeInfinity();
95 Point position = from;
96 while ((position += step) != to) {
97 if (get(position) == NULL ||
98 *get(position) == Piece())
99 continue;
100 num_obs++;
104 return PathInfo(direction, num_obs);
107 Point Board::find(const Piece& piece) const {
108 for (int i = 0; i < m_size.x; i++) {
109 for (int j = 0; j < m_size.y; j++) {
110 Point p(i, j);
111 if (*get(p) == piece)
112 return p;
116 return Point::invalid();
119 QStringList Board::borderCoords() const {
120 QStringList retv;
121 Point p = size();
122 for (int i = 0; i < p.x; i++)
123 retv << Point(i, 0).col();
124 for (int i = 1; i <= p.y; i++)
125 retv << QString::number(i);
126 return retv + retv;