64366da39f734d831f4a164d9dd07ca442498f07
[tagua/yd.git] / src / core / board.cpp
blob64366da39f734d831f4a164d9dd07ca442498f07
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 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 Piece();
49 void Board::set(const Point& p, const Piece& piece) {
50 if (valid(p)) {
51 m_data[p.x + p.y * m_size.x] = piece;
53 else
54 kError() << "point is not valid" << p;
57 bool Board::valid(const Point& p) const {
58 return p.x < m_size.x &&
59 p.x >= 0 &&
60 p.y < m_size.y &&
61 p.y >= 0;
64 PathInfo Board::path(const Point& from, const Point& to) const {
65 if (!valid(from) || !valid(to))
66 return PathInfo(PathInfo::Undefined, 0);
68 Point delta = to - from;
69 PathInfo::Direction direction;
71 if (delta.x == 0)
72 direction = PathInfo::Vertical;
73 else if (delta.y == 0)
74 direction = PathInfo::Horizontal;
75 else if (delta.x == delta.y)
76 direction = PathInfo::Diagonal1;
77 else if (delta.x == -delta.y)
78 direction = PathInfo::Diagonal2;
79 else
80 direction = PathInfo::Undefined;
82 int num_obs = 0;
83 if (direction != PathInfo::Undefined) {
84 Point step = delta.normalizeInfinity();
85 Point position = from;
86 while ((position += step) != to) {
87 if (get(position) == Piece())
88 continue;
89 num_obs++;
93 return PathInfo(direction, num_obs);
96 Point Board::find(const Piece& piece) const {
97 for (int i = 0; i < m_size.x; i++) {
98 for (int j = 0; j < m_size.y; j++) {
99 Point p(i, j);
100 if (get(p) == piece)
101 return p;
105 return Point::invalid();
108 QStringList Board::borderCoords() const {
109 QStringList retv;
110 Point p = size();
111 for (int i = 0; i < p.x; i++)
112 retv << Point(i, 0).col();
113 for (int i = 1; i <= p.y; i++)
114 retv << QString::number(i);
115 return retv + retv;