File indexing completed on 2024-02-25 04:08:50

0001 /*
0002     SPDX-FileCopyrightText: 2007 Paolo Capriotti <p.capriotti@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #ifndef GRID_H
0008 #define GRID_H
0009 
0010 #include "knavalbattle_debug.h"
0011 
0012 #include "coord.h"
0013 
0014 #define FOREACH_SQUARE(p, grid) \
0015     for (Coord p(0,0); p.x < grid.width(); p.x++) \
0016     for (p.y = 0; p.y < grid.height(); p.y++)
0017 
0018 template <typename T>
0019 class Grid
0020 {
0021     Coord m_size;
0022     T* m_grid;
0023     
0024     int convert(const Coord& p) const;
0025 public:
0026     Grid(const Coord& size);
0027     ~Grid();
0028     
0029     T& operator[](const Coord& p);
0030     const T& operator[](const Coord& p) const;
0031     
0032     bool valid(const Coord& p) const;
0033     inline int width() const { return m_size.x; }
0034     inline int height() const { return m_size.y; }
0035 };
0036 
0037 // Implementation
0038 
0039 template <typename T>
0040 Grid<T>::Grid(const Coord& size)
0041 : m_size(size)
0042 {
0043     m_grid = new T[m_size.x * m_size.y];
0044 }
0045 
0046 template <typename T>
0047 Grid<T>::~Grid()
0048 {
0049     delete[] m_grid;
0050 }
0051 
0052 template <typename T>
0053 int Grid<T>::convert(const Coord& p) const
0054 {
0055     return p.x + p.y * m_size.x;
0056 }
0057 
0058 template <typename T>
0059 bool Grid<T>::valid(const Coord& p) const
0060 {
0061     return p.x >= 0 && p.x < width() &&
0062             p.y >= 0 && p.y < height();
0063 }
0064 
0065 template <typename T>
0066 T& Grid<T>::operator[](const Coord& p)
0067 {
0068     Q_ASSERT(valid(p));
0069     return m_grid[convert(p)];
0070 }
0071 
0072 template <typename T>
0073 const T& Grid<T>::operator[](const Coord& p) const
0074 {
0075     Q_ASSERT(valid(p));
0076     return m_grid[convert(p)];
0077 }
0078 
0079 
0080 #endif // GRID_H
0081